This repository was archived by the owner on Mar 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathDialog.tsx
More file actions
416 lines (366 loc) · 12.9 KB
/
Dialog.tsx
File metadata and controls
416 lines (366 loc) · 12.9 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
import { Accessibility, dialogBehavior } from '@fluentui/accessibility'
import { FocusTrapZoneProps } from '@fluentui/react-bindings'
import { Unstable_NestingAuto } from '@fluentui/react-component-nesting-registry'
import { EventListener } from '@fluentui/react-component-event-listener'
import { Ref, toRefObject } from '@fluentui/react-component-ref'
import * as customPropTypes from '@fluentui/react-proptypes'
import * as _ from 'lodash'
import * as PropTypes from 'prop-types'
import * as React from 'react'
import * as keyboardKey from 'keyboard-key'
import {
UIComponentProps,
commonPropTypes,
ContentComponentProps,
AutoControlledComponent,
doesNodeContainClick,
applyAccessibilityKeyHandlers,
getOrGenerateIdFromShorthand,
} from '../../utils'
import { ComponentEventHandler, WithAsProp, ShorthandValue, withSafeTypeForAs } from '../../types'
import Button, { ButtonProps } from '../Button/Button'
import ButtonGroup from '../Button/ButtonGroup'
import Box, { BoxProps } from '../Box/Box'
import Header, { HeaderProps } from '../Header/Header'
import Portal, { TriggerAccessibility } from '../Portal/Portal'
import Flex from '../Flex/Flex'
import DialogFooter, { DialogFooterProps } from './DialogFooter'
export interface DialogSlotClassNames {
header: string
headerAction: string
content: string
overlay: string
footer: string
}
export interface DialogProps
extends UIComponentProps,
ContentComponentProps<ShorthandValue<BoxProps>> {
/** Accessibility behavior if overridden by the user. */
accessibility?: Accessibility
/** A dialog can contain actions. */
actions?: ShorthandValue<BoxProps>
/** A dialog can have a backdrop on its overlay. */
backdrop?: boolean
/** A dialog can contain a cancel button. */
cancelButton?: ShorthandValue<ButtonProps>
/** A dialog can be closed when a user clicks outside of it. */
closeOnOutsideClick?: boolean
/** A dialog can contain a confirm button. */
confirmButton?: ShorthandValue<ButtonProps>
/** A dialog can be open by default. */
defaultOpen?: boolean
/** A dialog can contain a header. */
header?: ShorthandValue<HeaderProps>
/** A dialog can contain a button next to the header. */
headerAction?: ShorthandValue<ButtonProps>
/** A dialog can contain a footer. */
footer?: ShorthandValue<DialogFooterProps>
/**
* Called after a user clicks the cancel button.
* @param event - React's original SyntheticEvent.
* @param data - All props.
*/
onCancel?: ComponentEventHandler<DialogProps>
/**
* Called after a user clicks the confirm button.
* @param event - React's original SyntheticEvent.
* @param data - All props.
*/
onConfirm?: ComponentEventHandler<DialogProps>
/**
* Called after a user opens the dialog.
* @param event - React's original SyntheticEvent.
* @param data - All props.
*/
onOpen?: ComponentEventHandler<DialogProps>
/** A dialog's open state can be controlled. */
open?: boolean
/** A dialog can contain a overlay. */
overlay?: ShorthandValue<BoxProps>
/** Controls whether or not focus trap should be applied, using boolean or FocusTrapZoneProps type value. */
trapFocus?: true | FocusTrapZoneProps
/** Element to be rendered in-place where the dialog is defined. */
trigger?: JSX.Element
}
export interface DialogState {
contentId?: string
headerId?: string
open?: boolean
}
class Dialog extends AutoControlledComponent<WithAsProp<DialogProps>, DialogState> {
static displayName = 'Dialog'
static className = 'ui-dialog'
static slotClassNames: DialogSlotClassNames
static propTypes = {
...commonPropTypes.createCommon({
children: false,
content: 'shorthand',
}),
actions: customPropTypes.itemShorthand,
backdrop: PropTypes.bool,
headerAction: customPropTypes.itemShorthand,
cancelButton: customPropTypes.itemShorthand,
closeOnOutsideClick: PropTypes.bool,
confirmButton: customPropTypes.itemShorthand,
defaultOpen: PropTypes.bool,
header: customPropTypes.itemShorthand,
onCancel: PropTypes.func,
onConfirm: PropTypes.func,
onOpen: PropTypes.func,
open: PropTypes.bool,
overlay: customPropTypes.itemShorthand,
trapFocus: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
trigger: PropTypes.any,
}
static defaultProps = {
accessibility: dialogBehavior as Accessibility,
actions: {},
backdrop: true,
closeOnOutsideClick: true,
overlay: {},
footer: {},
trapFocus: true,
}
static autoControlledProps = ['open']
static Footer = DialogFooter
actionHandlers = {
closeAndFocusTrigger: e => {
this.handleDialogCancel(e)
e.stopPropagation()
_.invoke(this.triggerRef, 'current.focus')
},
close: e => this.handleDialogCancel(e),
}
contentRef = React.createRef<HTMLElement>() as React.MutableRefObject<HTMLElement>
overlayRef = React.createRef<HTMLElement>() as React.MutableRefObject<HTMLElement>
triggerRef = React.createRef<HTMLElement>()
getInitialAutoControlledState(): DialogState {
return {
open: false,
}
}
static getAutoControlledStateFromProps(
props: DialogProps,
state: DialogState,
): Partial<DialogState> {
return {
contentId: getOrGenerateIdFromShorthand('dialog-content-', props.content, state.contentId),
headerId: getOrGenerateIdFromShorthand('dialog-header-', props.header, state.headerId),
}
}
handleDialogCancel = (e: Event | React.SyntheticEvent) => {
_.invoke(this.props, 'onCancel', e, { ...this.props, open: false })
this.setState({ open: false })
}
handleDialogConfirm = (e: React.SyntheticEvent) => {
_.invoke(this.props, 'onConfirm', e, { ...this.props, open: false })
this.setState({ open: false })
}
handleDialogOpen = (e: React.SyntheticEvent) => {
_.invoke(this.props, 'onOpen', e, { ...this.props, open: true })
this.setState({ open: true })
}
handleCancelButtonOverrides = (predefinedProps: ButtonProps) => ({
onClick: (e: React.SyntheticEvent, buttonProps: ButtonProps) => {
_.invoke(predefinedProps, 'onClick', e, buttonProps)
this.handleDialogCancel(e)
},
})
handleConfirmButtonOverrides = (predefinedProps: ButtonProps) => ({
onClick: (e: React.SyntheticEvent, buttonProps: ButtonProps) => {
_.invoke(predefinedProps, 'onClick', e, buttonProps)
this.handleDialogConfirm(e)
},
})
handleOverlayClick = (e: MouseEvent) => {
// Dialog has different conditions to close than Popup, so we don't need to iterate across all
// refs
const isInsideContentClick = doesNodeContainClick(
this.contentRef.current,
e,
this.context.target,
)
const isInsideOverlayClick = doesNodeContainClick(
this.overlayRef.current,
e,
this.context.target,
)
const shouldClose = !isInsideContentClick && isInsideOverlayClick
if (shouldClose) {
this.handleDialogCancel(e)
}
}
handleDocumentKeydown = (getRefs: Function) => (e: KeyboardEvent) => {
// if focus was lost from Dialog, for e.g. when click on Dialog's content
// and ESC is pressed, the opened Dialog should get closed and the trigger should get focus
const lastOverlayRef = getRefs().pop()
const isLastOpenedDialog: boolean =
lastOverlayRef && lastOverlayRef.current === this.overlayRef.current
if (keyboardKey.getCode(e) === keyboardKey.Escape && isLastOpenedDialog) {
this.handleDialogCancel(e)
_.invoke(this.triggerRef, 'current.focus')
}
}
renderComponent({ accessibility, classes, ElementType, styles, unhandledProps, rtl }) {
const {
actions,
cancelButton,
closeOnOutsideClick,
confirmButton,
content,
header,
headerAction,
overlay,
trapFocus,
trigger,
footer,
} = this.props
const { open } = this.state
const cancelElement = Button.create(cancelButton, {
generateKey: false,
overrideProps: this.handleCancelButtonOverrides,
})
const confirmElement = Button.create(confirmButton, {
defaultProps: () => ({
primary: true,
}),
generateKey: false,
overrideProps: this.handleConfirmButtonOverrides,
})
const dialogActions =
(cancelElement || confirmElement) &&
ButtonGroup.create(actions, {
defaultProps: () => ({
styles: styles.actions,
}),
generateKey: false,
overrideProps: {
content: (
<Flex gap="gap.smaller">
{cancelElement}
{confirmElement}
</Flex>
),
},
})
const dialogContent = (
<Ref innerRef={this.contentRef}>
<ElementType
className={classes.root}
// it's required to have an `rtl` attribute there as Dialog is rendered outside the main DOM tree
dir={rtl ? 'rtl' : undefined}
{...accessibility.attributes.popup}
{...unhandledProps}
{...applyAccessibilityKeyHandlers(accessibility.keyHandlers.popup, unhandledProps)}
>
{Header.create(header, {
defaultProps: () => ({
as: 'h2',
className: Dialog.slotClassNames.header,
styles: styles.header,
...accessibility.attributes.header,
}),
generateKey: false,
})}
{Button.create(headerAction, {
defaultProps: () => ({
className: Dialog.slotClassNames.headerAction,
styles: styles.headerAction,
text: true,
iconOnly: true,
...accessibility.attributes.headerAction,
}),
generateKey: false,
})}
{Box.create(content, {
defaultProps: () => ({
styles: styles.content,
className: Dialog.slotClassNames.content,
...accessibility.attributes.content,
}),
generateKey: false,
})}
{DialogFooter.create(footer, {
overrideProps: {
content: dialogActions,
className: Dialog.slotClassNames.footer,
styles: styles.footer,
},
generateKey: false,
})}
</ElementType>
</Ref>
)
const targetRef = toRefObject(this.context.target)
const triggerAccessibility: TriggerAccessibility = {
attributes: accessibility.attributes.trigger,
keyHandlers: accessibility.keyHandlers.trigger,
}
return (
<Portal
onTriggerClick={this.handleDialogOpen}
open={open}
trapFocus={trapFocus}
trigger={trigger}
triggerAccessibility={triggerAccessibility}
triggerRef={this.triggerRef}
>
<Unstable_NestingAuto>
{(getRefs, nestingRef) => (
<>
<Ref
innerRef={(contentNode: HTMLElement) => {
this.overlayRef.current = contentNode
nestingRef.current = contentNode
}}
>
{Box.create(overlay, {
defaultProps: () => ({
className: Dialog.slotClassNames.overlay,
styles: styles.overlay,
}),
generateKey: false,
overrideProps: { content: dialogContent },
})}
</Ref>
{closeOnOutsideClick && (
<EventListener
listener={this.handleOverlayClick}
targetRef={targetRef}
type="click"
capture
/>
)}
<EventListener
listener={this.handleDocumentKeydown(getRefs)}
targetRef={targetRef}
type="keydown"
capture
/>
</>
)}
</Unstable_NestingAuto>
</Portal>
)
}
}
Dialog.slotClassNames = {
header: `${Dialog.className}__header`,
headerAction: `${Dialog.className}__headerAction`,
content: `${Dialog.className}__content`,
overlay: `${Dialog.className}__overlay`,
footer: `${Dialog.className}__footer`,
}
/**
* A Dialog displays important information on top of a page which requires a user's attention, confirmation, or interaction.
* Dialogs are purposefully interruptive, so they should be used sparingly.
*
* @accessibility
* Implements [ARIA Dialog (Modal)](https://www.w3.org/TR/wai-aria-practices-1.1/#dialog_modal) design pattern.
* @accessibilityIssues
* [NVDA narrates dialog title and button twice](https://github.com/nvaccess/nvda/issues/10003)
* [NVDA does not recognize the ARIA 1.1 values of aria-haspopup](https://github.com/nvaccess/nvda/issues/8235)
* [Jaws does not announce token values of aria-haspopup](https://github.com/FreedomScientific/VFO-standards-support/issues/33)
* [Issue 989517: VoiceOver narrates dialog content and button twice](https://bugs.chromium.org/p/chromium/issues/detail?id=989517)
*/
export default withSafeTypeForAs<typeof Dialog, DialogProps>(Dialog)