-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
component.ts
38 lines (33 loc) · 1.15 KB
/
component.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
import { defineComponent, h, onScopeDispose, ref, watch } from 'vue-demi'
import { createFocusTrap } from 'focus-trap'
import type { FocusTrap } from 'focus-trap'
import type { RenderableComponent } from '@vueuse/core'
import { unrefElement } from '@vueuse/core'
import type { UseFocusTrapOptions } from '.'
export interface ComponentUseFocusTrapOptions extends RenderableComponent {
options?: UseFocusTrapOptions
}
export const UseFocusTrap = /* #__PURE__ */ defineComponent <ComponentUseFocusTrapOptions> ({
name: 'UseFocusTrap',
props: ['as', 'options'] as unknown as undefined,
setup(props, { slots }) {
let trap: undefined | FocusTrap
const target = ref()
const activate = () => trap && trap.activate()
const deactivate = () => trap && trap.deactivate()
watch(
() => unrefElement(target),
(el) => {
if (!el)
return
trap = createFocusTrap(el, props.options || {})
activate()
}, { flush: 'post' })
// Cleanup on unmount
onScopeDispose(() => deactivate())
return () => {
if (slots.default)
return h(props.as || 'div', { ref: target }, slots.default())
}
},
})