@react-aria/focus 3.21.5 → 3.22.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.
Files changed (40) hide show
  1. package/dist/import.mjs +16 -8
  2. package/dist/main.js +32 -24
  3. package/dist/main.js.map +1 -1
  4. package/dist/module.js +16 -8
  5. package/dist/module.js.map +1 -1
  6. package/dist/types/src/index.d.ts +16 -0
  7. package/package.json +14 -14
  8. package/src/index.ts +16 -13
  9. package/dist/FocusRing.main.js +0 -44
  10. package/dist/FocusRing.main.js.map +0 -1
  11. package/dist/FocusRing.mjs +0 -35
  12. package/dist/FocusRing.module.js +0 -35
  13. package/dist/FocusRing.module.js.map +0 -1
  14. package/dist/FocusScope.main.js +0 -760
  15. package/dist/FocusScope.main.js.map +0 -1
  16. package/dist/FocusScope.mjs +0 -747
  17. package/dist/FocusScope.module.js +0 -747
  18. package/dist/FocusScope.module.js.map +0 -1
  19. package/dist/types.d.ts +0 -133
  20. package/dist/types.d.ts.map +0 -1
  21. package/dist/useFocusRing.main.js +0 -55
  22. package/dist/useFocusRing.main.js.map +0 -1
  23. package/dist/useFocusRing.mjs +0 -50
  24. package/dist/useFocusRing.module.js +0 -50
  25. package/dist/useFocusRing.module.js.map +0 -1
  26. package/dist/useHasTabbableChild.main.js +0 -62
  27. package/dist/useHasTabbableChild.main.js.map +0 -1
  28. package/dist/useHasTabbableChild.mjs +0 -57
  29. package/dist/useHasTabbableChild.module.js +0 -57
  30. package/dist/useHasTabbableChild.module.js.map +0 -1
  31. package/dist/virtualFocus.main.js +0 -46
  32. package/dist/virtualFocus.main.js.map +0 -1
  33. package/dist/virtualFocus.mjs +0 -38
  34. package/dist/virtualFocus.module.js +0 -38
  35. package/dist/virtualFocus.module.js.map +0 -1
  36. package/src/FocusRing.tsx +0 -55
  37. package/src/FocusScope.tsx +0 -1039
  38. package/src/useFocusRing.ts +0 -79
  39. package/src/useHasTabbableChild.ts +0 -66
  40. package/src/virtualFocus.ts +0 -33
@@ -1,1039 +0,0 @@
1
- /*
2
- * Copyright 2020 Adobe. All rights reserved.
3
- * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License. You may obtain a copy
5
- * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- *
7
- * Unless required by applicable law or agreed to in writing, software distributed under
8
- * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
- * OF ANY KIND, either express or implied. See the License for the specific language
10
- * governing permissions and limitations under the License.
11
- */
12
-
13
- import {
14
- createShadowTreeWalker,
15
- getActiveElement,
16
- getEventTarget,
17
- getOwnerDocument,
18
- getOwnerWindow,
19
- isAndroid,
20
- isChrome,
21
- isFocusable,
22
- isTabbable,
23
- nodeContains,
24
- ShadowTreeWalker,
25
- useLayoutEffect
26
- } from '@react-aria/utils';
27
- import {FocusableElement, RefObject} from '@react-types/shared';
28
- import {focusSafely, getInteractionModality} from '@react-aria/interactions';
29
- import React, {JSX, ReactNode, useContext, useEffect, useMemo, useRef} from 'react';
30
-
31
- export interface FocusScopeProps {
32
- /** The contents of the focus scope. */
33
- children: ReactNode,
34
-
35
- /**
36
- * Whether to contain focus inside the scope, so users cannot
37
- * move focus outside, for example in a modal dialog.
38
- */
39
- contain?: boolean,
40
-
41
- /**
42
- * Whether to restore focus back to the element that was focused
43
- * when the focus scope mounted, after the focus scope unmounts.
44
- */
45
- restoreFocus?: boolean,
46
-
47
- /** Whether to auto focus the first focusable element in the focus scope on mount. */
48
- autoFocus?: boolean
49
- }
50
-
51
- export interface FocusManagerOptions {
52
- /** The element to start searching from. The currently focused element by default. */
53
- from?: Element,
54
- /** Whether to only include tabbable elements, or all focusable elements. */
55
- tabbable?: boolean,
56
- /** Whether focus should wrap around when it reaches the end of the scope. */
57
- wrap?: boolean,
58
- /** A callback that determines whether the given element is focused. */
59
- accept?: (node: Element) => boolean
60
- }
61
-
62
- export interface FocusManager {
63
- /** Moves focus to the next focusable or tabbable element in the focus scope. */
64
- focusNext(opts?: FocusManagerOptions): FocusableElement | null,
65
- /** Moves focus to the previous focusable or tabbable element in the focus scope. */
66
- focusPrevious(opts?: FocusManagerOptions): FocusableElement | null,
67
- /** Moves focus to the first focusable or tabbable element in the focus scope. */
68
- focusFirst(opts?: FocusManagerOptions): FocusableElement | null,
69
- /** Moves focus to the last focusable or tabbable element in the focus scope. */
70
- focusLast(opts?: FocusManagerOptions): FocusableElement | null
71
- }
72
-
73
- type ScopeRef = RefObject<Element[] | null> | null;
74
- interface IFocusContext {
75
- focusManager: FocusManager,
76
- parentNode: TreeNode | null
77
- }
78
-
79
- const FocusContext = React.createContext<IFocusContext | null>(null);
80
- const RESTORE_FOCUS_EVENT = 'react-aria-focus-scope-restore';
81
-
82
- let activeScope: ScopeRef = null;
83
-
84
- // This is a hacky DOM-based implementation of a FocusScope until this RFC lands in React:
85
- // https://github.com/reactjs/rfcs/pull/109
86
-
87
- /**
88
- * A FocusScope manages focus for its descendants. It supports containing focus inside
89
- * the scope, restoring focus to the previously focused element on unmount, and auto
90
- * focusing children on mount. It also acts as a container for a programmatic focus
91
- * management interface that can be used to move focus forward and back in response
92
- * to user events.
93
- */
94
- export function FocusScope(props: FocusScopeProps): JSX.Element {
95
- let {children, contain, restoreFocus, autoFocus} = props;
96
- let startRef = useRef<HTMLSpanElement>(null);
97
- let endRef = useRef<HTMLSpanElement>(null);
98
- let scopeRef = useRef<Element[]>([]);
99
- let {parentNode} = useContext(FocusContext) || {};
100
-
101
- // Create a tree node here so we can add children to it even before it is added to the tree.
102
- let node = useMemo(() => new TreeNode({scopeRef}), [scopeRef]);
103
-
104
- useLayoutEffect(() => {
105
- // If a new scope mounts outside the active scope, (e.g. DialogContainer launched from a menu),
106
- // use the active scope as the parent instead of the parent from context. Layout effects run bottom
107
- // up, so if the parent is not yet added to the tree, don't do this. Only the outer-most FocusScope
108
- // that is being added should get the activeScope as its parent.
109
- let parent = parentNode || focusScopeTree.root;
110
- if (focusScopeTree.getTreeNode(parent.scopeRef) && activeScope && !isAncestorScope(activeScope, parent.scopeRef)) {
111
- let activeNode = focusScopeTree.getTreeNode(activeScope);
112
- if (activeNode) {
113
- parent = activeNode;
114
- }
115
- }
116
-
117
- // Add the node to the parent, and to the tree.
118
- parent.addChild(node);
119
- focusScopeTree.addNode(node);
120
- }, [node, parentNode]);
121
-
122
- useLayoutEffect(() => {
123
- let node = focusScopeTree.getTreeNode(scopeRef);
124
- if (node) {
125
- node.contain = !!contain;
126
- }
127
- }, [contain]);
128
-
129
- useLayoutEffect(() => {
130
- // Find all rendered nodes between the sentinels and add them to the scope.
131
- let node = startRef.current?.nextSibling!;
132
- let nodes: Element[] = [];
133
- let stopPropagation = e => e.stopPropagation();
134
- while (node && node !== endRef.current) {
135
- nodes.push(node as Element);
136
- // Stop custom restore focus event from propagating to parent focus scopes.
137
- node.addEventListener(RESTORE_FOCUS_EVENT, stopPropagation);
138
- node = node.nextSibling as Element;
139
- }
140
-
141
- scopeRef.current = nodes;
142
-
143
- return () => {
144
- for (let node of nodes) {
145
- node.removeEventListener(RESTORE_FOCUS_EVENT, stopPropagation);
146
- }
147
- };
148
- }, [children]);
149
-
150
- useActiveScopeTracker(scopeRef, restoreFocus, contain);
151
- useFocusContainment(scopeRef, contain);
152
- useRestoreFocus(scopeRef, restoreFocus, contain);
153
- useAutoFocus(scopeRef, autoFocus);
154
-
155
- // This needs to be an effect so that activeScope is updated after the FocusScope tree is complete.
156
- // It cannot be a useLayoutEffect because the parent of this node hasn't been attached in the tree yet.
157
- useEffect(() => {
158
- const activeElement = getActiveElement(getOwnerDocument(scopeRef.current ? scopeRef.current[0] : undefined));
159
- let scope: TreeNode | null = null;
160
-
161
- if (isElementInScope(activeElement, scopeRef.current)) {
162
- // We need to traverse the focusScope tree and find the bottom most scope that
163
- // contains the active element and set that as the activeScope.
164
- for (let node of focusScopeTree.traverse()) {
165
- if (node.scopeRef && isElementInScope(activeElement, node.scopeRef.current)) {
166
- scope = node;
167
- }
168
- }
169
-
170
- if (scope === focusScopeTree.getTreeNode(scopeRef)) {
171
- activeScope = scope.scopeRef;
172
- }
173
- }
174
- }, [scopeRef]);
175
-
176
- // This layout effect cleanup is so that the tree node is removed synchronously with react before the RAF
177
- // in useRestoreFocus cleanup runs.
178
- useLayoutEffect(() => {
179
- return () => {
180
- // Scope may have been re-parented.
181
- let parentScope = focusScopeTree.getTreeNode(scopeRef)?.parent?.scopeRef ?? null;
182
-
183
- if (
184
- (scopeRef === activeScope || isAncestorScope(scopeRef, activeScope)) &&
185
- (!parentScope || focusScopeTree.getTreeNode(parentScope))
186
- ) {
187
- activeScope = parentScope;
188
- }
189
- focusScopeTree.removeTreeNode(scopeRef);
190
- };
191
- }, [scopeRef]);
192
-
193
- let focusManager = useMemo(() => createFocusManagerForScope(scopeRef), []);
194
- let value = useMemo(() => ({
195
- focusManager,
196
- parentNode: node
197
- }), [node, focusManager]);
198
-
199
- return (
200
- <FocusContext.Provider value={value}>
201
- <span data-focus-scope-start hidden ref={startRef} />
202
- {children}
203
- <span data-focus-scope-end hidden ref={endRef} />
204
- </FocusContext.Provider>
205
- );
206
- }
207
-
208
- /**
209
- * Returns a FocusManager interface for the parent FocusScope.
210
- * A FocusManager can be used to programmatically move focus within
211
- * a FocusScope, e.g. in response to user events like keyboard navigation.
212
- */
213
- export function useFocusManager(): FocusManager | undefined {
214
- return useContext(FocusContext)?.focusManager;
215
- }
216
-
217
- function createFocusManagerForScope(scopeRef: React.RefObject<Element[] | null>): FocusManager {
218
- return {
219
- focusNext(opts: FocusManagerOptions = {}) {
220
- let scope = scopeRef.current!;
221
- let {from, tabbable, wrap, accept} = opts;
222
- let node = from || getActiveElement(getOwnerDocument(scope[0] ?? undefined))!;
223
- let sentinel = scope[0].previousElementSibling!;
224
- let scopeRoot = getScopeRoot(scope);
225
- let walker = getFocusableTreeWalker(scopeRoot, {tabbable, accept}, scope);
226
- walker.currentNode = isElementInScope(node, scope) ? node : sentinel;
227
- let nextNode = walker.nextNode() as FocusableElement;
228
- if (!nextNode && wrap) {
229
- walker.currentNode = sentinel;
230
- nextNode = walker.nextNode() as FocusableElement;
231
- }
232
- if (nextNode) {
233
- focusElement(nextNode, true);
234
- }
235
- return nextNode;
236
- },
237
- focusPrevious(opts: FocusManagerOptions = {}) {
238
- let scope = scopeRef.current!;
239
- let {from, tabbable, wrap, accept} = opts;
240
- let node = from || getActiveElement(getOwnerDocument(scope[0] ?? undefined))!;
241
- let sentinel = scope[scope.length - 1].nextElementSibling!;
242
- let scopeRoot = getScopeRoot(scope);
243
- let walker = getFocusableTreeWalker(scopeRoot, {tabbable, accept}, scope);
244
- walker.currentNode = isElementInScope(node, scope) ? node : sentinel;
245
- let previousNode = walker.previousNode() as FocusableElement;
246
- if (!previousNode && wrap) {
247
- walker.currentNode = sentinel;
248
- previousNode = walker.previousNode() as FocusableElement;
249
- }
250
- if (previousNode) {
251
- focusElement(previousNode, true);
252
- }
253
- return previousNode;
254
- },
255
- focusFirst(opts = {}) {
256
- let scope = scopeRef.current!;
257
- let {tabbable, accept} = opts;
258
- let scopeRoot = getScopeRoot(scope);
259
- let walker = getFocusableTreeWalker(scopeRoot, {tabbable, accept}, scope);
260
- walker.currentNode = scope[0].previousElementSibling!;
261
- let nextNode = walker.nextNode() as FocusableElement;
262
- if (nextNode) {
263
- focusElement(nextNode, true);
264
- }
265
- return nextNode;
266
- },
267
- focusLast(opts = {}) {
268
- let scope = scopeRef.current!;
269
- let {tabbable, accept} = opts;
270
- let scopeRoot = getScopeRoot(scope);
271
- let walker = getFocusableTreeWalker(scopeRoot, {tabbable, accept}, scope);
272
- walker.currentNode = scope[scope.length - 1].nextElementSibling!;
273
- let previousNode = walker.previousNode() as FocusableElement;
274
- if (previousNode) {
275
- focusElement(previousNode, true);
276
- }
277
- return previousNode;
278
- }
279
- };
280
- }
281
-
282
- function getScopeRoot(scope: Element[]) {
283
- return scope[0].parentElement!;
284
- }
285
-
286
- function shouldContainFocus(scopeRef: ScopeRef) {
287
- let scope = focusScopeTree.getTreeNode(activeScope);
288
- while (scope && scope.scopeRef !== scopeRef) {
289
- if (scope.contain) {
290
- return false;
291
- }
292
-
293
- scope = scope.parent;
294
- }
295
-
296
- return true;
297
- }
298
-
299
- function getRadiosInGroup(element: HTMLInputElement): HTMLInputElement[] {
300
- if (!element.form) {
301
- // Radio buttons outside a form - query the document
302
- return Array.from(
303
- getOwnerDocument(element).querySelectorAll<HTMLInputElement>(
304
- `input[type="radio"][name="${CSS.escape(element.name)}"]`
305
- )
306
- ).filter(radio => !radio.form);
307
- }
308
-
309
- // namedItem returns RadioNodeList (iterable) for 2+ elements, but a single Element for exactly 1.
310
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormControlsCollection/namedItem
311
- const radioList = element.form.elements.namedItem(element.name);
312
- let ownerWindow = getOwnerWindow(element);
313
- if (radioList instanceof ownerWindow.RadioNodeList) {
314
- return Array.from(radioList).filter(
315
- (el): el is HTMLInputElement => el instanceof ownerWindow.HTMLInputElement
316
- );
317
- }
318
- if (radioList instanceof ownerWindow.HTMLInputElement) {
319
- return [radioList];
320
- }
321
- return [];
322
- }
323
-
324
- function isTabbableRadio(element: HTMLInputElement): boolean {
325
- if (element.checked) {
326
- return true;
327
- }
328
- const radios = getRadiosInGroup(element);
329
- return radios.length > 0 && !radios.some(radio => radio.checked);
330
- }
331
-
332
- function useFocusContainment(scopeRef: RefObject<Element[] | null>, contain?: boolean) {
333
- let focusedNode = useRef<FocusableElement>(undefined);
334
-
335
- let raf = useRef<ReturnType<typeof requestAnimationFrame>>(undefined);
336
- useLayoutEffect(() => {
337
- let scope = scopeRef.current;
338
- if (!contain) {
339
- // if contain was changed, then we should cancel any ongoing waits to pull focus back into containment
340
- if (raf.current) {
341
- cancelAnimationFrame(raf.current);
342
- raf.current = undefined;
343
- }
344
- return;
345
- }
346
-
347
- const ownerDocument = getOwnerDocument(scope ? scope[0] : undefined);
348
-
349
- // Handle the Tab key to contain focus within the scope
350
- let onKeyDown = (e) => {
351
- if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey || !shouldContainFocus(scopeRef) || e.isComposing) {
352
- return;
353
- }
354
-
355
- let focusedElement = getActiveElement(ownerDocument);
356
- let scope = scopeRef.current;
357
- if (!scope || !isElementInScope(focusedElement, scope)) {
358
- return;
359
- }
360
-
361
- let scopeRoot = getScopeRoot(scope);
362
- let walker = getFocusableTreeWalker(scopeRoot, {tabbable: true}, scope);
363
- if (!focusedElement) {
364
- return;
365
- }
366
- walker.currentNode = focusedElement;
367
- let nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;
368
- if (!nextElement) {
369
- walker.currentNode = e.shiftKey ? scope[scope.length - 1].nextElementSibling! : scope[0].previousElementSibling!;
370
- nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;
371
- }
372
-
373
- e.preventDefault();
374
- if (nextElement) {
375
- focusElement(nextElement, true);
376
- }
377
- };
378
-
379
- let onFocus: EventListener = (e) => {
380
- // If focusing an element in a child scope of the currently active scope, the child becomes active.
381
- // Moving out of the active scope to an ancestor is not allowed.
382
- if ((!activeScope || isAncestorScope(activeScope, scopeRef)) && isElementInScope(getEventTarget(e) as Element, scopeRef.current)) {
383
- activeScope = scopeRef;
384
- focusedNode.current = getEventTarget(e) as FocusableElement;
385
- } else if (shouldContainFocus(scopeRef) && !isElementInChildScope(getEventTarget(e) as Element, scopeRef)) {
386
- // If a focus event occurs outside the active scope (e.g. user tabs from browser location bar),
387
- // restore focus to the previously focused node or the first tabbable element in the active scope.
388
- if (focusedNode.current) {
389
- focusedNode.current.focus();
390
- } else if (activeScope && activeScope.current) {
391
- focusFirstInScope(activeScope.current);
392
- }
393
- } else if (shouldContainFocus(scopeRef)) {
394
- focusedNode.current = getEventTarget(e) as FocusableElement;
395
- }
396
- };
397
-
398
- let onBlur: EventListener = (e) => {
399
- // Firefox doesn't shift focus back to the Dialog properly without this
400
- if (raf.current) {
401
- cancelAnimationFrame(raf.current);
402
- }
403
- raf.current = requestAnimationFrame(() => {
404
- // Patches infinite focus coersion loop for Android Talkback where the user isn't able to move the virtual cursor
405
- // if within a containing focus scope. Bug filed against Chrome: https://issuetracker.google.com/issues/384844019.
406
- // Note that this means focus can leave focus containing modals due to this, but it is isolated to Chrome Talkback.
407
- let modality = getInteractionModality();
408
- let shouldSkipFocusRestore = (modality === 'virtual' || modality === null) && isAndroid() && isChrome();
409
-
410
- // Use document.activeElement instead of e.relatedTarget so we can tell if user clicked into iframe
411
- let activeElement = getActiveElement(ownerDocument);
412
- if (!shouldSkipFocusRestore && activeElement && shouldContainFocus(scopeRef) && !isElementInChildScope(activeElement, scopeRef)) {
413
- activeScope = scopeRef;
414
- let target = getEventTarget(e) as FocusableElement;
415
- if (target && target.isConnected) {
416
- focusedNode.current = target;
417
- focusedNode.current?.focus();
418
- } else if (activeScope.current) {
419
- focusFirstInScope(activeScope.current);
420
- }
421
- }
422
- });
423
- };
424
-
425
- ownerDocument.addEventListener('keydown', onKeyDown, false);
426
- ownerDocument.addEventListener('focusin', onFocus, false);
427
- scope?.forEach(element => element.addEventListener('focusin', onFocus, false));
428
- scope?.forEach(element => element.addEventListener('focusout', onBlur, false));
429
- return () => {
430
- ownerDocument.removeEventListener('keydown', onKeyDown, false);
431
- ownerDocument.removeEventListener('focusin', onFocus, false);
432
- scope?.forEach(element => element.removeEventListener('focusin', onFocus, false));
433
- scope?.forEach(element => element.removeEventListener('focusout', onBlur, false));
434
- };
435
- }, [scopeRef, contain]);
436
-
437
- // This is a useLayoutEffect so it is guaranteed to run before our async synthetic blur
438
-
439
- useLayoutEffect(() => {
440
- return () => {
441
- if (raf.current) {
442
- cancelAnimationFrame(raf.current);
443
- }
444
- };
445
- }, [raf]);
446
- }
447
-
448
- function isElementInAnyScope(element: Element) {
449
- return isElementInChildScope(element);
450
- }
451
-
452
- function isElementInScope(element?: Element | null, scope?: Element[] | null) {
453
- if (!element) {
454
- return false;
455
- }
456
- if (!scope) {
457
- return false;
458
- }
459
- return scope.some(node => nodeContains(node, element));
460
- }
461
-
462
- function isElementInChildScope(element: Element, scope: ScopeRef = null) {
463
- // If the element is within a top layer element (e.g. toasts), always allow moving focus there.
464
- if (element instanceof Element && element.closest('[data-react-aria-top-layer]')) {
465
- return true;
466
- }
467
-
468
- // node.contains in isElementInScope covers child scopes that are also DOM children,
469
- // but does not cover child scopes in portals.
470
- for (let {scopeRef: s} of focusScopeTree.traverse(focusScopeTree.getTreeNode(scope))) {
471
- if (s && isElementInScope(element, s.current)) {
472
- return true;
473
- }
474
- }
475
-
476
- return false;
477
- }
478
-
479
- /** @private */
480
- export function isElementInChildOfActiveScope(element: Element): boolean {
481
- return isElementInChildScope(element, activeScope);
482
- }
483
-
484
- function isAncestorScope(ancestor: ScopeRef, scope: ScopeRef) {
485
- let parent = focusScopeTree.getTreeNode(scope)?.parent;
486
- while (parent) {
487
- if (parent.scopeRef === ancestor) {
488
- return true;
489
- }
490
- parent = parent.parent;
491
- }
492
- return false;
493
- }
494
-
495
- function focusElement(element: FocusableElement | null, scroll = false) {
496
- if (element != null && !scroll) {
497
- try {
498
- focusSafely(element);
499
- } catch {
500
- // ignore
501
- }
502
- } else if (element != null) {
503
- try {
504
- element.focus();
505
- } catch {
506
- // ignore
507
- }
508
- }
509
- }
510
-
511
- function getFirstInScope(scope: Element[], tabbable = true) {
512
- let sentinel = scope[0].previousElementSibling!;
513
- let scopeRoot = getScopeRoot(scope);
514
- let walker = getFocusableTreeWalker(scopeRoot, {tabbable}, scope);
515
- walker.currentNode = sentinel;
516
- let nextNode = walker.nextNode();
517
-
518
- // If the scope does not contain a tabbable element, use the first focusable element.
519
- if (tabbable && !nextNode) {
520
- scopeRoot = getScopeRoot(scope);
521
- walker = getFocusableTreeWalker(scopeRoot, {tabbable: false}, scope);
522
- walker.currentNode = sentinel;
523
- nextNode = walker.nextNode();
524
- }
525
-
526
- return nextNode as FocusableElement;
527
- }
528
-
529
- function focusFirstInScope(scope: Element[], tabbable:boolean = true) {
530
- focusElement(getFirstInScope(scope, tabbable));
531
- }
532
-
533
- function useAutoFocus(scopeRef: RefObject<Element[] | null>, autoFocus?: boolean) {
534
- const autoFocusRef = React.useRef(autoFocus);
535
- useEffect(() => {
536
- if (autoFocusRef.current) {
537
- activeScope = scopeRef;
538
- const ownerDocument = getOwnerDocument(scopeRef.current ? scopeRef.current[0] : undefined);
539
- if (!isElementInScope(getActiveElement(ownerDocument), activeScope.current) && scopeRef.current) {
540
- focusFirstInScope(scopeRef.current);
541
- }
542
- }
543
- autoFocusRef.current = false;
544
- }, [scopeRef]);
545
- }
546
-
547
- function useActiveScopeTracker(scopeRef: RefObject<Element[] | null>, restore?: boolean, contain?: boolean) {
548
- // tracks the active scope, in case restore and contain are both false.
549
- // if either are true, this is tracked in useRestoreFocus or useFocusContainment.
550
- useLayoutEffect(() => {
551
- if (restore || contain) {
552
- return;
553
- }
554
-
555
- let scope = scopeRef.current;
556
- const ownerDocument = getOwnerDocument(scope ? scope[0] : undefined);
557
-
558
- let onFocus = (e) => {
559
- let target = getEventTarget(e) as Element;
560
- if (isElementInScope(target, scopeRef.current)) {
561
- activeScope = scopeRef;
562
- } else if (!isElementInAnyScope(target)) {
563
- activeScope = null;
564
- }
565
- };
566
-
567
- ownerDocument.addEventListener('focusin', onFocus, false);
568
- scope?.forEach(element => element.addEventListener('focusin', onFocus, false));
569
- return () => {
570
- ownerDocument.removeEventListener('focusin', onFocus, false);
571
- scope?.forEach(element => element.removeEventListener('focusin', onFocus, false));
572
- };
573
- }, [scopeRef, restore, contain]);
574
- }
575
-
576
- function shouldRestoreFocus(scopeRef: ScopeRef) {
577
- let scope = focusScopeTree.getTreeNode(activeScope);
578
- while (scope && scope.scopeRef !== scopeRef) {
579
- if (scope.nodeToRestore) {
580
- return false;
581
- }
582
-
583
- scope = scope.parent;
584
- }
585
-
586
- return scope?.scopeRef === scopeRef;
587
- }
588
-
589
- function useRestoreFocus(scopeRef: RefObject<Element[] | null>, restoreFocus?: boolean, contain?: boolean) {
590
- // create a ref during render instead of useLayoutEffect so the active element is saved before a child with autoFocus=true mounts.
591
- // eslint-disable-next-line no-restricted-globals
592
- const nodeToRestoreRef = useRef(typeof document !== 'undefined' ? getActiveElement(getOwnerDocument(scopeRef.current ? scopeRef.current[0] : undefined)) as FocusableElement : null);
593
-
594
- // restoring scopes should all track if they are active regardless of contain, but contain already tracks it plus logic to contain the focus
595
- // restoring-non-containing scopes should only care if they become active so they can perform the restore
596
- useLayoutEffect(() => {
597
- let scope = scopeRef.current;
598
- const ownerDocument = getOwnerDocument(scope ? scope[0] : undefined);
599
- if (!restoreFocus || contain) {
600
- return;
601
- }
602
-
603
- let onFocus = () => {
604
- // If focusing an element in a child scope of the currently active scope, the child becomes active.
605
- // Moving out of the active scope to an ancestor is not allowed.
606
- if ((!activeScope || isAncestorScope(activeScope, scopeRef)) &&
607
- isElementInScope(getActiveElement(ownerDocument), scopeRef.current)
608
- ) {
609
- activeScope = scopeRef;
610
- }
611
- };
612
-
613
- ownerDocument.addEventListener('focusin', onFocus, false);
614
- scope?.forEach(element => element.addEventListener('focusin', onFocus, false));
615
- return () => {
616
- ownerDocument.removeEventListener('focusin', onFocus, false);
617
- scope?.forEach(element => element.removeEventListener('focusin', onFocus, false));
618
- };
619
- // eslint-disable-next-line react-hooks/exhaustive-deps
620
- }, [scopeRef, contain]);
621
-
622
- useLayoutEffect(() => {
623
- const ownerDocument = getOwnerDocument(scopeRef.current ? scopeRef.current[0] : undefined);
624
-
625
- if (!restoreFocus) {
626
- return;
627
- }
628
-
629
- // Handle the Tab key so that tabbing out of the scope goes to the next element
630
- // after the node that had focus when the scope mounted. This is important when
631
- // using portals for overlays, so that focus goes to the expected element when
632
- // tabbing out of the overlay.
633
- let onKeyDown = (e: KeyboardEvent) => {
634
- if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey || !shouldContainFocus(scopeRef) || e.isComposing) {
635
- return;
636
- }
637
-
638
- let focusedElement = ownerDocument.activeElement as FocusableElement;
639
- if (!isElementInChildScope(focusedElement, scopeRef) || !shouldRestoreFocus(scopeRef)) {
640
- return;
641
- }
642
- let treeNode = focusScopeTree.getTreeNode(scopeRef);
643
- if (!treeNode) {
644
- return;
645
- }
646
- let nodeToRestore = treeNode.nodeToRestore;
647
-
648
- // Create a DOM tree walker that matches all tabbable elements
649
- let walker = getFocusableTreeWalker(ownerDocument.body, {tabbable: true});
650
-
651
- // Find the next tabbable element after the currently focused element
652
- walker.currentNode = focusedElement;
653
- let nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;
654
-
655
- if (!nodeToRestore || !nodeToRestore.isConnected || nodeToRestore === ownerDocument.body) {
656
- nodeToRestore = undefined;
657
- treeNode.nodeToRestore = undefined;
658
- }
659
-
660
- // If there is no next element, or it is outside the current scope, move focus to the
661
- // next element after the node to restore to instead.
662
- if ((!nextElement || !isElementInChildScope(nextElement, scopeRef)) && nodeToRestore) {
663
- walker.currentNode = nodeToRestore;
664
-
665
- // Skip over elements within the scope, in case the scope immediately follows the node to restore.
666
- do {
667
- nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;
668
- } while (isElementInChildScope(nextElement, scopeRef));
669
-
670
- e.preventDefault();
671
- e.stopPropagation();
672
- if (nextElement) {
673
- focusElement(nextElement, true);
674
- } else {
675
- // If there is no next element and the nodeToRestore isn't within a FocusScope (i.e. we are leaving the top level focus scope)
676
- // then move focus to the body.
677
- // Otherwise restore focus to the nodeToRestore (e.g menu within a popover -> tabbing to close the menu should move focus to menu trigger)
678
- if (!isElementInAnyScope(nodeToRestore)) {
679
- focusedElement.blur();
680
- } else {
681
- focusElement(nodeToRestore, true);
682
- }
683
- }
684
- }
685
- };
686
-
687
- if (!contain) {
688
- ownerDocument.addEventListener('keydown', onKeyDown as EventListener, true);
689
- }
690
-
691
- return () => {
692
- if (!contain) {
693
- ownerDocument.removeEventListener('keydown', onKeyDown as EventListener, true);
694
- }
695
- };
696
- }, [scopeRef, restoreFocus, contain]);
697
-
698
- // useLayoutEffect instead of useEffect so the active element is saved synchronously instead of asynchronously.
699
- useLayoutEffect(() => {
700
- const ownerDocument = getOwnerDocument(scopeRef.current ? scopeRef.current[0] : undefined);
701
-
702
- if (!restoreFocus) {
703
- return;
704
- }
705
-
706
- let treeNode = focusScopeTree.getTreeNode(scopeRef);
707
- if (!treeNode) {
708
- return;
709
- }
710
- treeNode.nodeToRestore = nodeToRestoreRef.current ?? undefined;
711
- return () => {
712
- let treeNode = focusScopeTree.getTreeNode(scopeRef);
713
- if (!treeNode) {
714
- return;
715
- }
716
- let nodeToRestore = treeNode.nodeToRestore;
717
-
718
- // if we already lost focus to the body and this was the active scope, then we should attempt to restore
719
- let activeElement = getActiveElement(ownerDocument);
720
- if (
721
- restoreFocus
722
- && nodeToRestore
723
- && (
724
- ((activeElement && isElementInChildScope(activeElement, scopeRef)) || (activeElement === ownerDocument.body && shouldRestoreFocus(scopeRef)))
725
- )
726
- ) {
727
- // freeze the focusScopeTree so it persists after the raf, otherwise during unmount nodes are removed from it
728
- let clonedTree = focusScopeTree.clone();
729
- requestAnimationFrame(() => {
730
- // Only restore focus if we've lost focus to the body, the alternative is that focus has been purposefully moved elsewhere
731
- if (ownerDocument.activeElement === ownerDocument.body) {
732
- // look up the tree starting with our scope to find a nodeToRestore still in the DOM
733
- let treeNode = clonedTree.getTreeNode(scopeRef);
734
- while (treeNode) {
735
- if (treeNode.nodeToRestore && treeNode.nodeToRestore.isConnected) {
736
- restoreFocusToElement(treeNode.nodeToRestore);
737
- return;
738
- }
739
- treeNode = treeNode.parent;
740
- }
741
-
742
- // If no nodeToRestore was found, focus the first element in the nearest
743
- // ancestor scope that is still in the tree.
744
- treeNode = clonedTree.getTreeNode(scopeRef);
745
- while (treeNode) {
746
- if (treeNode.scopeRef && treeNode.scopeRef.current && focusScopeTree.getTreeNode(treeNode.scopeRef)) {
747
- let node = getFirstInScope(treeNode.scopeRef.current, true);
748
- restoreFocusToElement(node);
749
- return;
750
- }
751
- treeNode = treeNode.parent;
752
- }
753
- }
754
- });
755
- }
756
- };
757
- }, [scopeRef, restoreFocus]);
758
- }
759
-
760
- function restoreFocusToElement(node: FocusableElement) {
761
- // Dispatch a custom event that parent elements can intercept to customize focus restoration.
762
- // For example, virtualized collection components reuse DOM elements, so the original element
763
- // might still exist in the DOM but representing a different item.
764
- if (node.dispatchEvent(new CustomEvent(RESTORE_FOCUS_EVENT, {bubbles: true, cancelable: true}))) {
765
- focusElement(node);
766
- }
767
- }
768
-
769
- /**
770
- * Create a [TreeWalker]{@link https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker}
771
- * that matches all focusable/tabbable elements.
772
- */
773
- export function getFocusableTreeWalker(root: Element, opts?: FocusManagerOptions, scope?: Element[]): ShadowTreeWalker | TreeWalker {
774
- let filter = opts?.tabbable ? isTabbable : isFocusable;
775
-
776
- // Ensure that root is an Element or fall back appropriately
777
- let rootElement = root?.nodeType === Node.ELEMENT_NODE ? (root as Element) : null;
778
-
779
- // Determine the document to use
780
- let doc = getOwnerDocument(rootElement);
781
-
782
- // Create a TreeWalker, ensuring the root is an Element or Document
783
- let walker = createShadowTreeWalker(
784
- doc,
785
- root || doc,
786
- NodeFilter.SHOW_ELEMENT,
787
- {
788
- acceptNode(node) {
789
- // Skip nodes inside the starting node.
790
- if (nodeContains(opts?.from, node)) {
791
- return NodeFilter.FILTER_REJECT;
792
- }
793
-
794
- if (opts?.tabbable
795
- && (node as Element).tagName === 'INPUT'
796
- && (node as HTMLInputElement).getAttribute('type') === 'radio') {
797
- // If the radio is in a form, we can get all the other radios by name
798
- if (!isTabbableRadio(node as HTMLInputElement)) {
799
- return NodeFilter.FILTER_REJECT;
800
- }
801
- // If the radio is in the same group as the current node and none are selected, we can skip it
802
- if ((walker.currentNode as Element).tagName === 'INPUT'
803
- && (walker.currentNode as HTMLInputElement).type === 'radio'
804
- && (walker.currentNode as HTMLInputElement).name === (node as HTMLInputElement).name) {
805
- return NodeFilter.FILTER_REJECT;
806
- }
807
- }
808
-
809
- if (filter(node as Element)
810
- && (!scope || isElementInScope(node as Element, scope))
811
- && (!opts?.accept || opts.accept(node as Element))
812
- ) {
813
- return NodeFilter.FILTER_ACCEPT;
814
- }
815
-
816
- return NodeFilter.FILTER_SKIP;
817
- }
818
- }
819
- );
820
-
821
- if (opts?.from) {
822
- walker.currentNode = opts.from;
823
- }
824
-
825
- return walker;
826
- }
827
-
828
- /**
829
- * Creates a FocusManager object that can be used to move focus within an element.
830
- */
831
- export function createFocusManager(ref: RefObject<Element | null>, defaultOptions: FocusManagerOptions = {}): FocusManager {
832
- return {
833
- focusNext(opts: FocusManagerOptions = {}) {
834
- let root = ref.current;
835
- if (!root) {
836
- return null;
837
- }
838
- let {from, tabbable = defaultOptions.tabbable, wrap = defaultOptions.wrap, accept = defaultOptions.accept} = opts;
839
- let node = from || getActiveElement(getOwnerDocument(root));
840
- let walker = getFocusableTreeWalker(root, {tabbable, accept});
841
- if (nodeContains(root, node)) {
842
- walker.currentNode = node!;
843
- }
844
- let nextNode = walker.nextNode() as FocusableElement;
845
- if (!nextNode && wrap) {
846
- walker.currentNode = root;
847
- nextNode = walker.nextNode() as FocusableElement;
848
- }
849
- if (nextNode) {
850
- focusElement(nextNode, true);
851
- }
852
- return nextNode;
853
- },
854
- focusPrevious(opts: FocusManagerOptions = defaultOptions) {
855
- let root = ref.current;
856
- if (!root) {
857
- return null;
858
- }
859
- let {from, tabbable = defaultOptions.tabbable, wrap = defaultOptions.wrap, accept = defaultOptions.accept} = opts;
860
- let node = from || getActiveElement(getOwnerDocument(root));
861
- let walker = getFocusableTreeWalker(root, {tabbable, accept});
862
- if (nodeContains(root, node)) {
863
- walker.currentNode = node!;
864
- } else {
865
- let next = last(walker);
866
- if (next) {
867
- focusElement(next, true);
868
- }
869
- return next ?? null;
870
- }
871
- let previousNode = walker.previousNode() as FocusableElement;
872
- if (!previousNode && wrap) {
873
- walker.currentNode = root;
874
- let lastNode = last(walker);
875
- if (!lastNode) {
876
- // couldn't wrap
877
- return null;
878
- }
879
- previousNode = lastNode;
880
- }
881
- if (previousNode) {
882
- focusElement(previousNode, true);
883
- }
884
- return previousNode ?? null;
885
- },
886
- focusFirst(opts = defaultOptions) {
887
- let root = ref.current;
888
- if (!root) {
889
- return null;
890
- }
891
- let {tabbable = defaultOptions.tabbable, accept = defaultOptions.accept} = opts;
892
- let walker = getFocusableTreeWalker(root, {tabbable, accept});
893
- let nextNode = walker.nextNode() as FocusableElement;
894
- if (nextNode) {
895
- focusElement(nextNode, true);
896
- }
897
- return nextNode;
898
- },
899
- focusLast(opts = defaultOptions) {
900
- let root = ref.current;
901
- if (!root) {
902
- return null;
903
- }
904
- let {tabbable = defaultOptions.tabbable, accept = defaultOptions.accept} = opts;
905
- let walker = getFocusableTreeWalker(root, {tabbable, accept});
906
- let next = last(walker);
907
- if (next) {
908
- focusElement(next, true);
909
- }
910
- return next ?? null;
911
- }
912
- };
913
- }
914
-
915
- function last(walker: ShadowTreeWalker | TreeWalker) {
916
- let next: FocusableElement | undefined = undefined;
917
- let last: FocusableElement;
918
- do {
919
- last = walker.lastChild() as FocusableElement;
920
- if (last) {
921
- next = last;
922
- }
923
- } while (last);
924
- return next;
925
- }
926
-
927
-
928
- class Tree {
929
- root: TreeNode;
930
- private fastMap = new Map<ScopeRef, TreeNode>();
931
-
932
- constructor() {
933
- this.root = new TreeNode({scopeRef: null});
934
- this.fastMap.set(null, this.root);
935
- }
936
-
937
- get size(): number {
938
- return this.fastMap.size;
939
- }
940
-
941
- getTreeNode(data: ScopeRef): TreeNode | undefined {
942
- return this.fastMap.get(data);
943
- }
944
-
945
- addTreeNode(scopeRef: ScopeRef, parent: ScopeRef, nodeToRestore?: FocusableElement): void {
946
- let parentNode = this.fastMap.get(parent ?? null);
947
- if (!parentNode) {
948
- return;
949
- }
950
- let node = new TreeNode({scopeRef});
951
- parentNode.addChild(node);
952
- node.parent = parentNode;
953
- this.fastMap.set(scopeRef, node);
954
- if (nodeToRestore) {
955
- node.nodeToRestore = nodeToRestore;
956
- }
957
- }
958
-
959
- addNode(node: TreeNode): void {
960
- this.fastMap.set(node.scopeRef, node);
961
- }
962
-
963
- removeTreeNode(scopeRef: ScopeRef): void {
964
- // never remove the root
965
- if (scopeRef === null) {
966
- return;
967
- }
968
- let node = this.fastMap.get(scopeRef);
969
- if (!node) {
970
- return;
971
- }
972
- let parentNode = node.parent;
973
- // when we remove a scope, check if any sibling scopes are trying to restore focus to something inside the scope we're removing
974
- // if we are, then replace the siblings restore with the restore from the scope we're removing
975
- for (let current of this.traverse()) {
976
- if (
977
- current !== node &&
978
- node.nodeToRestore &&
979
- current.nodeToRestore &&
980
- node.scopeRef &&
981
- node.scopeRef.current &&
982
- isElementInScope(current.nodeToRestore, node.scopeRef.current)
983
- ) {
984
- current.nodeToRestore = node.nodeToRestore;
985
- }
986
- }
987
- let children = node.children;
988
- if (parentNode) {
989
- parentNode.removeChild(node);
990
- if (children.size > 0) {
991
- children.forEach(child => parentNode && parentNode.addChild(child));
992
- }
993
- }
994
-
995
- this.fastMap.delete(node.scopeRef);
996
- }
997
-
998
- // Pre Order Depth First
999
- *traverse(node: TreeNode = this.root): Generator<TreeNode> {
1000
- if (node.scopeRef != null) {
1001
- yield node;
1002
- }
1003
- if (node.children.size > 0) {
1004
- for (let child of node.children) {
1005
- yield* this.traverse(child);
1006
- }
1007
- }
1008
- }
1009
-
1010
- clone(): Tree {
1011
- let newTree = new Tree();
1012
- for (let node of this.traverse()) {
1013
- newTree.addTreeNode(node.scopeRef, node.parent?.scopeRef ?? null, node.nodeToRestore);
1014
- }
1015
- return newTree;
1016
- }
1017
- }
1018
-
1019
- class TreeNode {
1020
- public scopeRef: ScopeRef;
1021
- public nodeToRestore?: FocusableElement;
1022
- public parent?: TreeNode;
1023
- public children: Set<TreeNode> = new Set();
1024
- public contain = false;
1025
-
1026
- constructor(props: {scopeRef: ScopeRef}) {
1027
- this.scopeRef = props.scopeRef;
1028
- }
1029
- addChild(node: TreeNode): void {
1030
- this.children.add(node);
1031
- node.parent = this;
1032
- }
1033
- removeChild(node: TreeNode): void {
1034
- this.children.delete(node);
1035
- node.parent = undefined;
1036
- }
1037
- }
1038
-
1039
- export let focusScopeTree: Tree = new Tree();