vanilla-aria-modals 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +7 -0
- package/README.md +197 -0
- package/package.json +33 -0
- package/src/ModalHandler.d.ts +41 -0
- package/src/ModalHandler.js +344 -0
package/LICENSE.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
ISC License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Angel Valentino
|
|
4
|
+
|
|
5
|
+
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
# ModalHandler
|
|
2
|
+
|
|
3
|
+
## Introduction
|
|
4
|
+
|
|
5
|
+
`ModalHandler` is a framework-agnostic utility for managing accessibility (A11y) events in modals or modal-like UIs within your web application. It supports modal stacking and key accessibility features, including focus trapping, focus management, and closing modals with the Escape key or an outside click.
|
|
6
|
+
|
|
7
|
+
Although designed primarily for modal interactions, it can be used in any UI logic that requires basic ARIA support and focus management.
|
|
8
|
+
|
|
9
|
+
It supports a dynamic number of modals and events. In SPAs or dynamic interfaces, navigating away or re-rendering a component without closing a modal can leave lingering event listeners on `document.body`, which may interfere with future interactions. A reset method is provided to call on route changes or component unmounts. See more at: [SPA / Advanced Usage](#spa--advanced-usage)
|
|
10
|
+
|
|
11
|
+
`ModalHandler` is written in vanilla JS for full flexibility. You can modify it directly in `node_modules` if needed. Just update the `.d.ts` file when changing public methods to keep IntelliSense accurate. Internals documentation, such as architecture and logic flow can be found [here](https://github.com/angelvalentino/vanilla-aria-modals/blob/main/docs/architecture.md).
|
|
12
|
+
|
|
13
|
+
## Set up
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import ModalHandler from './ModalHandler';
|
|
17
|
+
const modalHandler = new ModalHandler();
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`ModalHandler` is a singleton, so creating multiple instances returns the same object.
|
|
21
|
+
|
|
22
|
+
TypeScript types are used in the **docs** and in the **.d.ts** file to indicate the intended type and optionality of parameters, even though the class is fully vanilla JavaScript. This makes it easier to use, manage, and understand, without requiring any compiler.
|
|
23
|
+
|
|
24
|
+
<br>
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
A fully detailed example including the necessary JavaScript, HTML, and CSS files, can be found [here](https://github.com/angelvalentino/vanilla-aria-modals/tree/main/example).
|
|
29
|
+
|
|
30
|
+
**Note:** `lm` in the code stands for *HTMLElement*.
|
|
31
|
+
**Note:** `e.stopPropagation()` prevents other click events (like overlay clicks) from triggering while opening a modal. This can happen because when adding the open modal event, the ARIA events are also added during propagation and can trigger the overlay click event. It is already managed via the class with a timeout, but it is better for robustness to stop propagation here as well if bubbling is not needed in that instance.
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
// Basic example of showing a modal
|
|
35
|
+
showModal() {
|
|
36
|
+
modalContainerLm.style.display = 'block';
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Basic example of hiding a modal
|
|
40
|
+
hideModal() {
|
|
41
|
+
modalContainerLm.style.display = 'none';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
closeModal() {
|
|
45
|
+
hideModal();
|
|
46
|
+
// ...Your hide UI logic
|
|
47
|
+
|
|
48
|
+
// Restore focus
|
|
49
|
+
modalHandler.restoreFocus({
|
|
50
|
+
modalKey: 'myModal'
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Remove ARIA events added
|
|
54
|
+
modalHandler.removeA11yEvents({
|
|
55
|
+
modalKey: 'myModal',
|
|
56
|
+
modalLm: modalContentLm,
|
|
57
|
+
closeLms: [...modalCloseBtns]
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
openModal(e) {
|
|
63
|
+
// Stop event propagation to make sure no events are called on bubbling
|
|
64
|
+
e.stopPropagation();
|
|
65
|
+
|
|
66
|
+
showModal();
|
|
67
|
+
// ...Your show UI logic
|
|
68
|
+
|
|
69
|
+
// Add focus
|
|
70
|
+
modalHandler.addFocus({
|
|
71
|
+
modalKey: 'myModal',
|
|
72
|
+
firstFocusableLm: modalFirstFocusableLm
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Add ARIA events
|
|
76
|
+
modalHandler.addA11yEvents({
|
|
77
|
+
modalKey: 'myModal',
|
|
78
|
+
modalLm: modalContentLm,
|
|
79
|
+
modalLmOuterLimits: modalContentLm,
|
|
80
|
+
closeLms: [...modalCloseBtns],
|
|
81
|
+
closeHandler: closeModal
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const openModalBtn = document.getElementById('open-modal-btn');
|
|
86
|
+
openModalBtn.addEventListener('click', openModal);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
<br>
|
|
90
|
+
|
|
91
|
+
## SPA / Advanced Usage
|
|
92
|
+
|
|
93
|
+
In Single Page Applications (SPA) or frameworks like React, Vue, or vanilla JS with dynamic content, modals may persist across view changes. To prevent lingering events or broken focus, `ModalHandler` provides cleanup methods.
|
|
94
|
+
|
|
95
|
+
### Example: Cleanup on route change or component unmount
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
// Suppose your SPA route or component changes
|
|
99
|
+
function onRouteChange() {
|
|
100
|
+
// Clear leftover document events, active modals, and focus tracking
|
|
101
|
+
modalHandler.reset();
|
|
102
|
+
|
|
103
|
+
// Or individually:
|
|
104
|
+
// modalHandler.clearDocumentBodyEvents();
|
|
105
|
+
// modalHandler.clearActiveModals();
|
|
106
|
+
// modalHandler.clearFocusRegistry();
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
<br>
|
|
110
|
+
|
|
111
|
+
## Public API Methods
|
|
112
|
+
|
|
113
|
+
### setDebug()
|
|
114
|
+
Enables or disables debug logs, aimed for reviewing stacked modals, clear and close logic.
|
|
115
|
+
|
|
116
|
+
#### Parameters
|
|
117
|
+
- **`bool: boolean;`** **true** enables debug mode, **false** disables it.
|
|
118
|
+
|
|
119
|
+
Returns `void`
|
|
120
|
+
|
|
121
|
+
### addA11yEvents()
|
|
122
|
+
Registers ARIA events and modal stacking handling:
|
|
123
|
+
- Close at overlay click
|
|
124
|
+
- Close at ESC key
|
|
125
|
+
- Trap focus
|
|
126
|
+
- Modal stacking
|
|
127
|
+
|
|
128
|
+
#### Parameters
|
|
129
|
+
**Takes parameters as a single object, which are destructured inside the method.**
|
|
130
|
+
|
|
131
|
+
- **`modalKey: string;`** Unique modal identifier. Used for stacking and event management.
|
|
132
|
+
- **`modalLm?: HTMLElement | null;`** *(optional)* The main modal element. Used to trap focus inside the modal.
|
|
133
|
+
- **`modalLmOuterLimits?: HTMLElement | null;`** *(optional)* The container that defines the modal boundary. Used to detect clicks outside the modal. **modalLm** is usually used here, but depending on the UI we may not want to trap focus into the same container we want to close, maybe just in a part of it.
|
|
134
|
+
- **`closeLms?: HTMLElement[] | null;`** *(optional)* Array of elements that should trigger closing the modal (e.g., close buttons).
|
|
135
|
+
- **`exemptLms?: HTMLElement[];`** *(optional)* Array of elements that should not trigger closing even if clicked outside.
|
|
136
|
+
- **`closeHandler: () => void;`** Function to call when the modal should close. Usually should call **removeA11yEvents()**.
|
|
137
|
+
|
|
138
|
+
Returns `void`
|
|
139
|
+
|
|
140
|
+
### removeA11yEvents()
|
|
141
|
+
|
|
142
|
+
Removes all accessibility and interaction event listeners for the specific registered modal.
|
|
143
|
+
|
|
144
|
+
#### Parameters
|
|
145
|
+
**Takes parameters as a single object, which are destructured inside the method.**
|
|
146
|
+
|
|
147
|
+
- **`modalKey: string;`** Unique modal identifier. Must match the modalKey used in **addA11yEvents()**.
|
|
148
|
+
- **`modalLm?: HTMLElement | null;`** *(optional)* The main modal element. Used to be able to properly remove the trap focus event.
|
|
149
|
+
- **`closeLms?: HTMLElement[] | null;`** *(optional)* Array of close elements used in **addA11yEvents()**. Used to be able to properly remove the close event from the given elements.
|
|
150
|
+
|
|
151
|
+
Returns `void`
|
|
152
|
+
|
|
153
|
+
### addFocus()
|
|
154
|
+
|
|
155
|
+
Focuses a specific element inside a modal. If `auto` is **true**, the class automatically stores the last active element and manages its restoration later. If `auto` is **false**, the method returns the last active element so the user can handle it manually.
|
|
156
|
+
|
|
157
|
+
#### Parameters
|
|
158
|
+
**Takes parameters as a single object, which are destructured inside the method.**
|
|
159
|
+
|
|
160
|
+
- **`modalKey: string;`** Unique modal identifier.
|
|
161
|
+
- **`firstFocusableLm: HTMLElement;`** Element to receive focus.
|
|
162
|
+
- **`lastFocusedLm?: HTMLElement | null;`** *(optional)* Stores a custom element as the last focused. Defaults to **document.activeElement**.
|
|
163
|
+
- **`auto?: boolean;`** *(optional)* Defaults to **true**. If **false**, focus is returned but not stored for restoration. Can be used with truthy or falsy values as well.
|
|
164
|
+
|
|
165
|
+
Returns `HTMLElement | void`
|
|
166
|
+
|
|
167
|
+
### restoreFocus()
|
|
168
|
+
Restores focus to the element that was active before the modal opened.
|
|
169
|
+
|
|
170
|
+
#### Parameters
|
|
171
|
+
**Takes parameters as a single object, which are destructured inside the method.**
|
|
172
|
+
|
|
173
|
+
- **`modalKey: string;`** Unique modal identifier.
|
|
174
|
+
- **`lastFocusedLm?: HTMLElement | null;`** *(optional)* Custom element to restore focus to if auto is **false**.
|
|
175
|
+
- **`auto?: boolean;`** *(optional)* Defaults to **true**. If **false**, uses lastFocusedLm to restore focus instead of the stored one.
|
|
176
|
+
|
|
177
|
+
Returns `void`
|
|
178
|
+
|
|
179
|
+
### clearDocumentBodyEvents()
|
|
180
|
+
Clears any leftover document body event listeners.
|
|
181
|
+
|
|
182
|
+
Returns `void`
|
|
183
|
+
|
|
184
|
+
### clearActiveModals()
|
|
185
|
+
Resets the active modal stack.
|
|
186
|
+
|
|
187
|
+
Returns `void`
|
|
188
|
+
|
|
189
|
+
### clearFocusRegistry()
|
|
190
|
+
Clears stored focus references.
|
|
191
|
+
|
|
192
|
+
Returns `void`
|
|
193
|
+
|
|
194
|
+
### reset()
|
|
195
|
+
Combines **clearDocumentBodyEvents()**, **clearActiveModals()**, **clearFocusRegistry()** for a full cleanup.
|
|
196
|
+
|
|
197
|
+
Returns `void`
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vanilla-aria-modals",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Framework-agnostic utility for managing accessibility in modals or modal-like UIs, including modal stacking, focus management, and closing via Escape key or outside click.",
|
|
5
|
+
"main": "src/ModalHandler.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/angelvalentino/vanilla-aria-modals.git"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"modal",
|
|
15
|
+
"accessibility",
|
|
16
|
+
"aria",
|
|
17
|
+
"focus-trapping",
|
|
18
|
+
"keyboard",
|
|
19
|
+
"dialog",
|
|
20
|
+
"a11y",
|
|
21
|
+
"vanilla-js",
|
|
22
|
+
"ui",
|
|
23
|
+
"frontend",
|
|
24
|
+
"javascript"
|
|
25
|
+
],
|
|
26
|
+
"author": "Angel Valentino <angelvalentino294@gmail.com> (https://angelvalentino.dev)",
|
|
27
|
+
"license": "ISC",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/angelvalentino/vanilla-aria-modals/issues"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://github.com/angelvalentino/vanilla-aria-modals#readme",
|
|
32
|
+
"type": "module"
|
|
33
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export default class ModalHandler {
|
|
2
|
+
constructor();
|
|
3
|
+
|
|
4
|
+
setDebug(bool: boolean): void;
|
|
5
|
+
|
|
6
|
+
clearDocumentBodyEvents(): void;
|
|
7
|
+
|
|
8
|
+
clearActiveModals(): void;
|
|
9
|
+
|
|
10
|
+
clearFocusRegistry(): void;
|
|
11
|
+
|
|
12
|
+
reset(): void;
|
|
13
|
+
|
|
14
|
+
addA11yEvents(options: {
|
|
15
|
+
modalKey: string;
|
|
16
|
+
modalLm?: HTMLElement | null;
|
|
17
|
+
modalLmOuterLimits?: HTMLElement | null;
|
|
18
|
+
closeLms?: HTMLElement[] | null;
|
|
19
|
+
exemptLms?: HTMLElement[];
|
|
20
|
+
closeHandler: () => void;
|
|
21
|
+
}): void;
|
|
22
|
+
|
|
23
|
+
removeA11yEvents(options: {
|
|
24
|
+
modalKey: string;
|
|
25
|
+
modalLm?: HTMLElement | null;
|
|
26
|
+
closeLms?: HTMLElement[] | null;
|
|
27
|
+
}): void;
|
|
28
|
+
|
|
29
|
+
addFocus(options: {
|
|
30
|
+
modalKey: string;
|
|
31
|
+
firstFocusableLm: HTMLElement;
|
|
32
|
+
lastFocusedLm?: HTMLElement | null;
|
|
33
|
+
auto?: boolean;
|
|
34
|
+
}): HTMLElement | void;
|
|
35
|
+
|
|
36
|
+
restoreFocus(options: {
|
|
37
|
+
modalKey: string;
|
|
38
|
+
lastFocusedLm?: HTMLElement | null;
|
|
39
|
+
auto?: boolean;
|
|
40
|
+
}): void;
|
|
41
|
+
}
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
export default class ModalHandler {
|
|
2
|
+
#eventsHandler;
|
|
3
|
+
#activeModals;
|
|
4
|
+
#focusHandler;
|
|
5
|
+
#debug;
|
|
6
|
+
|
|
7
|
+
constructor() {
|
|
8
|
+
if (ModalHandler.instance) return ModalHandler.instance;
|
|
9
|
+
ModalHandler.instance = this;
|
|
10
|
+
this.#eventsHandler = {};
|
|
11
|
+
this.#activeModals = [];
|
|
12
|
+
this.#focusHandler = {};
|
|
13
|
+
this.#debug = false;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
setDebug(bool) {
|
|
17
|
+
this.#debug = Boolean(bool);
|
|
18
|
+
console.info(`[ModalHandler]: Debug mode ${this.#debug ? 'ON' : 'OFF'}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
#isActiveModal(modalKey) {
|
|
22
|
+
const modals = this.#activeModals;
|
|
23
|
+
return modals.length && modals[modals.length - 1] === modalKey;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
#registerModal(modalKey) {
|
|
27
|
+
if (this.#activeModals.includes(modalKey)) {
|
|
28
|
+
console.warn(`[ModalHandler]: Modal with key "${modalKey}" is already registered. Skipping.`);
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
this.#activeModals.push(modalKey);
|
|
33
|
+
|
|
34
|
+
if (this.#debug) {
|
|
35
|
+
console.log(`[ModalHandler][DEBUG]: Register modal with key => "${modalKey}"`);
|
|
36
|
+
console.log('[ModalHandler][DEBUG]: Active modal stack => ', this.#activeModals);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#unregisterModal(modalKey) {
|
|
43
|
+
if (!this.#activeModals.includes(modalKey)) {
|
|
44
|
+
console.warn(`[ModalHandler]: Modal with key "${modalKey}" was not registered. Nothing to remove.`);
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (this.#debug) {
|
|
49
|
+
console.log('[ModalHandler][DEBUG]: Active modal stack before filtering => ', this.#activeModals);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
this.#activeModals = this.#activeModals.filter(key => key !== modalKey);
|
|
53
|
+
|
|
54
|
+
if (this.#debug) {
|
|
55
|
+
console.log(`[ModalHandler][DEBUG]: Unregister modal with key => "${modalKey}"`);
|
|
56
|
+
console.log('[ModalHandler][DEBUG]: Active modal stack after filtering => ', this.#activeModals);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
#trapFocus(e, element) {
|
|
63
|
+
// Select all focusable elements within the given element
|
|
64
|
+
const focusableLms = element.querySelectorAll(`
|
|
65
|
+
a[href]:not([disabled]),
|
|
66
|
+
button:not([disabled]),
|
|
67
|
+
textarea:not([disabled]),
|
|
68
|
+
input:not([disabled]),
|
|
69
|
+
select:not([disabled]),
|
|
70
|
+
[tabindex]:not([tabindex="-1"])
|
|
71
|
+
`);
|
|
72
|
+
// Get the first and last focusable elements
|
|
73
|
+
const firstFocusableLm = focusableLms[0];
|
|
74
|
+
const lastFocusableLm = focusableLms[focusableLms.length - 1];
|
|
75
|
+
|
|
76
|
+
// Check if the Tab key was pressed
|
|
77
|
+
const isTabPressed = (e.key === 'Tab');
|
|
78
|
+
|
|
79
|
+
// Exit if the Tab key was not pressed
|
|
80
|
+
if (!isTabPressed) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (e.shiftKey) /* shift + tab */ {
|
|
85
|
+
if (document.activeElement === firstFocusableLm ) {
|
|
86
|
+
// If 'Shift + Tab' is pressed and focus is on the first element, move focus to the last element
|
|
87
|
+
lastFocusableLm.focus();
|
|
88
|
+
e.preventDefault();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
else /* tab */ {
|
|
92
|
+
if (document.activeElement === lastFocusableLm) {
|
|
93
|
+
// If Tab is pressed and focus is on the last element, move focus to the first element
|
|
94
|
+
firstFocusableLm.focus();
|
|
95
|
+
e.preventDefault();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
#handleTrapFocus(modalLm) {
|
|
101
|
+
return e => {
|
|
102
|
+
this.#trapFocus(e, modalLm);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
#handleEscapeKeyClose(closeHandler) {
|
|
107
|
+
return e => {
|
|
108
|
+
if (e.key === 'Escape') {
|
|
109
|
+
closeHandler(e);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
#handleOutsideClickClose(closeHandler, modalLmOuterLimits, exemptLms = []) {
|
|
115
|
+
return e => {
|
|
116
|
+
const clickedLm = e.target;
|
|
117
|
+
|
|
118
|
+
// Click was inside the modal
|
|
119
|
+
if (modalLmOuterLimits.contains(clickedLm)) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Click was outside the modal
|
|
124
|
+
const isClickOnExempt = exemptLms.some(exemptEl => exemptEl?.contains(clickedLm));
|
|
125
|
+
if (isClickOnExempt) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
closeHandler(e);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
#handleActiveModalClose(modalKey, closeHandler) {
|
|
134
|
+
return e => {
|
|
135
|
+
e.stopPropagation();
|
|
136
|
+
if (!this.#isActiveModal(modalKey)) return;
|
|
137
|
+
|
|
138
|
+
if (this.#debug) {
|
|
139
|
+
console.log(`[ModalHandler][DEBUG]: Close modal with key => "${modalKey}"`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
closeHandler(); // Only close if this is the topmost modal
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
clearDocumentBodyEvents() {
|
|
147
|
+
const documentBodyEvents = this.#eventsHandler.documentBody;
|
|
148
|
+
|
|
149
|
+
if (documentBodyEvents) {
|
|
150
|
+
if (this.#debug) {
|
|
151
|
+
console.log('[ModalHandler][DEBUG]: Stored document body events before clearing => ', documentBodyEvents);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
for (const key in documentBodyEvents) {
|
|
155
|
+
const events = documentBodyEvents[key];
|
|
156
|
+
|
|
157
|
+
events.forEach(eventHandler => {
|
|
158
|
+
document.body.removeEventListener(eventHandler.eventName, eventHandler.callback);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
events.length = 0;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (this.#debug) {
|
|
165
|
+
console.log('[ModalHandler][DEBUG]: Stored document body events after clearing => ', documentBodyEvents);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
if (this.#debug) {
|
|
170
|
+
console.log('[ModalHandler][DEBUG]: No document body events were found to be cleared.');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
clearActiveModals() {
|
|
176
|
+
if (this.#debug) {
|
|
177
|
+
console.log('[ModalHandler][DEBUG]: Active modal stack before clearing => ', this.#activeModals);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
this.#activeModals.length = 0;
|
|
181
|
+
|
|
182
|
+
if (this.#debug) {
|
|
183
|
+
console.log('[ModalHandler][DEBUG]: Active modal stack after clearing => ', this.#activeModals);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
clearFocusRegistry() {
|
|
188
|
+
if (this.#debug) {
|
|
189
|
+
console.log('[ModalHandler][DEBUG]: Focus registry before clearing => ', this.#focusHandler);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
for (const key in this.#focusHandler) {
|
|
193
|
+
delete this.#focusHandler[key];
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (this.#debug) {
|
|
197
|
+
console.log('[ModalHandler][DEBUG]: Focus registry after clearing => ', this.#focusHandler);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
reset() {
|
|
202
|
+
this.clearDocumentBodyEvents();
|
|
203
|
+
this.clearActiveModals();
|
|
204
|
+
this.clearFocusRegistry();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
addA11yEvents({
|
|
208
|
+
modalKey,
|
|
209
|
+
modalLm = null,
|
|
210
|
+
modalLmOuterLimits = null,
|
|
211
|
+
closeLms = null,
|
|
212
|
+
exemptLms = [],
|
|
213
|
+
closeHandler
|
|
214
|
+
}) {
|
|
215
|
+
// Extra guard to protect against event bubbling after modal open
|
|
216
|
+
setTimeout(() => {
|
|
217
|
+
// Register modal key and skip if already registered
|
|
218
|
+
const isNew = this.#registerModal(modalKey);
|
|
219
|
+
if (!isNew) return;
|
|
220
|
+
|
|
221
|
+
// Register event handlers reference
|
|
222
|
+
const handleActiveModalClose = this.#handleActiveModalClose(modalKey, closeHandler);
|
|
223
|
+
const escapeKeyHandler = this.#handleEscapeKeyClose(handleActiveModalClose);
|
|
224
|
+
const outsideClickHandler = this.#handleOutsideClickClose(handleActiveModalClose, modalLmOuterLimits, exemptLms);
|
|
225
|
+
const trapFocusHandler = this.#handleTrapFocus(modalLm);
|
|
226
|
+
|
|
227
|
+
// Attach event listeners
|
|
228
|
+
document.body.addEventListener('keydown', escapeKeyHandler);
|
|
229
|
+
|
|
230
|
+
if (modalLmOuterLimits) {
|
|
231
|
+
document.body.addEventListener('click', outsideClickHandler);
|
|
232
|
+
}
|
|
233
|
+
if (modalLm) {
|
|
234
|
+
modalLm.addEventListener('keydown', trapFocusHandler);
|
|
235
|
+
}
|
|
236
|
+
if (closeLms && Array.isArray(closeLms)) {
|
|
237
|
+
closeLms.forEach(closeLm => {
|
|
238
|
+
closeLm.addEventListener('click', handleActiveModalClose);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Ensure eventsHandler object exists for this modal
|
|
243
|
+
if (!this.#eventsHandler[modalKey]) {
|
|
244
|
+
this.#eventsHandler[modalKey] = {};
|
|
245
|
+
}
|
|
246
|
+
const eventsHandler = this.#eventsHandler[modalKey];
|
|
247
|
+
|
|
248
|
+
// Ensure the documentBody object and array exist for this modal key
|
|
249
|
+
if (!this.#eventsHandler.documentBody) {
|
|
250
|
+
this.#eventsHandler.documentBody = {};
|
|
251
|
+
}
|
|
252
|
+
if (!this.#eventsHandler.documentBody[modalKey]) {
|
|
253
|
+
this.#eventsHandler.documentBody[modalKey] = [];
|
|
254
|
+
}
|
|
255
|
+
const documentEvents = this.#eventsHandler.documentBody[modalKey];
|
|
256
|
+
|
|
257
|
+
// Store event handlers references so they can be removed later
|
|
258
|
+
eventsHandler.escapeKeyHandler = escapeKeyHandler;
|
|
259
|
+
modalLmOuterLimits && (eventsHandler.outsideClickHandler = outsideClickHandler);
|
|
260
|
+
modalLm && (eventsHandler.trapFocusHandler = trapFocusHandler);
|
|
261
|
+
closeLms && (eventsHandler.closeHandler = handleActiveModalClose);
|
|
262
|
+
|
|
263
|
+
// Keep references to body events for SPA view changes,
|
|
264
|
+
// so lingering events can be removed if the modal stays open across re-renders
|
|
265
|
+
documentEvents.push({ eventName: 'keydown', callback: escapeKeyHandler });
|
|
266
|
+
if (modalLmOuterLimits) {
|
|
267
|
+
documentEvents.push({ eventName: 'click', callback: outsideClickHandler });
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
removeA11yEvents({
|
|
273
|
+
modalKey,
|
|
274
|
+
modalLm = null,
|
|
275
|
+
closeLms = null
|
|
276
|
+
}) {
|
|
277
|
+
// Unregister modal key and skip if it wasn't registered
|
|
278
|
+
const isRegistered = this.#unregisterModal(modalKey);
|
|
279
|
+
if (!isRegistered) return;
|
|
280
|
+
|
|
281
|
+
const eventsHandler = this.#eventsHandler[modalKey];
|
|
282
|
+
|
|
283
|
+
// Remove event listeners from elements
|
|
284
|
+
document.body.removeEventListener('keydown', eventsHandler.escapeKeyHandler);
|
|
285
|
+
|
|
286
|
+
if (eventsHandler.outsideClickHandler) {
|
|
287
|
+
document.body.removeEventListener('click', eventsHandler.outsideClickHandler);
|
|
288
|
+
}
|
|
289
|
+
if (modalLm) {
|
|
290
|
+
modalLm.removeEventListener('keydown', eventsHandler.trapFocusHandler);
|
|
291
|
+
}
|
|
292
|
+
if (closeLms && Array.isArray(closeLms)) {
|
|
293
|
+
closeLms.forEach(closeLm => {
|
|
294
|
+
closeLm.removeEventListener('click', eventsHandler.closeHandler);
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Clean up stored handlers
|
|
299
|
+
delete this.#eventsHandler[modalKey];
|
|
300
|
+
const documentEvents = this.#eventsHandler.documentBody[modalKey];
|
|
301
|
+
documentEvents.length = 0;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
addFocus({
|
|
305
|
+
modalKey,
|
|
306
|
+
firstFocusableLm,
|
|
307
|
+
lastFocusedLm = null,
|
|
308
|
+
auto = true
|
|
309
|
+
}) {
|
|
310
|
+
if (auto && Object.hasOwn(this.#focusHandler, modalKey)) {
|
|
311
|
+
console.warn(`[ModalHandler]: Duplicate focus registration for modal "${modalKey}"`);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const lastFocusableLm = lastFocusedLm ? lastFocusedLm : document.activeElement;
|
|
316
|
+
if (auto) this.#focusHandler[modalKey] = lastFocusableLm;
|
|
317
|
+
|
|
318
|
+
// Needs a timeout for keyboard navigation, if not focus is unreliable
|
|
319
|
+
setTimeout(() => {
|
|
320
|
+
firstFocusableLm.focus();
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
if (!auto) return lastFocusableLm;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
restoreFocus({
|
|
327
|
+
modalKey,
|
|
328
|
+
lastFocusedLm = null,
|
|
329
|
+
auto = true
|
|
330
|
+
}) {
|
|
331
|
+
if (auto && !Object.hasOwn(this.#focusHandler, modalKey)) {
|
|
332
|
+
console.warn(`[ModalHandler]: No stored focus for modal "${modalKey}" to restore.`);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const lastFocusableLm = auto ? this.#focusHandler[modalKey] : lastFocusedLm;
|
|
337
|
+
lastFocusableLm.focus();
|
|
338
|
+
|
|
339
|
+
// Clean up the stored focus
|
|
340
|
+
if (auto) {
|
|
341
|
+
delete this.#focusHandler[modalKey];
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|