@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;
}
code
// Check if the overlay already exists by looking for a specific class
code
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
});
// Create a dedicated content container within the overlay
// Insert content into the contentContainer if provided
if (this.options.content) {
this.#setContent(this.options.content);
}
// 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.');
}
code
if (this.isActive) {
code
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.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.');
}
code
if (!this.isActive) {
code
console.warn('OverlayManager is already inactive.');
return this;
}
// Restore body scrolling if it was prevented
if (this.options.preventBodyScroll) {
// Iterate over each saved style property and restore or remove accordingly
for (const [property, value] of Object.entries(this.originalBodyStyles)) {
if (value) {
document.body.style[property] = value;
} else {
document.body.style.removeProperty(property);
}
}
window.scrollTo(this.scrollPosition.left, this.scrollPosition.top);
this.originalBodyStyles = {};
}
this.overlay.style.display = 'none';
this.overlay.style.pointerEvents = 'none'; // Release event capture
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) {
this.overlay.innerHTML = '';
code
if (newContent) {
code
let contentElement;
if (typeof newContent === 'function') {
contentElement = newContent();
} else if (typeof newContent === 'string') {
this.overlay.innerHTML = newContent;
} else if (newContent instanceof HTMLElement) {
contentElement = newContent;
} else {
console.warn('Unsupported content type for overlay.');
}
if (contentElement instanceof HTMLElement) {
this.overlay.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;
}
setContent(newContent) {
if (!this.isInitialized) {
throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.');
}
return this.#setContent(newContent);
}
/**
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.');
}
code
// Remove the keydown event listener to ensure complete cleanup
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');
}
code
if (this.plugins.has(plugin)) {
code
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;
}
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.
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();
}
}
}
"""
OverlayManager Documentation
Table of Contents
Introduction
Installation
Getting Started
Creating an OverlayManager Instance
Options
Overlay Controls
Starting the Overlay
Stopping the Overlay
Updating Overlay Content
Destroying the Overlay
Event Handling
Plugins
Creating a Plugin
Using a Plugin
Removing a Plugin
Plugin Lifecycle Hooks
Examples
Basic Usage
Custom Content and Styles
Preventing Body Scroll
Using Plugins
Best Practices
API Reference
Introduction
OverlayManager is a robust and flexible JavaScript class designed to manage overlays on specific target elements within your web application. By extending the EventTarget interface, it provides a seamless way to handle overlay states, manage content, and extend functionality through a plugin system.
Installation
To use OverlayManager, ensure that your project includes the class definition, either by importing it from a module or including it directly in your script.
Example: Including Directly
html
<script src="path/to/OverlayManager.js"></script>
Example: Importing as a Module
javascript
import OverlayManager from './OverlayManager.js';
Getting Started
Creating an OverlayManager Instance
OverlayManager instances are created using the static create method. This ensures that only one instance exists per target element.
OverlayManager supports a plugin system that allows you to extend its functionality without modifying the core class. Plugins can hook into various lifecycle events and add custom behavior.
Creating a Plugin
A plugin is a plain JavaScript object that can implement any of the following methods:
init(manager): Called during OverlayManager initialization.
onStart(manager): Called when the overlay starts.
onStop(manager): Called when the overlay stops.
onDestroy(manager): Called when the overlay is destroyed.
onContentChange(manager, newContent): Called when the overlay content changes.
Example Plugin: LoggerPlugin
javascript
const LoggerPlugin = {
init(manager) {
console.log('LoggerPlugin initialized.');
},
onStart(manager) {
console.log('Overlay has started.');
},
onStop(manager) {
console.log('Overlay has stopped.');
},
onDestroy(manager) {
console.log('Overlay has been destroyed.');
},
onContentChange(manager, newContent) {
console.log('Overlay content changed:', newContent);
},
};
Using a Plugin
To register a plugin with an OverlayManager instance, use the use method:
javascript
overlayManager.use(LoggerPlugin);
Behavior:
Adds the plugin to the internal plugin set.
If the overlay is already initialized, calls the plugin's init method immediately.
Removing a Plugin
To unregister a previously added plugin, use the remove method:
javascript
overlayManager.remove(LoggerPlugin);
Behavior:
Removes the plugin from the internal plugin set.
Calls the plugin's onDestroy method if available.
Plugin Lifecycle Hooks
Plugins can hook into different stages of the overlay's lifecycle:
init(manager): Initialize plugin resources.
onStart(manager): Execute when the overlay starts.
onStop(manager): Execute when the overlay stops.
onDestroy(manager): Clean up plugin resources.
onContentChange(manager, newContent): Respond to content updates.
Note: All plugin methods are optional. Implement only the hooks you need.
const overlayManager = OverlayManager.create(targetElement, {
content: '<p>Overlay with body scroll prevented.</p>',
preventBodyScroll: true,
});
overlayManager.start();
// Body scrolling is now disabled while the overlay is active
Singleton Instances: Use the static create method to ensure only one OverlayManager instance per target element.
Plugin Management: Avoid registering the same plugin multiple times. Use the remove method to clean up plugins when they're no longer needed.
Accessibility: Utilize focusTrap to maintain accessibility standards by trapping focus within the overlay.
Cleanup: Always call destroy when the overlay is no longer needed to prevent memory leaks.
Error Handling: Wrap plugin methods in try-catch blocks to handle potential errors without affecting the overlay's functionality.
API Reference
OverlayManager.create(targetElement, options)
Description:
Creates and initializes an OverlayManager instance for the specified target element. Ensures that only one instance exists per target element.
Parameters:
targetElement(HTMLElement): The element to be overlaid.
options(Object, optional): Configuration options.
Returns: OverlayManager instance.
overlayManager.start()
Description:
Activates the overlay, making it visible and applying necessary behaviors.
Returns: OverlayManager instance.
overlayManager.stop()
Description:
Deactivates the overlay, hiding it and removing applied behaviors.
Returns: OverlayManager instance.
overlayManager.setContent(newContent)
Description:
Updates the content displayed within the overlay.
Parameters:
newContent(HTMLElement | Function | string): The new content to display.
Returns: OverlayManager instance.
overlayManager.destroy()
Description:
Removes the overlay from the DOM and cleans up all associated resources.
Returns: OverlayManager instance.
overlayManager.use(plugin)
Description:
Registers a plugin to extend OverlayManager's functionality.
Parameters:
plugin(Object): The plugin object.
Returns: OverlayManager instance.
overlayManager.remove(plugin)
Description:
Unregisters a previously registered plugin.
Parameters:
plugin(Object): The plugin object to remove.
Returns: OverlayManager instance.
Events
init
Description: Fired when the overlay is initialized.
Event Detail:{ overlay: HTMLElement }
start
Description: Fired when the overlay becomes active.
Event Detail:{ overlay: HTMLElement }
stop
Description: Fired when the overlay is deactivated.
Event Detail:{ overlay: HTMLElement }
contentChange
Description: Fired when the overlay content is updated.
Event Detail:{ newContent: HTMLElement | Function | string }
destroy
Description: Fired when the overlay is destroyed.
Event Detail:{ overlay: HTMLElement }
Conclusion
OverlayManager provides a comprehensive solution for managing overlays within your web applications. With its extensible plugin system, event-driven architecture, and focus on accessibility, it ensures that overlays are both functional and user-friendly. By following this documentation, you can effectively integrate and customize OverlayManager to suit your project's needs.