@destyler/focus-trap 0.0.7-beta.9 → 0.2.0-beta.5

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/dist/index.mjs ADDED
@@ -0,0 +1,424 @@
1
+ import { addDomEvent, getActiveElement, getDocument, getEventTarget, getFocusables, getTabIndex, getTabbables, isDocument, isFocusable, isTabbable, raf } from "@destyler/dom";
2
+
3
+ //#region src/focus-trap.ts
4
+ const isTabEvent = (event) => event.key === "Tab";
5
+ const valueOrHandler = (value, ...params) => typeof value === "function" ? value(...params) : value;
6
+ const isEscapeEvent = (event) => !event.isComposing && event.key === "Escape";
7
+ const delay = (fn) => setTimeout(fn, 0);
8
+ function isSelectableInput(node) {
9
+ return node.localName === "input" && "select" in node && typeof node.select === "function";
10
+ }
11
+ const activeFocusTraps = {
12
+ activateTrap(trapStack, trap) {
13
+ if (trapStack.length > 0) {
14
+ const activeTrap = trapStack[trapStack.length - 1];
15
+ if (activeTrap !== trap) activeTrap.pause();
16
+ }
17
+ const trapIndex = trapStack.indexOf(trap);
18
+ if (trapIndex === -1) trapStack.push(trap);
19
+ else {
20
+ trapStack.splice(trapIndex, 1);
21
+ trapStack.push(trap);
22
+ }
23
+ },
24
+ deactivateTrap(trapStack, trap) {
25
+ const trapIndex = trapStack.indexOf(trap);
26
+ if (trapIndex !== -1) trapStack.splice(trapIndex, 1);
27
+ if (trapStack.length > 0) trapStack[trapStack.length - 1].unpause();
28
+ }
29
+ };
30
+ const sharedTrapStack = [];
31
+ var FocusTrap = class {
32
+ get active() {
33
+ return this.state.active;
34
+ }
35
+ get paused() {
36
+ return this.state.paused;
37
+ }
38
+ constructor(elements, options) {
39
+ this.state = {
40
+ containers: [],
41
+ containerGroups: [],
42
+ tabbableGroups: [],
43
+ nodeFocusedBeforeActivation: null,
44
+ mostRecentlyFocusedNode: null,
45
+ active: false,
46
+ paused: false,
47
+ delayInitialFocusTimer: void 0,
48
+ recentNavEvent: void 0
49
+ };
50
+ this.listenerCleanups = [];
51
+ this.handleFocus = (event) => {
52
+ const target = getEventTarget(event);
53
+ const targetContained = this.findContainerIndex(target, event) >= 0;
54
+ if (targetContained || isDocument(target)) {
55
+ if (targetContained) this.state.mostRecentlyFocusedNode = target;
56
+ } else {
57
+ event.stopImmediatePropagation();
58
+ let nextNode;
59
+ let navAcrossContainers = true;
60
+ if (this.state.mostRecentlyFocusedNode) {
61
+ if (getTabIndex(this.state.mostRecentlyFocusedNode) > 0) {
62
+ const mruContainerIdx = this.findContainerIndex(this.state.mostRecentlyFocusedNode);
63
+ const { tabbableNodes } = this.state.containerGroups[mruContainerIdx];
64
+ if (tabbableNodes.length > 0) {
65
+ const mruTabIdx = tabbableNodes.findIndex((node) => node === this.state.mostRecentlyFocusedNode);
66
+ if (mruTabIdx >= 0) {
67
+ if (this.config.isKeyForward(this.state.recentNavEvent)) {
68
+ if (mruTabIdx + 1 < tabbableNodes.length) {
69
+ nextNode = tabbableNodes[mruTabIdx + 1];
70
+ navAcrossContainers = false;
71
+ }
72
+ } else if (mruTabIdx - 1 >= 0) {
73
+ nextNode = tabbableNodes[mruTabIdx - 1];
74
+ navAcrossContainers = false;
75
+ }
76
+ }
77
+ }
78
+ } else if (!this.state.containerGroups.some((g) => g.tabbableNodes.some((n) => getTabIndex(n) > 0))) navAcrossContainers = false;
79
+ } else navAcrossContainers = false;
80
+ if (navAcrossContainers) nextNode = this.findNextNavNode({
81
+ target: this.state.mostRecentlyFocusedNode,
82
+ isBackward: this.config.isKeyBackward(this.state.recentNavEvent)
83
+ });
84
+ if (nextNode) this.tryFocus(nextNode);
85
+ else this.tryFocus(this.state.mostRecentlyFocusedNode || this.getInitialFocusNode());
86
+ }
87
+ this.state.recentNavEvent = void 0;
88
+ };
89
+ this.handlePointerDown = (event) => {
90
+ const target = getEventTarget(event);
91
+ if (this.findContainerIndex(target, event) >= 0) return;
92
+ if (valueOrHandler(this.config.clickOutsideDeactivates, event)) {
93
+ this.deactivate({ returnFocus: this.config.returnFocusOnDeactivate });
94
+ return;
95
+ }
96
+ if (valueOrHandler(this.config.allowOutsideClick, event)) return;
97
+ event.preventDefault();
98
+ };
99
+ this.handleClick = (event) => {
100
+ const target = getEventTarget(event);
101
+ if (this.findContainerIndex(target, event) >= 0) return;
102
+ if (valueOrHandler(this.config.clickOutsideDeactivates, event)) return;
103
+ if (valueOrHandler(this.config.allowOutsideClick, event)) return;
104
+ event.preventDefault();
105
+ event.stopImmediatePropagation();
106
+ };
107
+ this.handleTabKey = (event) => {
108
+ if (this.config.isKeyForward(event) || this.config.isKeyBackward(event)) {
109
+ this.state.recentNavEvent = event;
110
+ const isBackward = this.config.isKeyBackward(event);
111
+ const destinationNode = this.findNextNavNode({
112
+ event,
113
+ isBackward
114
+ });
115
+ if (!destinationNode) return;
116
+ if (isTabEvent(event)) event.preventDefault();
117
+ this.tryFocus(destinationNode);
118
+ }
119
+ };
120
+ this.handleEscapeKey = (event) => {
121
+ if (isEscapeEvent(event) && valueOrHandler(this.config.escapeDeactivates, event) !== false) {
122
+ event.preventDefault();
123
+ this.deactivate();
124
+ }
125
+ };
126
+ this.setupMutationObserver = () => {
127
+ this._mutationObserver = new (this.doc.defaultView || window).MutationObserver((mutations) => {
128
+ if (mutations.some((mutation) => {
129
+ return Array.from(mutation.removedNodes).includes(this.state.mostRecentlyFocusedNode);
130
+ })) this.tryFocus(this.getInitialFocusNode());
131
+ });
132
+ };
133
+ this.updateObservedNodes = () => {
134
+ this._mutationObserver?.disconnect();
135
+ if (this.state.active && !this.state.paused) this.state.containers.forEach((container) => {
136
+ this._mutationObserver?.observe(container, {
137
+ subtree: true,
138
+ childList: true
139
+ });
140
+ });
141
+ };
142
+ this.getInitialFocusNode = () => {
143
+ let node = this.getNodeForOption("initialFocus", { hasFallback: true });
144
+ if (node === false) return false;
145
+ if (node === void 0 || node && !isFocusable(node)) if (this.findContainerIndex(this.doc.activeElement) >= 0) node = this.doc.activeElement;
146
+ else {
147
+ const firstTabbableGroup = this.state.tabbableGroups[0];
148
+ node = firstTabbableGroup && firstTabbableGroup.firstTabbableNode || this.getNodeForOption("fallbackFocus");
149
+ }
150
+ else if (node === null) node = this.getNodeForOption("fallbackFocus");
151
+ if (!node) throw new Error("Your focus-trap needs to have at least one focusable element");
152
+ if (!node.isConnected) node = this.getNodeForOption("fallbackFocus");
153
+ return node;
154
+ };
155
+ this.tryFocus = (node) => {
156
+ if (node === false) return;
157
+ if (node === getActiveElement(this.doc)) return;
158
+ if (!node || !node.focus) {
159
+ this.tryFocus(this.getInitialFocusNode());
160
+ return;
161
+ }
162
+ node.focus({ preventScroll: !!this.config.preventScroll });
163
+ this.state.mostRecentlyFocusedNode = node;
164
+ if (isSelectableInput(node)) node.select();
165
+ };
166
+ this.deactivate = (deactivateOptions) => {
167
+ if (!this.state.active) return this;
168
+ const options$1 = {
169
+ onDeactivate: this.config.onDeactivate,
170
+ onPostDeactivate: this.config.onPostDeactivate,
171
+ checkCanReturnFocus: this.config.checkCanReturnFocus,
172
+ ...deactivateOptions
173
+ };
174
+ clearTimeout(this.state.delayInitialFocusTimer);
175
+ this.state.delayInitialFocusTimer = void 0;
176
+ this.removeListeners();
177
+ this.state.active = false;
178
+ this.state.paused = false;
179
+ this.updateObservedNodes();
180
+ activeFocusTraps.deactivateTrap(this.trapStack, this);
181
+ const onDeactivate = this.getOption(options$1, "onDeactivate");
182
+ const onPostDeactivate = this.getOption(options$1, "onPostDeactivate");
183
+ const checkCanReturnFocus = this.getOption(options$1, "checkCanReturnFocus");
184
+ const returnFocus = this.getOption(options$1, "returnFocus", "returnFocusOnDeactivate");
185
+ onDeactivate?.();
186
+ const finishDeactivation = () => {
187
+ delay(() => {
188
+ if (returnFocus) {
189
+ const returnFocusNode = this.getReturnFocusNode(this.state.nodeFocusedBeforeActivation);
190
+ this.tryFocus(returnFocusNode);
191
+ }
192
+ onPostDeactivate?.();
193
+ });
194
+ };
195
+ if (returnFocus && checkCanReturnFocus) {
196
+ checkCanReturnFocus(this.getReturnFocusNode(this.state.nodeFocusedBeforeActivation)).then(finishDeactivation, finishDeactivation);
197
+ return this;
198
+ }
199
+ finishDeactivation();
200
+ return this;
201
+ };
202
+ this.pause = (pauseOptions) => {
203
+ if (this.state.paused || !this.state.active) return this;
204
+ const onPause = this.getOption(pauseOptions, "onPause");
205
+ const onPostPause = this.getOption(pauseOptions, "onPostPause");
206
+ this.state.paused = true;
207
+ onPause?.();
208
+ this.removeListeners();
209
+ this.updateObservedNodes();
210
+ onPostPause?.();
211
+ return this;
212
+ };
213
+ this.unpause = (unpauseOptions) => {
214
+ if (!this.state.paused || !this.state.active) return this;
215
+ const onUnpause = this.getOption(unpauseOptions, "onUnpause");
216
+ const onPostUnpause = this.getOption(unpauseOptions, "onPostUnpause");
217
+ this.state.paused = false;
218
+ onUnpause?.();
219
+ this.updateTabbableNodes();
220
+ this.addListeners();
221
+ this.updateObservedNodes();
222
+ onPostUnpause?.();
223
+ return this;
224
+ };
225
+ this.updateContainerElements = (containerElements) => {
226
+ this.state.containers = Array.isArray(containerElements) ? containerElements.filter(Boolean) : [containerElements].filter(Boolean);
227
+ if (this.state.active) this.updateTabbableNodes();
228
+ this.updateObservedNodes();
229
+ return this;
230
+ };
231
+ this.getReturnFocusNode = (previousActiveElement) => {
232
+ const node = this.getNodeForOption("setReturnFocus", { params: [previousActiveElement] });
233
+ return node || (node === false ? false : previousActiveElement);
234
+ };
235
+ this.getOption = (configOverrideOptions, optionName, configOptionName) => {
236
+ return configOverrideOptions && configOverrideOptions[optionName] !== void 0 ? configOverrideOptions[optionName] : this.config[configOptionName || optionName];
237
+ };
238
+ this.getNodeForOption = (optionName, { hasFallback = false, params = [] } = {}) => {
239
+ let optionValue = this.config[optionName];
240
+ if (typeof optionValue === "function") optionValue = optionValue(...params);
241
+ if (optionValue === true) optionValue = void 0;
242
+ if (!optionValue) {
243
+ if (optionValue === void 0 || optionValue === false) return optionValue;
244
+ throw new Error(`\`${optionName}\` was specified but was not a node, or did not return a node`);
245
+ }
246
+ let node = optionValue;
247
+ if (typeof optionValue === "string") {
248
+ try {
249
+ node = this.doc.querySelector(optionValue);
250
+ } catch (err) {
251
+ throw new Error(`\`${optionName}\` appears to be an invalid selector; error="${err.message}"`);
252
+ }
253
+ if (!node) {
254
+ if (!hasFallback) throw new Error(`\`${optionName}\` as selector refers to no known node`);
255
+ }
256
+ }
257
+ return node;
258
+ };
259
+ this.findNextNavNode = (opts) => {
260
+ const { event, isBackward = false } = opts;
261
+ const target = opts.target || getEventTarget(event);
262
+ this.updateTabbableNodes();
263
+ let destinationNode = null;
264
+ if (this.state.tabbableGroups.length > 0) {
265
+ const containerIndex = this.findContainerIndex(target, event);
266
+ const containerGroup = containerIndex >= 0 ? this.state.containerGroups[containerIndex] : void 0;
267
+ if (containerIndex < 0) if (isBackward) destinationNode = this.state.tabbableGroups[this.state.tabbableGroups.length - 1].lastTabbableNode;
268
+ else destinationNode = this.state.tabbableGroups[0].firstTabbableNode;
269
+ else if (isBackward) {
270
+ let startOfGroupIndex = this.state.tabbableGroups.findIndex(({ firstTabbableNode }) => target === firstTabbableNode);
271
+ if (startOfGroupIndex < 0 && (containerGroup?.container === target || isFocusable(target) && !isTabbable(target) && !containerGroup?.nextTabbableNode(target, false))) startOfGroupIndex = containerIndex;
272
+ if (startOfGroupIndex >= 0) {
273
+ const destinationGroupIndex = startOfGroupIndex === 0 ? this.state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
274
+ const destinationGroup = this.state.tabbableGroups[destinationGroupIndex];
275
+ destinationNode = getTabIndex(target) >= 0 ? destinationGroup.lastTabbableNode : destinationGroup.lastDomTabbableNode;
276
+ } else if (!isTabEvent(event)) destinationNode = containerGroup?.nextTabbableNode(target, false);
277
+ } else {
278
+ let lastOfGroupIndex = this.state.tabbableGroups.findIndex(({ lastTabbableNode }) => target === lastTabbableNode);
279
+ if (lastOfGroupIndex < 0 && (containerGroup?.container === target || isFocusable(target) && !isTabbable(target) && !containerGroup?.nextTabbableNode(target))) lastOfGroupIndex = containerIndex;
280
+ if (lastOfGroupIndex >= 0) {
281
+ const destinationGroupIndex = lastOfGroupIndex === this.state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;
282
+ const destinationGroup = this.state.tabbableGroups[destinationGroupIndex];
283
+ destinationNode = getTabIndex(target) >= 0 ? destinationGroup.firstTabbableNode : destinationGroup.firstDomTabbableNode;
284
+ } else if (!isTabEvent(event)) destinationNode = containerGroup?.nextTabbableNode(target);
285
+ }
286
+ } else destinationNode = this.getNodeForOption("fallbackFocus");
287
+ return destinationNode;
288
+ };
289
+ this.trapStack = options.trapStack || sharedTrapStack;
290
+ const config = {
291
+ returnFocusOnDeactivate: true,
292
+ escapeDeactivates: true,
293
+ delayInitialFocus: true,
294
+ isKeyForward(e) {
295
+ return isTabEvent(e) && !e.shiftKey;
296
+ },
297
+ isKeyBackward(e) {
298
+ return isTabEvent(e) && e.shiftKey;
299
+ },
300
+ ...options
301
+ };
302
+ this.doc = config.document || getDocument(Array.isArray(elements) ? elements[0] : elements);
303
+ this.config = config;
304
+ this.updateContainerElements(elements);
305
+ this.setupMutationObserver();
306
+ }
307
+ findContainerIndex(element, event) {
308
+ const composedPath = typeof event?.composedPath === "function" ? event.composedPath() : void 0;
309
+ return this.state.containerGroups.findIndex(({ container, tabbableNodes }) => container.contains(element) || composedPath?.includes(container) || tabbableNodes.find((node) => node === element));
310
+ }
311
+ updateTabbableNodes() {
312
+ this.state.containerGroups = this.state.containers.map((container) => {
313
+ const tabbableNodes = getTabbables(container);
314
+ const focusableNodes = getFocusables(container);
315
+ const firstTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[0] : void 0;
316
+ const lastTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : void 0;
317
+ const firstDomTabbableNode = focusableNodes.find((node) => isTabbable(node));
318
+ const lastDomTabbableNode = focusableNodes.slice().reverse().find((node) => isTabbable(node));
319
+ const posTabIndexesFound = !!tabbableNodes.find((node) => getTabIndex(node) > 0);
320
+ function nextTabbableNode(node, forward = true) {
321
+ const nodeIdx = tabbableNodes.indexOf(node);
322
+ if (nodeIdx < 0) {
323
+ if (forward) return focusableNodes.slice(focusableNodes.indexOf(node) + 1).find((el) => isTabbable(el));
324
+ return focusableNodes.slice(0, focusableNodes.indexOf(node)).reverse().find((el) => isTabbable(el));
325
+ }
326
+ return tabbableNodes[nodeIdx + (forward ? 1 : -1)];
327
+ }
328
+ return {
329
+ container,
330
+ tabbableNodes,
331
+ focusableNodes,
332
+ posTabIndexesFound,
333
+ firstTabbableNode,
334
+ lastTabbableNode,
335
+ firstDomTabbableNode,
336
+ lastDomTabbableNode,
337
+ nextTabbableNode
338
+ };
339
+ });
340
+ this.state.tabbableGroups = this.state.containerGroups.filter((group) => group.tabbableNodes.length > 0);
341
+ if (this.state.tabbableGroups.length <= 0 && !this.getNodeForOption("fallbackFocus")) throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");
342
+ if (this.state.containerGroups.find((g) => g.posTabIndexesFound) && this.state.containerGroups.length > 1) throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.");
343
+ }
344
+ addListeners() {
345
+ if (!this.state.active) return;
346
+ activeFocusTraps.activateTrap(this.trapStack, this);
347
+ this.state.delayInitialFocusTimer = this.config.delayInitialFocus ? delay(() => {
348
+ this.tryFocus(this.getInitialFocusNode());
349
+ }) : this.tryFocus(this.getInitialFocusNode());
350
+ this.listenerCleanups.push(addDomEvent(this.doc, "focusin", this.handleFocus, true), addDomEvent(this.doc, "mousedown", this.handlePointerDown, {
351
+ capture: true,
352
+ passive: false
353
+ }), addDomEvent(this.doc, "touchstart", this.handlePointerDown, {
354
+ capture: true,
355
+ passive: false
356
+ }), addDomEvent(this.doc, "click", this.handleClick, {
357
+ capture: true,
358
+ passive: false
359
+ }), addDomEvent(this.doc, "keydown", this.handleTabKey, {
360
+ capture: true,
361
+ passive: false
362
+ }), addDomEvent(this.doc, "keydown", this.handleEscapeKey));
363
+ return this;
364
+ }
365
+ removeListeners() {
366
+ if (!this.state.active) return;
367
+ this.listenerCleanups.forEach((cleanup) => cleanup());
368
+ this.listenerCleanups = [];
369
+ return this;
370
+ }
371
+ activate(activateOptions) {
372
+ if (this.state.active) return this;
373
+ const onActivate = this.getOption(activateOptions, "onActivate");
374
+ const onPostActivate = this.getOption(activateOptions, "onPostActivate");
375
+ const checkCanFocusTrap = this.getOption(activateOptions, "checkCanFocusTrap");
376
+ if (!checkCanFocusTrap) this.updateTabbableNodes();
377
+ this.state.active = true;
378
+ this.state.paused = false;
379
+ this.state.nodeFocusedBeforeActivation = this.doc.activeElement || null;
380
+ onActivate?.();
381
+ const finishActivation = () => {
382
+ if (checkCanFocusTrap) this.updateTabbableNodes();
383
+ this.addListeners();
384
+ this.updateObservedNodes();
385
+ onPostActivate?.();
386
+ };
387
+ if (checkCanFocusTrap) {
388
+ checkCanFocusTrap(this.state.containers.concat()).then(finishActivation, finishActivation);
389
+ return this;
390
+ }
391
+ finishActivation();
392
+ return this;
393
+ }
394
+ };
395
+
396
+ //#endregion
397
+ //#region index.ts
398
+ function trapFocus(el, options = {}) {
399
+ let trap;
400
+ const cleanup = raf(() => {
401
+ const contentEl = typeof el === "function" ? el() : el;
402
+ if (!contentEl) return;
403
+ trap = new FocusTrap(contentEl, {
404
+ escapeDeactivates: false,
405
+ allowOutsideClick: true,
406
+ preventScroll: true,
407
+ returnFocusOnDeactivate: true,
408
+ delayInitialFocus: false,
409
+ fallbackFocus: contentEl,
410
+ ...options,
411
+ document: getDocument(contentEl)
412
+ });
413
+ try {
414
+ trap.activate();
415
+ } catch {}
416
+ });
417
+ return function destroy() {
418
+ trap?.deactivate();
419
+ cleanup();
420
+ };
421
+ }
422
+
423
+ //#endregion
424
+ export { FocusTrap, trapFocus };
package/package.json CHANGED
@@ -1,22 +1,31 @@
1
1
  {
2
2
  "name": "@destyler/focus-trap",
3
3
  "type": "module",
4
- "version": "0.0.7-beta.9",
4
+ "version": "0.2.0-beta.5",
5
5
  "description": "Focus trap util",
6
6
  "author": "Elone Hoo <elonehoo@gmail.com>",
7
7
  "license": "MIT",
8
+ "homepage": "https://github.com/destyler/destyler",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/destyler/destyler.git",
12
+ "directory": "packages/shareds/focus-trap"
13
+ },
8
14
  "exports": {
9
- ".": "./dist/index.js"
15
+ ".": "./dist/index.mjs"
10
16
  },
11
- "main": "dist/index.js",
12
- "module": "dist/index.js",
13
- "types": "dist/index.d.ts",
17
+ "main": "dist/index.mjs",
18
+ "module": "dist/index.mjs",
19
+ "types": "dist/index.d.mts",
14
20
  "files": [
15
21
  "*.d.ts",
16
22
  "dist"
17
23
  ],
18
24
  "dependencies": {
19
- "@destyler/dom": "0.0.7-beta.9"
25
+ "@destyler/dom": "0.2.0-beta.5"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
20
29
  },
21
30
  "scripts": {
22
31
  "clear": "rimraf ./dist",
package/dist/index.js DELETED
@@ -1,433 +0,0 @@
1
- import { addDomEvent, getActiveElement, getDocument, getEventTarget, getFocusables, getTabIndex, getTabbables, isDocument, isFocusable, isTabbable, raf } from "@destyler/dom";
2
-
3
- //#region src/focus-trap.ts
4
- const isTabEvent = (event) => event.key === "Tab";
5
- const valueOrHandler = (value, ...params) => typeof value === "function" ? value(...params) : value;
6
- const isEscapeEvent = (event) => !event.isComposing && event.key === "Escape";
7
- const delay = (fn) => setTimeout(fn, 0);
8
- function isSelectableInput(node) {
9
- return node.localName === "input" && "select" in node && typeof node.select === "function";
10
- }
11
- const activeFocusTraps = {
12
- activateTrap(trapStack, trap) {
13
- if (trapStack.length > 0) {
14
- const activeTrap = trapStack[trapStack.length - 1];
15
- if (activeTrap !== trap) activeTrap.pause();
16
- }
17
- const trapIndex = trapStack.indexOf(trap);
18
- if (trapIndex === -1) trapStack.push(trap);
19
- else {
20
- trapStack.splice(trapIndex, 1);
21
- trapStack.push(trap);
22
- }
23
- },
24
- deactivateTrap(trapStack, trap) {
25
- const trapIndex = trapStack.indexOf(trap);
26
- if (trapIndex !== -1) trapStack.splice(trapIndex, 1);
27
- if (trapStack.length > 0) trapStack[trapStack.length - 1].unpause();
28
- }
29
- };
30
- const sharedTrapStack = [];
31
- var FocusTrap = class {
32
- trapStack;
33
- config;
34
- doc;
35
- state = {
36
- containers: [],
37
- containerGroups: [],
38
- tabbableGroups: [],
39
- nodeFocusedBeforeActivation: null,
40
- mostRecentlyFocusedNode: null,
41
- active: false,
42
- paused: false,
43
- delayInitialFocusTimer: void 0,
44
- recentNavEvent: void 0
45
- };
46
- get active() {
47
- return this.state.active;
48
- }
49
- get paused() {
50
- return this.state.paused;
51
- }
52
- constructor(elements, options) {
53
- this.trapStack = options.trapStack || sharedTrapStack;
54
- const config = {
55
- returnFocusOnDeactivate: true,
56
- escapeDeactivates: true,
57
- delayInitialFocus: true,
58
- isKeyForward(e) {
59
- return isTabEvent(e) && !e.shiftKey;
60
- },
61
- isKeyBackward(e) {
62
- return isTabEvent(e) && e.shiftKey;
63
- },
64
- ...options
65
- };
66
- this.doc = config.document || getDocument(Array.isArray(elements) ? elements[0] : elements);
67
- this.config = config;
68
- this.updateContainerElements(elements);
69
- this.setupMutationObserver();
70
- }
71
- findContainerIndex(element, event) {
72
- const composedPath = typeof event?.composedPath === "function" ? event.composedPath() : void 0;
73
- return this.state.containerGroups.findIndex(({ container, tabbableNodes }) => container.contains(element) || composedPath?.includes(container) || tabbableNodes.find((node) => node === element));
74
- }
75
- updateTabbableNodes() {
76
- this.state.containerGroups = this.state.containers.map((container) => {
77
- const tabbableNodes = getTabbables(container);
78
- const focusableNodes = getFocusables(container);
79
- const firstTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[0] : void 0;
80
- const lastTabbableNode = tabbableNodes.length > 0 ? tabbableNodes[tabbableNodes.length - 1] : void 0;
81
- const firstDomTabbableNode = focusableNodes.find((node) => isTabbable(node));
82
- const lastDomTabbableNode = focusableNodes.slice().reverse().find((node) => isTabbable(node));
83
- const posTabIndexesFound = !!tabbableNodes.find((node) => getTabIndex(node) > 0);
84
- function nextTabbableNode(node, forward = true) {
85
- const nodeIdx = tabbableNodes.indexOf(node);
86
- if (nodeIdx < 0) {
87
- if (forward) return focusableNodes.slice(focusableNodes.indexOf(node) + 1).find((el) => isTabbable(el));
88
- return focusableNodes.slice(0, focusableNodes.indexOf(node)).reverse().find((el) => isTabbable(el));
89
- }
90
- return tabbableNodes[nodeIdx + (forward ? 1 : -1)];
91
- }
92
- return {
93
- container,
94
- tabbableNodes,
95
- focusableNodes,
96
- posTabIndexesFound,
97
- firstTabbableNode,
98
- lastTabbableNode,
99
- firstDomTabbableNode,
100
- lastDomTabbableNode,
101
- nextTabbableNode
102
- };
103
- });
104
- this.state.tabbableGroups = this.state.containerGroups.filter((group) => group.tabbableNodes.length > 0);
105
- if (this.state.tabbableGroups.length <= 0 && !this.getNodeForOption("fallbackFocus")) throw new Error("Your focus-trap must have at least one container with at least one tabbable node in it at all times");
106
- if (this.state.containerGroups.find((g) => g.posTabIndexesFound) && this.state.containerGroups.length > 1) throw new Error("At least one node with a positive tabindex was found in one of your focus-trap's multiple containers. Positive tabindexes are only supported in single-container focus-traps.");
107
- }
108
- listenerCleanups = [];
109
- addListeners() {
110
- if (!this.state.active) return;
111
- activeFocusTraps.activateTrap(this.trapStack, this);
112
- this.state.delayInitialFocusTimer = this.config.delayInitialFocus ? delay(() => {
113
- this.tryFocus(this.getInitialFocusNode());
114
- }) : this.tryFocus(this.getInitialFocusNode());
115
- this.listenerCleanups.push(addDomEvent(this.doc, "focusin", this.handleFocus, true), addDomEvent(this.doc, "mousedown", this.handlePointerDown, {
116
- capture: true,
117
- passive: false
118
- }), addDomEvent(this.doc, "touchstart", this.handlePointerDown, {
119
- capture: true,
120
- passive: false
121
- }), addDomEvent(this.doc, "click", this.handleClick, {
122
- capture: true,
123
- passive: false
124
- }), addDomEvent(this.doc, "keydown", this.handleTabKey, {
125
- capture: true,
126
- passive: false
127
- }), addDomEvent(this.doc, "keydown", this.handleEscapeKey));
128
- return this;
129
- }
130
- removeListeners() {
131
- if (!this.state.active) return;
132
- this.listenerCleanups.forEach((cleanup) => cleanup());
133
- this.listenerCleanups = [];
134
- return this;
135
- }
136
- handleFocus = (event) => {
137
- const target = getEventTarget(event);
138
- const targetContained = this.findContainerIndex(target, event) >= 0;
139
- if (targetContained || isDocument(target)) {
140
- if (targetContained) this.state.mostRecentlyFocusedNode = target;
141
- } else {
142
- event.stopImmediatePropagation();
143
- let nextNode;
144
- let navAcrossContainers = true;
145
- if (this.state.mostRecentlyFocusedNode) {
146
- if (getTabIndex(this.state.mostRecentlyFocusedNode) > 0) {
147
- const mruContainerIdx = this.findContainerIndex(this.state.mostRecentlyFocusedNode);
148
- const { tabbableNodes } = this.state.containerGroups[mruContainerIdx];
149
- if (tabbableNodes.length > 0) {
150
- const mruTabIdx = tabbableNodes.findIndex((node) => node === this.state.mostRecentlyFocusedNode);
151
- if (mruTabIdx >= 0) {
152
- if (this.config.isKeyForward(this.state.recentNavEvent)) {
153
- if (mruTabIdx + 1 < tabbableNodes.length) {
154
- nextNode = tabbableNodes[mruTabIdx + 1];
155
- navAcrossContainers = false;
156
- }
157
- } else if (mruTabIdx - 1 >= 0) {
158
- nextNode = tabbableNodes[mruTabIdx - 1];
159
- navAcrossContainers = false;
160
- }
161
- }
162
- }
163
- } else if (!this.state.containerGroups.some((g) => g.tabbableNodes.some((n) => getTabIndex(n) > 0))) navAcrossContainers = false;
164
- } else navAcrossContainers = false;
165
- if (navAcrossContainers) nextNode = this.findNextNavNode({
166
- target: this.state.mostRecentlyFocusedNode,
167
- isBackward: this.config.isKeyBackward(this.state.recentNavEvent)
168
- });
169
- if (nextNode) this.tryFocus(nextNode);
170
- else this.tryFocus(this.state.mostRecentlyFocusedNode || this.getInitialFocusNode());
171
- }
172
- this.state.recentNavEvent = void 0;
173
- };
174
- handlePointerDown = (event) => {
175
- const target = getEventTarget(event);
176
- if (this.findContainerIndex(target, event) >= 0) return;
177
- if (valueOrHandler(this.config.clickOutsideDeactivates, event)) {
178
- this.deactivate({ returnFocus: this.config.returnFocusOnDeactivate });
179
- return;
180
- }
181
- if (valueOrHandler(this.config.allowOutsideClick, event)) return;
182
- event.preventDefault();
183
- };
184
- handleClick = (event) => {
185
- const target = getEventTarget(event);
186
- if (this.findContainerIndex(target, event) >= 0) return;
187
- if (valueOrHandler(this.config.clickOutsideDeactivates, event)) return;
188
- if (valueOrHandler(this.config.allowOutsideClick, event)) return;
189
- event.preventDefault();
190
- event.stopImmediatePropagation();
191
- };
192
- handleTabKey = (event) => {
193
- if (this.config.isKeyForward(event) || this.config.isKeyBackward(event)) {
194
- this.state.recentNavEvent = event;
195
- const isBackward = this.config.isKeyBackward(event);
196
- const destinationNode = this.findNextNavNode({
197
- event,
198
- isBackward
199
- });
200
- if (!destinationNode) return;
201
- if (isTabEvent(event)) event.preventDefault();
202
- this.tryFocus(destinationNode);
203
- }
204
- };
205
- handleEscapeKey = (event) => {
206
- if (isEscapeEvent(event) && valueOrHandler(this.config.escapeDeactivates, event) !== false) {
207
- event.preventDefault();
208
- this.deactivate();
209
- }
210
- };
211
- _mutationObserver;
212
- setupMutationObserver = () => {
213
- const win = this.doc.defaultView || window;
214
- this._mutationObserver = new win.MutationObserver((mutations) => {
215
- const isFocusedNodeRemoved = mutations.some((mutation) => {
216
- const removedNodes = Array.from(mutation.removedNodes);
217
- return removedNodes.includes(this.state.mostRecentlyFocusedNode);
218
- });
219
- if (isFocusedNodeRemoved) this.tryFocus(this.getInitialFocusNode());
220
- });
221
- };
222
- updateObservedNodes = () => {
223
- this._mutationObserver?.disconnect();
224
- if (this.state.active && !this.state.paused) this.state.containers.forEach((container) => {
225
- this._mutationObserver?.observe(container, {
226
- subtree: true,
227
- childList: true
228
- });
229
- });
230
- };
231
- getInitialFocusNode = () => {
232
- let node = this.getNodeForOption("initialFocus", { hasFallback: true });
233
- if (node === false) return false;
234
- if (node === void 0 || node && !isFocusable(node)) if (this.findContainerIndex(this.doc.activeElement) >= 0) node = this.doc.activeElement;
235
- else {
236
- const firstTabbableGroup = this.state.tabbableGroups[0];
237
- const firstTabbableNode = firstTabbableGroup && firstTabbableGroup.firstTabbableNode;
238
- node = firstTabbableNode || this.getNodeForOption("fallbackFocus");
239
- }
240
- else if (node === null) node = this.getNodeForOption("fallbackFocus");
241
- if (!node) throw new Error("Your focus-trap needs to have at least one focusable element");
242
- if (!node.isConnected) node = this.getNodeForOption("fallbackFocus");
243
- return node;
244
- };
245
- tryFocus = (node) => {
246
- if (node === false) return;
247
- if (node === getActiveElement(this.doc)) return;
248
- if (!node || !node.focus) {
249
- this.tryFocus(this.getInitialFocusNode());
250
- return;
251
- }
252
- node.focus({ preventScroll: !!this.config.preventScroll });
253
- this.state.mostRecentlyFocusedNode = node;
254
- if (isSelectableInput(node)) node.select();
255
- };
256
- activate(activateOptions) {
257
- if (this.state.active) return this;
258
- const onActivate = this.getOption(activateOptions, "onActivate");
259
- const onPostActivate = this.getOption(activateOptions, "onPostActivate");
260
- const checkCanFocusTrap = this.getOption(activateOptions, "checkCanFocusTrap");
261
- if (!checkCanFocusTrap) this.updateTabbableNodes();
262
- this.state.active = true;
263
- this.state.paused = false;
264
- this.state.nodeFocusedBeforeActivation = this.doc.activeElement || null;
265
- onActivate?.();
266
- const finishActivation = () => {
267
- if (checkCanFocusTrap) this.updateTabbableNodes();
268
- this.addListeners();
269
- this.updateObservedNodes();
270
- onPostActivate?.();
271
- };
272
- if (checkCanFocusTrap) {
273
- checkCanFocusTrap(this.state.containers.concat()).then(finishActivation, finishActivation);
274
- return this;
275
- }
276
- finishActivation();
277
- return this;
278
- }
279
- deactivate = (deactivateOptions) => {
280
- if (!this.state.active) return this;
281
- const options = {
282
- onDeactivate: this.config.onDeactivate,
283
- onPostDeactivate: this.config.onPostDeactivate,
284
- checkCanReturnFocus: this.config.checkCanReturnFocus,
285
- ...deactivateOptions
286
- };
287
- clearTimeout(this.state.delayInitialFocusTimer);
288
- this.state.delayInitialFocusTimer = void 0;
289
- this.removeListeners();
290
- this.state.active = false;
291
- this.state.paused = false;
292
- this.updateObservedNodes();
293
- activeFocusTraps.deactivateTrap(this.trapStack, this);
294
- const onDeactivate = this.getOption(options, "onDeactivate");
295
- const onPostDeactivate = this.getOption(options, "onPostDeactivate");
296
- const checkCanReturnFocus = this.getOption(options, "checkCanReturnFocus");
297
- const returnFocus = this.getOption(options, "returnFocus", "returnFocusOnDeactivate");
298
- onDeactivate?.();
299
- const finishDeactivation = () => {
300
- delay(() => {
301
- if (returnFocus) {
302
- const returnFocusNode = this.getReturnFocusNode(this.state.nodeFocusedBeforeActivation);
303
- this.tryFocus(returnFocusNode);
304
- }
305
- onPostDeactivate?.();
306
- });
307
- };
308
- if (returnFocus && checkCanReturnFocus) {
309
- const returnFocusNode = this.getReturnFocusNode(this.state.nodeFocusedBeforeActivation);
310
- checkCanReturnFocus(returnFocusNode).then(finishDeactivation, finishDeactivation);
311
- return this;
312
- }
313
- finishDeactivation();
314
- return this;
315
- };
316
- pause = (pauseOptions) => {
317
- if (this.state.paused || !this.state.active) return this;
318
- const onPause = this.getOption(pauseOptions, "onPause");
319
- const onPostPause = this.getOption(pauseOptions, "onPostPause");
320
- this.state.paused = true;
321
- onPause?.();
322
- this.removeListeners();
323
- this.updateObservedNodes();
324
- onPostPause?.();
325
- return this;
326
- };
327
- unpause = (unpauseOptions) => {
328
- if (!this.state.paused || !this.state.active) return this;
329
- const onUnpause = this.getOption(unpauseOptions, "onUnpause");
330
- const onPostUnpause = this.getOption(unpauseOptions, "onPostUnpause");
331
- this.state.paused = false;
332
- onUnpause?.();
333
- this.updateTabbableNodes();
334
- this.addListeners();
335
- this.updateObservedNodes();
336
- onPostUnpause?.();
337
- return this;
338
- };
339
- updateContainerElements = (containerElements) => {
340
- this.state.containers = Array.isArray(containerElements) ? containerElements.filter(Boolean) : [containerElements].filter(Boolean);
341
- if (this.state.active) this.updateTabbableNodes();
342
- this.updateObservedNodes();
343
- return this;
344
- };
345
- getReturnFocusNode = (previousActiveElement) => {
346
- const node = this.getNodeForOption("setReturnFocus", { params: [previousActiveElement] });
347
- return node || (node === false ? false : previousActiveElement);
348
- };
349
- getOption = (configOverrideOptions, optionName, configOptionName) => {
350
- return configOverrideOptions && configOverrideOptions[optionName] !== void 0 ? configOverrideOptions[optionName] : this.config[configOptionName || optionName];
351
- };
352
- getNodeForOption = (optionName, { hasFallback = false, params = [] } = {}) => {
353
- let optionValue = this.config[optionName];
354
- if (typeof optionValue === "function") optionValue = optionValue(...params);
355
- if (optionValue === true) optionValue = void 0;
356
- if (!optionValue) {
357
- if (optionValue === void 0 || optionValue === false) return optionValue;
358
- throw new Error(`\`${optionName}\` was specified but was not a node, or did not return a node`);
359
- }
360
- let node = optionValue;
361
- if (typeof optionValue === "string") {
362
- try {
363
- node = this.doc.querySelector(optionValue);
364
- } catch (err) {
365
- throw new Error(`\`${optionName}\` appears to be an invalid selector; error="${err.message}"`);
366
- }
367
- if (!node) {
368
- if (!hasFallback) throw new Error(`\`${optionName}\` as selector refers to no known node`);
369
- }
370
- }
371
- return node;
372
- };
373
- findNextNavNode = (opts) => {
374
- const { event, isBackward = false } = opts;
375
- const target = opts.target || getEventTarget(event);
376
- this.updateTabbableNodes();
377
- let destinationNode = null;
378
- if (this.state.tabbableGroups.length > 0) {
379
- const containerIndex = this.findContainerIndex(target, event);
380
- const containerGroup = containerIndex >= 0 ? this.state.containerGroups[containerIndex] : void 0;
381
- if (containerIndex < 0) if (isBackward) destinationNode = this.state.tabbableGroups[this.state.tabbableGroups.length - 1].lastTabbableNode;
382
- else destinationNode = this.state.tabbableGroups[0].firstTabbableNode;
383
- else if (isBackward) {
384
- let startOfGroupIndex = this.state.tabbableGroups.findIndex(({ firstTabbableNode }) => target === firstTabbableNode);
385
- if (startOfGroupIndex < 0 && (containerGroup?.container === target || isFocusable(target) && !isTabbable(target) && !containerGroup?.nextTabbableNode(target, false))) startOfGroupIndex = containerIndex;
386
- if (startOfGroupIndex >= 0) {
387
- const destinationGroupIndex = startOfGroupIndex === 0 ? this.state.tabbableGroups.length - 1 : startOfGroupIndex - 1;
388
- const destinationGroup = this.state.tabbableGroups[destinationGroupIndex];
389
- destinationNode = getTabIndex(target) >= 0 ? destinationGroup.lastTabbableNode : destinationGroup.lastDomTabbableNode;
390
- } else if (!isTabEvent(event)) destinationNode = containerGroup?.nextTabbableNode(target, false);
391
- } else {
392
- let lastOfGroupIndex = this.state.tabbableGroups.findIndex(({ lastTabbableNode }) => target === lastTabbableNode);
393
- if (lastOfGroupIndex < 0 && (containerGroup?.container === target || isFocusable(target) && !isTabbable(target) && !containerGroup?.nextTabbableNode(target))) lastOfGroupIndex = containerIndex;
394
- if (lastOfGroupIndex >= 0) {
395
- const destinationGroupIndex = lastOfGroupIndex === this.state.tabbableGroups.length - 1 ? 0 : lastOfGroupIndex + 1;
396
- const destinationGroup = this.state.tabbableGroups[destinationGroupIndex];
397
- destinationNode = getTabIndex(target) >= 0 ? destinationGroup.firstTabbableNode : destinationGroup.firstDomTabbableNode;
398
- } else if (!isTabEvent(event)) destinationNode = containerGroup?.nextTabbableNode(target);
399
- }
400
- } else destinationNode = this.getNodeForOption("fallbackFocus");
401
- return destinationNode;
402
- };
403
- };
404
-
405
- //#endregion
406
- //#region index.ts
407
- function trapFocus(el, options = {}) {
408
- let trap;
409
- const cleanup = raf(() => {
410
- const contentEl = typeof el === "function" ? el() : el;
411
- if (!contentEl) return;
412
- trap = new FocusTrap(contentEl, {
413
- escapeDeactivates: false,
414
- allowOutsideClick: true,
415
- preventScroll: true,
416
- returnFocusOnDeactivate: true,
417
- delayInitialFocus: false,
418
- fallbackFocus: contentEl,
419
- ...options,
420
- document: getDocument(contentEl)
421
- });
422
- try {
423
- trap.activate();
424
- } catch {}
425
- });
426
- return function destroy() {
427
- trap?.deactivate();
428
- cleanup();
429
- };
430
- }
431
-
432
- //#endregion
433
- export { FocusTrap, trapFocus };
File without changes