-
Notifications
You must be signed in to change notification settings - Fork 1k
/
focus-trap.ts
296 lines (257 loc) · 8.36 KB
/
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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import {
computed,
defineComponent,
h,
onMounted,
ref,
watch,
// Types
PropType,
Fragment,
Ref,
} from 'vue'
import { render } from '../../utils/render'
import { Hidden, Features as HiddenFeatures } from '../../internal/hidden'
import { dom } from '../../utils/dom'
import { focusIn, Focus, focusElement, FocusResult } from '../../utils/focus-management'
import { match } from '../../utils/match'
import { useTabDirection, Direction as TabDirection } from '../../hooks/use-tab-direction'
import { getOwnerDocument } from '../../utils/owner'
import { useEventListener } from '../../hooks/use-event-listener'
import { microTask } from '../../utils/micro-task'
// import { disposables } from '../../utils/disposables'
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(
defineComponent({
name: 'FocusTrap',
props: {
as: { type: [Object, String], default: 'div' },
initialFocus: { type: Object as PropType<HTMLElement | null>, default: null },
features: { type: Number as PropType<Features>, default: Features.All },
containers: {
type: Object as PropType<Ref<Set<Ref<HTMLElement | null>>>>,
default: ref(new Set()),
},
},
inheritAttrs: false,
setup(props, { attrs, slots, expose }) {
let container = ref<HTMLElement | null>(null)
expose({ el: container, $el: container })
let ownerDocument = computed(() => getOwnerDocument(container))
useRestoreFocus(
{ ownerDocument },
computed(() => Boolean(props.features & Features.RestoreFocus))
)
let previousActiveElement = useInitialFocus(
{ ownerDocument, container, initialFocus: computed(() => props.initialFocus) },
computed(() => Boolean(props.features & Features.InitialFocus))
)
useFocusLock(
{
ownerDocument,
container,
containers: props.containers,
previousActiveElement,
},
computed(() => Boolean(props.features & Features.FocusLock))
)
let direction = useTabDirection()
function handleFocus() {
let el = dom(container) as HTMLElement
if (!el) return
// TODO: Cleanup once we are using real browser tests
if (process.env.NODE_ENV === 'test') {
microTask(() => {
match(direction.value, {
[TabDirection.Forwards]: () => focusIn(el, Focus.First),
[TabDirection.Backwards]: () => focusIn(el, Focus.Last),
})
})
} else {
match(direction.value, {
[TabDirection.Forwards]: () => focusIn(el, Focus.First),
[TabDirection.Backwards]: () => focusIn(el, Focus.Last),
})
}
}
return () => {
let slot = {}
let ourProps = { ref: container }
let { features, initialFocus, containers: _containers, ...theirProps } = props
return h(Fragment, [
Boolean(features & Features.TabLock) &&
h(Hidden, {
as: 'button',
type: 'button',
onFocus: handleFocus,
features: HiddenFeatures.Focusable,
}),
render({
ourProps,
theirProps: { ...attrs, ...theirProps },
slot,
attrs,
slots,
name: 'FocusTrap',
}),
Boolean(features & Features.TabLock) &&
h(Hidden, {
as: 'button',
type: 'button',
onFocus: handleFocus,
features: HiddenFeatures.Focusable,
}),
])
}
},
}),
{ features: Features }
)
function useRestoreFocus(
{ ownerDocument }: { ownerDocument: Ref<Document | null> },
enabled: Ref<boolean>
) {
let restoreElement = ref<HTMLElement | null>(null)
// Deliberately not using a ref, we don't want to trigger re-renders.
let mounted = { value: false }
onMounted(() => {
// Capture the currently focused element, before we try to move the focus inside the FocusTrap.
watch(
enabled,
(newValue, prevValue) => {
if (newValue === prevValue) return
if (!enabled.value) return
mounted.value = true
if (!restoreElement.value) {
restoreElement.value = ownerDocument.value?.activeElement as HTMLElement
}
},
{ immediate: true }
)
// Restore the focus when we unmount the component.
watch(
enabled,
(newValue, prevValue, onInvalidate) => {
if (newValue === prevValue) return
if (!enabled.value) return
onInvalidate(() => {
if (mounted.value === false) return
mounted.value = false
focusElement(restoreElement.value)
restoreElement.value = null
})
},
{ immediate: true }
)
})
}
function useInitialFocus(
{
ownerDocument,
container,
initialFocus,
}: {
ownerDocument: Ref<Document | null>
container: Ref<HTMLElement | null>
initialFocus?: Ref<HTMLElement | null>
},
enabled: Ref<boolean>
) {
let previousActiveElement = ref<HTMLElement | null>(null)
onMounted(() => {
watch(
// Handle initial focus
[container, initialFocus, enabled],
(newValues, prevValues) => {
if (newValues.every((value, idx) => prevValues?.[idx] === value)) return
if (!enabled.value) return
let containerElement = dom(container)
if (!containerElement) return
requestAnimationFrame(() => {
let initialFocusElement = dom(initialFocus)
let activeElement = ownerDocument.value?.activeElement as HTMLElement
if (initialFocusElement) {
if (initialFocusElement === activeElement) {
previousActiveElement.value = activeElement
return // Initial focus ref is already the active element
}
} else if (containerElement!.contains(activeElement)) {
previousActiveElement.value = activeElement
return // Already focused within Dialog
}
// Try to focus the initialFocus ref
if (initialFocusElement) {
focusElement(initialFocusElement)
} else {
if (focusIn(containerElement!, Focus.First | Focus.NoScroll) === FocusResult.Error) {
console.warn('There are no focusable elements inside the <FocusTrap />')
}
}
previousActiveElement.value = ownerDocument.value?.activeElement as HTMLElement
})
},
{ immediate: true, flush: 'post' }
)
})
return previousActiveElement
}
function useFocusLock(
{
ownerDocument,
container,
containers,
previousActiveElement,
}: {
ownerDocument: Ref<Document | null>
container: Ref<HTMLElement | null>
containers: Ref<Set<Ref<HTMLElement | null>>>
previousActiveElement: Ref<HTMLElement | null>
},
enabled: Ref<boolean>
) {
// Prevent programmatically escaping
useEventListener(
ownerDocument.value?.defaultView,
'focus',
(event) => {
if (!enabled.value) return
let allContainers = new Set(containers?.value)
allContainers.add(container)
let previous = previousActiveElement.value
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.value = toElement
focusElement(toElement)
}
} else {
focusElement(previousActiveElement.value)
}
},
true
)
}
function contains(containers: Set<Ref<HTMLElement | null>>, element: HTMLElement) {
for (let container of containers) {
if (container.value?.contains(element)) return true
}
return false
}