MCPcopy
hub / github.com/QwikDev/qwik / useTrapFocus

Function useTrapFocus

packages/docs/src/components/docsearch/useTrapFocus.ts:7–42  ·  view source on GitHub ↗
(props: UseTrapFocusProps)

Source from the content-addressed store, hash-verified

5}
6
7export function useTrapFocus(props: UseTrapFocusProps) {
8 useTask$(({ track }) => {
9 const container = track(() => props.containerRef.value) as HTMLElement;
10 if (!container) {
11 return undefined;
12 }
13
14 const focusableElements = container.querySelectorAll<HTMLElement>(
15 'a[href]:not([disabled]), button:not([disabled]), input:not([disabled])'
16 );
17 const firstElement = focusableElements[0];
18 const lastElement = focusableElements[focusableElements.length - 1];
19
20 function trapFocus(event: KeyboardEvent) {
21 if (event.key !== 'Tab') {
22 return;
23 }
24
25 if (event.shiftKey) {
26 if (document.activeElement === firstElement) {
27 event.preventDefault();
28 lastElement.focus();
29 }
30 } else if (document.activeElement === lastElement) {
31 event.preventDefault();
32 firstElement.focus();
33 }
34 }
35
36 container.addEventListener('keydown', trapFocus);
37
38 return () => {
39 container.removeEventListener('keydown', trapFocus);
40 };
41 });
42}

Callers

nothing calls this directly

Calls 2

trackFunction · 0.85
querySelectorAllMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…