To encapsulate the Toolbar within a Shadow DOM and ensure that its styles don't leak into the global scope (and vice versa), you'll need to modify the existing Toolbar class. By leveraging the Shadow DOM, you can provide better style encapsulation, preventing potential CSS conflicts and ensuring that the toolbar remains modular and reusable.
Below is the updated Toolbar class with Shadow DOM integration and in-shadow styles. I've also included detailed explanations of the changes made to facilitate understanding and further customization.
function el(elementName, { cls, css, ev, html, text, ...props }, children) {
// Create the element
const elem = document.createElement(elementName);
if (cls) {
elem.className = cls;
}
if (html) {
elem.innerHTML = html;
}
if (text) {
elem.textContent = text;
}
if (css) {
Object.assign(elem.style, css);
}
Object.assign(elem, props);
if (ev) {
for (const eventName in ev) {
elem.addEventListener(eventName, ev[eventName].bind(elem));
}
}
if (children) {
for (const child of children) {
if (typeof child === "string") {
elem.appendChild(document.createTextNode(child));
} else if (child instanceof Node) {
elem.appendChild(child);
}
}
}
return elem;
}
/**
* Toolbar Class
*
* A customizable toolbar encapsulated within a Shadow DOM.
* It can be positioned on the screen with predefined or custom positions.
* 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 {
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;
transition: opacity 0.3s ease, visibility 0.3s ease;
opacity: 0;
visibility: hidden;
}
.custom-toolbar.show {
opacity: 1;
visibility: visible;
}
.custom-toolbar .hidden {
display: none;
}
.custom-toolbar .toolbar-button {
display: flex;
align-items: center;
gap: 5px;
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.2s ease;
background-color: transparent;
}
.custom-toolbar .toolbar-button:hover {
background-color: rgba(0, 0, 0, 0.05);
}
.custom-toolbar .toolbar-button:active {
background-color: rgba(0, 0, 0, 0.1);
}
.custom-toolbar img,
.custom-toolbar .toolbar-icon-svg {
width: 20px;
height: 20px;
}
.custom-toolbar .toolbar-label-container {
display: inline-block;
}
/* Hide icon container if empty to prevent occupying space */
.custom-toolbar .toolbar-icon-container:empty {
display: none;
}
`;
/**
* 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" },
"top-right": { top: "20px", right: "20px" },
"top-center": { top: "20px", left: "50%", transform: "translateX(-50%)" },
"bottom-left": { bottom: "20px", left: "20px" },
"bottom-right": { bottom: "20px", right: "20px" },
"bottom-center": {
bottom: "20px",
left: "50%",
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.hostElement = null; // Host element for Shadow DOM
this.shadowRoot = null; // Shadow root
this.toolbar = null;
this.isInitialized = false;
this.isVisible = false;
this.buttonDataList = [];
this.options = options;
this._objectUrls = []; // To keep track of Object URLs from Blob icons
}
/**
* Initializes the toolbar by creating the host element, attaching Shadow DOM,
* injecting in-shadow CSS, applying positioning, adding any pre-initialized buttons,
* and appending it to the document body.
*
* @returns {void}
*/
init() {
if (this.isInitialized) return;
// Create host element
this.hostElement = document.createElement("div");
// Attach Shadow DOM
this.shadowRoot = this.hostElement.attachShadow({ mode: "closed" });
// Create a style element within Shadow DOM
const styleElement = el("style", { type: "text/css" }, [
this.predefinedCSS,
]);
this.shadowRoot.appendChild(styleElement);
// Create toolbar container within Shadow DOM
this.toolbar = el("div", { cls: "custom-toolbar" });
this.shadowRoot.appendChild(this.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 host element to the body
document.body.appendChild(this.hostElement);
this.isInitialized = true;
// Append buttons
for (const buttonData of this.buttonDataList) {
this.#renderButton(buttonData);
this.toolbar.appendChild(buttonData.button);
}
}
/**
* 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 { predefinedPositions } = Toolbar;
let styles = { position: "fixed", ...predefinedPositions["top-right"] };
if (typeof position === "string") {
// Use predefined position
if (position in predefinedPositions) {
styles = { position: "fixed", ...predefinedPositions[position] };
} else {
console.warn(
`Toolbar: Unknown predefined position "${position}". Falling back to "top-right".`
);
}
} else if (typeof position === "object") {
if (position.preset && predefinedPositions[position.preset]) {
styles = {
position: "fixed",
...predefinedPositions[position.preset],
...position.offsets,
};
} else {
styles = { position: "fixed", ...position };
}
}
Object.assign(this.hostElement.style, styles);
}
/**
* 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 Shadow DOM 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
for (const { button, clickHandler } of this.buttonDataList) {
button.removeEventListener("click", clickHandler);
button.remove();
}
this.buttonDataList.length = 0;
// Remove host element from DOM
this.hostElement?.parentNode?.removeChild(this.hostElement);
this.hostElement = null;
this.shadowRoot = null;
this.toolbar = null;
// Revoke all Object URLs created from Blob icons
this._objectUrls.forEach((url) => {
URL.revokeObjectURL(url);
});
this._objectUrls.length = 0;
// Reset state
this.isInitialized = false;
this.isVisible = false;
}
/**
* Adds a button to the toolbar.
*
* @param {Object} config - Configuration for the toggle button.
* @param {string} [config.label] - The common text label of the toggle button.
* @param {string|HTMLElement|Blob} [config.icon] - The common icon of the toggle button.
* @param {Object} [config.css] - Common CSS styles to apply to the toggle button.
* @param {Object} [config.attributes] - Common HTML attributes to set on the toggle button element.
* @param {boolean|Function} [config.initialState] - True for active, false for inactive
* @param {Object} [config.active] - Overrides for the active state.
* @param {string} [config.active.label] - Override label when active.
* @param {string|HTMLElement|Blob} [config.active.icon] - Override icon when active.
* @param {Object} [config.active.css] - Override CSS styles when active.
* @param {Object} [config.active.attributes] - Override HTML attributes when active.
* @param {Object} [config.inactive] - Overrides for the inactive state.
* @param {string} [config.inactive.label] - Override label when inactive.
* @param {string|HTMLElement|Blob} [config.inactive.icon] - Override icon when inactive.
* @param {Object} [config.inactive.css] - Override CSS styles when inactive.
* @param {Object} [config.inactive.attributes] - Override HTML attributes when inactive.
* @param {Function} [config.onClick] - Callback function when button is clicked. Receives the new state as a parameter.
*
* @returns {void}
*/
addButton(config) {
const buttonData = this.#createButton(config);
if (this.isInitialized) {
this.#renderButton(buttonData);
this.toolbar.appendChild(buttonData.button);
}
}
#renderButton(buttonData, prevState = null) {
const { button, currentState, buttonStates } = buttonData;
const newState = buttonStates[currentState ? 1 : 0] ?? {};
const { label, icon, css = {}, attr = {} } = newState;
// Update button children only if the label or icon changed
const children = [];
if (icon) children.push(icon);
if (label) children.push(label);
if (children.length > 0) {
button.replaceChildren(...children);
}
// Update button styles
for (const property in buttonData.prevCss || {}) {
if (!(property in css)) {
button.style[property] = ""; // Remove previous styles that are no longer present
}
}
Object.assign(button.style, css); // Apply new styles
buttonData.prevCss = css; // Store current styles for future reference
// Update button attributes
for (const property in buttonData.prevAttr || {}) {
if (!(property in attr)) {
button.removeAttribute(property); // Remove previous attributes that are no longer present
}
}
for (const property in attr) {
button.setAttribute(property, attr[property]); // Set new or updated attributes
}
buttonData.prevAttr = attr; // Store current attributes for future reference
}
#createButton(buttonConfig) {
const { active, inactive, initialState } = buttonConfig;
const isToggleButton = !!active;
const buttonStates = [this.#parseButtonConfig(buttonConfig, inactive)];
if (isToggleButton) {
buttonStates.push(this.#parseButtonConfig(buttonConfig, active));
}
const buttonData = { currentState: !!initialState, buttonStates };
const clickHandler = this.#createClickHandler(
buttonData,
buttonConfig,
isToggleButton
);
const button = el("button", {
cls: "toolbar-button",
...(clickHandler ? { ev: { click: clickHandler } } : null),
});
Object.assign(buttonData, { button, clickHandler });
this.buttonDataList.push(buttonData);
return buttonData;
}
#createClickHandler(buttonData, { onClick }, isToggleButton) {
if (typeof onClick !== "function") {
return null;
}
const $this = this;
return isToggleButton
? function (ev) {
const button = this;
const prevState = buttonData.currentState;
const currentState = (buttonData.currentState = !buttonData.currentState);
$this.#renderButton(buttonData, prevState);
return onClick.call(button, ev, currentState);
}
: onClick;
}
#parseButtonConfig(commonConfig, stateSpecificConfig) {
const {
label: commonLabel,
icon: commonIcon,
css: commonCss,
attr: commonAttr,
} = commonConfig;
const {
label = commonLabel,
icon = commonIcon,
css,
attr,
} = stateSpecificConfig || {};
return {
label:
typeof label === "string"
? el("span", { cls: "toolbar-label-container", text: label })
: null,
icon: this.#createIconElement(icon),
css: { ...commonCss, ...css },
attr: { ...commonAttr, ...attr },
};
}
/**
* 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} iconData - The icon data for the current state.
* @returns {HTMLElement|null} - The created icon element or null if no icon is provided.
*/
#createIconElement(iconData) {
if (!iconData) {
return null; // Return null if no icon is provided
}
let iconElement;
if (typeof iconData === "string") {
// Check if it's a valid URL (including data URLs)
if (this.#isUrl(iconData)) {
iconElement = el("img", {
src: iconData,
alt: "",
});
} else if (/^\s*<svg/.test(iconData)) {
iconElement = el("span", {
html: iconData,
cls: "toolbar-icon-svg",
});
} else {
iconElement = el("span", {
text: iconData,
cls: "toolbar-icon-text",
});
}
} else if (iconData instanceof Blob) {
const objectUrl = URL.createObjectURL(iconData);
this._objectUrls.push(objectUrl); // Track the Object URL for later revocation
iconElement = el("img", {
src: objectUrl,
alt: "",
});
} else if (iconData instanceof HTMLElement) {
iconElement = iconData.cloneNode(true);
} else {
iconElement = null;
}
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.
*/
#isUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
}
Key Changes and Explanations
-
Shadow DOM Integration:
- Host Element: Introduced
this.hostElement as a container for the Shadow DOM. This div acts as the host for all toolbar elements.
- Shadow Root: Attached a closed Shadow Root (
this.shadowRoot) to the host element. Using { mode: "closed" } ensures that the Shadow DOM is encapsulated and not accessible from the outside. If you want the Shadow DOM to be accessible for debugging or other purposes, you can set it to { mode: "open" }.
- Appending to Body: Instead of appending the toolbar directly to the
document.body, the host element containing the Shadow Root is appended.
-
In-Shadow Stylesheet:
- Moved the
predefinedCSS into a <style> tag within the Shadow DOM. This ensures that styles are scoped only to the toolbar and do not affect the global scope.
- Removed the injection of the stylesheet into the
document.head, as it's now encapsulated within the Shadow DOM.
-
Positioning Adjustments:
- Ensured that the
position: fixed; style is applied to the hostElement instead of the toolbar container. This way, the entire toolbar (within the Shadow DOM) can be positioned independently.
- Adjusted the
applyPosition method to set styles on the hostElement to maintain correct positioning.
-
Event Listeners and Button Rendering:
- No significant changes were needed here, as event listeners and button rendering work seamlessly within the Shadow DOM. The
el function is used to create and manage elements within the Shadow DOM.
-
Cleanup Enhancements:
- Updated the
destroy method to remove the hostElement from the DOM, effectively removing the entire Shadow DOM and its contents.
- Ensured that all Object URLs created for
Blob icons are revoked during destruction to prevent memory leaks.
-
Mode of Shadow Root:
- The Shadow Root is set to
closed, which means it's not accessible via JavaScript from outside the class. If you need to access the Shadow DOM for debugging or manipulation outside the class, consider setting it to .
Usage Examples
Here's how you can use the updated Toolbar class with Shadow DOM:
import Toolbar from './Toolbar.js';
// Create a new toolbar instance with default options
const toolbar = new Toolbar({
position: 'top-right', // You can choose from predefined positions
style: {
// Additional styles if needed
},
});
// Add buttons before initializing the toolbar
toolbar.addButton({
label: 'Home',
icon: 'https://example.com/home-icon.png',
onClick: () => {
console.log('Home button clicked!');
},
});
toolbar.addButton({
label: 'Settings',
icon: '<svg>...</svg>', // SVG as a string
onClick: () => {
console.log('Settings button clicked!');
},
});
// Initialize and show the toolbar
toolbar.start();
// Later, you can add more buttons dynamically
toolbar.addButton({
label: 'Profile',
icon: '😊',
onClick: () => {
console.log('Profile button clicked!');
},
});
// To hide the toolbar
// toolbar.stop();
// To destroy the toolbar completely
// toolbar.destroy();
Benefits of Using Shadow DOM
-
Style Encapsulation: The styles defined within the Shadow DOM do not leak out to the parent document, and external styles do not affect the components inside the Shadow DOM. This prevents unintended style overrides and conflicts.
-
Modularity: Encapsulating the toolbar within the Shadow DOM makes it a self-contained component, enhancing reusability across different parts of an application or even across different projects.
-
Maintainability: With encapsulated styles and structure, maintaining and updating the toolbar becomes more straightforward, as changes are localized within the component.
Additional Considerations
-
Flexibility with Shadow DOM Modes: Depending on your needs, you might choose between open and closed Shadow DOM modes. open allows external JavaScript to access the Shadow Root via the shadowRoot property, which can be useful for debugging or dynamic interactions.
-
Styling Custom Elements: If you plan to convert the Toolbar into a Custom Element in the future, the encapsulation provided by Shadow DOM becomes even more advantageous.
-
Responsiveness and Accessibility: Ensure that the toolbar remains responsive across different screen sizes and is accessible (e.g., proper ARIA labels, keyboard navigation).
-
Performance: While Shadow DOM provides numerous benefits, be mindful of performance implications, especially if creating multiple instances or handling complex interactions within the Shadow DOM.
By integrating Shadow DOM into your Toolbar class, you enhance its robustness, reusability, and maintainability, making it a more polished and professional component for your projects.