-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Modal.js
449 lines (399 loc) · 12.1 KB
/
Modal.js
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
/**
* Copyright IBM Corp. 2016, 2018
*
* 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 from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import { Close20 } from '@carbon/icons-react';
import toggleClass from '../../tools/toggleClass';
import Button from '../Button';
import deprecate from '../../prop-types/deprecate';
import requiredIfGivenPropExists from '../../prop-types/requiredIfGivenPropExists';
import wrapFocus, {
elementOrParentIsFloatingMenu,
} from '../../internal/wrapFocus';
import setupGetInstanceId from '../../tools/setupGetInstanceId';
const { prefix } = settings;
const getInstanceId = setupGetInstanceId();
export default class Modal extends Component {
static propTypes = {
/**
* 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 whether the modal should be button-less
*/
passiveModal: PropTypes.bool,
/**
* Provide whether the modal content has a form element.
* If `true` is used here, non-form child content should have `bx--modal-content__regular-content` class.
*/
hasForm: PropTypes.bool,
/**
* Specify a handler for closing modal.
* The handler should care of closing modal, e.g. changing `open` prop.
*/
onRequestClose: PropTypes.func,
/**
* Specify the DOM element ID of the top-level node.
*/
id: 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 label to be read by screen readers on the modal root node
*/
modalAriaLabel: PropTypes.string,
/**
* Specify the text for the secondary button
*/
secondaryButtonText: PropTypes.string,
/**
* Specify the text for the primary button
*/
primaryButtonText: PropTypes.string,
/**
* Specify whether the Modal is currently open
*/
open: PropTypes.bool,
/**
* 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 keypresses.
*/
onKeyDown: PropTypes.func,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string,
/**
* Specify whether the Button should be disabled, or not
*/
primaryButtonDisabled: PropTypes.bool,
/**
* Specify a handler for the secondary button.
* Useful if separate handler from `onRequestClose` is desirable
*/
onSecondarySubmit: PropTypes.func,
/**
* Specify whether the Modal is for dangerous actions
*/
danger: PropTypes.bool,
/**
* Specify if Enter key should be used as "submit" action
*/
shouldSubmitOnEnter: PropTypes.bool,
/**
* 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),
/**
* Specify a CSS selector that matches the DOM element that should
* be focused when the Modal opens
*/
selectorPrimaryFocus: PropTypes.string,
/**
* Specify the size variant.
*/
size: PropTypes.oneOf(['xs', 'sm', 'lg']),
/**
* Deprecated; Used for advanced focus-wrapping feature using 3rd party library,
* but it's now achieved without a 3rd party library.
*/
focusTrap: deprecate(
PropTypes.bool,
`\nThe prop \`focusTrap\` for Modal has been deprecated, as the feature of \`focusTrap\` runs by default.`
),
/**
* Specify whether the modal contains scrolling content
*/
hasScrollingContent: PropTypes.bool,
/**
* Required props for the accessibility label of the header
*/
['aria-label']: requiredIfGivenPropExists(
'hasScrollingContent',
PropTypes.string
),
};
static defaultProps = {
onRequestClose: () => {},
onRequestSubmit: () => {},
primaryButtonDisabled: false,
onKeyDown: () => {},
passiveModal: false,
iconDescription: 'close the modal',
modalHeading: '',
modalLabel: '',
selectorPrimaryFocus: '[data-modal-primary-focus]',
hasScrollingContent: false,
};
button = React.createRef();
outerModal = React.createRef();
innerModal = React.createRef();
startTrap = React.createRef();
endTrap = React.createRef();
modalInstanceId = `modal-${getInstanceId()}`;
modalLabelId = `${prefix}--modal-header__label--${this.modalInstanceId}`;
modalHeadingId = `${prefix}--modal-header__heading--${this.modalInstanceId}`;
handleKeyDown = evt => {
if (this.props.open) {
if (evt.which === 27) {
this.props.onRequestClose(evt);
}
if (evt.which === 13 && this.props.shouldSubmitOnEnter) {
this.props.onRequestSubmit(evt);
}
}
};
handleMousedown = evt => {
if (
this.innerModal.current &&
!this.innerModal.current.contains(evt.target) &&
!elementOrParentIsFloatingMenu(
evt.target,
this.props.selectorsFloatingMenus
)
) {
this.props.onRequestClose(evt);
}
};
handleBlur = ({
target: oldActiveNode,
relatedTarget: currentActiveNode,
}) => {
const { open, selectorsFloatingMenus } = this.props;
if (open && currentActiveNode && oldActiveNode) {
const { current: modalNode } = this.innerModal;
const { current: startTrapNode } = this.startTrap;
const { current: endTrapNode } = this.endTrap;
wrapFocus({
modalNode,
startTrapNode,
endTrapNode,
currentActiveNode,
oldActiveNode,
selectorsFloatingMenus,
});
}
};
componentDidUpdate(prevProps) {
if (!prevProps.open && this.props.open) {
this.beingOpen = true;
} else if (prevProps.open && !this.props.open) {
this.beingOpen = false;
}
toggleClass(
document.body,
`${prefix}--body--with-modal-open`,
this.props.open
);
}
initialFocus = focusContainerElement => {
const containerElement = focusContainerElement || this.innerModal.current;
const primaryFocusElement = containerElement
? containerElement.querySelector(this.props.selectorPrimaryFocus)
: null;
if (primaryFocusElement) {
return primaryFocusElement;
}
return this.button && this.button.current;
};
focusButton = focusContainerElement => {
const target = this.initialFocus(focusContainerElement);
if (target) {
target.focus();
}
};
componentWillUnmount() {
toggleClass(document.body, `${prefix}--body--with-modal-open`, false);
}
componentDidMount() {
toggleClass(
document.body,
`${prefix}--body--with-modal-open`,
this.props.open
);
if (!this.props.open) {
return;
}
this.focusButton(this.innerModal.current);
}
handleTransitionEnd = evt => {
if (
evt.target === evt.currentTarget && // Not to handle `onTransitionEnd` on child DOM nodes
this.outerModal.current &&
this.outerModal.current.offsetWidth &&
this.outerModal.current.offsetHeight &&
this.beingOpen
) {
this.focusButton(evt.currentTarget);
this.beingOpen = false;
}
};
render() {
const {
modalHeading,
modalLabel,
modalAriaLabel,
passiveModal,
hasForm,
secondaryButtonText,
primaryButtonText,
open,
onRequestClose,
onRequestSubmit,
onSecondarySubmit,
iconDescription,
primaryButtonDisabled,
danger,
selectorPrimaryFocus, // eslint-disable-line
selectorsFloatingMenus, // eslint-disable-line
shouldSubmitOnEnter, // eslint-disable-line
size,
hasScrollingContent,
...other
} = this.props;
const onSecondaryButtonClick = onSecondarySubmit
? onSecondarySubmit
: onRequestClose;
const modalClasses = classNames({
[`${prefix}--modal`]: true,
[`${prefix}--modal-tall`]: !passiveModal,
'is-visible': open,
[`${prefix}--modal--danger`]: this.props.danger,
[this.props.className]: this.props.className,
});
const containerClasses = classNames(`${prefix}--modal-container`, {
[`${prefix}--modal-container--${size}`]: size,
});
const contentClasses = classNames(`${prefix}--modal-content`, {
[`${prefix}--modal-content--with-form`]: hasForm,
[`${prefix}--modal-scroll-content`]: hasScrollingContent,
});
const modalButton = (
<button
className={`${prefix}--modal-close`}
type="button"
onClick={onRequestClose}
title={iconDescription}
aria-label={iconDescription}
ref={this.button}>
<Close20
aria-label={iconDescription}
className={`${prefix}--modal-close__icon`}
/>
</button>
);
const ariaLabel =
modalLabel || this.props['aria-label'] || modalAriaLabel || modalHeading;
const getAriaLabelledBy = modalLabel
? this.modalLabelId
: this.modalHeadingId;
const hasScrollingContentProps = hasScrollingContent
? {
tabIndex: 0,
role: 'region',
'aria-label': ariaLabel,
'aria-labelledby': getAriaLabelledBy,
}
: {};
const modalBody = (
<div
ref={this.innerModal}
role="dialog"
className={containerClasses}
aria-label={ariaLabel}
aria-modal="true"
tabIndex="-1">
<div className={`${prefix}--modal-header`}>
{passiveModal && modalButton}
{modalLabel && (
<h2
id={this.modalLabelId}
className={`${prefix}--modal-header__label`}>
{modalLabel}
</h2>
)}
<h3
id={this.modalHeadingId}
className={`${prefix}--modal-header__heading`}>
{modalHeading}
</h3>
{!passiveModal && modalButton}
</div>
<div
className={contentClasses}
{...hasScrollingContentProps}
aria-labelledby={getAriaLabelledBy}>
{this.props.children}
</div>
{hasScrollingContent && (
<div className={`${prefix}--modal-content--overflow-indicator`} />
)}
{!passiveModal && (
<div className={`${prefix}--modal-footer`}>
<Button kind="secondary" onClick={onSecondaryButtonClick}>
{secondaryButtonText}
</Button>
<Button
kind={danger ? 'danger' : 'primary'}
disabled={primaryButtonDisabled}
onClick={onRequestSubmit}
inputref={this.button}>
{primaryButtonText}
</Button>
</div>
)}
</div>
);
return (
<div
{...other}
onKeyDown={this.handleKeyDown}
onMouseDown={this.handleMousedown}
onBlur={this.handleBlur}
className={modalClasses}
role="presentation"
onTransitionEnd={this.props.open ? this.handleTransitionEnd : undefined}
ref={this.outerModal}>
{/* Non-translatable: Focus-wrap code makes this `<span>` not actually read by screen readers */}
<span
ref={this.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={this.endTrap}
tabIndex="0"
role="link"
className={`${prefix}--visually-hidden`}>
Focus sentinel
</span>
</div>
);
}
}