MCPcopy Create free account
hub / github.com/adobe/react-spectrum / FocusScope

Function FocusScope

packages/react-aria/src/focus/FocusScope.tsx:104–226  ·  view source on GitHub ↗
(props: FocusScopeProps)

Source from the content-addressed store, hash-verified

102 * to user events.
103 */
104export function FocusScope(props: FocusScopeProps): JSX.Element {
105 let {children, contain, restoreFocus, autoFocus} = props;
106 let startRef = useRef<HTMLSpanElement>(null);
107 let endRef = useRef<HTMLSpanElement>(null);
108 let scopeRef = useRef<Element[]>([]);
109 let {parentNode} = useContext(FocusContext) || {};
110
111 // Create a tree node here so we can add children to it even before it is added to the tree.
112 let node = useMemo(() => new TreeNode({scopeRef}), [scopeRef]);
113
114 useLayoutEffect(() => {
115 // If a new scope mounts outside the active scope, (e.g. DialogContainer launched from a menu),
116 // use the active scope as the parent instead of the parent from context. Layout effects run bottom
117 // up, so if the parent is not yet added to the tree, don't do this. Only the outer-most FocusScope
118 // that is being added should get the activeScope as its parent.
119 let parent = parentNode || focusScopeTree.root;
120 if (
121 focusScopeTree.getTreeNode(parent.scopeRef) &&
122 activeScope &&
123 !isAncestorScope(activeScope, parent.scopeRef)
124 ) {
125 let activeNode = focusScopeTree.getTreeNode(activeScope);
126 if (activeNode) {
127 parent = activeNode;
128 }
129 }
130
131 // Add the node to the parent, and to the tree.
132 parent.addChild(node);
133 focusScopeTree.addNode(node);
134 }, [node, parentNode]);
135
136 useLayoutEffect(() => {
137 let node = focusScopeTree.getTreeNode(scopeRef);
138 if (node) {
139 node.contain = !!contain;
140 }
141 }, [contain]);
142
143 useLayoutEffect(() => {
144 // Find all rendered nodes between the sentinels and add them to the scope.
145 let node = startRef.current?.nextSibling!;
146 let nodes: Element[] = [];
147 let stopPropagation = e => e.stopPropagation();
148 while (node && node !== endRef.current) {
149 nodes.push(node as Element);
150 // Stop custom restore focus event from propagating to parent focus scopes.
151 node.addEventListener(RESTORE_FOCUS_EVENT, stopPropagation);
152 node = node.nextSibling as Element;
153 }
154
155 scopeRef.current = nodes;
156
157 return () => {
158 for (let node of nodes) {
159 node.removeEventListener(RESTORE_FOCUS_EVENT, stopPropagation);
160 }
161 };

Callers

nothing calls this directly

Calls 15

getActiveElementFunction · 0.90
getOwnerDocumentFunction · 0.90
isAncestorScopeFunction · 0.85
useActiveScopeTrackerFunction · 0.85
useFocusContainmentFunction · 0.85
useRestoreFocusFunction · 0.85
useAutoFocusFunction · 0.85
isElementInScopeFunction · 0.85
getTreeNodeMethod · 0.80
addChildMethod · 0.80
pushMethod · 0.80

Tested by

no test coverage detected