forked from vercel/commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfocus-trap.tsx
67 lines (60 loc) · 1.54 KB
/
focus-trap.tsx
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
import React, { useEffect, RefObject } from 'react'
import { tabbable } from 'tabbable'
interface Props {
children: React.ReactNode | any
focusFirst?: boolean
}
export default function FocusTrap({ children, focusFirst = false }: Props) {
const root: RefObject<any> = React.useRef()
const anchor: RefObject<any> = React.useRef(document.activeElement)
const returnFocus = () => {
// Returns focus to the last focused element prior to trap.
if (anchor) {
anchor.current.focus()
}
}
const trapFocus = () => {
// Focus the container element
if (root.current) {
root.current.focus()
if (focusFirst) {
selectFirstFocusableEl()
}
}
}
const selectFirstFocusableEl = () => {
// Try to find focusable elements, if match then focus
// Up to 6 seconds of load time threshold
let match = false
let end = 60 // Try to find match at least n times
let i = 0
const timer = setInterval(() => {
if (!match !== i > end) {
match = !!tabbable(root.current).length
if (match) {
// Attempt to focus the first el
tabbable(root.current)[0].focus()
}
i = i + 1
} else {
// Clear interval after n attempts
clearInterval(timer)
}
}, 100)
}
useEffect(() => {
setTimeout(trapFocus, 20)
return () => {
returnFocus()
}
}, [root, children])
return React.createElement(
'div',
{
ref: root,
className: 'outline-none focus-trap',
tabIndex: -1,
},
children
)
}