Untitled conversation
- Usercode
- Assistant
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.
*/
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.isActive = false;
this.isInitialized = false;
this.options = {
zIndex: 1000,
ariaRole: 'dialog',
focusTrap: true,
...options,
};
this.plugins = [];
this.previousActiveElement = null;
// Bind methods
this.handleKeyDown = this.handleKeyDown.bind(this);
}
/**
* Factory method to create and initialize an OverlayManager instance.
* @param {HTMLElement} targetElement - The element to be overlaid.
* @param {Object} [options] - Optional settings.
* @returns {OverlayManager} - The initialized OverlayManager instance.
*/
static create(targetElement, options = {}) {
const manager = new OverlayManager(targetElement, options);
manager.init();
return manager;
}
/**
* 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');
// Insert content into the overlay if provided
if (this.options.content) {
let contentElement;
if (typeof this.options.content === 'function') {
// If content is a function, call it to get the element
contentElement = this.options.content();
} else if (typeof this.options.content === 'string') {
// If content is a string, set it as innerHTML
this.overlay.innerHTML = this.options.content;
} else if (this.options.content instanceof HTMLElement) {
// If content is an HTMLElement, append it directly
contentElement = this.options.content;
} else {
console.warn('Unsupported content type for overlay.');
}
if (contentElement instanceof HTMLElement) {
this.overlay.appendChild(contentElement);
}
}
// 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') {
plugin.init(this);
}
});
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;
}
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') {
plugin.onStart(this);
}
});
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;
}
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;
}
this.dispatchEvent(new CustomEvent('stop', { detail: { overlay: this.overlay } }));
// Execute plugin stop hooks
this.plugins.forEach(plugin => {
if (typeof plugin.onStop === 'function') {
plugin.onStop(this);
}
});
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
this.overlay.innerHTML = '';
if (newContent) {
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') {
plugin.onContentChange(this, newContent);
}
});
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.');
}
if (this.overlay && this.overlay.parentElement === this.targetElement) {
this.targetElement.removeChild(this.overlay);
this.dispatchEvent(new CustomEvent('destroy', { detail: { overlay: this.overlay } }));
}
this.overlay = null;
this.isActive = false;
this.isInitialized = false;
// Execute plugin destroy hooks
this.plugins.forEach(plugin => {
if (typeof plugin.onDestroy === 'function') {
plugin.onDestroy(this);
}
});
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');
}
this.plugins.push(plugin);
// If already initialized, initialize the plugin immediately
if (this.isInitialized && typeof plugin.init === 'function') {
plugin.init(this);
}
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.overlay.querySelectorAll(focusableSelectors.join(','));
const firstFocusable = focusableElements[0];
const lastFocusable = focusableElements[focusableElements.length - 1];
if (firstFocusable) firstFocusable.focus();
this.overlay.addEventListener('keydown', this.handleKeyDown);
}
/**
* Handles keydown events to maintain focus within the overlay.
* @param {KeyboardEvent} event - The keyboard event.
* @private
*/
handleKeyDown(event) {
if (event.key !== 'Tab') return;
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.overlay.querySelectorAll(focusableSelectors.join(','));
const focusable = Array.prototype.slice.call(focusableElements);
if (focusable.length === 0) {
event.preventDefault();
return;
}
const firstFocusable = focusable[0];
const lastFocusable = focusable[focusable.length - 1];
const currentIndex = focusable.indexOf(document.activeElement);
if (event.shiftKey) {
// Shift + Tab
if (document.activeElement === firstFocusable) {
lastFocusable.focus();
event.preventDefault();
}
} else {
// Tab
if (document.activeElement === lastFocusable) {
firstFocusable.focus();
event.preventDefault();
}
}
}
}
check for any errors in focustrapping and plugin features in the class. if no we can proceed.
The provided OverlayManager class is well-structured and incorporates robust features for managing overlays, including focus trapping and plugin support. However, upon closer inspection, there are a couple of areas within the focus trapping and plugin functionalities that could benefit from improvements or bug fixes. Here's a detailed analysis:
a. Unused Variable currentIndex
In the handleKeyDown method, the variable currentIndex is calculated but never utilized:
const currentIndex = focusable.indexOf(document.activeElement);
Recommendation:
currentIndex if it's not needed to clean up the code.b. Removing Event Listeners
When the overlay is stopped or destroyed, the keydown event listener added during trapFocus remains attached to the overlay. This can lead to memory leaks or unintended behavior, especially if the overlay is reinitialized.
Implementation:
Add a Reference to the Handler:
Ensure that the event handler (handleKeyDown) can be referenced when removing the listener.
Remove the Event Listener in stop and destroy:
stop() {
// ... existing code ...
// Remove the keydown event listener to prevent memory leaks
if (this.options.focusTrap) {
this.overlay.removeEventListener('keydown', this.handleKeyDown);
}
// ... existing code ...
}
destroy() {
// ... existing code ...
// Remove the keydown event listener to ensure complete cleanup
if (this.options.focusTrap && this.overlay) {
this.overlay.removeEventListener('keydown', this.handleKeyDown);
}
// ... existing code ...
}
Explanation:
stop(), removing the event listener ensures that focus trapping is disabled when the overlay is no longer active.destroy(), it guarantees that all event listeners are cleaned up when the overlay is removed from the DOM, preventing potential memory leaks.The plugin system is thoughtfully integrated, allowing for extensibility. However, there are a couple of considerations to ensure robustness:
a. Preventing Duplicate Plugin Registrations
Currently, the use method allows multiple registrations of the same plugin, which can lead to redundant or conflicting behaviors.
Implementation:
Modify the use method to check for existing plugins before adding a new one:
use(plugin) {
if (typeof plugin !== 'object' || plugin === null) {
throw new TypeError('Plugin must be an object');
}
if (this.plugins.includes(plugin)) {
console.warn('Plugin is already registered.');
return this;
}
this.plugins.push(plugin);
// If already initialized, initialize the plugin immediately
if (this.isInitialized && typeof plugin.init === 'function') {
plugin.init(this);
}
return this;
}
Explanation:
includes. If it is, a warning is logged, and the method returns early.b. Enhancing Plugin Removal (Optional)
While not present in the current implementation, providing a method to remove plugins can further enhance the flexibility of the OverlayManager.
Implementation:
Add a remove method to handle plugin deregistration:
remove(plugin) {
const index = this.plugins.indexOf(plugin);
if (index === -1) {
console.warn('Plugin not found.');
return this;
}
// If the plugin has a destroy method, call it
if (typeof plugin.onDestroy === 'function') {
plugin.onDestroy(this);
}
this.plugins.splice(index, 1);
return this;
}
Explanation:
onDestroy method is executed.While not directly related to focus trapping or plugins, here are a few supplementary suggestions to further improve the OverlayManager:
a. Accessibility Enhancements
aria-labelledby or aria-describedby) for better accessibility.b. Error Handling and Logging
c. Documentation and Comments
Overall, the OverlayManager class exhibits a solid foundation with its focus trapping and plugin architecture. By addressing the minor issues highlighted above, particularly in event listener management and plugin registration, the class will be more robust, maintainable, and reliable. Once these adjustments are made, the OverlayManager should be well-prepared for deployment and further extension.
Not yet included in a published release.