/
focus-trap.tsx
276 lines (235 loc) · 7.88 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import React, {
useEffect,
useRef,
// Types
ElementType,
MutableRefObject,
Ref,
} from 'react'
import { Props } from '../../types'
import { forwardRefWithAs, render } from '../../utils/render'
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
import { useSyncRefs } from '../../hooks/use-sync-refs'
import { Features as HiddenFeatures, Hidden } from '../../internal/hidden'
import { focusElement, focusIn, Focus, FocusResult } from '../../utils/focus-management'
import { match } from '../../utils/match'
import { useEvent } from '../../hooks/use-event'
import { useTabDirection, Direction as TabDirection } from '../../hooks/use-tab-direction'
import { useIsMounted } from '../../hooks/use-is-mounted'
import { useOwnerDocument } from '../../hooks/use-owner'
import { useEventListener } from '../../hooks/use-event-listener'
import { microTask } from '../../utils/micro-task'
import { useWatch } from '../../hooks/use-watch'
let DEFAULT_FOCUS_TRAP_TAG = 'div' as const
enum Features {
/** No features enabled for the focus trap. */
None = 1 << 0,
/** Ensure that we move focus initially into the container. */
InitialFocus = 1 << 1,
/** Ensure that pressing `Tab` and `Shift+Tab` is trapped within the container. */
TabLock = 1 << 2,
/** Ensure that programmatically moving focus outside of the container is disallowed. */
FocusLock = 1 << 3,
/** Ensure that we restore the focus when unmounting the focus trap. */
RestoreFocus = 1 << 4,
/** Enable all features. */
All = InitialFocus | TabLock | FocusLock | RestoreFocus,
}
export let FocusTrap = Object.assign(
forwardRefWithAs(function FocusTrap<TTag extends ElementType = typeof DEFAULT_FOCUS_TRAP_TAG>(
props: Props<TTag> & {
initialFocus?: MutableRefObject<HTMLElement | null>
features?: Features
containers?: MutableRefObject<Set<MutableRefObject<HTMLElement | null>>>
},
ref: Ref<HTMLDivElement>
) {
let container = useRef<HTMLDivElement | null>(null)
let focusTrapRef = useSyncRefs(container, ref)
let { initialFocus, containers, features = Features.All, ...theirProps } = props
if (!useServerHandoffComplete()) {
features = Features.None
}
let ownerDocument = useOwnerDocument(container)
useRestoreFocus({ ownerDocument }, Boolean(features & Features.RestoreFocus))
let previousActiveElement = useInitialFocus(
{ ownerDocument, container, initialFocus },
Boolean(features & Features.InitialFocus)
)
useFocusLock(
{ ownerDocument, container, containers, previousActiveElement },
Boolean(features & Features.FocusLock)
)
let direction = useTabDirection()
let handleFocus = useEvent(() => {
let el = container.current as HTMLElement
if (!el) return
// TODO: Cleanup once we are using real browser tests
if (process.env.NODE_ENV === 'test') {
microTask(() => {
match(direction.current, {
[TabDirection.Forwards]: () => focusIn(el, Focus.First),
[TabDirection.Backwards]: () => focusIn(el, Focus.Last),
})
})
} else {
match(direction.current, {
[TabDirection.Forwards]: () => focusIn(el, Focus.First),
[TabDirection.Backwards]: () => focusIn(el, Focus.Last),
})
}
})
let ourProps = { ref: focusTrapRef }
return (
<>
{Boolean(features & Features.TabLock) && (
<Hidden
as="button"
type="button"
onFocus={handleFocus}
features={HiddenFeatures.Focusable}
/>
)}
{render({
ourProps,
theirProps,
defaultTag: DEFAULT_FOCUS_TRAP_TAG,
name: 'FocusTrap',
})}
{Boolean(features & Features.TabLock) && (
<Hidden
as="button"
type="button"
onFocus={handleFocus}
features={HiddenFeatures.Focusable}
/>
)}
</>
)
}),
{ features: Features }
)
function useRestoreFocus({ ownerDocument }: { ownerDocument: Document | null }, enabled: boolean) {
let restoreElement = useRef<HTMLElement | null>(null)
// Capture the currently focused element, before we try to move the focus inside the FocusTrap.
useEventListener(
ownerDocument?.defaultView,
'focusout',
(event) => {
if (!enabled) return
if (restoreElement.current) return
restoreElement.current = event.target as HTMLElement
},
true
)
// Restore the focus to the previous element when `enabled` becomes false again
useWatch(() => {
if (enabled) return
if (ownerDocument?.activeElement === ownerDocument?.body) {
focusElement(restoreElement.current)
}
restoreElement.current = null
}, [enabled])
// Restore the focus to the previous element when the component is unmounted
let trulyUnmounted = useRef(false)
useEffect(() => {
trulyUnmounted.current = false
return () => {
trulyUnmounted.current = true
microTask(() => {
if (!trulyUnmounted.current) return
focusElement(restoreElement.current)
restoreElement.current = null
})
}
}, [])
}
function useInitialFocus(
{
ownerDocument,
container,
initialFocus,
}: {
ownerDocument: Document | null
container: MutableRefObject<HTMLElement | null>
initialFocus?: MutableRefObject<HTMLElement | null>
},
enabled: boolean
) {
let previousActiveElement = useRef<HTMLElement | null>(null)
// Handle initial focus
useWatch(() => {
if (!enabled) return
let containerElement = container.current
if (!containerElement) return
let activeElement = ownerDocument?.activeElement as HTMLElement
if (initialFocus?.current) {
if (initialFocus?.current === activeElement) {
previousActiveElement.current = activeElement
return // Initial focus ref is already the active element
}
} else if (containerElement.contains(activeElement)) {
previousActiveElement.current = activeElement
return // Already focused within Dialog
}
// Try to focus the initialFocus ref
if (initialFocus?.current) {
focusElement(initialFocus.current)
} else {
if (focusIn(containerElement, Focus.First) === FocusResult.Error) {
console.warn('There are no focusable elements inside the <FocusTrap />')
}
}
previousActiveElement.current = ownerDocument?.activeElement as HTMLElement
}, [enabled])
return previousActiveElement
}
function useFocusLock(
{
ownerDocument,
container,
containers,
previousActiveElement,
}: {
ownerDocument: Document | null
container: MutableRefObject<HTMLElement | null>
containers?: MutableRefObject<Set<MutableRefObject<HTMLElement | null>>>
previousActiveElement: MutableRefObject<HTMLElement | null>
},
enabled: boolean
) {
let mounted = useIsMounted()
// Prevent programmatically escaping the container
useEventListener(
ownerDocument?.defaultView,
'focus',
(event) => {
if (!enabled) return
if (!mounted.current) return
let allContainers = new Set(containers?.current)
allContainers.add(container)
let previous = previousActiveElement.current
if (!previous) return
let toElement = event.target as HTMLElement | null
if (toElement && toElement instanceof HTMLElement) {
if (!contains(allContainers, toElement)) {
event.preventDefault()
event.stopPropagation()
focusElement(previous)
} else {
previousActiveElement.current = toElement
focusElement(toElement)
}
} else {
focusElement(previousActiveElement.current)
}
},
true
)
}
function contains(containers: Set<MutableRefObject<HTMLElement | null>>, element: HTMLElement) {
for (let container of containers) {
if (container.current?.contains(element)) return true
}
return false
}