-
Notifications
You must be signed in to change notification settings - Fork 219
/
Copy pathModal.tsx
541 lines (454 loc) · 13.8 KB
/
Modal.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
/* eslint-disable @typescript-eslint/no-use-before-define, react/prop-types */
import activeElement from 'dom-helpers/activeElement';
import contains from 'dom-helpers/contains';
import canUseDOM from 'dom-helpers/canUseDOM';
import listen from 'dom-helpers/listen';
import PropTypes from 'prop-types';
import React, {
useState,
useRef,
useCallback,
useImperativeHandle,
forwardRef,
useEffect,
} from 'react';
import ReactDOM from 'react-dom';
import useMounted from '@restart/hooks/useMounted';
import useWillUnmount from '@restart/hooks/useWillUnmount';
import usePrevious from '@restart/hooks/usePrevious';
import useEventCallback from '@restart/hooks/useEventCallback';
import ModalManager from './ModalManager';
import useWaitForDOMRef, { DOMContainer } from './useWaitForDOMRef';
import { TransitionCallbacks } from './types';
let manager: ModalManager;
export type ModalTransitionComponent = React.ComponentType<
{
in: boolean;
appear?: boolean;
unmountOnExit?: boolean;
} & TransitionCallbacks
>;
export interface RenderModalDialogProps {
style: React.CSSProperties | undefined;
className: string | undefined;
tabIndex: number;
role: string;
ref: React.RefCallback<Element>;
'aria-modal': boolean | undefined;
}
export interface RenderModalBackdropProps {
ref: React.RefCallback<Element>;
onClick: (event: React.SyntheticEvent) => void;
}
/*
Modal props are split into a version with and without index signature so that you can fully use them in another projects
This is due to Typescript not playing well with index singatures e.g. when using Omit
*/
export interface BaseModalProps extends TransitionCallbacks {
children?: React.ReactElement;
role?: string;
style?: React.CSSProperties;
className?: string;
show?: boolean;
container?: DOMContainer;
onShow?: () => void;
onHide?: () => void;
manager?: ModalManager;
backdrop?: true | false | 'static';
renderDialog?: (props: RenderModalDialogProps) => React.ReactNode;
renderBackdrop?: (props: RenderModalBackdropProps) => React.ReactNode;
onEscapeKeyDown?: (e: KeyboardEvent) => void;
onBackdropClick?: (e: React.SyntheticEvent) => void;
containerClassName?: string;
keyboard?: boolean;
transition?: ModalTransitionComponent;
backdropTransition?: ModalTransitionComponent;
autoFocus?: boolean;
enforceFocus?: boolean;
restoreFocus?: boolean;
restoreFocusOptions?: {
preventScroll: boolean;
};
}
export interface ModalProps extends BaseModalProps {
[other: string]: any;
}
function getManager() {
if (!manager) manager = new ModalManager();
return manager;
}
function useModalManager(provided?: ModalManager) {
const modalManager = provided || getManager();
const modal = useRef({
dialog: (null as any) as HTMLElement,
backdrop: (null as any) as HTMLElement,
});
return Object.assign(modal.current, {
add: (container: HTMLElement, className?: string) =>
modalManager.add(modal.current, container, className),
remove: () => modalManager.remove(modal.current),
isTopModal: () => modalManager.isTopModal(modal.current),
setDialogRef: useCallback((ref: HTMLElement | null) => {
modal.current.dialog = ref!;
}, []),
setBackdropRef: useCallback((ref: HTMLElement | null) => {
modal.current.backdrop = ref!;
}, []),
});
}
export interface ModalHandle {
dialog: HTMLElement | null;
backdrop: HTMLElement | null;
}
const Modal: React.ForwardRefExoticComponent<
ModalProps & React.RefAttributes<ModalHandle>
> = forwardRef(
(
{
show = false,
role = 'dialog',
className,
style,
children,
backdrop = true,
keyboard = true,
onBackdropClick,
onEscapeKeyDown,
transition,
backdropTransition,
autoFocus = true,
enforceFocus = true,
restoreFocus = true,
restoreFocusOptions,
renderDialog,
renderBackdrop = (props: RenderModalBackdropProps) => <div {...props} />,
manager: providedManager,
container: containerRef,
containerClassName,
onShow,
onHide = () => {},
onExit,
onExited,
onExiting,
onEnter,
onEntering,
onEntered,
...rest
}: ModalProps,
ref: React.Ref<ModalHandle>,
) => {
const container = useWaitForDOMRef(containerRef);
const modal = useModalManager(providedManager);
const isMounted = useMounted();
const prevShow = usePrevious(show);
const [exited, setExited] = useState(!show);
const lastFocusRef = useRef<HTMLElement | null>(null);
useImperativeHandle(ref, () => modal, [modal]);
if (canUseDOM && !prevShow && show) {
lastFocusRef.current = activeElement() as HTMLElement;
}
if (!transition && !show && !exited) {
setExited(true);
} else if (show && exited) {
setExited(false);
}
const handleShow = useEventCallback(() => {
modal.add(container!, containerClassName);
removeKeydownListenerRef.current = listen(
document as any,
'keydown',
handleDocumentKeyDown,
);
removeFocusListenerRef.current = listen(
document as any,
'focus',
// the timeout is necessary b/c this will run before the new modal is mounted
// and so steals focus from it
() => setTimeout(handleEnforceFocus),
true,
);
if (onShow) {
onShow();
}
// autofocus after onShow to not trigger a focus event for previous
// modals before this one is shown.
if (autoFocus) {
const currentActiveElement = activeElement(document) as HTMLElement;
if (
modal.dialog &&
currentActiveElement &&
!contains(modal.dialog, currentActiveElement)
) {
lastFocusRef.current = currentActiveElement;
modal.dialog.focus();
}
}
});
const handleHide = useEventCallback(() => {
modal.remove();
removeKeydownListenerRef.current?.();
removeFocusListenerRef.current?.();
if (restoreFocus) {
// Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917)
lastFocusRef.current?.focus?.(restoreFocusOptions);
lastFocusRef.current = null;
}
});
// TODO: try and combine these effects: https://github.com/react-bootstrap/react-overlays/pull/794#discussion_r409954120
// Show logic when:
// - show is `true` _and_ `container` has resolved
useEffect(() => {
if (!show || !container) return;
handleShow();
}, [show, container, /* should never change: */ handleShow]);
// Hide cleanup logic when:
// - `exited` switches to true
// - component unmounts;
useEffect(() => {
if (!exited) return;
handleHide();
}, [exited, handleHide]);
useWillUnmount(() => {
handleHide();
});
// --------------------------------
const handleEnforceFocus = useEventCallback(() => {
if (!enforceFocus || !isMounted() || !modal.isTopModal()) {
return;
}
const currentActiveElement = activeElement();
if (
modal.dialog &&
currentActiveElement &&
!contains(modal.dialog, currentActiveElement)
) {
modal.dialog.focus();
}
});
const handleBackdropClick = useEventCallback((e: React.SyntheticEvent) => {
if (e.target !== e.currentTarget) {
return;
}
onBackdropClick?.(e);
if (backdrop === true) {
onHide();
}
});
const handleDocumentKeyDown = useEventCallback((e: KeyboardEvent) => {
if (keyboard && e.keyCode === 27 && modal.isTopModal()) {
onEscapeKeyDown?.(e);
if (!e.defaultPrevented) {
onHide();
}
}
});
const removeFocusListenerRef = useRef<ReturnType<typeof listen> | null>();
const removeKeydownListenerRef = useRef<ReturnType<typeof listen> | null>();
const handleHidden: TransitionCallbacks['onExited'] = (...args) => {
setExited(true);
onExited?.(...args);
};
const Transition = transition;
if (!container || !(show || (Transition && !exited))) {
return null;
}
const dialogProps = {
role,
ref: modal.setDialogRef,
// apparently only works on the dialog role element
'aria-modal': role === 'dialog' ? true : undefined,
...rest,
style,
className,
tabIndex: -1,
};
let dialog = renderDialog ? (
renderDialog(dialogProps)
) : (
<div {...dialogProps}>
{React.cloneElement(children!, { role: 'document' })}
</div>
);
if (Transition) {
dialog = (
<Transition
appear
unmountOnExit
in={!!show}
onExit={onExit}
onExiting={onExiting}
onExited={handleHidden}
onEnter={onEnter}
onEntering={onEntering}
onEntered={onEntered}
>
{dialog}
</Transition>
);
}
let backdropElement = null;
if (backdrop) {
const BackdropTransition = backdropTransition;
backdropElement = renderBackdrop({
ref: modal.setBackdropRef,
onClick: handleBackdropClick,
});
if (BackdropTransition) {
backdropElement = (
<BackdropTransition appear in={!!show}>
{backdropElement}
</BackdropTransition>
);
}
}
return (
<>
{ReactDOM.createPortal(
<>
{backdropElement}
{dialog}
</>,
container,
)}
</>
);
},
);
const propTypes = {
/**
* Set the visibility of the Modal
*/
show: PropTypes.bool,
/**
* A DOM element, a `ref` to an element, or function that returns either. The Modal is appended to it's `container` element.
*
* For the sake of assistive technologies, the container should usually be the document body, so that the rest of the
* page content can be placed behind a virtual backdrop as well as a visual one.
*/
container: PropTypes.any,
/**
* A callback fired when the Modal is opening.
*/
onShow: PropTypes.func,
/**
* A callback fired when either the backdrop is clicked, or the escape key is pressed.
*
* The `onHide` callback only signals intent from the Modal,
* you must actually set the `show` prop to `false` for the Modal to close.
*/
onHide: PropTypes.func,
/**
* Include a backdrop component.
*/
backdrop: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['static'])]),
/**
* A function that returns the dialog component. Useful for custom
* rendering. **Note:** the component should make sure to apply the provided ref.
*
* ```js static
* renderDialog={props => <MyDialog {...props} />}
* ```
*/
renderDialog: PropTypes.func,
/**
* A function that returns a backdrop component. Useful for custom
* backdrop rendering.
*
* ```js
* renderBackdrop={props => <MyBackdrop {...props} />}
* ```
*/
renderBackdrop: PropTypes.func,
/**
* A callback fired when the escape key, if specified in `keyboard`, is pressed.
*
* If preventDefault() is called on the keyboard event, closing the modal will be cancelled.
*/
onEscapeKeyDown: PropTypes.func,
/**
* A callback fired when the backdrop, if specified, is clicked.
*/
onBackdropClick: PropTypes.func,
/**
* A css class or set of classes applied to the modal container when the modal is open,
* and removed when it is closed.
*/
containerClassName: PropTypes.string,
/**
* Close the modal when escape key is pressed
*/
keyboard: PropTypes.bool,
/**
* A `[email protected]` `<Transition/>` component used
* to control animations for the dialog component.
*/
transition: PropTypes.elementType,
/**
* A `[email protected]` `<Transition/>` component used
* to control animations for the backdrop components.
*/
backdropTransition: PropTypes.elementType,
/**
* When `true` The modal will automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes. This also
* works correctly with any Modal children that have the `autoFocus` prop.
*
* Generally this should never be set to `false` as it makes the Modal less
* accessible to assistive technologies, like screen readers.
*/
autoFocus: PropTypes.bool,
/**
* When `true` The modal will prevent focus from leaving the Modal while open.
*
* Generally this should never be set to `false` as it makes the Modal less
* accessible to assistive technologies, like screen readers.
*/
enforceFocus: PropTypes.bool,
/**
* When `true` The modal will restore focus to previously focused element once
* modal is hidden
*/
restoreFocus: PropTypes.bool,
/**
* Options passed to focus function when `restoreFocus` is set to `true`
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus#Parameters
*/
restoreFocusOptions: PropTypes.shape({
preventScroll: PropTypes.bool,
}),
/**
* Callback fired before the Modal transitions in
*/
onEnter: PropTypes.func,
/**
* Callback fired as the Modal begins to transition in
*/
onEntering: PropTypes.func,
/**
* Callback fired after the Modal finishes transitioning in
*/
onEntered: PropTypes.func,
/**
* Callback fired right before the Modal transitions out
*/
onExit: PropTypes.func,
/**
* Callback fired as the Modal begins to transition out
*/
onExiting: PropTypes.func,
/**
* Callback fired after the Modal finishes transitioning out
*/
onExited: PropTypes.func,
/**
* A ModalManager instance used to track and manage the state of open
* Modals. Useful when customizing how modals interact within a container
*/
manager: PropTypes.instanceOf(ModalManager),
};
Modal.displayName = 'Modal';
Modal.propTypes = propTypes as any;
export default Object.assign(Modal, {
Manager: ModalManager,
});