-
Notifications
You must be signed in to change notification settings - Fork 664
Expand file tree
/
Copy pathDialog.tsx
More file actions
532 lines (468 loc) · 17.5 KB
/
Dialog.tsx
File metadata and controls
532 lines (468 loc) · 17.5 KB
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
import React, {useCallback, useEffect, useRef, useState, type SyntheticEvent} from 'react'
import type {ButtonProps} from '../Button'
import {Button, IconButton} from '../Button'
import {useMergedRefs, useOnEscapePress, useProvidedRefOrCreate} from '../hooks'
import {useFocusTrap} from '../hooks/useFocusTrap'
import {XIcon} from '@primer/octicons-react'
import {useFocusZone} from '../hooks/useFocusZone'
import {FocusKeys} from '@primer/behaviors'
import Portal from '../Portal'
import {useId} from '../hooks/useId'
import {ScrollableRegion} from '../ScrollableRegion'
import type {ResponsiveValue} from '../hooks/useResponsiveValue'
import type {ForwardRefComponent as PolymorphicForwardRefComponent} from '../utils/polymorphic'
import classes from './Dialog.module.css'
import {clsx} from 'clsx'
import {useSlots} from '../hooks/useSlots'
import {useResizeObserver} from '../hooks/useResizeObserver'
/* Dialog Version 2 */
/**
* Ref count for data-dialog-scroll-disabled attribute management.
* Tracks how many dialogs are currently open to know when to remove the attribute.
* This is client-only: it is only accessed inside useEffect, which never runs on the server.
*/
let dialogScrollDisabledCount = 0
/**
* Props that characterize a button to be rendered into the footer of
* a Dialog.
*/
export type DialogButtonProps = Omit<ButtonProps, 'content'> & {
/**
* The variant of Button to use
*/
buttonType?: 'default' | 'primary' | 'danger' | 'normal'
/**
* The Button's inner text
*/
content: React.ReactNode
/**
* If true, and if this is the only button with autoFocus set to true,
* focus this button automatically when the dialog appears.
*/
autoFocus?: boolean
/**
* A reference to the rendered Button’s DOM node, used together with
* `autoFocus` for `focusTrap`’s `initialFocus`.
*/
ref?: React.RefObject<HTMLButtonElement | null>
}
/**
* Props to customize the rendering of the Dialog.
*/
export interface DialogProps {
/**
* Title of the Dialog. Also serves as the aria-label for this Dialog.
*/
title?: React.ReactNode
/**
* The Dialog's subtitle. Optional. Rendered below the title in smaller
* type with less contrast. Also serves as the aria-describedby for this
* Dialog.
*/
subtitle?: React.ReactNode
/**
* Provide a custom renderer for the dialog header. This content is
* rendered directly into the dialog body area, full bleed from edge
* to edge, top to the start of the body element.
*
* Warning: using a custom renderer may violate Primer UX principles.
*/
renderHeader?: React.FunctionComponent<React.PropsWithChildren<DialogHeaderProps>>
/**
* Provide a custom render function for the dialog body. This content is
* rendered directly into the dialog body area, full bleed from edge to
* edge, header to footer.
*
* Warning: using a custom renderer may violate Primer UX principles.
*/
renderBody?: React.FunctionComponent<React.PropsWithChildren<DialogProps>>
/**
* Provide a custom render function for the dialog footer. This content is
* rendered directly into the dialog footer area, full bleed from edge to
* edge, end of the body element to bottom.
*
* Warning: using a custom renderer may violate Primer UX principles.
*/
renderFooter?: React.FunctionComponent<React.PropsWithChildren<DialogProps>>
/**
* Specifies the buttons to be rendered in the Dialog footer.
*/
footerButtons?: DialogButtonProps[]
/**
* This method is invoked when a gesture to close the dialog is used (either
* an Escape key press, clicking the backdrop, or clicking the "X" in the top-right corner). The
* gesture argument indicates the gesture that was used to close the dialog
* ('close-button' or 'escape').
*/
onClose: (gesture: 'close-button' | 'escape') => void
/**
* Default: "dialog". The ARIA role to assign to this dialog.
* @see https://www.w3.org/TR/wai-aria-practices-1.1/#dialog_modal
* @see https://www.w3.org/TR/wai-aria-practices-1.1/#alertdialog
*/
role?: 'dialog' | 'alertdialog'
/**
* The width of the dialog.
* small: 296px
* medium: 320px
* large: 480px
* xlarge: 640px
*/
width?: DialogWidth
/**
* The height of the dialog.
* small: 296x480
* large: 480x640
* auto: variable based on contents
*/
height?: DialogHeight
/**
* The position of the dialog
*/
position?: 'center' | 'left' | 'right' | ResponsiveValue<'left' | 'right' | 'bottom' | 'fullscreen' | 'center'>
/**
* The vertical alignment of the dialog. Only applies when position is 'center' (the default).
* top: positions the Dialog ~4rem from the top of the screen, horizontally centered
* center: (default) vertically centers the Dialog on the screen
* bottom: positions the Dialog near the bottom of the screen, horizontally centered
*/
align?: 'top' | 'center' | 'bottom'
/**
* Return focus to this element when the Dialog closes,
* instead of the element that had focus immediately before the Dialog opened
*/
returnFocusRef?: React.RefObject<HTMLElement | null>
/**
* The element to focus when the Dialog opens
*/
initialFocusRef?: React.RefObject<HTMLElement | null>
/**
* Additional class names to apply to the dialog
*/
className?: string
/**
* Additional styles to apply to the dialog
*/
style?: React.CSSProperties
}
/**
* Props that are passed to a component that serves as a dialog header
*/
export interface DialogHeaderProps extends DialogProps {
/**
* ID of the element that will be used as the `aria-labelledby` attribute on the
* dialog. This ID should be set to the element that renders the dialog's title.
*/
dialogLabelId: string
/**
* ID of the element that will be used as the `aria-describedby` attribute on the
* dialog. This ID should be set to the element that renders the dialog's subtitle.
*/
dialogDescriptionId: string
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const heightMap = {
small: '480px',
large: '640px',
auto: 'auto',
} as const
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const widthMap = {
small: '296px',
medium: '320px',
large: '480px',
xlarge: '640px',
} as const
export type DialogWidth = keyof typeof widthMap
export type DialogHeight = keyof typeof heightMap
const DefaultHeader: React.FC<React.PropsWithChildren<DialogHeaderProps>> = ({
dialogLabelId,
title,
subtitle,
dialogDescriptionId,
onClose,
}) => {
const onCloseClick = useCallback(() => {
onClose('close-button')
}, [onClose])
return (
<Dialog.Header>
<div className={classes.HeaderInner}>
<div className={classes.HeaderContent}>
<Dialog.Title id={dialogLabelId}>{title ?? 'Dialog'}</Dialog.Title>
{subtitle && <Dialog.Subtitle id={dialogDescriptionId}>{subtitle}</Dialog.Subtitle>}
</div>
<Dialog.CloseButton onClose={onCloseClick} />
</div>
</Dialog.Header>
)
}
const DefaultBody: React.FC<React.PropsWithChildren<DialogProps>> = ({children}) => {
return <Dialog.Body>{children}</Dialog.Body>
}
const DefaultFooter: React.FC<React.PropsWithChildren<DialogProps>> = ({footerButtons}) => {
const {containerRef: footerRef} = useFocusZone({
bindKeys: FocusKeys.ArrowHorizontal | FocusKeys.Tab,
focusInStrategy: 'closest',
})
return footerButtons ? (
<Dialog.Footer ref={footerRef as React.RefObject<HTMLDivElement>}>
<Dialog.Buttons buttons={footerButtons} />
</Dialog.Footer>
) : null
}
const defaultPosition = {
narrow: 'center',
regular: 'center',
}
const defaultFooterButtons: Array<DialogButtonProps> = []
// Minimum room needed for body content before forcing footer buttons into horizontal scroll.
const MIN_BODY_HEIGHT = 48
// useful to determine whether we're inside a Dialog from a nested component
export const DialogContext = React.createContext<object | undefined>(undefined)
const DIALOG_CONTEXT_VALUE = Object.freeze({})
const _Dialog = React.forwardRef<HTMLDivElement, React.PropsWithChildren<DialogProps>>((props, forwardedRef) => {
const {
title = 'Dialog',
subtitle = '',
renderHeader,
renderBody,
renderFooter,
onClose,
role = 'dialog',
width = 'xlarge',
height = 'auto',
footerButtons = defaultFooterButtons,
position = defaultPosition,
align,
returnFocusRef,
initialFocusRef,
className,
style,
} = props
const dialogLabelId = useId()
const dialogDescriptionId = useId()
const autoFocusedFooterButtonRef = useRef<HTMLButtonElement>(null)
for (const footerButton of footerButtons) {
if (footerButton.autoFocus) {
// eslint-disable-next-line react-hooks/immutability
footerButton.ref = autoFocusedFooterButtonRef
}
}
const [lastMouseDownIsBackdrop, setLastMouseDownIsBackdrop] = useState<boolean>(false)
const [footerButtonLayout, setFooterButtonLayout] = useState<'scroll' | 'wrap'>('wrap')
const defaultedProps = {...props, title, subtitle, role, dialogLabelId, dialogDescriptionId}
const onBackdropClick = useCallback(
(e: SyntheticEvent) => {
if (e.target === e.currentTarget && lastMouseDownIsBackdrop) {
onClose('escape')
}
},
[onClose, lastMouseDownIsBackdrop],
)
const [slots, childrenWithoutSlots] = useSlots(props.children, {
body: Dialog.Body,
header: Dialog.Header,
footer: Dialog.Footer,
})
const dialogRef = useRef<HTMLDivElement>(null)
const mergedDialogRef = useMergedRefs(forwardedRef, dialogRef)
const backdropRef = useRef<HTMLDivElement>(null)
useFocusTrap({
containerRef: dialogRef,
initialFocusRef: initialFocusRef ?? autoFocusedFooterButtonRef,
// eslint-disable-next-line react-hooks/refs
restoreFocusOnCleanUp: returnFocusRef?.current ? false : true,
returnFocusRef,
})
useOnEscapePress(
(event: KeyboardEvent) => {
onClose('escape')
event.preventDefault()
},
[onClose],
)
React.useEffect(() => {
const scrollbarWidth = window.innerWidth - document.body.clientWidth
dialogScrollDisabledCount++
document.body.style.setProperty('--prc-dialog-scrollgutter', `${scrollbarWidth}px`)
document.body.setAttribute('data-dialog-scroll-disabled', '')
return () => {
dialogScrollDisabledCount--
if (dialogScrollDisabledCount === 0) {
document.body.style.removeProperty('--prc-dialog-scrollgutter')
document.body.removeAttribute('data-dialog-scroll-disabled')
}
}
}, [])
const header = slots.header ?? (renderHeader ?? DefaultHeader)(defaultedProps)
const body = slots.body ?? (renderBody ?? DefaultBody)({...defaultedProps, children: childrenWithoutSlots})
const footer = slots.footer ?? (renderFooter ?? DefaultFooter)(defaultedProps)
const hasFooter = footer != null
const updateFooterButtonLayout = useCallback(() => {
if (!hasFooter) {
return
}
const dialogElement = dialogRef.current
if (!(dialogElement instanceof HTMLElement)) {
return
}
const bodyWrapper = dialogElement.querySelector(`.${classes.DialogOverflowWrapper}`)
if (!(bodyWrapper instanceof HTMLElement)) {
return
}
// We temporarily force "wrap" the footer layout so that the browser can calculate the body height -
// when the footer is wrapping. This is instantaneous with what we set below (`dialogElement.setAttribute('data-footer-button-layout', newLayout)`).
dialogElement.setAttribute('data-footer-button-layout', 'wrap')
const bodyHeight = bodyWrapper.clientHeight
const newLayout = bodyHeight >= MIN_BODY_HEIGHT ? 'wrap' : 'scroll'
dialogElement.setAttribute('data-footer-button-layout', newLayout)
setFooterButtonLayout(newLayout)
}, [hasFooter])
useResizeObserver(updateFooterButtonLayout, backdropRef)
const positionDataAttributes =
typeof position === 'string'
? {'data-position-regular': position}
: Object.fromEntries(
Object.entries(position).map(([key, value]) => {
return [`data-position-${key}`, value]
}),
)
return (
<DialogContext.Provider value={DIALOG_CONTEXT_VALUE}>
<Portal>
<div
ref={backdropRef}
className={classes.Backdrop}
{...positionDataAttributes}
{...(align && {'data-align': align})}
onClick={onBackdropClick}
onMouseDown={(e: React.MouseEvent<HTMLDivElement>) => {
setLastMouseDownIsBackdrop(e.target === e.currentTarget)
}}
>
<div
ref={mergedDialogRef}
role={role}
aria-labelledby={dialogLabelId}
aria-describedby={dialogDescriptionId}
aria-modal
{...positionDataAttributes}
{...(align && {'data-align': align})}
data-width={width}
data-height={height}
data-has-footer={hasFooter ? '' : undefined}
data-footer-button-layout={hasFooter ? footerButtonLayout : undefined}
className={clsx(className, classes.Dialog)}
style={style}
>
{header}
<ScrollableRegion aria-labelledby={dialogLabelId} className={classes.DialogOverflowWrapper}>
{body}
</ScrollableRegion>
{footer}
</div>
</div>
</Portal>
</DialogContext.Provider>
)
})
_Dialog.displayName = 'Dialog'
type StyledHeaderProps = React.ComponentProps<'div'>
const Header = React.forwardRef<HTMLDivElement, StyledHeaderProps>(function Header({className, ...rest}, forwardRef) {
return <div ref={forwardRef} className={clsx(className, classes.Header)} {...rest} />
}) as PolymorphicForwardRefComponent<'div', StyledHeaderProps>
Header.displayName = 'Dialog.Header'
type StyledTitleProps = React.ComponentProps<'h1'>
const Title = React.forwardRef<HTMLHeadingElement, StyledTitleProps>(function Title({className, ...rest}, forwardRef) {
return <h1 ref={forwardRef} className={clsx(className, classes.Title)} {...rest} />
})
Title.displayName = 'Dialog.Title'
type StyledSubtitleProps = React.ComponentProps<'h2'>
const Subtitle = React.forwardRef<HTMLHeadingElement, StyledSubtitleProps>(function Subtitle(
{className, ...rest},
forwardRef,
) {
return <h2 ref={forwardRef} className={clsx(className, classes.Subtitle)} {...rest} />
})
Subtitle.displayName = 'Dialog.Subtitle'
type StyledBodyProps = React.ComponentProps<'div'>
const Body = React.forwardRef<HTMLDivElement, StyledBodyProps>(function Body({className, ...rest}, forwardRef) {
return <div ref={forwardRef} className={clsx(className, classes.Body)} {...rest} />
}) as PolymorphicForwardRefComponent<'div', StyledBodyProps>
Body.displayName = 'Dialog.Body'
type StyledFooterProps = React.ComponentProps<'div'>
const Footer = React.forwardRef<HTMLDivElement, StyledFooterProps>(function Footer({className, ...rest}, forwardRef) {
return <div ref={forwardRef} className={clsx(className, classes.Footer)} {...rest} />
}) as PolymorphicForwardRefComponent<'div', StyledFooterProps>
Footer.displayName = 'Dialog.Footer'
const Buttons: React.FC<React.PropsWithChildren<{buttons: DialogButtonProps[]}>> = ({buttons}) => {
const autoFocusRef = useProvidedRefOrCreate<HTMLButtonElement>(buttons.find(button => button.autoFocus)?.ref)
let autoFocusCount = 0
const [hasRendered, setHasRendered] = useState(0)
useEffect(() => {
// hack to work around dialogs originating from other focus traps.
if (hasRendered === 1) {
autoFocusRef.current?.focus()
} else {
// eslint-disable-next-line react-hooks/set-state-in-effect
setHasRendered(hasRendered + 1)
}
}, [autoFocusRef, hasRendered])
return (
<>
{buttons.map((dialogButtonProps, index) => {
const {content, buttonType = 'default', autoFocus = false, ...buttonProps} = dialogButtonProps
return (
<Button
key={index}
{...buttonProps}
// 'normal' value is equivalent to 'default', this is used for backwards compatibility
variant={buttonType === 'normal' ? 'default' : buttonType}
// @ts-expect-error it needs a non nullable ref
ref={autoFocus && autoFocusCount === 0 ? (autoFocusCount++, autoFocusRef) : null}
>
{content}
</Button>
)
})}
</>
)
}
const CloseButton: React.FC<React.PropsWithChildren<{onClose: () => void}>> = ({onClose}) => {
return <IconButton icon={XIcon} aria-label="Close" onClick={onClose} variant="invisible" />
}
/**
* A dialog is a type of overlay that can be used for confirming actions, asking
* for disambiguation, and presenting small forms. They generally allow the user
* to focus on a quick task without having to navigate to a different page.
*
* Dialogs appear in the page after a direct user interaction. Don't show dialogs
* on page load or as system alerts.
*
* Dialogs appear centered in the page, with a visible backdrop that dims the rest
* of the window for focus.
*
* All dialogs have a title and a close button.
*
* Dialogs are modal. Dialogs can be dismissed by clicking on the close button,
* pressing the escape key, or by interacting with another button in the dialog.
* To avoid losing information and missing important messages, clicking outside
* of the dialog will not close it.
*
* The sub components provided (e.g. Header, Title, etc.) are available for custom
* renderers only. They are not intended to be used otherwise.
*/
Header.__SLOT__ = Symbol('Dialog.Header')
Footer.__SLOT__ = Symbol('Dialog.Footer')
Body.__SLOT__ = Symbol('Dialog.Body')
export const Dialog = Object.assign(_Dialog, {
__SLOT__: Symbol('Dialog'),
Header,
Title,
Subtitle,
Body,
Footer,
Buttons,
CloseButton,
})