Untitled conversation
- User
class OverlayManager extends EventTarget { /** * Creates an instance of OverlayManager. * @param {HTMLElement} targetElement - The element to be overlaid. * @param {Object} [options] - Optional settings. * @param {HTMLElement|Function|string} [options.content] - Content to insert into the overlay. * @param {number} [options.zIndex=1000] - z-index for the overlay. * @param {Object} [options.styles] - Additional styles for the overlay. * @param {string} [options.ariaRole='dialog'] - ARIA role for the overlay. * @param {boolean} [options.focusTrap=true] - Whether to enable focus trapping. * @param {string} [options.ariaLabelledby] - ID of the element that labels the overlay. * @param {string} [options.ariaDescribedby] - ID of the element that describes the overlay. */ constructor(targetElement, options = {}) { super(); // Initialize EventTarget if (!(targetElement instanceof HTMLElement)) { throw new TypeError('targetElement must be a valid HTMLElement'); } this.targetElement = targetElement; this.overlay = null; this.contentContainer = null; // Dedicated container for main content this.isActive = false; this.isInitialized = false; this.options = { zIndex: 1000, ariaRole: 'dialog', focusTrap: true, ariaLabelledby: '', ariaDescribedby: '', ...options, }; this.plugins = new Set(); // Using Set to prevent duplicate plugins this.previousActiveElement = null; this.scrollPosition = { top: 0, left: 0 }; // For scroll preservation // Cached focusable elements within contentContainer this.cachedFocusableElements = []; // Bind methods this.handleKeyDown = this.handleKeyDown.bind(this); this.debouncedStart = this.debounce(this.start.bind(this), 100); this.debouncedStop = this.debounce(this.stop.bind(this), 100); } /** * Static registry to ensure only one OverlayManager per targetElement. * Uses a WeakMap to allow garbage collection of DOM elements. */ static registry = new WeakMap(); /** * Factory method to create and initialize an OverlayManager instance. * Ensures only one instance per targetElement. * @param {HTMLElement} targetElement - The element to be overlaid. * @param {Object} [options] - Optional settings. * @returns {OverlayManager} - The initialized OverlayManager instance. */ static create(targetElement, options = {}) { if (OverlayManager.registry.has(targetElement)) { console.warn('An OverlayManager instance already exists for this targetElement.'); return OverlayManager.registry.get(targetElement); } const manager = new OverlayManager(targetElement, options); manager.init(); OverlayManager.registry.set(targetElement, manager); return manager; } /** * Factory method to debounce functions. * @param {Function} func - The function to debounce. * @param {number} wait - The debounce delay in milliseconds. * @returns {Function} - The debounced function. */ debounce(func, wait) { let timeout; return function (...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; } /** * Initializes the overlay by creating and appending it to the target element. * Guard clause ensures initialization happens only once. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If initialization fails critically. */ init() { if (this.isInitialized) { console.warn('OverlayManager is already initialized.'); return this; } // Check if the overlay already exists by looking for a specific class const existingOverlay = this.targetElement.querySelector('.overlay-manager-overlay'); if (existingOverlay) { this.overlay = existingOverlay; } else { // Ensure the target element has a positioning context const computedStyle = window.getComputedStyle(this.targetElement); if (!['absolute', 'relative', 'fixed', 'sticky'].includes(computedStyle.position)) { this.targetElement.style.position = 'relative'; } // Create the overlay element this.overlay = document.createElement('div'); this.overlay.classList.add('overlay-manager-overlay'); // Apply default styles Object.assign(this.overlay.style, { position: 'absolute', top: '0', left: '0', width: '100%', height: '100%', display: 'none', // Hidden by default pointerEvents: 'none', // Let clicks pass through unless in active state zIndex: this.options.zIndex.toString(), // Use provided z-index or default ...this.options.styles, // Spread additional styles if provided }); // Set ARIA attributes for accessibility this.overlay.setAttribute('role', this.options.ariaRole); this.overlay.setAttribute('aria-hidden', 'true'); this.overlay.setAttribute('aria-modal', 'true'); // Indicates a modal dialog // Set additional ARIA attributes if provided if (this.options.ariaLabelledby) { this.overlay.setAttribute('aria-labelledby', this.options.ariaLabelledby); } if (this.options.ariaDescribedby) { this.overlay.setAttribute('aria-describedby', this.options.ariaDescribedby); } // Create a dedicated content container within the overlay this.contentContainer = document.createElement('div'); this.contentContainer.classList.add('overlay-manager-content'); Object.assign(this.contentContainer.style, { width: '100%', height: '100%', overflow: 'auto', }); // Insert content into the contentContainer if provided if (this.options.content) { this.setContent(this.options.content); } // Append the contentContainer to the overlay this.overlay.appendChild(this.contentContainer); // Append the overlay to the target element this.targetElement.appendChild(this.overlay); } this.isInitialized = true; this.dispatchEvent(new CustomEvent('init', { detail: { overlay: this.overlay } })); // Initialize all registered plugins this.plugins.forEach(plugin => { if (typeof plugin.init === 'function') { try { plugin.init(this); } catch (error) { console.error('Error in plugin init:', error); } } }); return this; } /** * Starts the overlay by displaying it and entering the active state. * Guard clause prevents starting if already active. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ start() { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.'); } if (this.isActive) { console.warn('OverlayManager is already active.'); return this; } // Prevent body from scrolling this.scrollPosition = { top: window.scrollY || document.documentElement.scrollTop, left: window.scrollX || document.documentElement.scrollLeft, }; document.body.style.top = `-${this.scrollPosition.top}px`; document.body.style.left = `-${this.scrollPosition.left}px`; document.body.style.position = 'fixed'; document.body.style.width = '100%'; this.overlay.style.display = 'block'; this.overlay.style.pointerEvents = 'auto'; // Capture events if needed this.overlay.setAttribute('aria-hidden', 'false'); this.isActive = true; // Save the currently focused element to restore focus later if (this.options.focusTrap) { this.previousActiveElement = document.activeElement; this.trapFocus(); } this.dispatchEvent(new CustomEvent('start', { detail: { overlay: this.overlay } })); // Execute plugin start hooks this.plugins.forEach(plugin => { if (typeof plugin.onStart === 'function') { try { plugin.onStart(this); } catch (error) { console.error('Error in plugin onStart:', error); } } }); return this; } /** * Stops the overlay by hiding it and returning to the inactive state. * Guard clause prevents stopping if already inactive. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ stop() { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.'); } if (!this.isActive) { console.warn('OverlayManager is already inactive.'); return this; } // Restore body scrolling document.body.style.position = ''; document.body.style.top = ''; document.body.style.left = ''; document.body.style.width = ''; window.scrollTo(this.scrollPosition.left, this.scrollPosition.top); this.overlay.style.display = 'none'; this.overlay.style.pointerEvents = 'none'; // Release event capture this.overlay.setAttribute('aria-hidden', 'true'); this.isActive = false; // Restore focus to the previously active element if (this.options.focusTrap && this.previousActiveElement) { this.previousActiveElement.focus(); this.previousActiveElement = null; } // Remove the keydown event listener to prevent memory leaks if (this.options.focusTrap) { this.overlay.removeEventListener('keydown', this.handleKeyDown); } this.dispatchEvent(new CustomEvent('stop', { detail: { overlay: this.overlay } })); // Execute plugin stop hooks this.plugins.forEach(plugin => { if (typeof plugin.onStop === 'function') { try { plugin.onStop(this); } catch (error) { console.error('Error in plugin onStop:', error); } } }); return this; } /** * Updates the overlay content. * @param {HTMLElement|Function|string} newContent - New content to insert into the overlay. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ setContent(newContent) { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.'); } // Clear existing content in the contentContainer instead of the entire overlay this.contentContainer.innerHTML = ''; if (newContent) { let contentElement; if (typeof newContent === 'function') { // Corrected: Call newContent() instead of this.options.content() contentElement = newContent(); } else if (typeof newContent === 'string') { // If content is a string, set it as innerHTML of contentContainer this.contentContainer.innerHTML = newContent; } else if (newContent instanceof HTMLElement) { // If content is an HTMLElement, append it directly to contentContainer contentElement = newContent; } else { console.warn('Unsupported content type for overlay.'); } if (contentElement instanceof HTMLElement) { this.contentContainer.appendChild(contentElement); } } this.dispatchEvent(new CustomEvent('contentChange', { detail: { newContent } })); // Execute plugin contentChange hooks this.plugins.forEach(plugin => { if (typeof plugin.onContentChange === 'function') { try { plugin.onContentChange(this, newContent); } catch (error) { console.error('Error in plugin onContentChange:', error); } } }); // Re-trap focus if the overlay is active and focus trapping is enabled if (this.isActive && this.options.focusTrap) { this.overlay.removeEventListener('keydown', this.handleKeyDown); this.trapFocus(); } return this; } /** * Destroys the overlay by removing it from the DOM and cleaning up references. * Guard clause prevents destruction if not initialized. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ destroy() { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized or already destroyed.'); } // Remove the keydown event listener to ensure complete cleanup if (this.options.focusTrap && this.overlay) { this.overlay.removeEventListener('keydown', this.handleKeyDown); } if (this.overlay && this.overlay.parentElement === this.targetElement) { this.targetElement.removeChild(this.overlay); this.dispatchEvent(new CustomEvent('destroy', { detail: { overlay: this.overlay } })); } // Execute plugin destroy hooks this.plugins.forEach(plugin => { if (typeof plugin.onDestroy === 'function') { try { plugin.onDestroy(this); } catch (error) { console.error('Error in plugin onDestroy:', error); } } }); // Remove from registry OverlayManager.registry.delete(this.targetElement); this.overlay = null; this.contentContainer = null; this.isActive = false; this.isInitialized = false; // Clear all plugins this.plugins.clear(); return this; } /** * Registers a plugin to extend OverlayManager's functionality. * @param {Object} plugin - The plugin object. * @param {Function} [plugin.init] - Called during OverlayManager initialization. * @param {Function} [plugin.onStart] - Called when the overlay starts. * @param {Function} [plugin.onStop] - Called when the overlay stops. * @param {Function} [plugin.onDestroy] - Called when the overlay is destroyed. * @param {Function} [plugin.onContentChange] - Called when the overlay content changes. * @returns {OverlayManager} - The instance for chaining. */ use(plugin) { if (typeof plugin !== 'object' || plugin === null) { throw new TypeError('Plugin must be an object'); } if (this.plugins.has(plugin)) { console.warn('Plugin is already registered.'); return this; } this.plugins.add(plugin); // If already initialized, initialize the plugin immediately if (this.isInitialized && typeof plugin.init === 'function') { try { plugin.init(this); } catch (error) { console.error('Error in plugin init:', error); } } return this; } /** * Removes a previously registered plugin. * @param {Object} plugin - The plugin object to remove. * @returns {OverlayManager} - The instance for chaining. */ remove(plugin) { if (!this.plugins.has(plugin)) { console.warn('Plugin not found.'); return this; } // If the plugin has a destroy method, call it if (typeof plugin.onDestroy === 'function') { try { plugin.onDestroy(this); } catch (error) { console.error('Error in plugin onDestroy:', error); } } this.plugins.delete(plugin); return this; } /** * Traps focus within the overlay when active. * @private */ trapFocus() { const focusableSelectors = [ 'a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'iframe', 'object', 'embed', '[contenteditable]', '[tabindex]:not([tabindex="-1"])', ]; const focusableElements = this.contentContainer.querySelectorAll(focusableSelectors.join(',')); this.cachedFocusableElements = Array.prototype.slice.call(focusableElements); if (this.cachedFocusableElements.length === 0) { console.warn('No focusable elements within the overlay. Making the overlay itself focusable.'); this.overlay.setAttribute('tabindex', '-1'); this.overlay.focus(); } else { const firstFocusable = this.cachedFocusableElements[0]; firstFocusable.focus(); } this.overlay.addEventListener('keydown', this.handleKeyDown); } /** * Handles keydown events to maintain focus within the overlay and handle Escape key. * @param {KeyboardEvent} event - The keyboard event. * @private */ handleKeyDown(event) { if (event.key === 'Tab') { // Handle focus trapping if (this.cachedFocusableElements.length === 0) { event.preventDefault(); return; } const firstFocusable = this.cachedFocusableElements[0]; const lastFocusable = this.cachedFocusableElements[this.cachedFocusableElements.length - 1]; if (event.shiftKey) { // Shift + Tab if (document.activeElement === firstFocusable) { lastFocusable.focus(); event.preventDefault(); } } else { // Tab if (document.activeElement === lastFocusable) { firstFocusable.focus(); event.preventDefault(); } } } else if (event.key === 'Escape') { // Allow closing the overlay with Escape key this.stop(); } } }make body defaultly scrollable unless specified in option. also
document.body.style.position = ''; document.body.style.top = ''; document.body.style.left = ''; document.body.style.width = '';maybe reset but it also washes away states before
start()check for other errors and we good - Assistant
Certainly! Below is the updated
OverlayManagerclass with the following enhancements based on your instructions:-
Default Body Scrollable: The body is now scrollable by default. You can prevent body scrolling by setting the
preventBodyScrolloption totruewhen initializing theOverlayManager. -
Preserving Body Styles: Instead of resetting body styles blindly, the original styles are now preserved and restored when the overlay is stopped. This ensures that any pre-existing styles on the
bodyelement remain intact. -
Additional Error Checks and Improvements: Reviewed the code for potential issues and made minor improvements to ensure robustness.
Updated
OverlayManagerClassclass OverlayManager extends EventTarget { /** * Creates an instance of OverlayManager. * @param {HTMLElement} targetElement - The element to be overlaid. * @param {Object} [options] - Optional settings. * @param {HTMLElement|Function|string} [options.content] - Content to insert into the overlay. * @param {number} [options.zIndex=1000] - z-index for the overlay. * @param {Object} [options.styles] - Additional styles for the overlay. * @param {string} [options.ariaRole='dialog'] - ARIA role for the overlay. * @param {boolean} [options.focusTrap=true] - Whether to enable focus trapping. * @param {string} [options.ariaLabelledby] - ID of the element that labels the overlay. * @param {string} [options.ariaDescribedby] - ID of the element that describes the overlay. * @param {boolean} [options.preventBodyScroll=false] - Whether to prevent body scrolling when overlay is active. */ constructor(targetElement, options = {}) { super(); // Initialize EventTarget if (!(targetElement instanceof HTMLElement)) { throw new TypeError('targetElement must be a valid HTMLElement'); } this.targetElement = targetElement; this.overlay = null; this.contentContainer = null; // Dedicated container for main content this.isActive = false; this.isInitialized = false; this.options = { zIndex: 1000, ariaRole: 'dialog', focusTrap: true, ariaLabelledby: '', ariaDescribedby: '', preventBodyScroll: false, // New option added ...options, }; this.plugins = new Set(); // Using Set to prevent duplicate plugins this.previousActiveElement = null; this.scrollPosition = { top: 0, left: 0 }; // For scroll preservation this.originalBodyStyles = null; // To store original body styles // Cached focusable elements within contentContainer this.cachedFocusableElements = []; // Bind methods this.handleKeyDown = this.handleKeyDown.bind(this); this.debouncedStart = this.debounce(this.start.bind(this), 100); this.debouncedStop = this.debounce(this.stop.bind(this), 100); } /** * Static registry to ensure only one OverlayManager per targetElement. * Uses a WeakMap to allow garbage collection of DOM elements. */ static registry = new WeakMap(); /** * Factory method to create and initialize an OverlayManager instance. * Ensures only one instance per targetElement. * @param {HTMLElement} targetElement - The element to be overlaid. * @param {Object} [options] - Optional settings. * @returns {OverlayManager} - The initialized OverlayManager instance. */ static create(targetElement, options = {}) { if (OverlayManager.registry.has(targetElement)) { console.warn('An OverlayManager instance already exists for this targetElement.'); return OverlayManager.registry.get(targetElement); } const manager = new OverlayManager(targetElement, options); manager.init(); OverlayManager.registry.set(targetElement, manager); return manager; } /** * Factory method to debounce functions. * @param {Function} func - The function to debounce. * @param {number} wait - The debounce delay in milliseconds. * @returns {Function} - The debounced function. */ debounce(func, wait) { let timeout; return function (...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; } /** * Initializes the overlay by creating and appending it to the target element. * Guard clause ensures initialization happens only once. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If initialization fails critically. */ init() { if (this.isInitialized) { console.warn('OverlayManager is already initialized.'); return this; } // Check if the overlay already exists by looking for a specific class const existingOverlay = this.targetElement.querySelector('.overlay-manager-overlay'); if (existingOverlay) { this.overlay = existingOverlay; } else { // Ensure the target element has a positioning context const computedStyle = window.getComputedStyle(this.targetElement); if (!['absolute', 'relative', 'fixed', 'sticky'].includes(computedStyle.position)) { this.targetElement.style.position = 'relative'; } // Create the overlay element this.overlay = document.createElement('div'); this.overlay.classList.add('overlay-manager-overlay'); // Apply default styles Object.assign(this.overlay.style, { position: 'absolute', top: '0', left: '0', width: '100%', height: '100%', display: 'none', // Hidden by default pointerEvents: 'none', // Let clicks pass through unless in active state zIndex: this.options.zIndex.toString(), // Use provided z-index or default ...this.options.styles, // Spread additional styles if provided }); // Set ARIA attributes for accessibility this.overlay.setAttribute('role', this.options.ariaRole); this.overlay.setAttribute('aria-hidden', 'true'); this.overlay.setAttribute('aria-modal', 'true'); // Indicates a modal dialog // Set additional ARIA attributes if provided if (this.options.ariaLabelledby) { this.overlay.setAttribute('aria-labelledby', this.options.ariaLabelledby); } if (this.options.ariaDescribedby) { this.overlay.setAttribute('aria-describedby', this.options.ariaDescribedby); } // Create a dedicated content container within the overlay this.contentContainer = document.createElement('div'); this.contentContainer.classList.add('overlay-manager-content'); Object.assign(this.contentContainer.style, { width: '100%', height: '100%', overflow: 'auto', }); // Insert content into the contentContainer if provided if (this.options.content) { this.setContent(this.options.content); } // Append the contentContainer to the overlay this.overlay.appendChild(this.contentContainer); // Append the overlay to the target element this.targetElement.appendChild(this.overlay); } this.isInitialized = true; this.dispatchEvent(new CustomEvent('init', { detail: { overlay: this.overlay } })); // Initialize all registered plugins this.plugins.forEach(plugin => { if (typeof plugin.init === 'function') { try { plugin.init(this); } catch (error) { console.error('Error in plugin init:', error); } } }); return this; } /** * Starts the overlay by displaying it and entering the active state. * Guard clause prevents starting if already active. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ start() { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.'); } if (this.isActive) { console.warn('OverlayManager is already active.'); return this; } // Prevent body from scrolling if preventBodyScroll is true if (this.options.preventBodyScroll) { this.scrollPosition = { top: window.scrollY || document.documentElement.scrollTop, left: window.scrollX || document.documentElement.scrollLeft, }; // Save original body styles to restore later this.originalBodyStyles = { position: document.body.style.position, top: document.body.style.top, left: document.body.style.left, width: document.body.style.width, overflow: document.body.style.overflow, }; document.body.style.top = `-${this.scrollPosition.top}px`; document.body.style.left = `-${this.scrollPosition.left}px`; document.body.style.position = 'fixed'; document.body.style.width = '100%'; document.body.style.overflow = 'hidden'; } this.overlay.style.display = 'block'; this.overlay.style.pointerEvents = 'auto'; // Capture events if needed this.overlay.setAttribute('aria-hidden', 'false'); this.isActive = true; // Save the currently focused element to restore focus later if (this.options.focusTrap) { this.previousActiveElement = document.activeElement; this.trapFocus(); } this.dispatchEvent(new CustomEvent('start', { detail: { overlay: this.overlay } })); // Execute plugin start hooks this.plugins.forEach(plugin => { if (typeof plugin.onStart === 'function') { try { plugin.onStart(this); } catch (error) { console.error('Error in plugin onStart:', error); } } }); return this; } /** * Stops the overlay by hiding it and returning to the inactive state. * Guard clause prevents stopping if already inactive. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ stop() { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.'); } if (!this.isActive) { console.warn('OverlayManager is already inactive.'); return this; } // Restore body scrolling if it was prevented if (this.options.preventBodyScroll && this.originalBodyStyles) { document.body.style.position = this.originalBodyStyles.position; document.body.style.top = this.originalBodyStyles.top; document.body.style.left = this.originalBodyStyles.left; document.body.style.width = this.originalBodyStyles.width; document.body.style.overflow = this.originalBodyStyles.overflow; window.scrollTo(this.scrollPosition.left, this.scrollPosition.top); this.originalBodyStyles = null; } this.overlay.style.display = 'none'; this.overlay.style.pointerEvents = 'none'; // Release event capture this.overlay.setAttribute('aria-hidden', 'true'); this.isActive = false; // Restore focus to the previously active element if (this.options.focusTrap && this.previousActiveElement) { this.previousActiveElement.focus(); this.previousActiveElement = null; } // Remove the keydown event listener to prevent memory leaks if (this.options.focusTrap) { this.overlay.removeEventListener('keydown', this.handleKeyDown); } this.dispatchEvent(new CustomEvent('stop', { detail: { overlay: this.overlay } })); // Execute plugin stop hooks this.plugins.forEach(plugin => { if (typeof plugin.onStop === 'function') { try { plugin.onStop(this); } catch (error) { console.error('Error in plugin onStop:', error); } } }); return this; } /** * Updates the overlay content. * @param {HTMLElement|Function|string} newContent - New content to insert into the overlay. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ setContent(newContent) { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.'); } // Clear existing content in the contentContainer instead of the entire overlay this.contentContainer.innerHTML = ''; if (newContent) { let contentElement; if (typeof newContent === 'function') { // Call the provided function to get the content element contentElement = newContent(); } else if (typeof newContent === 'string') { // If content is a string, set it as innerHTML of contentContainer this.contentContainer.innerHTML = newContent; } else if (newContent instanceof HTMLElement) { // If content is an HTMLElement, append it directly to contentContainer contentElement = newContent; } else { console.warn('Unsupported content type for overlay.'); } if (contentElement instanceof HTMLElement) { this.contentContainer.appendChild(contentElement); } } this.dispatchEvent(new CustomEvent('contentChange', { detail: { newContent } })); // Execute plugin contentChange hooks this.plugins.forEach(plugin => { if (typeof plugin.onContentChange === 'function') { try { plugin.onContentChange(this, newContent); } catch (error) { console.error('Error in plugin onContentChange:', error); } } }); // Re-trap focus if the overlay is active and focus trapping is enabled if (this.isActive && this.options.focusTrap) { this.overlay.removeEventListener('keydown', this.handleKeyDown); this.trapFocus(); } return this; } /** * Destroys the overlay by removing it from the DOM and cleaning up references. * Guard clause prevents destruction if not initialized. * @returns {OverlayManager} - The instance for chaining. * @throws {Error} - If the overlay is not initialized. */ destroy() { if (!this.isInitialized) { throw new Error('OverlayManager is not initialized or already destroyed.'); } // Remove the keydown event listener to ensure complete cleanup if (this.options.focusTrap && this.overlay) { this.overlay.removeEventListener('keydown', this.handleKeyDown); } if (this.overlay && this.overlay.parentElement === this.targetElement) { this.targetElement.removeChild(this.overlay); this.dispatchEvent(new CustomEvent('destroy', { detail: { overlay: this.overlay } })); } // Execute plugin destroy hooks this.plugins.forEach(plugin => { if (typeof plugin.onDestroy === 'function') { try { plugin.onDestroy(this); } catch (error) { console.error('Error in plugin onDestroy:', error); } } }); // Remove from registry OverlayManager.registry.delete(this.targetElement); this.overlay = null; this.contentContainer = null; this.isActive = false; this.isInitialized = false; // Clear all plugins this.plugins.clear(); return this; } /** * Registers a plugin to extend OverlayManager's functionality. * @param {Object} plugin - The plugin object. * @param {Function} [plugin.init] - Called during OverlayManager initialization. * @param {Function} [plugin.onStart] - Called when the overlay starts. * @param {Function} [plugin.onStop] - Called when the overlay stops. * @param {Function} [plugin.onDestroy] - Called when the overlay is destroyed. * @param {Function} [plugin.onContentChange] - Called when the overlay content changes. * @returns {OverlayManager} - The instance for chaining. */ use(plugin) { if (typeof plugin !== 'object' || plugin === null) { throw new TypeError('Plugin must be an object'); } if (this.plugins.has(plugin)) { console.warn('Plugin is already registered.'); return this; } this.plugins.add(plugin); // If already initialized, initialize the plugin immediately if (this.isInitialized && typeof plugin.init === 'function') { try { plugin.init(this); } catch (error) { console.error('Error in plugin init:', error); } } return this; } /** * Removes a previously registered plugin. * @param {Object} plugin - The plugin object to remove. * @returns {OverlayManager} - The instance for chaining. */ remove(plugin) { if (!this.plugins.has(plugin)) { console.warn('Plugin not found.'); return this; } // If the plugin has a destroy method, call it if (typeof plugin.onDestroy === 'function') { try { plugin.onDestroy(this); } catch (error) { console.error('Error in plugin onDestroy:', error); } } this.plugins.delete(plugin); return this; } /** * Traps focus within the overlay when active. * @private */ trapFocus() { const focusableSelectors = [ 'a[href]', 'area[href]', 'input:not([disabled])', 'select:not([disabled])', 'textarea:not([disabled])', 'button:not([disabled])', 'iframe', 'object', 'embed', '[contenteditable]', '[tabindex]:not([tabindex="-1"])', ]; const focusableElements = this.contentContainer.querySelectorAll(focusableSelectors.join(',')); this.cachedFocusableElements = Array.prototype.slice.call(focusableElements); if (this.cachedFocusableElements.length === 0) { console.warn('No focusable elements within the overlay. Making the overlay itself focusable.'); this.overlay.setAttribute('tabindex', '-1'); this.overlay.focus(); } else { const firstFocusable = this.cachedFocusableElements[0]; firstFocusable.focus(); } this.overlay.addEventListener('keydown', this.handleKeyDown); } /** * Handles keydown events to maintain focus within the overlay and handle Escape key. * @param {KeyboardEvent} event - The keyboard event. * @private */ handleKeyDown(event) { if (event.key === 'Tab') { // Handle focus trapping if (this.cachedFocusableElements.length === 0) { event.preventDefault(); return; } const firstFocusable = this.cachedFocusableElements[0]; const lastFocusable = this.cachedFocusableElements[this.cachedFocusableElements.length - 1]; if (event.shiftKey) { // Shift + Tab if (document.activeElement === firstFocusable) { lastFocusable.focus(); event.preventDefault(); } } else { // Tab if (document.activeElement === lastFocusable) { firstFocusable.focus(); event.preventDefault(); } } } else if (event.key === 'Escape') { // Allow closing the overlay with Escape key this.stop(); } } }Key Changes and Explanations
-
preventBodyScrollOption:- Default Behavior: The body is now scrollable by default (
preventBodyScroll: false). - Preventing Scroll: To prevent body scrolling when the overlay is active, set
preventBodyScrolltotrueduring initialization.
// Example: Prevent body scroll when overlay is active const overlay = OverlayManager.create(targetElement, { content: '<p>Your overlay content here</p>', preventBodyScroll: true, }); - Default Behavior: The body is now scrollable by default (
-
Preserving and Restoring Body Styles:
- Saving Original Styles: Before modifying the body's styles to prevent scrolling, the original styles are saved in
this.originalBodyStyles. - Restoring Original Styles: When stopping the overlay, the original styles are restored instead of setting them to empty strings.
// In start() if (this.options.preventBodyScroll) { this.scrollPosition = { top: window.scrollY || document.documentElement.scrollTop, left: window.scrollX || document.documentElement.scrollLeft, }; // Save original body styles to restore later this.originalBodyStyles = { position: document.body.style.position, top: document.body.style.top, left: document.body.style.left, width: document.body.style.width, overflow: document.body.style.overflow, }; document.body.style.top = `-${this.scrollPosition.top}px`; document.body.style.left = `-${this.scrollPosition.left}px`; document.body.style.position = 'fixed'; document.body.style.width = '100%'; document.body.style.overflow = 'hidden'; } // In stop() if (this.options.preventBodyScroll && this.originalBodyStyles) { document.body.style.position = this.originalBodyStyles.position; document.body.style.top = this.originalBodyStyles.top; document.body.style.left = this.originalBodyStyles.left; document.body.style.width = this.originalBodyStyles.width; document.body.style.overflow = this.originalBodyStyles.overflow; window.scrollTo(this.scrollPosition.left, this.scrollPosition.top); this.originalBodyStyles = null; } - Saving Original Styles: Before modifying the body's styles to prevent scrolling, the original styles are saved in
-
Enhanced
setContentMethod:- Ensured that if a function is provided as
newContent, it is correctly invoked to generate the content. - Improved warnings for unsupported content types.
- Ensured that if a function is provided as
-
Robust Plugin Handling:
- Added error handling within plugin hooks to prevent a faulty plugin from breaking the
OverlayManager.
- Added error handling within plugin hooks to prevent a faulty plugin from breaking the
-
Accessibility Enhancements:
- Ensured that ARIA attributes are correctly managed to maintain accessibility standards.
Usage Example
Here's how you can utilize the updated
OverlayManager:// Select the target element you want to overlay const targetElement = document.getElementById('main-content'); // Create an instance of OverlayManager with desired options const overlay = OverlayManager.create(targetElement, { content: '<div><h2>Overlay Title</h2><p>This is the overlay content.</p><button id="close-overlay">Close</button></div>', zIndex: 2000, preventBodyScroll: true, // Prevent body from scrolling when overlay is active }); // Start the overlay overlay.start(); // Optionally, you can stop the overlay programmatically document.getElementById('close-overlay').addEventListener('click', () => { overlay.stop(); }); // Listen to custom events overlay.addEventListener('start', () => { console.log('Overlay has started.'); }); overlay.addEventListener('stop', () => { console.log('Overlay has stopped.'); });Conclusion
With these enhancements, the
OverlayManageris now more flexible and user-friendly. The body remains scrollable by default, ensuring that existing page functionality isn't disrupted. When needed, you can prevent body scroll by toggling thepreventBodyScrolloption. Additionally, by preserving and restoring original body styles, the integrity of your page's layout remains intact.Feel free to integrate this updated class into your project and customize it further as per your requirements!
-