To accommodate your requirements, we'll enhance the existing Toolbar class with the following features:
-
Allowing Buttons to Be Added Before Initialization:
- Current Behavior: Buttons can only be added after the toolbar is initialized. If attempted before, a warning is logged.
- Desired Behavior: Buttons can be added at any time—before or after initialization. If the toolbar is already initialized, they are immediately appended. Otherwise, they are stored and appended once initialization occurs.
-
Supporting Button Content Enhancements:
- Image Support: Buttons can include images (via URLs, SVGs, emojis, etc.) alongside labels.
- Label Alignment: If a label is present, it should be centered relative to the image.
Implementation Steps
-
Modify Button Storage:
- Introduce arrays to store buttons added before initialization.
- During initialization, append these stored buttons to the toolbar.
-
Enhance addButton and addToggleButton Methods:
- Update these methods to accept an options object allowing specification of images and labels.
- Adjust the button creation logic to handle different types of images and optional labels.
-
Adjust CSS for Enhanced Button Layout:
- Update styles to properly align images and labels within buttons.
Updated Toolbar Class
Below is the updated Toolbar class implementing the above features:
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 position styles
const positions = {
"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%)",
},
};
// Apply default position if none provided
let selectedPosition = positions["top-right"]; // default
if (position && positions[position]) {
selectedPosition = positions[position];
} else if (position && typeof position === "object") {
// Allow custom positioning via an object
selectedPosition = position;
}
// Apply styles
for (const [prop, value] of Object.entries(selectedPosition)) {
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");
}
}
Explanation of Changes
-
Storing Buttons Before Initialization:
- Properties Added:
this._preInitButtons: Array to store regular buttons added before initialization.
this._preInitToggleButtons: Array to store toggle buttons added before initialization.
- Modification in
init(): After initializing the toolbar, iterate over these pre-initialized arrays and create buttons accordingly.
-
Enhanced addButton and addToggleButton Methods:
- Parameters Changed: Instead of accepting separate
label and onClick parameters, these methods now accept an options object and a callback.
- Button Options:
label: Text label for the button.
icon: Can be a URL string, SVG string, emoji, or an HTMLElement representing the icon.
- Implementation:
- If the toolbar is already initialized, buttons are created immediately.
- If not, they're stored in the pre-initialization arrays.
-
Internal _createButton Method:
- Handles the creation of both regular and toggle buttons based on the
isToggle flag.
- Integrates both
icon and label into the button, ensuring proper layout.
- Attaches event listeners appropriately, maintaining references for potential cleanup.
-
Icon Handling:
- Method
_createIconElement: Determines the type of icon provided and creates the appropriate DOM element.
- URL String: Creates an
<img> element.
- SVG String: Creates a
<span> with innerHTML set to the SVG string.
- Emoji or Text: Creates a
<span> with the text content.
- HTMLElement: Appends the provided element directly.
- Utility Methods:
_isValidUrl: Checks if a string is a valid URL.
Usage Examples
1. Adding Buttons Before Initialization
import Toolbar from './Toolbar.js';
const toolbar = new Toolbar({ position: 'bottom-center' });
// Add buttons before initializing
toolbar.addButton(
{ label: 'Home', icon: '🏠' },
() => { console.log('Home clicked'); }
);
toolbar.addButton(
{ label: 'Settings', icon: 'https://example.com/settings-icon.png' },
() => { console.log('Settings clicked'); }
);
// Now initialize/start the toolbar
toolbar.start();
2. Adding Buttons After Initialization
// Assuming toolbar is already started as above
// Add a toggle button with an SVG icon and label
const svgIcon = `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 5V19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M5 12H19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
`;
toolbar.addToggleButton(
{ label: 'Grid', icon: svgIcon },
(isActive) => { console.log(`Grid is now ${isActive ? 'active' : 'inactive'}`); }
);
// Add another regular button with an emoji
toolbar.addButton(
{ label: 'Profile', icon: '👤' },
() => { console.log('Profile clicked'); }
);
Benefits of These Enhancements
- Flexibility: Users can add buttons at any point, ensuring a more flexible integration.
- Rich Content: Supporting various icon types (images, SVGs, emojis) allows for more visually appealing and informative buttons.
- Maintainability: Centralized button creation logic ensures consistency and easier future modifications.
Final Notes
- Error Handling: The class now gracefully handles attempts to add buttons before initialization by storing them and appending upon initialization.
- Customization: Developers can further customize button styles or behaviors by extending the
Toolbar class or modifying the injected CSS.
- Performance: By preventing multiple CSS injections and efficiently managing event listeners, the class maintains optimal performance.
Feel free to integrate and adapt this enhanced Toolbar class to suit your specific needs!