@carbon/react
Version:
React components for the Carbon Design System
628 lines (621 loc) • 23.5 kB
JavaScript
/**
* 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 { extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import PropTypes from 'prop-types';
import React, { useRef, useState, useEffect, cloneElement } from 'react';
import cx from 'classnames';
import { Close } from '@carbon/icons-react';
import { toggleClass } from '../../tools/toggleClass.js';
import Button from '../Button/Button.js';
import '../Button/Button.Skeleton.js';
import ButtonSet from '../ButtonSet/ButtonSet.js';
import InlineLoading from '../InlineLoading/InlineLoading.js';
import { Layer } from '../Layer/index.js';
import requiredIfGivenPropIsTruthy from '../../prop-types/requiredIfGivenPropIsTruthy.js';
import { wrapFocus, wrapFocusWithoutSentinels, elementOrParentIsFloatingMenu } from '../../internal/wrapFocus.js';
import useIsomorphicEffect from '../../internal/useIsomorphicEffect.js';
import { useId } from '../../internal/useId.js';
import { usePrefix } from '../../internal/usePrefix.js';
import { usePreviousValue } from '../../internal/usePreviousValue.js';
import { Escape, Enter, Tab } from '../../internal/keyboard/keys.js';
import { match } from '../../internal/keyboard/match.js';
import { IconButton } from '../IconButton/index.js';
import { noopFn } from '../../internal/noopFn.js';
import '../Text/index.js';
import { useFeatureFlag } from '../FeatureFlags/index.js';
import { composeEventHandlers } from '../../tools/events.js';
import { deprecate } from '../../prop-types/deprecate.js';
import { Dialog } from '../Dialog/Dialog.js';
import { AILabel } from '../AILabel/index.js';
import { isComponentElement } from '../../internal/utils.js';
import { warning } from '../../internal/warning.js';
import { debounce } from '../../node_modules/es-toolkit/dist/compat/function/debounce.js';
import { Text } from '../Text/Text.js';
const ModalSizes = ['xs', 'sm', 'md', 'lg'];
const invalidOutsideClickMessage = '`Modal`: `preventCloseOnClickOutside` should not be `false` when `passiveModal` is `false`. Non-passive `Modal`s should not be dismissible by clicking outside.';
const Modal = /*#__PURE__*/React.forwardRef(function Modal({
'aria-label': ariaLabelProp,
children,
className,
decorator,
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 = !passiveModal,
isFullWidth,
launcherButtonRef,
loadingStatus = 'inactive',
loadingDescription,
loadingIconDescription,
onLoadingSuccess = noopFn,
slug,
...rest
}, ref) {
const prefix = usePrefix();
const button = useRef(null);
const secondaryButton = useRef(null);
const contentRef = useRef(null);
const innerModal = useRef(null);
const startTrap = useRef(null);
const endTrap = useRef(null);
const wrapFocusTimeout = useRef(null);
const [isScrollable, setIsScrollable] = useState(false);
const prevOpen = usePreviousValue(open);
const modalInstanceId = `modal-${useId()}`;
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 = cx({
[`${prefix}--btn--loading`]: loadingStatus !== 'inactive'
});
const loadingActive = loadingStatus !== 'inactive';
const focusTrapWithoutSentinels = useFeatureFlag('enable-experimental-focus-wrap-without-sentinels');
const enableDialogElement = useFeatureFlag('enable-dialog-element');
process.env.NODE_ENV !== "production" ? warning(!(focusTrapWithoutSentinels && enableDialogElement), '`<Modal>` detected both `focusTrapWithoutSentinels` and ' + '`enableDialogElement` feature flags are enabled. The native dialog ' + 'element handles focus, so `enableDialogElement` must be off for ' + '`focusTrapWithoutSentinels` to have any effect.') : void 0;
if (!passiveModal && preventCloseOnClickOutside === false) {
console.error(invalidOutsideClickMessage);
}
function isCloseButton(element) {
return !onSecondarySubmit && element === secondaryButton.current || element.classList.contains(modalCloseButtonClass);
}
function handleKeyDown(evt) {
const {
target
} = evt;
evt.stopPropagation();
if (open && target instanceof HTMLElement) {
if (match(evt, Enter) && shouldSubmitOnEnter && !isCloseButton(target) && document.activeElement !== button.current) {
onRequestSubmit(evt);
}
if (focusTrapWithoutSentinels && !enableDialogElement && match(evt, Tab) && innerModal.current) {
wrapFocusWithoutSentinels({
containerNode: innerModal.current,
currentActiveNode: target,
event: evt
});
}
}
}
function handleOnClick(evt) {
const {
target
} = evt;
evt.stopPropagation();
if (!preventCloseOnClickOutside && target instanceof Node && !elementOrParentIsFloatingMenu(target, selectorsFloatingMenus) && innerModal.current && !innerModal.current.contains(target)) {
onRequestClose(evt);
}
}
function handleBlur({
target: oldActiveNode,
relatedTarget: currentActiveNode
}) {
if (!enableDialogElement && open && oldActiveNode instanceof HTMLElement && currentActiveNode instanceof HTMLElement) {
const {
current: bodyNode
} = innerModal;
const {
current: startTrapNode
} = startTrap;
const {
current: endTrapNode
} = endTrap;
// use setTimeout to ensure focus is set after all browser default focus behavior. Fixes issue of
// focus not wrapping in Firefox
wrapFocusTimeout.current = setTimeout(() => {
wrapFocus({
bodyNode,
startTrapNode,
endTrapNode,
currentActiveNode,
oldActiveNode,
selectorsFloatingMenus
});
if (wrapFocusTimeout.current) {
clearTimeout(wrapFocusTimeout.current);
}
});
}
// Adjust scroll if needed so that element with focus is not obscured by gradient
const modalContent = document.querySelector(`.${prefix}--modal-content`);
if (!modalContent || !modalContent.classList.contains(`${prefix}--modal-scroll-content`) || !currentActiveNode || !modalContent.contains(currentActiveNode)) {
return;
}
const lastContent = modalContent.children[modalContent.children.length - 1];
const gradientSpacing = modalContent.scrollHeight - lastContent.offsetTop - lastContent.clientHeight;
for (let elem of modalContent.children) {
if (elem.contains(currentActiveNode)) {
const spaceBelow = modalContent.clientHeight - elem.offsetTop + modalContent.scrollTop - elem.clientHeight;
if (spaceBelow < gradientSpacing) {
modalContent.scrollTop = modalContent.scrollTop + (gradientSpacing - spaceBelow);
}
break;
}
}
}
const onSecondaryButtonClick = onSecondarySubmit ? onSecondarySubmit : onRequestClose;
const modalClasses = cx(`${prefix}--modal`, {
[`${prefix}--modal-tall`]: !passiveModal,
'is-visible': open,
[`${prefix}--modal--danger`]: danger,
[`${prefix}--modal--slug`]: slug,
[`${prefix}--modal--decorator`]: decorator
}, className);
const containerClasses = cx(`${prefix}--modal-container`, {
[`${prefix}--modal-container--${size}`]: size,
[`${prefix}--modal-container--full-width`]: isFullWidth
});
const contentClasses = cx(`${prefix}--modal-content`, {
[`${prefix}--modal-scroll-content`]: hasScrollingContent || isScrollable
});
const footerClasses = cx(`${prefix}--modal-footer`, {
[`${prefix}--modal-footer--three-button`]: Array.isArray(secondaryButtons) && secondaryButtons.length === 2
});
const asStringOrUndefined = node => {
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 || isScrollable ? {
tabIndex: 0,
role: 'region',
'aria-label': ariaLabel,
'aria-labelledby': getAriaLabelledBy
} : {};
const alertDialogProps = {};
if (alert && passiveModal) {
alertDialogProps.role = 'alert';
}
if (alert && !passiveModal) {
alertDialogProps.role = 'alertdialog';
alertDialogProps['aria-describedby'] = modalBodyId;
}
useEffect(() => {
if (!open) return;
const handleEscapeKey = event => {
if (match(event, Escape)) {
event.preventDefault();
event.stopPropagation();
onRequestClose(event);
}
};
document.addEventListener('keydown', handleEscapeKey, true);
return () => {
document.removeEventListener('keydown', handleEscapeKey, true);
};
}, [open]);
useEffect(() => {
return () => {
if (!enableDialogElement) {
toggleClass(document.body, `${prefix}--body--with-modal-open`, false);
}
};
}, [prefix, enableDialogElement]);
useEffect(() => {
if (!enableDialogElement) {
toggleClass(document.body, `${prefix}--body--with-modal-open`, open ?? false);
}
}, [open, prefix, enableDialogElement]);
useEffect(() => {
if (!enableDialogElement && prevOpen && !open && launcherButtonRef) {
setTimeout(() => {
if ('current' in launcherButtonRef) {
launcherButtonRef.current?.focus();
}
});
}
}, [open, prevOpen, launcherButtonRef, enableDialogElement]);
useEffect(() => {
if (!enableDialogElement) {
const initialFocus = focusContainerElement => {
const containerElement = focusContainerElement || innerModal.current;
const primaryFocusElement = containerElement && (containerElement.querySelector(selectorPrimaryFocus) || danger && containerElement.querySelector(`.${prefix}--btn--secondary`));
if (primaryFocusElement) {
return primaryFocusElement;
}
return button && button.current;
};
const focusButton = focusContainerElement => {
const target = initialFocus(focusContainerElement);
if (target !== null) {
target.focus();
}
};
if (open) {
focusButton(innerModal.current);
}
}
}, [open, selectorPrimaryFocus, danger, prefix, enableDialogElement]);
useIsomorphicEffect(() => {
if (contentRef.current) {
setIsScrollable(contentRef.current.scrollHeight > contentRef.current.clientHeight);
}
function handler() {
if (contentRef.current) {
setIsScrollable(contentRef.current.scrollHeight > contentRef.current.clientHeight);
}
}
const debouncedHandler = debounce(handler, 200);
window.addEventListener('resize', debouncedHandler);
return () => {
debouncedHandler.cancel();
window.removeEventListener('resize', debouncedHandler);
};
}, []);
// AILabel always size `sm`
const candidate = slug ?? decorator;
const candidateIsAILabel = isComponentElement(candidate, AILabel);
const normalizedDecorator = candidateIsAILabel ? /*#__PURE__*/cloneElement(candidate, {
size: 'sm'
}) : null;
const modalButton = /*#__PURE__*/React.createElement("div", {
className: `${prefix}--modal-close-button`
}, /*#__PURE__*/React.createElement(IconButton, {
className: modalCloseButtonClass,
label: closeButtonLabel,
onClick: onRequestClose,
"aria-label": closeButtonLabel,
align: "left",
ref: button
}, /*#__PURE__*/React.createElement(Close, {
size: 20,
"aria-hidden": "true",
tabIndex: "-1",
className: `${modalCloseButtonClass}__icon`
})));
// alertdialog is the only permitted aria role for a native dialog element
// https://www.w3.org/TR/html-aria/#docconformance:~:text=Role%3A-,alertdialog,-.%20(dialog%20is
const isAlertDialog = alert && !passiveModal;
const modalBody = enableDialogElement ? /*#__PURE__*/React.createElement(Dialog, {
open: open,
focusAfterCloseRef: launcherButtonRef,
modal: true,
ref: innerModal,
role: isAlertDialog ? 'alertdialog' : '',
"aria-describedby": isAlertDialog ? modalBodyId : '',
className: containerClasses,
"aria-label": ariaLabel
}, /*#__PURE__*/React.createElement("div", {
className: `${prefix}--modal-header`
}, modalLabel && /*#__PURE__*/React.createElement(Text, {
as: "h2",
id: modalLabelId,
className: `${prefix}--modal-header__label`
}, modalLabel), /*#__PURE__*/React.createElement(Text, {
as: "h2",
id: modalHeadingId,
className: `${prefix}--modal-header__heading`
}, modalHeading), decorator ? /*#__PURE__*/React.createElement("div", {
className: `${prefix}--modal--inner__decorator`
}, normalizedDecorator) : '', /*#__PURE__*/React.createElement("div", {
className: `${prefix}--modal-close-button`
}, /*#__PURE__*/React.createElement(IconButton, {
className: modalCloseButtonClass,
label: closeButtonLabel,
onClick: onRequestClose,
"aria-label": closeButtonLabel,
align: "left",
ref: button
}, /*#__PURE__*/React.createElement(Close, {
size: 20,
"aria-hidden": "true",
tabIndex: "-1",
className: `${modalCloseButtonClass}__icon`
})))), /*#__PURE__*/React.createElement(Layer, _extends({
ref: contentRef,
id: modalBodyId,
className: contentClasses
}, hasScrollingContentProps), children), !passiveModal && /*#__PURE__*/React.createElement(ButtonSet, {
className: footerClasses,
"aria-busy": loadingActive
}, Array.isArray(secondaryButtons) && secondaryButtons.length <= 2 ? secondaryButtons.map(({
buttonText,
onClick: onButtonClick
}, i) => /*#__PURE__*/React.createElement(Button, {
key: `${buttonText}-${i}`,
kind: "secondary",
onClick: onButtonClick
}, buttonText)) : secondaryButtonText && /*#__PURE__*/React.createElement(Button, {
disabled: loadingActive,
kind: "secondary",
onClick: onSecondaryButtonClick,
ref: secondaryButton
}, secondaryButtonText), /*#__PURE__*/React.createElement(Button, {
className: primaryButtonClass,
kind: danger ? 'danger' : 'primary',
disabled: loadingActive || primaryButtonDisabled,
onClick: onRequestSubmit,
ref: button
}, loadingStatus === 'inactive' ? primaryButtonText : /*#__PURE__*/React.createElement(InlineLoading, {
status: loadingStatus,
description: loadingDescription,
iconDescription: loadingIconDescription,
className: `${prefix}--inline-loading--btn`,
onSuccess: onLoadingSuccess
})))) : /*#__PURE__*/React.createElement(React.Fragment, null, !enableDialogElement && !focusTrapWithoutSentinels && /*#__PURE__*/React.createElement("span", {
ref: startTrap,
tabIndex: 0,
role: "link",
className: `${prefix}--visually-hidden`
}, "Focus sentinel"), /*#__PURE__*/React.createElement("div", _extends({
ref: innerModal,
role: "dialog"
}, alertDialogProps, {
className: containerClasses,
"aria-label": ariaLabel,
"aria-modal": "true",
tabIndex: -1
}), /*#__PURE__*/React.createElement("div", {
className: `${prefix}--modal-header`
}, passiveModal && modalButton, modalLabel && /*#__PURE__*/React.createElement(Text, {
as: "h2",
id: modalLabelId,
className: `${prefix}--modal-header__label`
}, modalLabel), /*#__PURE__*/React.createElement(Text, {
as: "h2",
id: modalHeadingId,
className: `${prefix}--modal-header__heading`
}, modalHeading), slug ? normalizedDecorator : decorator ? /*#__PURE__*/React.createElement("div", {
className: `${prefix}--modal--inner__decorator`
}, normalizedDecorator) : '', !passiveModal && modalButton), /*#__PURE__*/React.createElement(Layer, _extends({
ref: contentRef,
id: modalBodyId,
className: contentClasses
}, hasScrollingContentProps), children), !passiveModal && /*#__PURE__*/React.createElement(ButtonSet, {
className: footerClasses,
"aria-busy": loadingActive
}, Array.isArray(secondaryButtons) && secondaryButtons.length <= 2 ? secondaryButtons.map(({
buttonText,
onClick: onButtonClick
}, i) => /*#__PURE__*/React.createElement(Button, {
key: `${buttonText}-${i}`,
kind: "secondary",
onClick: onButtonClick
}, buttonText)) : secondaryButtonText && /*#__PURE__*/React.createElement(Button, {
disabled: loadingActive,
kind: "secondary",
onClick: onSecondaryButtonClick,
ref: secondaryButton
}, secondaryButtonText), /*#__PURE__*/React.createElement(Button, {
className: primaryButtonClass,
kind: danger ? 'danger' : 'primary',
disabled: loadingActive || primaryButtonDisabled,
onClick: onRequestSubmit,
ref: button
}, loadingStatus === 'inactive' ? primaryButtonText : /*#__PURE__*/React.createElement(InlineLoading, {
status: loadingStatus,
description: loadingDescription,
iconDescription: loadingIconDescription,
className: `${prefix}--inline-loading--btn`,
onSuccess: onLoadingSuccess
})))), !enableDialogElement && !focusTrapWithoutSentinels && /*#__PURE__*/React.createElement("span", {
ref: endTrap,
tabIndex: 0,
role: "link",
className: `${prefix}--visually-hidden`
}, "Focus sentinel"));
return /*#__PURE__*/React.createElement(Layer, _extends({}, rest, {
level: 0,
onKeyDown: handleKeyDown,
onClick: composeEventHandlers([rest?.onClick, handleOnClick]),
onBlur: handleBlur,
className: modalClasses,
role: "presentation",
ref: ref
}), modalBody);
});
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 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,
/**
* **Experimental**: Provide a decorator component to be rendered inside the `Modal` component
*/
decorator: PropTypes.node,
/**
* 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.oneOfType([
// `PropTypes.instanceOf(HTMLButtonElement)` alone won't work because
// `HTMLButtonElement` is not defined in the test environment even
// though `testEnvironment` is set to `jsdom`.
typeof HTMLButtonElement !== 'undefined' ? PropTypes.instanceOf(HTMLButtonElement) : PropTypes.any, PropTypes.oneOf([null])]).isRequired
})]),
/**
* 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: (props, propName) => {
if (!props.passiveModal && props[propName] === false) {
return new Error(invalidOutsideClickMessage);
}
return null;
},
/**
* 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),
slug: deprecate(PropTypes.node, 'The `slug` prop has been deprecated and will be removed in the next major version. Use the decorator prop instead.')
};
export { ModalSizes, Modal as default };