/
use-focus-trap.ts
83 lines (69 loc) · 2.44 KB
/
use-focus-trap.ts
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
import { useCallback, useEffect, useRef } from 'react';
import { FOCUS_SELECTOR, focusable, tabbable } from './tabbable';
import { scopeTab } from './scope-tab';
import { createAriaHider } from './create-aria-hider';
export function useFocusTrap(active = true): (instance: HTMLElement | null) => void {
const ref = useRef<HTMLElement | null>();
const restoreAria = useRef<Function | null>(null);
const setRef = useCallback(
(node: HTMLElement | null) => {
if (!active) {
return;
}
if (node === ref.current || node === null) {
return;
}
if (restoreAria.current) {
restoreAria.current();
}
if (node) {
const processNode = (_node: HTMLElement) => {
restoreAria.current = createAriaHider(_node);
let focusElement: HTMLElement = node.querySelector('[data-autofocus]');
if (!focusElement) {
const children = Array.from<HTMLElement>(node.querySelectorAll(FOCUS_SELECTOR));
focusElement = children.find(tabbable) || children.find(focusable) || null;
if (!focusElement && focusable(node)) focusElement = node;
}
if (focusElement) {
focusElement.focus({ preventScroll: true });
} else if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.warn(
'[@mantine/hooks/use-focus-trap] Failed to find focusable element within provided node',
node
);
}
};
// Delay processing the HTML node by a frame. This ensures focus is assigned correctly.
setTimeout(() => {
if (node.ownerDocument) {
processNode(node);
} else if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.warn('[@mantine/hooks/use-focus-trap] Ref node is not part of the dom', node);
}
});
ref.current = node;
} else {
ref.current = null;
}
},
[active]
);
useEffect(() => {
if (!active) {
return undefined;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Tab' && ref.current) {
scopeTab(ref.current, event);
}
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [active]);
return setRef;
}