/
Modal.tsx
782 lines (680 loc) · 19.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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes, { ReactNodeLike } from 'prop-types';
import React, { useRef, useEffect } from 'react';
import classNames from 'classnames';
import { Close } from '@carbon/icons-react';
import toggleClass from '../../tools/toggleClass';
import Button from '../Button';
import ButtonSet from '../ButtonSet';
import InlineLoading from '../InlineLoading';
import requiredIfGivenPropIsTruthy from '../../prop-types/requiredIfGivenPropIsTruthy';
import wrapFocus, {
elementOrParentIsFloatingMenu,
} from '../../internal/wrapFocus';
import setupGetInstanceId from '../../tools/setupGetInstanceId';
import { usePrefix } from '../../internal/usePrefix';
import { keys, match } from '../../internal/keyboard';
import { IconButton } from '../IconButton';
import { noopFn } from '../../internal/noopFn';
import { Text } from '../Text';
import { ReactAttr } from '../../types/common';
import { InlineLoadingStatus } from '../InlineLoading/InlineLoading';
const getInstanceId = setupGetInstanceId();
export const ModalSizes = ['xs', 'sm', 'md', 'lg'] as const;
export type ModalSize = (typeof ModalSizes)[number];
export interface ModalSecondaryButton {
buttonText?: string;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
}
export interface ModalProps extends ReactAttr<HTMLDivElement> {
/**
* Specify whether the Modal is displaying an alert, error or warning
* Should go hand in hand with the danger prop.
*/
alert?: boolean;
/**
* Required props for the accessibility label of the header
*/
'aria-label'?: string;
/**
* Provide the contents of your Modal
*/
children?: React.ReactNode;
/**
* Specify an optional className to be applied to the modal root node
*/
className?: string;
/**
* Specify an label for the close button of the modal; defaults to close
*/
closeButtonLabel?: string;
/**
* Specify whether the Modal is for dangerous actions
*/
danger?: boolean;
/**
* Specify whether the modal contains scrolling content
*/
hasScrollingContent?: boolean;
/**
* Specify the DOM element ID of the top-level node.
*/
id?: string;
/**
* Specify whether or not the Modal content should have any inner padding.
*/
isFullWidth?: boolean;
/**
* Provide a ref to return focus to once the modal is closed.
*/
launcherButtonRef?: any; // TODO FIXME
/**
* Specify the description for the loading text
*/
loadingDescription?: string;
/**
* Specify the description for the loading text
*/
loadingIconDescription?: string;
/**
* Specify loading status
*/
loadingStatus?: InlineLoadingStatus;
/**
* Specify a label to be read by screen readers on the modal root node
*/
modalAriaLabel?: string;
/**
* Specify the content of the modal header title.
*/
modalHeading?: React.ReactNode;
/**
* Specify the content of the modal header label.
*/
modalLabel?: React.ReactNode;
/**
* Specify a handler for keypresses.
* @deprecated this property is unused
*/
onKeyDown?: React.KeyboardEventHandler<HTMLElement>;
/**
* Specify an optional handler to be invoked when loading is
* successful
*/
onLoadingSuccess?: () => void;
/**
* Specify a handler for closing modal.
* The handler should care of closing modal, e.g. changing `open` prop.
*/
onRequestClose?: React.ReactEventHandler<HTMLElement>;
/**
* Specify a handler for "submitting" modal.
* The handler should care of closing modal, e.g. changing `open` prop, if necessary.
*/
onRequestSubmit?: React.ReactEventHandler<HTMLElement>;
/**
* Specify a handler for the secondary button.
* Useful if separate handler from `onRequestClose` is desirable
*/
onSecondarySubmit?: React.ReactEventHandler<HTMLElement>;
/**
* Specify whether the Modal is currently open
*/
open?: boolean;
/**
* Specify whether the modal should be button-less
*/
passiveModal?: boolean;
/**
* Prevent closing on click outside of modal
*/
preventCloseOnClickOutside?: boolean;
/**
* Specify whether the Button should be disabled, or not
*/
primaryButtonDisabled?: boolean;
/**
* Specify the text for the primary button
*/
primaryButtonText?: React.ReactNode;
/**
* Specify the text for the secondary button
*/
secondaryButtonText?: React.ReactNode;
/**
* Specify an array of config objects for secondary buttons
*/
secondaryButtons?: ModalSecondaryButton[];
/**
* Specify a CSS selector that matches the DOM element that should
* be focused when the Modal opens
*/
selectorPrimaryFocus?: string;
/**
* Specify CSS selectors that match DOM elements working as floating menus.
* Focusing on those elements won't trigger "focus-wrap" behavior
*/
selectorsFloatingMenus?: string[];
/**
* Specify if Enter key should be used as "submit" action
*/
shouldSubmitOnEnter?: boolean;
/**
* Specify the size variant.
*/
size?: ModalSize;
/**
* **Experimental**: Provide a `Slug` component to be rendered inside the `Modal` component
*/
slug?: ReactNodeLike;
}
const Modal = React.forwardRef(function Modal(
{
'aria-label': ariaLabelProp,
children,
className,
modalHeading = '',
modalLabel = '',
modalAriaLabel,
passiveModal = false,
secondaryButtonText,
primaryButtonText,
open,
onRequestClose = noopFn,
onRequestSubmit = noopFn,
onSecondarySubmit,
primaryButtonDisabled = false,
danger,
alert,
secondaryButtons,
selectorPrimaryFocus = '[data-modal-primary-focus]',
selectorsFloatingMenus,
shouldSubmitOnEnter,
size,
hasScrollingContent = false,
closeButtonLabel = 'Close',
preventCloseOnClickOutside = false,
isFullWidth,
launcherButtonRef,
loadingStatus = 'inactive',
loadingDescription,
loadingIconDescription,
onLoadingSuccess = noopFn,
slug,
...rest
}: ModalProps,
ref: React.LegacyRef<HTMLDivElement>
) {
const prefix = usePrefix();
const button = useRef<HTMLButtonElement>(null);
const secondaryButton = useRef();
const innerModal = useRef<HTMLDivElement>(null);
const startTrap = useRef<HTMLSpanElement>(null);
const endTrap = useRef<HTMLSpanElement>(null);
const modalInstanceId = `modal-${getInstanceId()}`;
const modalLabelId = `${prefix}--modal-header__label--${modalInstanceId}`;
const modalHeadingId = `${prefix}--modal-header__heading--${modalInstanceId}`;
const modalBodyId = `${prefix}--modal-body--${modalInstanceId}`;
const modalCloseButtonClass = `${prefix}--modal-close`;
const primaryButtonClass = classNames({
[`${prefix}--btn--loading`]: loadingStatus !== 'inactive',
});
const loadingActive = loadingStatus !== 'inactive';
function isCloseButton(element: Element) {
return (
(!onSecondarySubmit && element === secondaryButton.current) ||
element.classList.contains(modalCloseButtonClass)
);
}
function handleKeyDown(evt: React.KeyboardEvent<HTMLDivElement>) {
if (open) {
if (match(evt, keys.Escape)) {
onRequestClose(evt);
}
if (
match(evt, keys.Enter) &&
shouldSubmitOnEnter &&
!isCloseButton(evt.target as Element)
) {
onRequestSubmit(evt);
}
}
}
function handleMousedown(evt: React.MouseEvent<HTMLDivElement>) {
const target = evt.target as Node;
if (
innerModal.current &&
!innerModal.current.contains(target) &&
!elementOrParentIsFloatingMenu(target, selectorsFloatingMenus) &&
!preventCloseOnClickOutside
) {
onRequestClose(evt);
}
}
function handleBlur({
target: oldActiveNode,
relatedTarget: currentActiveNode,
}: React.FocusEvent<HTMLDivElement>) {
if (open && currentActiveNode && oldActiveNode) {
const { current: bodyNode } = innerModal;
const { current: startTrapNode } = startTrap;
const { current: endTrapNode } = endTrap;
wrapFocus({
bodyNode,
startTrapNode,
endTrapNode,
currentActiveNode,
oldActiveNode,
selectorsFloatingMenus,
});
}
}
const onSecondaryButtonClick = onSecondarySubmit
? onSecondarySubmit
: onRequestClose;
const modalClasses = classNames(
`${prefix}--modal`,
{
[`${prefix}--modal-tall`]: !passiveModal,
'is-visible': open,
[`${prefix}--modal--danger`]: danger,
[`${prefix}--modal--slug`]: slug,
},
className
);
const containerClasses = classNames(`${prefix}--modal-container`, {
[`${prefix}--modal-container--${size}`]: size,
[`${prefix}--modal-container--full-width`]: isFullWidth,
});
const contentClasses = classNames(`${prefix}--modal-content`, {
[`${prefix}--modal-scroll-content`]: hasScrollingContent,
});
const footerClasses = classNames(`${prefix}--modal-footer`, {
[`${prefix}--modal-footer--three-button`]:
Array.isArray(secondaryButtons) && secondaryButtons.length === 2,
});
const asStringOrUndefined = (node: React.ReactNode): string | undefined => {
return typeof node === 'string' ? node : undefined;
};
const modalLabelStr = asStringOrUndefined(modalLabel);
const modalHeadingStr = asStringOrUndefined(modalHeading);
const ariaLabel =
modalLabelStr || ariaLabelProp || modalAriaLabel || modalHeadingStr;
const getAriaLabelledBy = modalLabel ? modalLabelId : modalHeadingId;
const hasScrollingContentProps = hasScrollingContent
? {
tabIndex: 0,
role: 'region',
'aria-label': ariaLabel,
'aria-labelledby': getAriaLabelledBy,
}
: {};
const alertDialogProps: ReactAttr<HTMLDivElement> = {};
if (alert && passiveModal) {
alertDialogProps.role = 'alert';
}
if (alert && !passiveModal) {
alertDialogProps.role = 'alertdialog';
alertDialogProps['aria-describedby'] = modalBodyId;
}
useEffect(() => {
return () => {
toggleClass(document.body, `${prefix}--body--with-modal-open`, false);
};
}, [prefix]);
useEffect(() => {
toggleClass(
document.body,
`${prefix}--body--with-modal-open`,
open ?? false
);
}, [open, prefix]);
useEffect(() => {
if (!open && launcherButtonRef) {
setTimeout(() => {
launcherButtonRef?.current?.focus();
});
}
}, [open, launcherButtonRef]);
useEffect(() => {
const initialFocus = (focusContainerElement: HTMLElement | null) => {
const containerElement = focusContainerElement || innerModal.current;
const primaryFocusElement = containerElement
? containerElement.querySelector<HTMLElement | SVGElement>(
danger ? `.${prefix}--btn--secondary` : selectorPrimaryFocus
)
: null;
if (primaryFocusElement) {
return primaryFocusElement;
}
return button && button.current;
};
const focusButton = (focusContainerElement: HTMLElement | null) => {
const target = initialFocus(focusContainerElement);
if (target !== null) {
target.focus();
}
};
if (open) {
focusButton(innerModal.current);
}
}, [open, selectorPrimaryFocus, danger, prefix]);
// Slug is always size `lg`
let normalizedSlug;
if (slug && slug['type']?.displayName === 'Slug') {
normalizedSlug = React.cloneElement(slug as React.ReactElement<any>, {
size: 'lg',
});
}
const modalButton = (
<div className={`${prefix}--modal-close-button`}>
<IconButton
className={modalCloseButtonClass}
label={closeButtonLabel}
onClick={onRequestClose}
title={closeButtonLabel}
aria-label={closeButtonLabel}
align="left"
ref={button}>
<Close
size={20}
aria-hidden="true"
tabIndex="-1"
className={`${modalCloseButtonClass}__icon`}
/>
</IconButton>
</div>
);
const modalBody = (
<div
ref={innerModal}
role="dialog"
{...alertDialogProps}
className={containerClasses}
aria-label={ariaLabel}
aria-modal="true"
tabIndex={-1}>
<div className={`${prefix}--modal-header`}>
{passiveModal && modalButton}
{modalLabel && (
<Text
as="h2"
id={modalLabelId}
className={`${prefix}--modal-header__label`}>
{modalLabel}
</Text>
)}
<Text
as="h3"
id={modalHeadingId}
className={`${prefix}--modal-header__heading`}>
{modalHeading}
</Text>
{normalizedSlug}
{!passiveModal && modalButton}
</div>
<div
id={modalBodyId}
className={contentClasses}
{...hasScrollingContentProps}>
{children}
</div>
{hasScrollingContent && (
<div className={`${prefix}--modal-content--overflow-indicator`} />
)}
{!passiveModal && (
<ButtonSet className={footerClasses} aria-busy={loadingActive}>
{Array.isArray(secondaryButtons) && secondaryButtons.length <= 2
? secondaryButtons.map(
({ buttonText, onClick: onButtonClick }, i) => (
<Button
key={`${buttonText}-${i}`}
kind="secondary"
onClick={onButtonClick}>
{buttonText}
</Button>
)
)
: secondaryButtonText && (
<Button
disabled={loadingActive}
kind="secondary"
onClick={onSecondaryButtonClick}
ref={secondaryButton}>
{secondaryButtonText}
</Button>
)}
<Button
className={primaryButtonClass}
kind={danger ? 'danger' : 'primary'}
disabled={loadingActive || primaryButtonDisabled}
onClick={onRequestSubmit}
ref={button}>
{loadingStatus === 'inactive' ? (
primaryButtonText
) : (
<InlineLoading
status={loadingStatus}
description={loadingDescription}
iconDescription={loadingIconDescription}
className={`${prefix}--inline-loading--btn`}
onSuccess={onLoadingSuccess}
/>
)}
</Button>
</ButtonSet>
)}
</div>
);
return (
<div
{...rest}
onKeyDown={handleKeyDown}
onMouseDown={handleMousedown}
onBlur={handleBlur}
className={modalClasses}
role="presentation"
ref={ref}>
{/* Non-translatable: Focus-wrap code makes this `<span>` not actually read by screen readers */}
<span
ref={startTrap}
tabIndex={0}
role="link"
className={`${prefix}--visually-hidden`}>
Focus sentinel
</span>
{modalBody}
{/* Non-translatable: Focus-wrap code makes this `<span>` not actually read by screen readers */}
<span
ref={endTrap}
tabIndex={0}
role="link"
className={`${prefix}--visually-hidden`}>
Focus sentinel
</span>
</div>
);
});
Modal.propTypes = {
/**
* Specify whether the Modal is displaying an alert, error or warning
* Should go hand in hand with the danger prop.
*/
alert: PropTypes.bool,
/**
* Required props for the accessibility label of the header
*/
['aria-label']: requiredIfGivenPropIsTruthy(
'hasScrollingContent',
PropTypes.string
),
/**
* Provide the contents of your Modal
*/
children: PropTypes.node,
/**
* Specify an optional className to be applied to the modal root node
*/
className: PropTypes.string,
/**
* Specify an label for the close button of the modal; defaults to close
*/
closeButtonLabel: PropTypes.string,
/**
* Specify whether the Modal is for dangerous actions
*/
danger: PropTypes.bool,
/**
* Specify whether the modal contains scrolling content
*/
hasScrollingContent: PropTypes.bool,
/**
* Specify the DOM element ID of the top-level node.
*/
id: PropTypes.string,
/**
* Specify whether or not the Modal content should have any inner padding.
*/
isFullWidth: PropTypes.bool,
/**
* Provide a ref to return focus to once the modal is closed.
*/
launcherButtonRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({
current: PropTypes.any,
}),
]),
/**
* Specify the description for the loading text
*/
loadingDescription: PropTypes.string,
/**
* Specify the description for the loading text
*/
loadingIconDescription: PropTypes.string,
/**
* loading status
*/
loadingStatus: PropTypes.oneOf(['inactive', 'active', 'finished', 'error']),
/**
* Specify a label to be read by screen readers on the modal root node
*/
modalAriaLabel: PropTypes.string,
/**
* Specify the content of the modal header title.
*/
modalHeading: PropTypes.node,
/**
* Specify the content of the modal header label.
*/
modalLabel: PropTypes.node,
/**
* Specify a handler for keypresses.
*/
onKeyDown: PropTypes.func,
/**
* Provide an optional handler to be invoked when loading is
* successful
*/
onLoadingSuccess: PropTypes.func,
/**
* Specify a handler for closing modal.
* The handler should care of closing modal, e.g. changing `open` prop.
*/
onRequestClose: PropTypes.func,
/**
* Specify a handler for "submitting" modal.
* The handler should care of closing modal, e.g. changing `open` prop, if necessary.
*/
onRequestSubmit: PropTypes.func,
/**
* Specify a handler for the secondary button.
* Useful if separate handler from `onRequestClose` is desirable
*/
onSecondarySubmit: PropTypes.func,
/**
* Specify whether the Modal is currently open
*/
open: PropTypes.bool,
/**
* Specify whether the modal should be button-less
*/
passiveModal: PropTypes.bool,
/**
* Prevent closing on click outside of modal
*/
preventCloseOnClickOutside: PropTypes.bool,
/**
* Specify whether the Button should be disabled, or not
*/
primaryButtonDisabled: PropTypes.bool,
/**
* Specify the text for the primary button
*/
primaryButtonText: PropTypes.node,
/**
* Specify the text for the secondary button
*/
secondaryButtonText: PropTypes.node,
/**
* Specify an array of config objects for secondary buttons
* (`Array<{
* buttonText: string,
* onClick: function,
* }>`).
*/
secondaryButtons: (props, propName, componentName) => {
if (props.secondaryButtons) {
if (
!Array.isArray(props.secondaryButtons) ||
props.secondaryButtons.length !== 2
) {
return new Error(
`${propName} needs to be an array of two button config objects`
);
}
const shape = {
buttonText: PropTypes.node,
onClick: PropTypes.func,
};
props[propName].forEach((secondaryButton) => {
PropTypes.checkPropTypes(
shape,
secondaryButton,
propName,
componentName
);
});
}
return null;
},
/**
* Specify a CSS selector that matches the DOM element that should
* be focused when the Modal opens
*/
selectorPrimaryFocus: PropTypes.string,
/**
* Specify CSS selectors that match DOM elements working as floating menus.
* Focusing on those elements won't trigger "focus-wrap" behavior
*/
selectorsFloatingMenus: PropTypes.arrayOf(PropTypes.string.isRequired),
/**
* Specify if Enter key should be used as "submit" action
*/
shouldSubmitOnEnter: PropTypes.bool,
/**
* Specify the size variant.
*/
size: PropTypes.oneOf(ModalSizes),
/**
* **Experimental**: Provide a `Slug` component to be rendered inside the `Modal` component
*/
slug: PropTypes.node,
};
export default Modal;