move the static css injection to init and is removable upon destroy. [code] // Static…
- User
move the static css injection to init and is removable upon destroy.
/** * Toolbar Class * * A customizable toolbar that can be positioned on the screen with predefined or custom positions. * It supports adding regular and toggle buttons, both before and after initialization. */ export default class Toolbar { /** * Predefined CSS styles for the toolbar and its buttons. * These styles are injected into the document once and shared across all instances. * * @private * @static * @type {string} */ static predefinedCSS = ` /* 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; } /* Optional: SVG Icon Styling */ .toolbar-icon-svg { display: inline-block; width: 20px; height: 20px; } `; /** * Predefined positions with default offsets. * These configurations can be used by any instance of the Toolbar class. * * @private * @static * @type {Object} */ static 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%)", }, }; /** * Creates an instance of Toolbar. * * @param {Object} [options={}] - Configuration options for the toolbar. * @param {string|Object} [options.position='top-right'] - * - If a string, it should be one of the predefined positions: * - "top-left" * - "top-right" * - "top-center" * - "bottom-left" * - "bottom-right" * - "bottom-center" * - If an object, it can specify a preset with optional custom offsets or entirely custom CSS positioning. * - `{ preset: 'top-left', offsets: { top: '30px', left: '25px' } }` * - `{ top: '50px', right: '100px' }` (completely custom) * @param {Object} [options.style] - Additional CSS styles to apply to the toolbar container. */ 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 // Store buttons added before initialization this._preInitButtons = []; this._preInitToggleButtons = []; // Inject predefined CSS if not already injected if (!Toolbar._cssInjected) { Toolbar.injectStaticStyles(); Toolbar._cssInjected = true; } } /** * Initializes the toolbar by creating the container, applying positioning, * adding any pre-initialized buttons, and appending it to the document body. * * @returns {void} */ init() { if (this.isInitialized) return; // 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 = []; } /** * Injects necessary CSS styles into the document head. * This method injects static CSS shared across all instances. * * @private * @static * @returns {void} */ static injectStaticStyles() { const styleElement = document.createElement("style"); styleElement.type = "text/css"; styleElement.appendChild(document.createTextNode(Toolbar.predefinedCSS)); document.head.appendChild(styleElement); } /** * Applies positioning to the toolbar based on the provided options. * Supports predefined positions with optional custom offsets and completely custom positioning. * * @private * @returns {void} */ applyPosition() { const { position } = this.options; const styles = {}; if (typeof position === "string") { // Use predefined position if (Toolbar.predefinedPositions[position]) { Object.assign(styles, Toolbar.predefinedPositions[position]); // Retain transform if present (e.g., top-center) } else { console.warn( `Toolbar: Unknown predefined position "${position}". Falling back to "top-right".` ); Object.assign(styles, Toolbar.predefinedPositions["top-right"]); } } else if (typeof position === "object") { if (position.preset && Toolbar.predefinedPositions[position.preset]) { Object.assign(styles, Toolbar.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, Toolbar.predefinedPositions["top-right"]); } // Apply styles to the toolbar for (const [prop, value] of Object.entries(styles)) { this.toolbar.style[prop] = value; } } /** * Displays the toolbar on the screen. Initializes it if not already initialized. * * @returns {void} */ start() { if (!this.isInitialized) { this.init(); } this.toolbar.classList.add("show"); this.isVisible = true; } /** * Hides the toolbar from the screen without destroying it. * * @returns {void} */ stop() { if (this.toolbar) { this.toolbar.classList.remove("show"); this.isVisible = false; } } /** * Destroys the toolbar by removing it from the DOM, deleting injected styles, * and clearing all buttons and event listeners. * * @returns {void} */ 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; // Reset state this.isInitialized = false; this.isVisible = false; this.buttons = []; this.toggleButtons = []; this._preInitButtons = []; this._preInitToggleButtons = []; } /** * Adds a regular 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 {Object} [options.attributes] - Additional HTML attributes to set on the button element. * @param {Function} onClick - Callback function when the button is clicked. * * @returns {void} * * @example * toolbar.addButton({ * label: "Save", * icon: "💾", * attributes: { * id: "save-button", * 'data-action': 'save' * } * }, () => { * console.log("Save button clicked!"); * }); */ addButton(options, onClick) { if (this.isInitialized) { this._createButton(false, options, onClick); } else { this._preInitButtons.push({ options, onClick }); } } /** * Adds a toggle button to the toolbar. * * @param {Object} options - Configuration for the toggle button. * @param {string} [options.label] - The text label of the toggle button. * @param {string|HTMLElement} [options.icon] - The icon for the toggle button. * @param {boolean} [options.initialState=false] - The initial toggled state of the button. * @param {Object} [options.attributes] - Additional HTML attributes to set on the toggle button element. * @param {Function} onToggle - Callback function when the toggle state changes. Receives the new state as a parameter. * * @returns {void} * * @example * toolbar.addToggleButton({ * label: "Dark Mode", * icon: "🌙", * initialState: true, * attributes: { * id: "dark-mode-toggle", * } * }, (isActive) => { * document.body.classList.toggle('dark-mode', isActive); * console.log(`Dark Mode is now ${isActive ? 'ON' : 'OFF'}`); * }); */ addToggleButton(options, onToggle) { if (this.isInitialized) { this._createButton(true, options, onToggle); } else { this._preInitToggleButtons.push({ options, onToggle }); } } /** * Creates a button or toggle button and appends it to the toolbar. * * @private * @param {boolean} isToggle - Determines if the button is a toggle button. * @param {Object} options - Button configuration options. * @param {Function} callback - Callback function for click or toggle events. * * @returns {void} */ _createButton(isToggle, options, callback) { const button = document.createElement("button"); button.className = isToggle ? "toolbar-toggle-button" : "toolbar-button"; // Set additional attributes if provided if (options.attributes && typeof options.attributes === "object") { for (const [attr, value] of Object.entries(options.attributes)) { button.setAttribute(attr, value); } } // 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); } // Initialize toggle state if it's a toggle button if (isToggle && options.initialState) { button.classList.add("active"); } // 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); } } /** * Creates an icon element based on the provided icon data. * Supports URLs, SVG strings, emojis, and HTMLElements. * * @private * @param {string|HTMLElement} icon - The icon data. * @returns {HTMLElement} - The created icon element. */ _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; } /** * Checks if a given string is a valid URL. * * @private * @param {string} string - The string to validate. * @returns {boolean} - True if the string is a valid URL, false otherwise. */ _isValidUrl(string) { try { new URL(string); return true; } catch (_) { return false; } } /** * Checks if a given string is an SVG. * * @private * @param {string} string - The string to check. * @returns {boolean} - True if the string starts with '<svg', false otherwise. */ _isSVG(string) { return string.trim().startsWith("<svg"); } } - Assistant