UNPKG

react-cm-ui

Version:
701 lines (602 loc) 24.9 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _lodash = require("lodash"); var _reactPortal = require("react-portal"); var _react = _interopRequireDefault(require("react")); var _classnames = _interopRequireDefault(require("classnames")); var _propTypes = _interopRequireDefault(require("prop-types")); var _reactDom = _interopRequireDefault(require("react-dom")); var _reactCustomScrollbars = _interopRequireDefault(require("react-custom-scrollbars")); var _constants = require("../../global/constants"); var _button = _interopRequireDefault(require("../../inputs/button")); var _domUtils = _interopRequireDefault(require("../../utils/domUtils")); var _icon = _interopRequireDefault(require("../../dataDisplay/icon")); var _modalActions = _interopRequireDefault(require("./modalActions")); var _modalContent = _interopRequireDefault(require("./modalContent")); var _withStyles = _interopRequireDefault(require("../../styles/withStyles")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var propTypes = { /** * If `true`, Modal's height will adjust to the content. */ autoHeight: _propTypes["default"].bool, /** * The content of the Modal */ children: _propTypes["default"].node, /** * Override or extend the styles applied to Modal. */ classes: _propTypes["default"].shape({ closeButton: _propTypes["default"].string, dimmer: _propTypes["default"].string, innerContainerClasses: _propTypes["default"].string, padding: _propTypes["default"].string, root: _propTypes["default"].string, scrollContainer: _propTypes["default"].string }), /** * Assign additional class names to Modal. */ className: _propTypes["default"].string, /** * Add a `data-testid` attribute to the Modal's Close Button. * Used for DOM Testing. * See https://testing-library.com/docs/queries/bytestid/. */ closeButtonDataTestId: _propTypes["default"].string, /** * Used for DOM testing. https://testing-library.com/docs/queries/bytestid/ */ dataTestId: _propTypes["default"].string, /** * The `height` of the Modal. */ height: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]), /** * The `id` of the Modal. */ id: _propTypes["default"].string, /** * If `true`, Modal is open. */ isOpen: _propTypes["default"].bool.isRequired, /** * The `maxHeight` of the Modal. */ maxHeight: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]), /** * The `maxWidth` of the Modal. */ maxWidth: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]), /** * The `minHeight` of the Modal. */ minHeight: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]), /** * The `minWidth` of the Modal. */ minWidth: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]), /** * Boolean indicating whether or not the Modal can be closed when the user clicks outside of it. */ onClickOutside: _propTypes["default"].bool, /** * Event handler for closing the Modal. * Only used when Modal needs a close button in the top right. */ onClose: _propTypes["default"].func, /** * Event handler called after close animation has completed. */ onCloseComplete: _propTypes["default"].func, /** * Event handler called after open animation has completed. */ onOpenComplete: _propTypes["default"].func, /** * HC's theme. */ theme: _propTypes["default"].shape({ zIndex: _propTypes["default"].shape({ modal: _propTypes["default"].number }) }).isRequired, /** * The `width` of the Modal. */ width: _propTypes["default"].oneOfType([_propTypes["default"].number, _propTypes["default"].string]) }; var defaultProps = { autoHeight: true, children: null, classes: null, className: null, dataTestId: "".concat(_constants.UI_CLASS_NAME, "-modal"), /** * If autoHeight is false the Inner Container's height needs to have a pixel value * for the scroll container to work appropriately, otherwise content inside is hidden. */ height: null, id: null, maxHeight: '100%', maxWidth: 'none', minHeight: null, minWidth: '375px', onClickOutside: false, onClose: null, onCloseComplete: undefined, onOpenComplete: undefined, width: null }; var MODAL_ANIMATION_OUT_CLASS_NAME = "".concat(_constants.BEM_MODAL, "-animation_out"); var styles = function styles(_ref) { var _$concat, _root; var breakpoints = _ref.breakpoints, palette = _ref.palette, shape = _ref.shape, spacing = _ref.spacing, zIndex = _ref.zIndex; return { '@keyframes modalDimmerFadeIn': { '0%': { opacity: 0 }, '100%': { opacity: 1 } }, '@keyframes modalDimmerFadeOut': { '0%': { opacity: 1 }, '100%': { opacity: 0 } }, '@keyframes modalSlideIn': { '0%': { opacity: 0, transform: 'translateY(-44px)' }, '100%': { opacity: 1, transform: 'translateY(0)' } }, '@keyframes modalSlideOut': { '0%': { opacity: 1, transform: 'translateY(0)' }, '100%': { opacity: 0, transform: 'translateY(-44px)' } }, closeButton: _defineProperty({ borderRadius: spacing(1.5), margin: 0, position: 'absolute', right: spacing(1), top: spacing(1), zIndex: 1 }, breakpoints.up('md'), { right: -spacing(1.5), top: -spacing(1.5) }), dimmer: { animation: '$modalDimmerFadeIn 150ms ease-out forwards', animationDelay: '100ms', backfaceVisibility: 'hidden', backgroundColor: 'rgba(255, 255, 255, .7)', height: '100%', left: 0, opacity: 0, position: 'absolute', top: 0, width: '100%', zIndex: "".concat(zIndex.drawer + 2) }, innerContainerClasses: { animation: '$modalSlideIn 200ms ease-out forwards', backfaceVisibility: 'hidden', backgroundColor: palette.background.primary, borderRadius: shape.borderRadius, boxShadow: '0 15px 28px 0 rgba(0, 0, 0, 0.13)', position: 'relative' }, padding: {}, root: (_root = { alignItems: 'center', backfaceVisibility: 'hidden', display: 'flex', height: '100%', justifyContent: 'center', left: 0, minWidth: 320, position: 'fixed', top: 0, width: '100%', zIndex: zIndex.drawer }, _defineProperty(_root, breakpoints.up('md'), { padding: spacing(3) }), _defineProperty(_root, "&.".concat(MODAL_ANIMATION_OUT_CLASS_NAME), (_$concat = {}, _defineProperty(_$concat, "& .".concat(_constants.BEM_MODAL_INNER_CONTAINER), { animation: '$modalSlideOut 333ms forwards' }), _defineProperty(_$concat, "& ".concat(_constants.BEM_MODAL_DIMMER), { animation: '$modalDimmerFadeOut 150ms ease-out forwards' }), _$concat)), _root), scrollContainer: _defineProperty({ padding: [[spacing(5), spacing(2), spacing(2)]], position: 'relative' }, breakpoints.up('md'), { padding: spacing(3) }) }; }; var Modal = /*#__PURE__*/function (_React$Component) { _inherits(Modal, _React$Component); var _super = _createSuper(Modal); function Modal(props) { var _this; _classCallCheck(this, Modal); _this = _super.call(this, props); _this.state = _objectSpread(_objectSpread({}, _this.getDimensions()), {}, { isOpen: props.isOpen }); _this.mounted = false; _this.modalContainerNode = null; _this.getAutoHeightMax = _this.getAutoHeightMax.bind(_assertThisInitialized(_this)); _this.onClickOutside = _this.onClickOutside.bind(_assertThisInitialized(_this)); _this.onClose = _this.onClose.bind(_assertThisInitialized(_this)); _this.onCloseAnimationComplete = _this.onCloseAnimationComplete.bind(_assertThisInitialized(_this)); _this.onCloseBefore = _this.onCloseBefore.bind(_assertThisInitialized(_this)); _this.onOpen = _this.onOpen.bind(_assertThisInitialized(_this)); _this.onOpenAnimationComplete = _this.onOpenAnimationComplete.bind(_assertThisInitialized(_this)); _this.onResize = _this.onResize.bind(_assertThisInitialized(_this)); return _this; } _createClass(Modal, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; var isOpen = this.props.isOpen; this.mounted = true; window.addEventListener('resize', this.onResize); this.onResize(); if (isOpen) { this.setState({ isOpen: isOpen }, function () { _this2.onOpen(); }); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var _this3 = this; var _this$props = this.props, height = _this$props.height, isOpen = _this$props.isOpen, maxHeight = _this$props.maxHeight, maxWidth = _this$props.maxWidth, minHeight = _this$props.minHeight, minWidth = _this$props.minWidth, width = _this$props.width; if (!prevProps.isOpen && isOpen) { this.setState({ isOpen: isOpen }, function () { _this3.onOpen(); }); } if (prevProps.isOpen && !isOpen) { this.onCloseBefore(); } if (prevProps.height !== height || prevProps.maxHeight !== maxHeight || prevProps.maxWidth !== maxWidth || prevProps.minHeight !== minHeight || prevProps.minWidth !== minWidth || prevProps.width !== width) { this.setState(this.getDimensions()); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.mounted = false; window.removeEventListener('resize', this.onResize); } }, { key: "onClickOutside", value: function onClickOutside(event) { var _this$props2 = this.props, onClickOutside = _this$props2.onClickOutside, onClose = _this$props2.onClose; if (this.modalContainerRef.contains(event.target) || !onClickOutside) { return; } if ((0, _lodash.isFunction)(onClose)) { this.onClose(); } } }, { key: "onClose", value: function onClose() { var _this$props3 = this.props, onClickOutside = _this$props3.onClickOutside, onClose = _this$props3.onClose; if (onClickOutside) { document.removeEventListener('click', this.onClickOutside); } if ((0, _lodash.isFunction)(onClose)) { onClose(); } } }, { key: "onCloseAnimationComplete", value: function onCloseAnimationComplete() { var _this4 = this; var animationEvent = _domUtils["default"].cssAnimationType(this.modalContainerRef); this.modalContainerRef.removeEventListener(animationEvent, this.onCloseAnimationComplete); this.toggleBodyStyle({ enable: false }); this.setState({ isOpen: false }, function () { var onCloseComplete = _this4.props.onCloseComplete; if ((0, _lodash.isFunction)(onCloseComplete)) { onCloseComplete(); } }); } }, { key: "onCloseBefore", value: function onCloseBefore() { // eslint-disable-next-line react/no-find-dom-node var portalNode = _reactDom["default"].findDOMNode(this); var modalContainer = portalNode.querySelector(".".concat(_constants.BEM_MODAL_INNER_CONTAINER)); var animationEvent = _domUtils["default"].cssAnimationType(modalContainer); portalNode.classList.add(MODAL_ANIMATION_OUT_CLASS_NAME); this.modalContainerNode.addEventListener(animationEvent, this.onCloseAnimationComplete); } }, { key: "onOpen", value: function onOpen() { var _this$props4 = this.props, autoHeight = _this$props4.autoHeight, onClickOutside = _this$props4.onClickOutside, maxWidth = _this$props4.maxWidth, theme = _this$props4.theme; // eslint-disable-next-line react/no-find-dom-node var portalNode = _reactDom["default"].findDOMNode(this); this.modalContainerNode = portalNode.querySelector(".".concat(_constants.BEM_MODAL_INNER_CONTAINER)); var modalLength = document.querySelectorAll(".".concat(_constants.UI_CLASS_NAME, ".").concat(_constants.BEM_MODAL)).length; var animationEvent = _domUtils["default"].cssAnimationType(this.modalContainerNode); this.modalContainerNode.addEventListener(animationEvent, this.onOpenAnimationComplete); if (onClickOutside) { document.addEventListener('click', this.onClickOutside); } var newZIndex = theme.zIndex.modal + 2; // adding 2 accounts for the first .modal and .modal-dimmers- z-indexes if (modalLength >= 2) { newZIndex += modalLength; portalNode.style.zIndex = newZIndex; this.modalContainerNode.style.zIndex = newZIndex; portalNode.querySelector(".".concat(_constants.BEM_MODAL_DIMMER)).style.display = 'none'; } else { this.toggleBodyStyle({ enable: true }); portalNode.style.zIndex = newZIndex - 1; this.modalContainerNode.style.zIndex = newZIndex + modalLength; } if (!(0, _lodash.isUndefined)(maxWidth)) { if ((0, _lodash.isNumber)(maxWidth)) { this.modalContainerNode.style.maxWidth = "".concat(maxWidth, "px"); } else if ((0, _lodash.isString)(maxWidth)) { this.modalContainerNode.style.maxWidth = maxWidth; } else { this.modalContainerNode.style.maxWidth = null; } } else { this.modalContainerNode.style.maxWidth = '768px'; } if (autoHeight) { var newAutoHeightMax = this.getAutoHeightMax(); this.setState({ autoHeightMax: newAutoHeightMax }); } } }, { key: "onOpenAnimationComplete", value: function onOpenAnimationComplete() { var animationEvent = _domUtils["default"].cssAnimationType(this.modalContainerRef); this.modalContainerNode.removeEventListener(animationEvent, this.onOpenAnimationComplete); var onOpenComplete = this.props.onOpenComplete; if (typeof onOpenComplete === 'function') { onOpenComplete(); } } }, { key: "onResize", value: function onResize() { if (this.mounted) { this.setState(this.getDimensions()); } } }, { key: "getDimensions", value: function getDimensions() { var _this$props5 = this.props, autoHeight = _this$props5.autoHeight, height = _this$props5.height, maxHeight = _this$props5.maxHeight, maxWidth = _this$props5.maxWidth, minHeight = _this$props5.minHeight, minWidth = _this$props5.minWidth, width = _this$props5.width; var dimensions = { height: '100%', maxHeight: '100%', maxWidth: 'none', minHeight: 'auto', minWidth: '375px', width: '100%' }; if (window.matchMedia('(min-width: 768px)').matches === true) { dimensions = { height: height, maxHeight: maxHeight, maxWidth: maxWidth, minHeight: minHeight, minWidth: minWidth, width: width }; } if (autoHeight) { var newAutoHeightMax = this.getAutoHeightMax(); dimensions = _objectSpread(_objectSpread({}, dimensions), {}, { autoHeightMax: newAutoHeightMax }); } return dimensions; } }, { key: "getAutoHeightMax", value: function getAutoHeightMax() { var isOpen = this.props.isOpen; if (this.mounted && isOpen) { // eslint-disable-next-line react/no-find-dom-node var portalNode = _reactDom["default"].findDOMNode(this); if (portalNode) { var modalPaddingBottom = parseInt(getComputedStyle(portalNode).paddingBottom, 10); var modalPaddingTop = parseInt(getComputedStyle(portalNode).paddingTop, 10); var modalHeight = portalNode.offsetHeight; return modalHeight - modalPaddingBottom - modalPaddingTop; } } return null; } }, { key: "toggleBodyStyle", value: function toggleBodyStyle() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { enable: false }, enable = _ref2.enable; if (enable) { var _window = window, pageYOffset = _window.pageYOffset; document.body.style.overflowY = 'scroll'; document.body.style.position = 'fixed'; document.body.style.top = "-".concat(pageYOffset, "px"); document.body.style.width = '100%'; } else { var topPosition = parseInt(document.body.style.top, 10); document.body.style.overflowY = null; document.body.style.position = null; document.body.style.top = null; document.body.style.width = null; window.scroll(0, Math.abs(topPosition)); } } }, { key: "render", value: function render() { var _this5 = this; var _this$props6 = this.props, autoHeight = _this$props6.autoHeight, children = _this$props6.children, classes = _this$props6.classes, className = _this$props6.className, closeButtonDataTestId = _this$props6.closeButtonDataTestId, dataTestId = _this$props6.dataTestId, id = _this$props6.id, onCloseProp = _this$props6.onClose; var _this$state = this.state, autoHeightMax = _this$state.autoHeightMax, height = _this$state.height, isOpen = _this$state.isOpen, maxHeight = _this$state.maxHeight, maxWidth = _this$state.maxWidth, minHeight = _this$state.minHeight, minWidth = _this$state.minWidth, width = _this$state.width; if (!isOpen) { return null; } var rootClasses = (0, _classnames["default"])(_constants.UI_CLASS_NAME, _constants.BEM_MODAL, classes.root, className); var containerInnerStyles = { height: height, maxHeight: maxHeight, maxWidth: maxWidth, minHeight: minHeight, minWidth: minWidth, width: width }; return /*#__PURE__*/_react["default"].createElement(_reactPortal.Portal, null, /*#__PURE__*/_react["default"].createElement("div", { className: rootClasses, "data-testid": dataTestId, id: id }, /*#__PURE__*/_react["default"].createElement("div", { className: (0, _classnames["default"])(_constants.BEM_MODAL_INNER_CONTAINER, classes.innerContainerClasses), ref: function ref(_ref4) { _this5.modalContainerRef = _ref4; }, style: containerInnerStyles }, (0, _lodash.isFunction)(onCloseProp) && /*#__PURE__*/_react["default"].createElement(_button["default"], { className: "".concat(_constants.BEM_MODAL, "--close_button"), classes: { root: classes.closeButton }, "data-testid": closeButtonDataTestId, designVersion: 2, onClick: this.onClose, icon: true, title: "Close" }, /*#__PURE__*/_react["default"].createElement(_icon["default"], { compact: true, title: false, type: "close" })), /*#__PURE__*/_react["default"].createElement(_reactCustomScrollbars["default"], { autoHeight: autoHeight, autoHeightMax: autoHeightMax || null, autoHide: true, onScrollStart: this.onScrollStart, onScrollStop: this.onScrollStop }, /*#__PURE__*/_react["default"].createElement("div", { className: (0, _classnames["default"])(classes.scrollContainer, classes.padding), ref: function ref(_ref3) { _this5.modalScrollContainerRef = _ref3; } }, children))), /*#__PURE__*/_react["default"].createElement("div", { className: (0, _classnames["default"])(_constants.BEM_MODAL_DIMMER, classes.dimmer), "data-testid": "".concat(dataTestId, "_dimmer") }))); } }]); return Modal; }(_react["default"].Component); Modal.Actions = _modalActions["default"]; Modal.Content = _modalContent["default"]; Modal.propTypes = propTypes; Modal.defaultProps = defaultProps; var _default = (0, _withStyles["default"])(styles, { withTheme: true })(Modal); exports["default"] = _default;