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