Certainly! To accommodate your requirements:
-
Allow Custom Positioning Besides Predefined Positions: The applyPosition method is enhanced to accept fully custom positioning via an object containing any CSS positioning properties.
-
Allow Predefined Positions with Custom Offsets: When using a predefined position, you can now specify custom offsets to tweak individual top, bottom, left, or right values instead of the default 20px.
-
Reduce Code Duplication: The applyPosition method has been refactored to minimize repetitive code by leveraging a more dynamic approach to apply positioning styles.
Below is the amended Toolbar class incorporating these changes:
export default class Toolbar {
constructor(options = {}) {
this.toolbar = null;
this.isInitialized = false;
this.isVisible = false;
this.buttons = [];
this.toggleButtons = [];
this.options = options;
this.styleElement = null; // To keep track of injected CSS
// New: Store buttons added before initialization
this._preInitButtons = [];
this._preInitToggleButtons = [];
}
// Initialize the toolbar
init() {
if (this.isInitialized) return;
// Inject CSS styles
this.injectStyles();
// Create toolbar container
this.toolbar = document.createElement("div");
this.toolbar.className = "custom-toolbar";
// Apply positioning based on options
this.applyPosition();
// Apply additional styling if provided
if (this.options.style) {
Object.assign(this.toolbar.style, this.options.style);
}
// Append to body
document.body.appendChild(this.toolbar);
this.isInitialized = true;
// Append pre-initialized buttons
this._preInitButtons.forEach(({ options, onClick }) => {
this._createButton(false, options, onClick);
});
this._preInitToggleButtons.forEach(({ options, onToggle }) => {
this._createButton(true, options, onToggle);
});
// Clear pre-init arrays
this._preInitButtons = [];
this._preInitToggleButtons = [];
}
// Inject CSS styles into the document
injectStyles() {
if (this.styleElement) return; // Prevent multiple injections
const css = `
/* Toolbar Styles */
.custom-toolbar {
position: fixed;
background-color: #ffffff;
border: 1px solid #e0e0e0;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
padding: 10px;
display: flex;
gap: 10px;
z-index: 1000;
transition: opacity 0.3s ease, visibility 0.3s ease;
opacity: 0;
visibility: hidden;
}
.custom-toolbar.show {
opacity: 1;
visibility: visible;
}
.toolbar-button,
.toolbar-toggle-button {
display: flex;
align-items: center;
gap: 5px;
padding: 8px 12px;
border: none;
border-radius: 4px;
background-color: #1976d2;
color: #ffffff;
cursor: pointer;
font-size: 14px;
transition: background-color 0.2s ease;
}
.toolbar-button:hover,
.toolbar-toggle-button:hover {
background-color: #1565c0;
}
.toolbar-toggle-button.active {
background-color: #388e3c;
}
.toolbar-button img,
.toolbar-toggle-button img {
max-width: 20px;
max-height: 20px;
}
.toolbar-button span,
.toolbar-toggle-button span {
display: inline-block;
}
`;
this.styleElement = document.createElement("style");
this.styleElement.type = "text/css";
this.styleElement.appendChild(document.createTextNode(css));
document.head.appendChild(this.styleElement);
}
// Apply positioning based on options
applyPosition() {
const { position } = this.options;
// Define predefined positions with default offsets
const predefinedPositions = {
"top-left": { top: "20px", left: "20px", right: "auto", bottom: "auto" },
"top-right": { top: "20px", right: "20px", left: "auto", bottom: "auto" },
"top-center": {
top: "20px",
left: "50%",
right: "auto",
bottom: "auto",
transform: "translateX(-50%)",
},
"bottom-left": {
bottom: "20px",
left: "20px",
top: "auto",
right: "auto",
},
"bottom-right": {
bottom: "20px",
right: "20px",
top: "auto",
left: "auto",
},
"bottom-center": {
bottom: "20px",
left: "50%",
right: "auto",
top: "auto",
transform: "translateX(-50%)",
},
};
const styles = {};
if (typeof position === "string") {
// Use predefined position
if (predefinedPositions[position]) {
Object.assign(styles, predefinedPositions[position]);
// Remove transform to allow custom offsets if any
if (styles.transform) {
delete styles.transform;
}
} else {
console.warn(
`Toolbar: Unknown predefined position "${position}". Falling back to "top-right".`
);
Object.assign(styles, predefinedPositions["top-right"]);
}
} else if (typeof position === "object") {
if (position.preset && predefinedPositions[position.preset]) {
Object.assign(styles, predefinedPositions[position.preset]);
// Apply custom offsets if provided
if (position.offsets && typeof position.offsets === "object") {
Object.assign(styles, position.offsets);
}
// If transform is provided in offsets, apply it
if (position.offsets && position.offsets.transform) {
styles.transform = position.offsets.transform;
}
} else {
// Assume custom positioning
Object.assign(styles, position);
}
} else {
// Default to top-right if position is not specified correctly
Object.assign(styles, predefinedPositions["top-right"]);
}
// Apply styles to the toolbar
for (const [prop, value] of Object.entries(styles)) {
this.toolbar.style[prop] = value;
}
}
// Show the toolbar
start() {
if (!this.isInitialized) {
this.init();
}
this.toolbar.classList.add("show");
this.isVisible = true;
}
// Hide the toolbar
stop() {
if (this.toolbar) {
this.toolbar.classList.remove("show");
this.isVisible = false;
}
}
// Destroy the toolbar
destroy() {
if (!this.isInitialized) return;
// Remove all event listeners from buttons
this.buttons.forEach((button) => {
if (button._handleClick) {
button.removeEventListener("click", button._handleClick);
}
});
this.toggleButtons.forEach((button) => {
if (button._handleClick) {
button.removeEventListener("click", button._handleClick);
}
});
// Remove toolbar from DOM
this.toolbar?.parentNode?.removeChild(this.toolbar);
this.toolbar = null;
// Remove injected styles
this.styleElement?.parentNode?.removeChild(this.styleElement);
this.styleElement = null;
// Reset state
this.isInitialized = false;
this.isVisible = false;
this.buttons = [];
this.toggleButtons = [];
this._preInitButtons = [];
this._preInitToggleButtons = [];
}
/**
* Add a button to the toolbar.
* @param {Object} options - Configuration for the button.
* @param {string} options.label - The text label of the button.
* @param {string|HTMLElement} options.icon - The icon for the button (URL, SVG string, emoji, or HTMLElement).
* @param {Function} onClick - Callback function when the button is clicked.
*/
addButton(options, onClick) {
if (this.isInitialized) {
this._createButton(false, options, onClick);
} else {
this._preInitButtons.push({ options, onClick });
}
}
/**
* Add a toggle button to the toolbar.
* @param {Object} options - Configuration for the toggle button.
* @param {string} options.label - The text label of the button.
* @param {string|HTMLElement} options.icon - The icon for the toggle button.
* @param {Function} onToggle - Callback function when the toggle state changes. Receives the new state as a parameter.
*/
addToggleButton(options, onToggle) {
if (this.isInitialized) {
this._createButton(true, options, onToggle);
} else {
this._preInitToggleButtons.push({ options, onToggle });
}
}
// Internal method to create buttons
_createButton(isToggle, options, callback) {
const button = document.createElement("button");
button.className = isToggle ? "toolbar-toggle-button" : "toolbar-button";
// If icon is provided
if (options.icon) {
const iconElement = this._createIconElement(options.icon);
button.appendChild(iconElement);
}
// If label is provided
if (options.label) {
const labelElement = document.createElement("span");
labelElement.textContent = options.label;
button.appendChild(labelElement);
}
// Bind event listener and keep reference for later removal
let handleClick;
if (isToggle) {
handleClick = () => {
const isActive = button.classList.toggle("active");
callback(isActive);
};
} else {
handleClick = (event) => {
callback(event);
};
}
button.addEventListener("click", handleClick);
button._handleClick = handleClick; // Custom property to reference the listener
this.toolbar.appendChild(button);
if (isToggle) {
this.toggleButtons.push(button);
} else {
this.buttons.push(button);
}
}
// Helper method to create icon elements
_createIconElement(icon) {
let iconElement;
if (typeof icon === "string") {
if (this._isValidUrl(icon)) {
// If icon is a URL, create an img element
iconElement = document.createElement("img");
iconElement.src = icon;
iconElement.alt = "";
} else if (this._isSVG(icon)) {
// If icon is an SVG string, create a span with innerHTML
iconElement = document.createElement("span");
iconElement.innerHTML = icon;
// Optional: Add a class for SVG styling if needed
iconElement.className = "toolbar-icon-svg";
} else {
// Assume icon is an emoji or plain text
iconElement = document.createElement("span");
iconElement.textContent = icon;
}
} else if (icon instanceof HTMLElement) {
// If icon is an HTMLElement, append it directly
iconElement = icon;
} else {
// Fallback: empty span
iconElement = document.createElement("span");
}
return iconElement;
}
// Utility method to check if a string is a valid URL
_isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
// Utility method to check if a string is an SVG
_isSVG(string) {
return string.trim().startsWith("<svg");
}
}
Detailed Changes
-
Modified applyPosition Method:
The applyPosition method now handles more flexible positioning options by allowing for both predefined positions with customizable offsets and completely custom positioning.
// Apply positioning based on options
applyPosition() {
const { position } = this.options;
// Define predefined positions with default offsets
const predefinedPositions = {
"top-left": { top: "20px", left: "20px", right: "auto", bottom: "auto" },
"top-right": { top: "20px", right: "20px", left: "auto", bottom: "auto" },
"top-center": {
top: "20px",
left: "50%",
right: "auto",
bottom: "auto",
transform: "translateX(-50%)",
},
"bottom-left": {
bottom: "20px",
left: "20px",
top: "auto",
right: "auto",
},
"bottom-right": {
bottom: "20px",
right: "20px",
top: "auto",
left: "auto",
},
"bottom-center": {
bottom: "20px",
left: "50%",
right: "auto",
top: "auto",
transform: "translateX(-50%)",
},
};
const styles = {};
if (typeof position === "string") {
// Use predefined position
if (predefinedPositions[position]) {
Object.assign(styles, predefinedPositions[position]);
// Remove transform to allow custom offsets if any
if (styles.transform) {
delete styles.transform;
}
} else {
console.warn(
`Toolbar: Unknown predefined position "${position}". Falling back to "top-right".`
);
Object.assign(styles, predefinedPositions["top-right"]);
}
} else if (typeof position === "object") {
if (position.preset && predefinedPositions[position.preset]) {
Object.assign(styles, predefinedPositions[position.preset]);
// Apply custom offsets if provided
if (position.offsets && typeof position.offsets === "object") {
Object.assign(styles, position.offsets);
}
// If transform is provided in offsets, apply it
if (position.offsets && position.offsets.transform) {
styles.transform = position.offsets.transform;
}
} else {
// Assume custom positioning
Object.assign(styles, position);
}
} else {
// Default to top-right if position is not specified correctly
Object.assign(styles, predefinedPositions["top-right"]);
}
// Apply styles to the toolbar
for (const [prop, value] of Object.entries(styles)) {
this.toolbar.style[prop] = value;
}
}
-
Usage Examples:
-
Using a Predefined Position with Default Offsets:
const toolbar = new Toolbar({
position: "top-left",
});
-
Using a Predefined Position with Custom Offsets:
Summary
With these amendments:
-
Custom Positioning: You can define any custom position by passing an object with desired CSS positioning properties.
-
Predefined Positions with Custom Offsets: Utilize the existing predefined positions and tweak their default offsets according to your layout needs.
-
Code Efficiency: The Toolbar class now handles positioning in a more streamlined manner, reducing redundancy and enhancing maintainability.
Feel free to integrate this updated Toolbar class into your project. Let me know if you need further assistance or additional features!