Untitled conversation
- Usercode
- Assistant
/**
* 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.
*
* @private
* @type {string}
*/
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
this._objectUrls = []; // To keep track of Object URLs from Blob icons
// Store buttons added before initialization
this._preInitButtons = [];
this._preInitToggleButtons = [];
}
/**
* Initializes the toolbar by creating the container, injecting CSS, applying positioning,
* adding any pre-initialized buttons, and appending it to the document body.
*
* @returns {void}
*/
init() {
if (this.isInitialized) return;
// Inject CSS specific to this instance
this.styleElement = document.createElement("style");
this.styleElement.type = "text/css";
this.styleElement.appendChild(document.createTextNode(this.predefinedCSS));
document.head.appendChild(this.styleElement);
// 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 = [];
}
/**
* 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 and its injected CSS from the DOM,
* revoking any Object URLs created from Blob icons, 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;
// Remove injected CSS
this.styleElement?.parentNode?.removeChild(this.styleElement);
this.styleElement = null;
// Revoke all Object URLs created from Blob icons
this._objectUrls.forEach((url) => {
URL.revokeObjectURL(url);
});
this._objectUrls = [];
// 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|Blob} [options.icon] - The icon for the button (URL, Data URL, Base64 string, Blob, 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
* // Using a Base64 string (without Data URL prefix)
* const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAAAUA...'; // Truncated for brevity
* toolbar.addButton({
* label: 'Base64 Icon',
* icon: base64Image,
* }, () => {
* console.log('Base64 Icon 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|Blob} [options.icon] - The icon for the toggle button (URL, Data URL, Base64 string, Blob, SVG string, emoji, or HTMLElement).
* @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
* // Using a Blob object
* const imageBlob = new Blob([/* binary data * /], { type: 'image/png' });
* toolbar.addToggleButton({
* label: 'Blob Icon',
* icon: imageBlob,
* initialState: true,
* }, (isActive) => {
* console.log(`Blob Icon Toggle 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, Data URLs, Base64 strings, Blob objects, SVG strings, emojis, and HTMLElements.
*
* @private
* @param {string|HTMLElement|Blob} 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 (includes Data URLs), 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 a raw Base64 string, prepend Data URL prefix
const dataUrl = `data:image/png;base64,${icon}`;
iconElement = document.createElement("img");
iconElement.src = dataUrl;
iconElement.alt = "";
}
} else if (icon instanceof Blob) {
// If icon is a Blob, create an Object URL
const objectUrl = URL.createObjectURL(icon);
this._objectUrls.push(objectUrl); // Track the Object URL for later revocation
iconElement = document.createElement("img");
iconElement.src = objectUrl;
iconElement.alt = "";
} 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 (including Data URLs).
*
* @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");
}
}
modify addToggleButton to allow different texts/same text for the binary state and the ability to set initial binary state
To modify the addToggleButton method to allow different texts (or the same text) for the binary states and to set the initial binary state, we'll enhance the Toolbar class by introducing new options: activeLabel and inactiveLabel. These options enable developers to specify distinct labels for the toggle button's active and inactive states. Additionally, we'll ensure that the initial state of the toggle button can be set as desired.
Below is the updated Toolbar class with the necessary modifications:
/**
* 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.
*
* @private
* @type {string}
*/
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
this._objectUrls = []; // To keep track of Object URLs from Blob icons
// Store buttons added before initialization
this._preInitButtons = [];
this._preInitToggleButtons = [];
}
/**
* Initializes the toolbar by creating the container, injecting CSS, applying positioning,
* adding any pre-initialized buttons, and appending it to the document body.
*
* @returns {void}
*/
init() {
if (this.isInitialized) return;
// Inject CSS specific to this instance
this.styleElement = document.createElement("style");
this.styleElement.type = "text/css";
this.styleElement.appendChild(document.createTextNode(this.predefinedCSS));
document.head.appendChild(this.styleElement);
// 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 = [];
}
/**
* 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 and its injected CSS from the DOM,
* revoking any Object URLs created from Blob icons, 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;
// Remove injected CSS
this.styleElement?.parentNode?.removeChild(this.styleElement);
this.styleElement = null;
// Revoke all Object URLs created from Blob icons
this._objectUrls.forEach((url) => {
URL.revokeObjectURL(url);
});
this._objectUrls = [];
// 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|Blob} [options.icon] - The icon for the button (URL, Data URL, Base64 string, Blob, 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
* // Using a Base64 string (without Data URL prefix)
* const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAAAUA...'; // Truncated for brevity
* toolbar.addButton({
* label: 'Base64 Icon',
* icon: base64Image,
* }, () => {
* console.log('Base64 Icon 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 default text label of the toggle button.
* @param {string} [options.activeLabel] - The text label when the toggle button is active.
* @param {string} [options.inactiveLabel] - The text label when the toggle button is inactive.
* @param {string|HTMLElement|Blob} [options.icon] - The icon for the toggle button (URL, Data URL, Base64 string, Blob, SVG string, emoji, or HTMLElement).
* @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
* // Using a Blob object
* const imageBlob = new Blob([/* binary data * /], { type: 'image/png' });
* toolbar.addToggleButton({
* label: 'Blob Icon',
* icon: imageBlob,
* initialState: true,
* activeLabel: 'Active State',
* inactiveLabel: 'Inactive State',
* }, (isActive) => {
* console.log(`Blob Icon Toggle 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);
}
// Create label span
const labelElement = document.createElement("span");
// Determine initial label based on toggle state
if (isToggle) {
const isActive = options.initialState || false;
if (isActive && options.activeLabel) {
labelElement.textContent = options.activeLabel;
} else if (!isActive && options.inactiveLabel) {
labelElement.textContent = options.inactiveLabel;
} else {
labelElement.textContent = options.label || "";
}
} else {
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");
// Update label based on the new state
if (options.activeLabel && options.inactiveLabel) {
labelElement.textContent = isActive
? options.activeLabel
: options.inactiveLabel;
} else if (isActive && options.activeLabel) {
labelElement.textContent = options.activeLabel;
} else if (!isActive && options.inactiveLabel) {
labelElement.textContent = options.inactiveLabel;
}
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, Data URLs, Base64 strings, Blob objects, SVG strings, emojis, and HTMLElements.
*
* @private
* @param {string|HTMLElement|Blob} 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 (includes Data URLs), 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 a raw Base64 string, prepend Data URL prefix
const dataUrl = `data:image/png;base64,${icon}`;
iconElement = document.createElement("img");
iconElement.src = dataUrl;
iconElement.alt = "";
}
} else if (icon instanceof Blob) {
// If icon is a Blob, create an Object URL
const objectUrl = URL.createObjectURL(icon);
this._objectUrls.push(objectUrl); // Track the Object URL for later revocation
iconElement = document.createElement("img");
iconElement.src = objectUrl;
iconElement.alt = "";
} 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 (including Data URLs).
*
* @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");
}
}
Enhanced addToggleButton Documentation:
activeLabel: Specifies the text label when the toggle button is in the active state.inactiveLabel: Specifies the text label when the toggle button is in the inactive state.activeLabel and inactiveLabel options.Updated _createButton Method:
activeLabel and inactiveLabel.activeLabel and inactiveLabel are provided, the button's label updates based on its state.label option or leaves it empty.initialState and the provided labels.Preserved Existing Functionality:
activeLabel and inactiveLabel are not provided, the toggle button behaves as before, using the label for both states.Here's how you can utilize the updated addToggleButton method with different labels for each state and set the initial state:
const toolbar = new Toolbar({
position: 'bottom-right',
});
// Add a toggle button with different labels for active and inactive states
toolbar.addToggleButton({
label: 'Toggle Feature',
activeLabel: 'Feature ON',
inactiveLabel: 'Feature OFF',
initialState: false,
icon: 'https://example.com/icon.png',
}, (isActive) => {
console.log(`Feature is now ${isActive ? 'enabled' : 'disabled'}.`);
});
// Start the toolbar
toolbar.start();
In this example:
initialState is false).activeIcon and inactiveIcon similar to labels.aria attributes if necessary.This enhancement provides greater flexibility in managing toggle buttons, allowing for more dynamic and informative user interfaces.
Not yet included in a published release.