-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathdialog.ts
506 lines (437 loc) · 15 KB
/
dialog.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// WAI-ARIA: https://www.w3.org/WAI/ARIA/apg/patterns/dialogmodal/
import {
computed,
defineComponent,
h,
inject,
nextTick,
onMounted,
onUnmounted,
provide,
ref,
watchEffect,
type InjectionKey,
type PropType,
type Ref,
} from 'vue'
import { FocusTrap } from '../../components/focus-trap/focus-trap'
import { useDocumentOverflowLockedEffect } from '../../hooks/document-overflow/use-document-overflow'
import { useEventListener } from '../../hooks/use-event-listener'
import { useId } from '../../hooks/use-id'
import { useInert } from '../../hooks/use-inert'
import { useOutsideClick } from '../../hooks/use-outside-click'
import { useRootContainers } from '../../hooks/use-root-containers'
import { State, useOpenClosed } from '../../internal/open-closed'
import { ForcePortalRoot } from '../../internal/portal-force-root'
import { StackMessage, useStackProvider } from '../../internal/stack-context'
import { Keys } from '../../keyboard'
import { dom } from '../../utils/dom'
import { match } from '../../utils/match'
import { getOwnerDocument } from '../../utils/owner'
import { Features, render } from '../../utils/render'
import { Description, useDescriptions } from '../description/description'
import { Portal, PortalGroup, useNestedPortals } from '../portal/portal'
enum DialogStates {
Open,
Closed,
}
interface StateDefinition {
dialogState: Ref<DialogStates>
titleId: Ref<string | null>
panelRef: Ref<HTMLDivElement | null>
setTitleId(id: string | null): void
close(): void
}
let DialogContext = Symbol('DialogContext') as InjectionKey<StateDefinition>
function useDialogContext(component: string) {
let context = inject(DialogContext, null)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <Dialog /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useDialogContext)
throw err
}
return context
}
// ---
let Missing = 'DC8F892D-2EBD-447C-A4C8-A03058436FF4'
export let Dialog = defineComponent({
name: 'Dialog',
inheritAttrs: false, // Manually handling this
props: {
as: { type: [Object, String], default: 'div' },
static: { type: Boolean, default: false },
unmount: { type: Boolean, default: true },
open: { type: [Boolean, String], default: Missing },
initialFocus: { type: Object as PropType<HTMLElement | null>, default: null },
id: { type: String, default: () => `headlessui-dialog-${useId()}` },
role: { type: String as PropType<'dialog' | 'alertdialog'>, default: 'dialog' },
},
emits: { close: (_close: boolean) => true },
setup(props, { emit, attrs, slots, expose }) {
let ready = ref(false)
onMounted(() => {
ready.value = true
})
let didWarnOnRole = false
let role = computed(() => {
if (props.role === 'dialog' || props.role === 'alertdialog') {
return props.role
}
if (!didWarnOnRole) {
didWarnOnRole = true
console.warn(
`Invalid role [${role}] passed to <Dialog />. Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`
)
}
return 'dialog'
})
let nestedDialogCount = ref(0)
let usesOpenClosedState = useOpenClosed()
let open = computed(() => {
if (props.open === Missing && usesOpenClosedState !== null) {
return (usesOpenClosedState.value & State.Open) === State.Open
}
return props.open
})
let internalDialogRef = ref<HTMLDivElement | null>(null)
let ownerDocument = computed(() => getOwnerDocument(internalDialogRef))
expose({ el: internalDialogRef, $el: internalDialogRef })
// Validations
let hasOpen = props.open !== Missing || usesOpenClosedState !== null
if (!hasOpen) {
throw new Error(`You forgot to provide an \`open\` prop to the \`Dialog\`.`)
}
if (typeof open.value !== 'boolean') {
throw new Error(
`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${
open.value === Missing ? undefined : props.open
}`
)
}
let dialogState = computed(() =>
!ready.value ? DialogStates.Closed : open.value ? DialogStates.Open : DialogStates.Closed
)
let enabled = computed(() => dialogState.value === DialogStates.Open)
let hasNestedDialogs = computed(() => nestedDialogCount.value > 1) // 1 is the current dialog
let hasParentDialog = inject(DialogContext, null) !== null
let [portals, PortalWrapper] = useNestedPortals()
let {
resolveContainers: resolveRootContainers,
mainTreeNodeRef,
MainTreeNode,
} = useRootContainers({
portals,
defaultContainers: [computed(() => api.panelRef.value ?? internalDialogRef.value)],
})
// If there are multiple dialogs, then you can be the root, the leaf or one
// in between. We only care about whether you are the top most one or not.
let position = computed(() => (!hasNestedDialogs.value ? 'leaf' : 'parent'))
// When the `Dialog` is wrapped in a `Transition` (or another Headless UI component that exposes
// the OpenClosed state) then we get some information via context about its state. When the
// `Transition` is about to close, then the `State.Closing` state will be exposed. This allows us
// to enable/disable certain functionality in the `Dialog` upfront instead of waiting until the
// `Transition` is done transitioning.
let isClosing = computed(() =>
usesOpenClosedState !== null
? (usesOpenClosedState.value & State.Closing) === State.Closing
: false
)
// Ensure other elements can't be interacted with
let inertOthersEnabled = computed(() => {
// Nested dialogs should not modify the `inert` property, only the root one should.
if (hasParentDialog) return false
if (isClosing.value) return false
return enabled.value
})
let resolveRootOfMainTreeNode = computed(() => {
return (Array.from(ownerDocument.value?.querySelectorAll('body > *') ?? []).find((root) => {
// Skip the portal root, we don't want to make that one inert
if (root.id === 'headlessui-portal-root') return false
// Find the root of the main tree node
return root.contains(dom(mainTreeNodeRef)) && root instanceof HTMLElement
}) ?? null) as HTMLElement | null
})
useInert(resolveRootOfMainTreeNode, inertOthersEnabled)
// This would mark the parent dialogs as inert
let inertParentDialogs = computed(() => {
if (hasNestedDialogs.value) return true
return enabled.value
})
let resolveRootOfParentDialog = computed(() => {
return (Array.from(
ownerDocument.value?.querySelectorAll('[data-headlessui-portal]') ?? []
).find((root) => root.contains(dom(mainTreeNodeRef)) && root instanceof HTMLElement) ??
null) as HTMLElement | null
})
useInert(resolveRootOfParentDialog, inertParentDialogs)
useStackProvider({
type: 'Dialog',
enabled: computed(() => dialogState.value === DialogStates.Open),
element: internalDialogRef,
onUpdate: (message, type) => {
if (type !== 'Dialog') return
return match(message, {
[StackMessage.Add]: () => (nestedDialogCount.value += 1),
[StackMessage.Remove]: () => (nestedDialogCount.value -= 1),
})
},
})
let describedby = useDescriptions({
name: 'DialogDescription',
slot: computed(() => ({ open: open.value })),
})
let titleId = ref<StateDefinition['titleId']['value']>(null)
let api = {
titleId,
panelRef: ref(null),
dialogState,
setTitleId(id: string | null) {
if (titleId.value === id) return
titleId.value = id
},
close() {
emit('close', false)
},
}
provide(DialogContext, api)
// Handle outside click
let outsideClickEnabled = computed(() => {
if (!enabled.value) return false
if (hasNestedDialogs.value) return false
return true
})
useOutsideClick(
resolveRootContainers,
(event, target) => {
event.preventDefault()
api.close()
nextTick(() => target?.focus())
},
outsideClickEnabled
)
// Handle `Escape` to close
let escapeToCloseEnabled = computed(() => {
if (hasNestedDialogs.value) return false
if (dialogState.value !== DialogStates.Open) return false
return true
})
useEventListener(ownerDocument.value?.defaultView, 'keydown', (event) => {
if (!escapeToCloseEnabled.value) return
if (event.defaultPrevented) return
if (event.key !== Keys.Escape) return
event.preventDefault()
event.stopPropagation()
api.close()
})
// Scroll lock
let scrollLockEnabled = computed(() => {
if (isClosing.value) return false
if (dialogState.value !== DialogStates.Open) return false
if (hasParentDialog) return false
return true
})
useDocumentOverflowLockedEffect(ownerDocument, scrollLockEnabled, (meta) => ({
containers: [...(meta.containers ?? []), resolveRootContainers],
}))
// Trigger close when the FocusTrap gets hidden
watchEffect((onInvalidate) => {
if (dialogState.value !== DialogStates.Open) return
let container = dom(internalDialogRef)
if (!container) return
let observer = new ResizeObserver((entries) => {
for (let entry of entries) {
let rect = entry.target.getBoundingClientRect()
if (rect.x === 0 && rect.y === 0 && rect.width === 0 && rect.height === 0) {
api.close()
}
}
})
observer.observe(container)
onInvalidate(() => observer.disconnect())
})
return () => {
let { id, open: _, initialFocus, ...theirProps } = props
let ourProps = {
// Manually passthrough the attributes, because Vue can't automatically pass
// it to the underlying div because of all the wrapper components below.
...attrs,
ref: internalDialogRef,
id,
role: role.value,
'aria-modal': dialogState.value === DialogStates.Open ? true : undefined,
'aria-labelledby': titleId.value,
'aria-describedby': describedby.value,
}
let slot = { open: dialogState.value === DialogStates.Open }
return h(ForcePortalRoot, { force: true }, () => [
h(Portal, () =>
h(PortalGroup, { target: internalDialogRef.value }, () =>
h(ForcePortalRoot, { force: false }, () =>
h(
FocusTrap,
{
initialFocus,
containers: resolveRootContainers,
features: enabled.value
? match(position.value, {
parent: FocusTrap.features.RestoreFocus,
leaf: FocusTrap.features.All & ~FocusTrap.features.FocusLock,
})
: FocusTrap.features.None,
},
() =>
h(PortalWrapper, {}, () =>
render({
ourProps,
theirProps: { ...theirProps, ...attrs },
slot,
attrs,
slots,
visible: dialogState.value === DialogStates.Open,
features: Features.RenderStrategy | Features.Static,
name: 'Dialog',
})
)
)
)
)
),
h(MainTreeNode),
])
}
},
})
// ---
export let DialogOverlay = defineComponent({
name: 'DialogOverlay',
props: {
as: { type: [Object, String], default: 'div' },
id: { type: String, default: () => `headlessui-dialog-overlay-${useId()}` },
},
setup(props, { attrs, slots }) {
let api = useDialogContext('DialogOverlay')
function handleClick(event: MouseEvent) {
if (event.target !== event.currentTarget) return
event.preventDefault()
event.stopPropagation()
api.close()
}
return () => {
let { id, ...theirProps } = props
let ourProps = {
id,
'aria-hidden': true,
onClick: handleClick,
}
return render({
ourProps,
theirProps,
slot: { open: api.dialogState.value === DialogStates.Open },
attrs,
slots,
name: 'DialogOverlay',
})
}
},
})
// ---
export let DialogBackdrop = defineComponent({
name: 'DialogBackdrop',
props: {
as: { type: [Object, String], default: 'div' },
id: { type: String, default: () => `headlessui-dialog-backdrop-${useId()}` },
},
inheritAttrs: false,
setup(props, { attrs, slots, expose }) {
let api = useDialogContext('DialogBackdrop')
let internalBackdropRef = ref(null)
expose({ el: internalBackdropRef, $el: internalBackdropRef })
onMounted(() => {
if (api.panelRef.value === null) {
throw new Error(
`A <DialogBackdrop /> component is being used, but a <DialogPanel /> component is missing.`
)
}
})
return () => {
let { id, ...theirProps } = props
let ourProps = {
id,
ref: internalBackdropRef,
'aria-hidden': true,
}
return h(ForcePortalRoot, { force: true }, () =>
h(Portal, () =>
render({
ourProps,
theirProps: { ...attrs, ...theirProps },
slot: { open: api.dialogState.value === DialogStates.Open },
attrs,
slots,
name: 'DialogBackdrop',
})
)
)
}
},
})
// ---
export let DialogPanel = defineComponent({
name: 'DialogPanel',
props: {
as: { type: [Object, String], default: 'div' },
id: { type: String, default: () => `headlessui-dialog-panel-${useId()}` },
},
setup(props, { attrs, slots, expose }) {
let api = useDialogContext('DialogPanel')
expose({ el: api.panelRef, $el: api.panelRef })
function handleClick(event: MouseEvent) {
event.stopPropagation()
}
return () => {
let { id, ...theirProps } = props
let ourProps = {
id,
ref: api.panelRef,
onClick: handleClick,
}
return render({
ourProps,
theirProps,
slot: { open: api.dialogState.value === DialogStates.Open },
attrs,
slots,
name: 'DialogPanel',
})
}
},
})
// ---
export let DialogTitle = defineComponent({
name: 'DialogTitle',
props: {
as: { type: [Object, String], default: 'h2' },
id: { type: String, default: () => `headlessui-dialog-title-${useId()}` },
},
setup(props, { attrs, slots }) {
let api = useDialogContext('DialogTitle')
onMounted(() => {
api.setTitleId(props.id)
onUnmounted(() => api.setTitleId(null))
})
return () => {
let { id, ...theirProps } = props
let ourProps = { id }
return render({
ourProps,
theirProps,
slot: { open: api.dialogState.value === DialogStates.Open },
attrs,
slots,
name: 'DialogTitle',
})
}
},
})
// ---
export let DialogDescription = Description