-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
dialog.tsx
603 lines (510 loc) · 17.5 KB
/
dialog.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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
'use client'
// WAI-ARIA: https://www.w3.org/WAI/ARIA/apg/patterns/dialogmodal/
import React, {
Fragment,
createContext,
createRef,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
type ContextType,
type ElementType,
type MutableRefObject,
type MouseEvent as ReactMouseEvent,
type Ref,
type RefObject,
} from 'react'
import { useEscape } from '../../hooks/use-escape'
import { useEvent } from '../../hooks/use-event'
import { useId } from '../../hooks/use-id'
import { useInertOthers } from '../../hooks/use-inert-others'
import { useIsTouchDevice } from '../../hooks/use-is-touch-device'
import { useOnDisappear } from '../../hooks/use-on-disappear'
import { useOutsideClick } from '../../hooks/use-outside-click'
import { useOwnerDocument } from '../../hooks/use-owner'
import {
MainTreeProvider,
useMainTreeNode,
useRootContainers,
} from '../../hooks/use-root-containers'
import { useScrollLock } from '../../hooks/use-scroll-lock'
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
import { useSyncRefs } from '../../hooks/use-sync-refs'
import { CloseProvider } from '../../internal/close-provider'
import { ResetOpenClosedProvider, State, useOpenClosed } from '../../internal/open-closed'
import { ForcePortalRoot } from '../../internal/portal-force-root'
import type { Props } from '../../types'
import { match } from '../../utils/match'
import {
RenderFeatures,
forwardRefWithAs,
useRender,
type HasDisplayName,
type PropsForFeatures,
type RefProp,
} from '../../utils/render'
import {
Description,
useDescriptions,
type _internal_ComponentDescription,
} from '../description/description'
import { FocusTrap, FocusTrapFeatures } from '../focus-trap/focus-trap'
import { Portal, PortalGroup, useNestedPortals } from '../portal/portal'
import { Transition, TransitionChild } from '../transition/transition'
enum DialogStates {
Open,
Closed,
}
interface StateDefinition {
titleId: string | null
panelRef: MutableRefObject<HTMLElement | null>
}
enum ActionTypes {
SetTitleId,
}
type Actions = { type: ActionTypes.SetTitleId; id: string | null }
let reducers: {
[P in ActionTypes]: (
state: StateDefinition,
action: Extract<Actions, { type: P }>
) => StateDefinition
} = {
[ActionTypes.SetTitleId](state, action) {
if (state.titleId === action.id) return state
return { ...state, titleId: action.id }
},
}
let DialogContext = createContext<
| [
{
dialogState: DialogStates
unmount: boolean
close: () => void
setTitleId: (id: string | null) => void
},
StateDefinition,
]
| null
>(null)
DialogContext.displayName = 'DialogContext'
function useDialogContext(component: string) {
let context = useContext(DialogContext)
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
}
function stateReducer(state: StateDefinition, action: Actions) {
return match(action.type, reducers, state, action)
}
// ---
let InternalDialog = forwardRefWithAs(function InternalDialog<
TTag extends ElementType = typeof DEFAULT_DIALOG_TAG,
>(props: DialogProps<TTag>, ref: Ref<HTMLElement>) {
let internalId = useId()
let {
id = `headlessui-dialog-${internalId}`,
open,
onClose,
initialFocus,
role = 'dialog',
autoFocus = true,
__demoMode = false,
unmount = false,
...theirProps
} = props
let didWarnOnRole = useRef(false)
role = (function () {
if (role === 'dialog' || role === 'alertdialog') {
return role
}
if (!didWarnOnRole.current) {
didWarnOnRole.current = true
console.warn(
`Invalid role [${role}] passed to <Dialog />. Only \`dialog\` and and \`alertdialog\` are supported. Using \`dialog\` instead.`
)
}
return 'dialog'
})()
let usesOpenClosedState = useOpenClosed()
if (open === undefined && usesOpenClosedState !== null) {
// Update the `open` prop based on the open closed state
open = (usesOpenClosedState & State.Open) === State.Open
}
let internalDialogRef = useRef<HTMLElement | null>(null)
let dialogRef = useSyncRefs(internalDialogRef, ref)
let ownerDocument = useOwnerDocument(internalDialogRef)
let dialogState = open ? DialogStates.Open : DialogStates.Closed
let [state, dispatch] = useReducer(stateReducer, {
titleId: null,
descriptionId: null,
panelRef: createRef(),
} as StateDefinition)
let close = useEvent(() => onClose(false))
let setTitleId = useEvent((id: string | null) => dispatch({ type: ActionTypes.SetTitleId, id }))
let ready = useServerHandoffComplete()
let enabled = ready ? dialogState === DialogStates.Open : false
let [portals, PortalWrapper] = useNestedPortals()
// We use this because reading these values during initial render(s)
// can result in `null` rather then the actual elements
// This doesn't happen when using certain components like a
// `<Dialog.Title>` because they cause the parent to re-render
let defaultContainer: RefObject<HTMLElement> = {
get current() {
return state.panelRef.current ?? internalDialogRef.current
},
}
let mainTreeNode = useMainTreeNode()
let { resolveContainers: resolveRootContainers } = useRootContainers({
mainTreeNode,
portals,
defaultContainers: [defaultContainer],
})
// 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 =
usesOpenClosedState !== null ? (usesOpenClosedState & State.Closing) === State.Closing : false
// Ensure other elements can't be interacted with
let inertOthersEnabled = __demoMode ? false : isClosing ? false : enabled
useInertOthers(inertOthersEnabled, {
allowed: useEvent(() => [
// Allow the headlessui-portal of the Dialog to be interactive. This
// contains the current dialog and the necessary focus guard elements.
internalDialogRef.current?.closest<HTMLElement>('[data-headlessui-portal]') ?? null,
]),
disallowed: useEvent(() => [
// Disallow the "main" tree root node
mainTreeNode?.closest<HTMLElement>('body > *:not(#headlessui-portal-root)') ?? null,
]),
})
// Close Dialog on outside click
useOutsideClick(enabled, resolveRootContainers, (event) => {
event.preventDefault()
close()
})
// Handle `Escape` to close
useEscape(enabled, ownerDocument?.defaultView, (event) => {
event.preventDefault()
event.stopPropagation()
// Ensure that we blur the current activeElement to prevent maintaining
// focus and potentially scrolling the page to the end (because the Dialog
// is rendered in a Portal at the end of the document.body and the browser
// tries to keep the focused element in view)
//
// Typically only happens in Safari.
if (
document.activeElement &&
'blur' in document.activeElement &&
typeof document.activeElement.blur === 'function'
) {
document.activeElement.blur()
}
close()
})
// Scroll lock
let scrollLockEnabled = __demoMode ? false : isClosing ? false : enabled
useScrollLock(scrollLockEnabled, ownerDocument, resolveRootContainers)
// Ensure we close the dialog as soon as the dialog itself becomes hidden
useOnDisappear(enabled, internalDialogRef, close)
let [describedby, DescriptionProvider] = useDescriptions()
let contextBag = useMemo<ContextType<typeof DialogContext>>(
() => [{ dialogState, close, setTitleId, unmount }, state],
[dialogState, state, close, setTitleId, unmount]
)
let slot = useMemo(
() => ({ open: dialogState === DialogStates.Open }) satisfies DialogRenderPropArg,
[dialogState]
)
let ourProps = {
ref: dialogRef,
id,
role,
tabIndex: -1,
'aria-modal': __demoMode ? undefined : dialogState === DialogStates.Open ? true : undefined,
'aria-labelledby': state.titleId,
'aria-describedby': describedby,
unmount,
}
let shouldMoveFocusInside = !useIsTouchDevice()
let focusTrapFeatures = FocusTrapFeatures.None
if (enabled && !__demoMode) {
focusTrapFeatures |= FocusTrapFeatures.RestoreFocus
focusTrapFeatures |= FocusTrapFeatures.TabLock
if (autoFocus) {
focusTrapFeatures |= FocusTrapFeatures.AutoFocus
}
if (shouldMoveFocusInside) {
focusTrapFeatures |= FocusTrapFeatures.InitialFocus
}
}
let render = useRender()
return (
<ResetOpenClosedProvider>
<ForcePortalRoot force={true}>
<Portal>
<DialogContext.Provider value={contextBag}>
<PortalGroup target={internalDialogRef}>
<ForcePortalRoot force={false}>
<DescriptionProvider slot={slot}>
<PortalWrapper>
<FocusTrap
initialFocus={initialFocus}
initialFocusFallback={internalDialogRef}
containers={resolveRootContainers}
features={focusTrapFeatures}
>
<CloseProvider value={close}>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_DIALOG_TAG,
features: DialogRenderFeatures,
visible: dialogState === DialogStates.Open,
name: 'Dialog',
})}
</CloseProvider>
</FocusTrap>
</PortalWrapper>
</DescriptionProvider>
</ForcePortalRoot>
</PortalGroup>
</DialogContext.Provider>
</Portal>
</ForcePortalRoot>
</ResetOpenClosedProvider>
)
})
// ---
let DEFAULT_DIALOG_TAG = 'div' as const
type DialogRenderPropArg = {
open: boolean
}
type DialogPropsWeControl = 'aria-describedby' | 'aria-labelledby' | 'aria-modal'
let DialogRenderFeatures = RenderFeatures.RenderStrategy | RenderFeatures.Static
export type DialogProps<TTag extends ElementType = typeof DEFAULT_DIALOG_TAG> = Props<
TTag,
DialogRenderPropArg,
DialogPropsWeControl,
PropsForFeatures<typeof DialogRenderFeatures> & {
open?: boolean
onClose: (value: boolean) => void
initialFocus?: MutableRefObject<HTMLElement | null>
role?: 'dialog' | 'alertdialog'
autoFocus?: boolean
transition?: boolean
__demoMode?: boolean
}
>
function DialogFn<TTag extends ElementType = typeof DEFAULT_DIALOG_TAG>(
props: DialogProps<TTag>,
ref: Ref<HTMLElement>
) {
let { transition = false, open, ...rest } = props
// Validations
let usesOpenClosedState = useOpenClosed()
let hasOpen = props.hasOwnProperty('open') || usesOpenClosedState !== null
let hasOnClose = props.hasOwnProperty('onClose')
if (!hasOpen && !hasOnClose) {
throw new Error(
`You have to provide an \`open\` and an \`onClose\` prop to the \`Dialog\` component.`
)
}
if (!hasOpen) {
throw new Error(
`You provided an \`onClose\` prop to the \`Dialog\`, but forgot an \`open\` prop.`
)
}
if (!hasOnClose) {
throw new Error(
`You provided an \`open\` prop to the \`Dialog\`, but forgot an \`onClose\` prop.`
)
}
if (!usesOpenClosedState && typeof props.open !== 'boolean') {
throw new Error(
`You provided an \`open\` prop to the \`Dialog\`, but the value is not a boolean. Received: ${props.open}`
)
}
if (typeof props.onClose !== 'function') {
throw new Error(
`You provided an \`onClose\` prop to the \`Dialog\`, but the value is not a function. Received: ${props.onClose}`
)
}
if ((open !== undefined || transition) && !rest.static) {
return (
<MainTreeProvider>
<Transition show={open} transition={transition} unmount={rest.unmount}>
<InternalDialog ref={ref} {...rest} />
</Transition>
</MainTreeProvider>
)
}
return (
<MainTreeProvider>
<InternalDialog ref={ref} open={open} {...rest} />
</MainTreeProvider>
)
}
// ---
let DEFAULT_PANEL_TAG = 'div' as const
type PanelRenderPropArg = {
open: boolean
}
export type DialogPanelProps<TTag extends ElementType = typeof DEFAULT_PANEL_TAG> = Props<
TTag,
PanelRenderPropArg,
never,
{ transition?: boolean }
>
function PanelFn<TTag extends ElementType = typeof DEFAULT_PANEL_TAG>(
props: DialogPanelProps<TTag>,
ref: Ref<HTMLElement>
) {
let internalId = useId()
let { id = `headlessui-dialog-panel-${internalId}`, transition = false, ...theirProps } = props
let [{ dialogState, unmount }, state] = useDialogContext('Dialog.Panel')
let panelRef = useSyncRefs(ref, state.panelRef)
let slot = useMemo(
() => ({ open: dialogState === DialogStates.Open }) satisfies PanelRenderPropArg,
[dialogState]
)
// Prevent the click events inside the Dialog.Panel from bubbling through the React Tree which
// could submit wrapping <form> elements even if we portalled the Dialog.
let handleClick = useEvent((event: ReactMouseEvent) => {
event.stopPropagation()
})
let ourProps = {
ref: panelRef,
id,
onClick: handleClick,
}
let Wrapper = transition ? TransitionChild : Fragment
let wrapperProps = transition ? { unmount } : {}
let render = useRender()
return (
<Wrapper {...wrapperProps}>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_PANEL_TAG,
name: 'Dialog.Panel',
})}
</Wrapper>
)
}
// ---
let DEFAULT_BACKDROP_TAG = 'div' as const
type BackdropRenderPropArg = {
open: boolean
}
export type DialogBackdropProps<TTag extends ElementType = typeof DEFAULT_BACKDROP_TAG> = Props<
TTag,
BackdropRenderPropArg,
never,
{ transition?: boolean }
>
function BackdropFn<TTag extends ElementType = typeof DEFAULT_BACKDROP_TAG>(
props: DialogBackdropProps<TTag>,
ref: Ref<HTMLElement>
) {
let { transition = false, ...theirProps } = props
let [{ dialogState, unmount }] = useDialogContext('Dialog.Backdrop')
let slot = useMemo(
() => ({ open: dialogState === DialogStates.Open }) satisfies BackdropRenderPropArg,
[dialogState]
)
let ourProps = { ref, 'aria-hidden': true }
let Wrapper = transition ? TransitionChild : Fragment
let wrapperProps = transition ? { unmount } : {}
let render = useRender()
return (
<Wrapper {...wrapperProps}>
{render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_BACKDROP_TAG,
name: 'Dialog.Backdrop',
})}
</Wrapper>
)
}
// ---
let DEFAULT_TITLE_TAG = 'h2' as const
type TitleRenderPropArg = {
open: boolean
}
export type DialogTitleProps<TTag extends ElementType = typeof DEFAULT_TITLE_TAG> = Props<
TTag,
TitleRenderPropArg
>
function TitleFn<TTag extends ElementType = typeof DEFAULT_TITLE_TAG>(
props: DialogTitleProps<TTag>,
ref: Ref<HTMLElement>
) {
let internalId = useId()
let { id = `headlessui-dialog-title-${internalId}`, ...theirProps } = props
let [{ dialogState, setTitleId }] = useDialogContext('Dialog.Title')
let titleRef = useSyncRefs(ref)
useEffect(() => {
setTitleId(id)
return () => setTitleId(null)
}, [id, setTitleId])
let slot = useMemo(
() => ({ open: dialogState === DialogStates.Open }) satisfies TitleRenderPropArg,
[dialogState]
)
let ourProps = { ref: titleRef, id }
let render = useRender()
return render({
ourProps,
theirProps,
slot,
defaultTag: DEFAULT_TITLE_TAG,
name: 'Dialog.Title',
})
}
// ---
export interface _internal_ComponentDialog extends HasDisplayName {
<TTag extends ElementType = typeof DEFAULT_DIALOG_TAG>(
props: DialogProps<TTag> & RefProp<typeof DialogFn>
): React.JSX.Element
}
export interface _internal_ComponentDialogPanel extends HasDisplayName {
<TTag extends ElementType = typeof DEFAULT_PANEL_TAG>(
props: DialogPanelProps<TTag> & RefProp<typeof PanelFn>
): React.JSX.Element
}
export interface _internal_ComponentDialogBackdrop extends HasDisplayName {
<TTag extends ElementType = typeof DEFAULT_BACKDROP_TAG>(
props: DialogBackdropProps<TTag> & RefProp<typeof BackdropFn>
): React.JSX.Element
}
export interface _internal_ComponentDialogTitle extends HasDisplayName {
<TTag extends ElementType = typeof DEFAULT_TITLE_TAG>(
props: DialogTitleProps<TTag> & RefProp<typeof TitleFn>
): React.JSX.Element
}
export interface _internal_ComponentDialogDescription extends _internal_ComponentDescription {}
let DialogRoot = forwardRefWithAs(DialogFn) as _internal_ComponentDialog
export let DialogPanel = forwardRefWithAs(PanelFn) as _internal_ComponentDialogPanel
export let DialogBackdrop = forwardRefWithAs(BackdropFn) as _internal_ComponentDialogBackdrop
export let DialogTitle = forwardRefWithAs(TitleFn) as _internal_ComponentDialogTitle
/** @deprecated use `<Description>` instead of `<DialogDescription>` */
export let DialogDescription = Description as _internal_ComponentDialogDescription
export let Dialog = Object.assign(DialogRoot, {
/** @deprecated use `<DialogPanel>` instead of `<Dialog.Panel>` */
Panel: DialogPanel,
/** @deprecated use `<DialogTitle>` instead of `<Dialog.Title>` */
Title: DialogTitle,
/** @deprecated use `<Description>` instead of `<Dialog.Description>` */
Description: Description as _internal_ComponentDialogDescription,
})