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

Function useFocusContainment

packages/react-aria/src/focus/FocusScope.tsx:352–492  ·  view source on GitHub ↗
(scopeRef: RefObject<Element[] | null>, contain?: boolean)

Source from the content-addressed store, hash-verified

350}
351
352function useFocusContainment(scopeRef: RefObject<Element[] | null>, contain?: boolean) {
353 let focusedNode = useRef<FocusableElement>(undefined);
354
355 let raf = useRef<ReturnType<typeof requestAnimationFrame>>(undefined);
356 useLayoutEffect(() => {
357 let scope = scopeRef.current;
358 if (!contain) {
359 // if contain was changed, then we should cancel any ongoing waits to pull focus back into containment
360 if (raf.current) {
361 cancelAnimationFrame(raf.current);
362 raf.current = undefined;
363 }
364 return;
365 }
366
367 const ownerDocument = getOwnerDocument(scope ? scope[0] : undefined);
368
369 // Handle the Tab key to contain focus within the scope
370 let onKeyDown = e => {
371 if (
372 e.key !== 'Tab' ||
373 e.altKey ||
374 e.ctrlKey ||
375 e.metaKey ||
376 !shouldContainFocus(scopeRef) ||
377 e.isComposing
378 ) {
379 return;
380 }
381
382 let focusedElement = getActiveElement(ownerDocument);
383 let scope = scopeRef.current;
384 if (!scope || !isElementInScope(focusedElement, scope)) {
385 return;
386 }
387
388 let scopeRoot = getScopeRoot(scope);
389 let walker = getFocusableTreeWalker(scopeRoot, {tabbable: true}, scope);
390 if (!focusedElement) {
391 return;
392 }
393 walker.currentNode = focusedElement;
394 let nextElement = (
395 e.shiftKey ? walker.previousNode() : walker.nextNode()
396 ) as FocusableElement;
397 if (!nextElement) {
398 walker.currentNode = e.shiftKey
399 ? scope[scope.length - 1].nextElementSibling!
400 : scope[0].previousElementSibling!;
401 nextElement = (e.shiftKey ? walker.previousNode() : walker.nextNode()) as FocusableElement;
402 }
403
404 e.preventDefault();
405 if (nextElement) {
406 focusElement(nextElement, true);
407 if (nextElement instanceof getOwnerWindow(nextElement).HTMLInputElement) {
408 nextElement.select();
409 }

Callers 1

FocusScopeFunction · 0.85

Calls 3

getOwnerDocumentFunction · 0.90
addEventListenerMethod · 0.80
removeEventListenerMethod · 0.80

Tested by

no test coverage detected