Certainly! Below are several test cases designed to validate the functionality of the OverlayManager class. These tests can be run in CodePen by incorporating the provided HTML, CSS, and JavaScript code.
Overview of Test Cases
- Initialization Test: Verify that the
OverlayManager initializes correctly with a target element.
- Content Insertion Test: Check if content is properly inserted into the overlay.
- Start and Stop Overlay Test: Ensure that the overlay can be started (shown) and stopped (hidden) correctly.
- Focus Trap Test: Confirm that focus is trapped within the overlay when active.
- Prevent Body Scroll Test: Validate that body scrolling is prevented when the overlay is active (if enabled).
- Z-Index Test: Ensure that the overlay's
z-index is applied correctly.
- Plugin Test: Test the plugin registration and lifecycle hooks.
- Destroy Overlay Test: Verify that the overlay can be destroyed properly.
Implementation in CodePen
Below is a comprehensive example that includes the OverlayManager class and the test cases. You can copy this code into CodePen's respective HTML, CSS, and JavaScript sections to run the tests.
1. HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OverlayManager Test Cases</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>OverlayManager Test Cases</h1>
<!-- Target Element for Overlay -->
<div id="target-element" class="target">
<p>This is the target element. The overlay will appear over this.</p>
<button id="focusable-button">Focusable Button</button>
</div>
<!-- Controls for Test Cases -->
<div class="controls">
<button id="init-overlay">Initialize Overlay</button>
<button id="start-overlay">Start Overlay</button>
<button id="stop-overlay">Stop Overlay</button>
<button id="change-content">Change Content</button>
<button id="destroy-overlay">Destroy Overlay</button>
</div>
<!-- Plugin Registration -->
<button id="register-plugin">Register Plugin</button>
<button id="remove-plugin">Remove Plugin</button>
</body>
</html>
2. CSS
/* styles.css */
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.target {
position: relative;
width: 80%;
margin: 0 auto;
padding: 20px;
border: 2px solid #333;
background-color: #f9f9f9;
}
.controls {
margin-top: 20px;
}
.controls button {
margin-right: 10px;
padding: 10px 15px;
font-size: 16px;
}
.overlay-manager-overlay {
background-color: rgba(0, 0, 0, 0.7);
color: white;
display: flex;
align-items: center;
justify-content: center;
}
3. JavaScript
// JavaScript Code (Include the OverlayManager class first)
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 {boolean} [options.focusTrap=true] - Whether to enable focus trapping.
* @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.isActive = false;
this.isInitialized = false;
this.options = {
zIndex: 1000,
focusTrap: true,
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 = {}; // 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
});
// Insert content into the overlay 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.');
}
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 = 'flex';
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.');
}
if (!this.isActive) {
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) {
if (!this.isInitialized) {
throw new Error('OverlayManager is not initialized. Call init() or use the create() factory method.');
}
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') {
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.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.overlay.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();
}
}
}
// Test Cases Implementation
document.addEventListener('DOMContentLoaded', () => {
const targetElement = document.getElementById('target-element');
let overlayManager = null;
let testPlugin = {
init(manager) {
console.log('Plugin initialized.');
},
onStart(manager) {
console.log('Plugin: Overlay started.');
},
onStop(manager) {
console.log('Plugin: Overlay stopped.');
},
onContentChange(manager, newContent) {
console.log('Plugin: Content changed to:', newContent);
},
onDestroy(manager) {
console.log('Plugin: Overlay destroyed.');
}
};
// Test Case 1: Initialization Test
document.getElementById('init-overlay').addEventListener('click', () => {
if (!overlayManager) {
overlayManager = OverlayManager.create(targetElement, {
content: '<div><h2>Initial Overlay Content</h2><button id="inside-overlay">Inside Overlay Button</button></div>',
zIndex: 2000,
styles: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
color: '#fff',
},
focusTrap: true,
preventBodyScroll: true
});
overlayManager.addEventListener('init', (e) => {
console.log('Overlay initialized:', e.detail.overlay);
});
overlayManager.addEventListener('start', (e) => {
console.log('Overlay started:', e.detail.overlay);
});
overlayManager.addEventListener('stop', (e) => {
console.log('Overlay stopped:', e.detail.overlay);
});
overlayManager.addEventListener('contentChange', (e) => {
console.log('Overlay content changed:', e.detail.newContent);
});
overlayManager.addEventListener('destroy', (e) => {
console.log('Overlay destroyed:', e.detail.overlay);
});
console.log('OverlayManager instance created and initialized.');
} else {
console.warn('OverlayManager is already initialized.');
}
});
// Test Case 2: Start Overlay Test
document.getElementById('start-overlay').addEventListener('click', () => {
if (overlayManager) {
overlayManager.start();
console.log('Overlay started.');
} else {
console.error('OverlayManager is not initialized.');
}
});
// Test Case 3: Stop Overlay Test
document.getElementById('stop-overlay').addEventListener('click', () => {
if (overlayManager) {
overlayManager.stop();
console.log('Overlay stopped.');
} else {
console.error('OverlayManager is not initialized.');
}
});
// Test Case 4: Content Insertion Test
document.getElementById('change-content').addEventListener('click', () => {
if (overlayManager) {
const newContent = `
<div>
<h2>Updated Overlay Content</h2>
<p>This is new content inside the overlay.</p>
<button id="new-overlay-button">New Overlay Button</button>
</div>
`;
overlayManager.setContent(newContent);
console.log('Overlay content updated.');
} else {
console.error('OverlayManager is not initialized.');
}
});
// Test Case 5: Destroy Overlay Test
document.getElementById('destroy-overlay').addEventListener('click', () => {
if (overlayManager) {
overlayManager.destroy();
overlayManager = null;
console.log('OverlayManager instance destroyed.');
} else {
console.error('OverlayManager is not initialized or already destroyed.');
}
});
// Test Case 6: Plugin Registration Test
document.getElementById('register-plugin').addEventListener('click', () => {
if (overlayManager) {
overlayManager.use(testPlugin);
console.log('Plugin registered.');
} else {
console.error('OverlayManager is not initialized.');
}
});
// Test Case 7: Plugin Removal Test
document.getElementById('remove-plugin').addEventListener('click', () => {
if (overlayManager) {
overlayManager.remove(testPlugin);
console.log('Plugin removed.');
} else {
console.error('OverlayManager is not initialized.');
}
});
// Additional: Event Listener for Buttons Inside Overlay
// Since the overlay's content can change, use event delegation
targetElement.addEventListener('click', (event) => {
if (event.target.id === 'inside-overlay') {
alert('Inside Overlay Button Clicked!');
}
if (event.target.id === 'new-overlay-button') {
alert('New Overlay Button Clicked!');
}
});
});
Explanation of Test Cases
-
Initialization Test (#init-overlay):
- Action: Click the "Initialize Overlay" button.
- Expectation: An
OverlayManager instance is created and initialized with specified options (content, z-index, styles, focus trap, and body scroll prevention). Console logs confirm initialization.
-
Start Overlay Test (#start-overlay):
- Action: Click the "Start Overlay" button.
- Expectation: The overlay becomes visible over the target element. Focus trapping is active, and body scrolling is prevented. Console logs confirm the overlay has started.
-
Stop Overlay Test (#stop-overlay):
- Action: Click the "Stop Overlay" button.
- Expectation: The overlay is hidden. Focus is returned to the previously active element, and body scrolling is restored. Console logs confirm the overlay has stopped.
-
Content Insertion Test (#change-content):
- Action: Click the "Change Content" button.
- Expectation: The overlay's content is updated to the new HTML provided. Console logs confirm the content change. New buttons within the overlay are functional and can trigger alerts when clicked.
-
Destroy Overlay Test (#destroy-overlay):
- Action: Click the "Destroy Overlay" button.
- Expectation: The overlay is removed from the DOM, and the
OverlayManager instance is cleaned up. Console logs confirm destruction.
-
Plugin Registration Test (#register-plugin):
- Action: Click the "Register Plugin" button.
- Expectation: A test plugin is registered with the
OverlayManager. Plugin lifecycle hooks (init, onStart, onStop, onContentChange, onDestroy) log messages to the console when triggered.
-
Plugin Removal Test (#remove-plugin):
- : Click the "Remove Plugin" button.
Running the Test Cases
-
Setup:
- Navigate to CodePen.
- Create a new pen.
- Copy the HTML, CSS, and JavaScript sections into their respective areas in CodePen.
-
Executing Tests:
- Use the buttons provided in the interface to run each test case.
- Observe the overlay behavior on the page.
- Check the browser's console (press
F12 or Ctrl+Shift+I) to view log messages confirming each action's success.
-
Interacting with Overlay:
- When the overlay is active, try navigating using the
Tab key to test focus trapping.
- Click buttons inside the overlay to ensure event listeners are working.
- Press the
Escape key to close the overlay and verify that it stops as expected.
Notes
-
Event Delegation for Overlay Content: Since the overlay's content can be dynamic, event listeners for elements inside the overlay are attached to the targetElement using event delegation. This ensures that dynamically added buttons inside the overlay respond to clicks.
-
Plugin Functionality: The test plugin logs messages during various lifecycle events, demonstrating how plugins can extend the OverlayManager's functionality.
-
Prevent Body Scroll: The preventBodyScroll option is enabled during initialization, ensuring that the background content does not scroll when the overlay is active. This is particularly useful for modal dialogs and similar overlays.
By following this setup and executing the provided test cases, you can thoroughly validate the OverlayManager class's functionality within a live environment like CodePen.