-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-focus-trap.tsx
More file actions
58 lines (51 loc) · 1.52 KB
/
use-focus-trap.tsx
File metadata and controls
58 lines (51 loc) · 1.52 KB
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
import React, { useRef, useEffect, useState } from 'react';
export default function useFocusTrap({
autoFocus = true,
betterPreventScroll = false,
}: {
autoFocus?: boolean;
betterPreventScroll?: boolean;
} = {}) {
const startFocusRef = useRef<HTMLDivElement>(null);
const endFocusRef = useRef<HTMLDivElement>(null);
const [hasFocusOnMount, setHasFocusOnMount] = useState(false);
function handleStartKeyDown(e: React.KeyboardEvent) {
if (e.keyCode === 9 && e.shiftKey && endFocusRef.current) {
endFocusRef.current.focus({ preventScroll: true });
}
}
function handleEndKeyDown(e: React.KeyboardEvent) {
if (e.keyCode === 9 && !e.shiftKey && startFocusRef.current) {
startFocusRef.current.focus({ preventScroll: true });
}
}
useEffect(() => {
if (startFocusRef.current && !hasFocusOnMount && autoFocus) {
startFocusRef.current.focus();
setHasFocusOnMount(true);
}
}, [startFocusRef.current, autoFocus]);
useEffect(() => {
if (endFocusRef.current && betterPreventScroll) {
Object.assign(endFocusRef.current.style, {
position: 'absolute',
top: '0px',
});
}
}, [endFocusRef, betterPreventScroll]);
function focusTrapStart() {
return (
<div
ref={startFocusRef}
tabIndex={0}
onKeyDown={handleStartKeyDown}
></div>
);
}
function focusTrapEnd() {
return (
<div ref={endFocusRef} tabIndex={0} onKeyDown={handleEndKeyDown}></div>
);
}
return [focusTrapStart, focusTrapEnd];
}