"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModalContent = exports.ModalOverlay = exports.ModalCloseButton = exports.ModalBody = exports.ModalFooter = exports.ModalTransition = exports.ModalHeader = exports.Modal = void 0;

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _autoId = require("@reach/auto-id");

var _ariaHidden = require("aria-hidden");

var _exenv = _interopRequireDefault(require("exenv"));

var _react = _interopRequireWildcard(require("react"));

var _cjs = _interopRequireDefault(require("react-focus-lock/dist/cjs"));

var _reactSpring = require("react-spring");

var _Box = require("../Box");

var _Card = require("../Card");

var _CloseButton = require("../CloseButton");

var _Flex = require("../Flex");

var _useForkRef = require("../hooks/useForkRef");

var _Portal = require("../Portal");

var _getFocusables = require("../utils/getFocusables");

var _wrapEvent = require("../utils/wrapEvent");

var _styles = _interopRequireWildcard(require("./styles"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

var __jsx = _react["default"].createElement;
var canUseDOM = _exenv["default"].canUseDOM;
var ModalContext = /*#__PURE__*/(0, _react.createContext)({});

var useModalContext = function useModalContext() {
  return (0, _react.useContext)(ModalContext);
};

function useAriaHider(_ref) {
  var isOpen = _ref.isOpen,
      id = _ref.id,
      enableInert = _ref.enableInert,
      _ref$container = _ref.container,
      container = _ref$container === void 0 ? canUseDOM ? document.body : null : _ref$container;
  var mountRef = (0, _react.useRef)(canUseDOM ? document.getElementById(id) || document.createElement('div') : null);
  (0, _react.useEffect)(function () {
    var undoAriaHidden = null;
    var mountNode = mountRef.current;

    if (isOpen && canUseDOM) {
      mountRef.current.id = id;
      container.appendChild(mountRef.current);

      if (enableInert) {
        undoAriaHidden = (0, _ariaHidden.hideOthers)(mountNode);
      }
    }

    return function () {
      if (enableInert && undoAriaHidden != null) {
        undoAriaHidden();
      }

      if (mountNode.parentElement) {
        mountNode.parentElement.removeChild(mountNode);
      }
    };
  }, [isOpen, id, enableInert, container]);
  return mountRef;
}

var Modal = function Modal(_ref2) {
  var isOpen = _ref2.isOpen,
      initialFocusRef = _ref2.initialFocusRef,
      finalFocusRef = _ref2.finalFocusRef,
      onClose = _ref2.onClose,
      _ref2$blockScrollOnMo = _ref2.blockScrollOnMount,
      blockScrollOnMount = _ref2$blockScrollOnMo === void 0 ? true : _ref2$blockScrollOnMo,
      _ref2$closeOnEsc = _ref2.closeOnEsc,
      closeOnEsc = _ref2$closeOnEsc === void 0 ? true : _ref2$closeOnEsc,
      _ref2$closeOnOverlayC = _ref2.closeOnOverlayClick,
      closeOnOverlayClick = _ref2$closeOnOverlayC === void 0 ? true : _ref2$closeOnOverlayC,
      _ref2$useInert = _ref2.useInert,
      useInert = _ref2$useInert === void 0 ? true : _ref2$useInert,
      _ref2$scrollBehavior = _ref2.scrollBehavior,
      scrollBehavior = _ref2$scrollBehavior === void 0 ? 'outside' : _ref2$scrollBehavior,
      _ref2$isCentered = _ref2.isCentered,
      isCentered = _ref2$isCentered === void 0 ? true : _ref2$isCentered,
      _ref2$addAriaLabels = _ref2.addAriaLabels,
      addAriaLabels = _ref2$addAriaLabels === void 0 ? true : _ref2$addAriaLabels,
      preserveScrollBarGap = _ref2.preserveScrollBarGap,
      _ref2$formatIds = _ref2.formatIds,
      formatIds = _ref2$formatIds === void 0 ? function (id) {
    return {
      content: "modal-".concat(id),
      header: "modal-".concat(id, "-header"),
      body: "modal-".concat(id, "-body")
    };
  } : _ref2$formatIds,
      container = _ref2.container,
      _ref2$returnFocusOnCl = _ref2.returnFocusOnClose,
      returnFocusOnClose = _ref2$returnFocusOnCl === void 0 ? true : _ref2$returnFocusOnCl,
      children = _ref2.children,
      id = _ref2.id,
      _ref2$size = _ref2.size,
      size = _ref2$size === void 0 ? 'md' : _ref2$size;
  var contentRef = (0, _react.useRef)(null);
  var uuid = (0, _autoId.useId)();

  var _id = id || uuid;

  var contentId = formatIds(_id)['content'];
  var headerId = formatIds(_id)['header'];
  var bodyId = formatIds(_id)['body'];
  var portalId = "chakra-portal-".concat(_id);
  var addAriaLabelledby = false;
  var addAriaDescribedby = false;

  if (typeof addAriaLabels === 'object') {
    addAriaLabelledby = addAriaLabels['header'];
    addAriaDescribedby = addAriaLabels['body'];
  }

  if (typeof addAriaLabels === 'boolean') {
    addAriaLabelledby = addAriaLabels;
    addAriaDescribedby = addAriaLabels;
  } // body-scroll-lock package broken on ssr
  // useEffect(() => {
  // const dialogNode = contentRef.current;
  // if (isOpen && blockScrollOnMount && __BROWSER__) {
  //     disableBodyScroll(dialogNode, {
  //         reserveScrollBarGap: preserveScrollBarGap,
  //     });
  // }
  // return () => {
  //     if (__BROWSER__) {
  //         return enableBodyScroll(dialogNode);
  //     }
  //     return null;
  // };
  // }, [isOpen, blockScrollOnMount, preserveScrollBarGap]);


  (0, _react.useEffect)(function () {
    var func = function func(event) {
      if (event.key === 'Escape' && closeOnEsc) {
        onClose(event, 'pressedEscape');
      }
    };

    if (isOpen && !closeOnOverlayClick && canUseDOM) {
      document.addEventListener('keydown', func);
    }

    return function () {
      if (canUseDOM) {
        document.removeEventListener('keydown', func);
      }
    };
  }, [isOpen, onClose, closeOnOverlayClick, closeOnEsc]);
  var mountRef = useAriaHider({
    isOpen: isOpen,
    id: portalId,
    enableInert: useInert,
    // @ts-ignore
    container: container
  });
  var context = {
    isOpen: isOpen,
    initialFocusRef: initialFocusRef,
    onClose: onClose,
    blockScrollOnMount: blockScrollOnMount,
    closeOnEsc: closeOnEsc,
    closeOnOverlayClick: closeOnOverlayClick,
    returnFocusOnClose: returnFocusOnClose,
    contentRef: contentRef,
    scrollBehavior: scrollBehavior,
    isCentered: isCentered,
    headerId: headerId,
    bodyId: bodyId,
    contentId: contentId,
    size: size,
    addAriaLabelledby: addAriaLabelledby,
    addAriaDescribedby: addAriaDescribedby
  };
  var activateFocusLock = (0, _react.useCallback)(function () {
    if (initialFocusRef && initialFocusRef.current) {
      initialFocusRef.current.focus();
    } else if (contentRef.current) {
      var focusables = (0, _getFocusables.getFocusables)(contentRef.current);

      if (focusables.length === 0) {
        contentRef.current.focus();
      }
    }
  }, [initialFocusRef]);
  var deactivateFocusLock = (0, _react.useCallback)(function () {
    if (finalFocusRef && finalFocusRef.current) {
      finalFocusRef.current.focus();
    }
  }, [finalFocusRef]);
  if (!isOpen) return null;
  return __jsx(ModalContext.Provider, {
    value: context
  }, __jsx(_Portal.Portal, {
    container: mountRef.current
  }, __jsx(_cjs["default"], {
    returnFocus: returnFocusOnClose && !finalFocusRef,
    onActivation: activateFocusLock,
    onDeactivation: deactivateFocusLock
  }, children)));
};

exports.Modal = Modal;

var ModalOverlay = /*#__PURE__*/_react["default"].forwardRef(function (props, ref) {
  return __jsx(_Box.Box, (0, _extends2["default"])({
    pos: "fixed",
    bg: "overlay",
    left: "0",
    top: "0",
    w: "100vw",
    h: "100vh",
    ref: ref,
    zIndex: "overlay",
    onClick: (0, _wrapEvent.wrapEvent)(props.onClick, function (event) {
      event.stopPropagation();
    })
  }, props));
});

exports.ModalOverlay = ModalOverlay;

var ModalContent = /*#__PURE__*/_react["default"].forwardRef(function (_ref3, ref) {
  var onClick = _ref3.onClick,
      children = _ref3.children,
      zIndex = _ref3.zIndex,
      noStyles = _ref3.noStyles,
      props = (0, _objectWithoutProperties2["default"])(_ref3, ["onClick", "children", "zIndex", "noStyles"]);

  var _useModalContext = useModalContext(),
      contentRef = _useModalContext.contentRef,
      onClose = _useModalContext.onClose,
      isCentered = _useModalContext.isCentered,
      bodyId = _useModalContext.bodyId,
      headerId = _useModalContext.headerId,
      contentId = _useModalContext.contentId,
      size = _useModalContext.size,
      closeOnEsc = _useModalContext.closeOnEsc,
      addAriaLabelledby = _useModalContext.addAriaLabelledby,
      addAriaDescribedby = _useModalContext.addAriaDescribedby,
      scrollBehavior = _useModalContext.scrollBehavior,
      closeOnOverlayClick = _useModalContext.closeOnOverlayClick;

  var _contentRef = (0, _useForkRef.useForkRef)(ref, contentRef);

  var modalWrapperStyleProps = (0, _styles.useModalWrapperStyle)({
    scrollBehavior: scrollBehavior,
    isCentered: isCentered,
    noStyles: noStyles
  });
  var modalStyleProps = (0, _styles["default"])({
    scrollBehavior: scrollBehavior,
    isCentered: isCentered,
    noStyles: noStyles
  });
  return __jsx(_Box.Box, (0, _extends2["default"])({
    pos: "fixed",
    d: "flex" // alignItems="center"
    ,
    left: "0",
    top: "0",
    w: "100%",
    h: "100%",
    zIndex: zIndex || 'modal',
    onClick: function onClick(event) {
      event.stopPropagation();

      if (closeOnOverlayClick) {
        onClose(event, 'clickedOverlay');
      }
    },
    onKeyDown: function onKeyDown(event) {
      if (event.key === 'Escape') {
        event.stopPropagation();

        if (closeOnEsc) {
          onClose(event, 'pressedEscape');
        }
      }
    }
  }, modalWrapperStyleProps), __jsx(_Card.Card, (0, _extends2["default"])({
    d: "flex",
    ref: _contentRef,
    as: "section",
    role: "dialog",
    "aria-modal": "true",
    tabIndex: -1,
    maxWidth: size,
    id: contentId
  }, addAriaDescribedby && {
    'aria-describedby': bodyId
  }, addAriaLabelledby && {
    'aria-labelledby': headerId
  }, {
    zIndex: zIndex || 'modal',
    onClick: (0, _wrapEvent.wrapEvent)(onClick, function (event) {
      return event.stopPropagation();
    })
  }, modalStyleProps, props), children));
});

exports.ModalContent = ModalContent;
var ModalHeader = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useModalContext2 = useModalContext(),
      headerId = _useModalContext2.headerId;

  return __jsx(_Flex.Flex, (0, _extends2["default"])({
    justify: "space-between",
    align: "center",
    ref: ref,
    px: "spacing-lg",
    py: "spacing",
    id: headerId,
    as: "header",
    position: "relative"
  }, props));
});
exports.ModalHeader = ModalHeader;
var ModalFooter = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  return __jsx(_Flex.Flex, (0, _extends2["default"])({
    justify: "flex-end",
    ref: ref,
    px: "spacing-lg",
    py: "spacing",
    as: "footer"
  }, props));
});
exports.ModalFooter = ModalFooter;
var ModalBody = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useModalContext3 = useModalContext(),
      bodyId = _useModalContext3.bodyId,
      scrollBehavior = _useModalContext3.scrollBehavior;

  var style = {};

  if (scrollBehavior === 'inside') {
    style = {
      overflowY: 'auto'
    };
  }

  return __jsx(_Box.Box, (0, _extends2["default"])({
    ref: ref,
    id: bodyId,
    px: "spacing-lg",
    py: "spacing",
    flex: "1",
    color: "bodyText"
  }, style, props));
});
exports.ModalBody = ModalBody;
var ModalCloseButton = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _useModalContext4 = useModalContext(),
      onClose = _useModalContext4.onClose;

  return __jsx(_CloseButton.CloseButton, (0, _extends2["default"])({
    ref: ref,
    onClick: onClose,
    position: "absolute",
    top: "12px",
    right: "24px"
  }, props));
});
exports.ModalCloseButton = ModalCloseButton;

var ModalTransition = function ModalTransition(_ref4) {
  var isOpen = _ref4.isOpen,
      _ref4$duration = _ref4.duration,
      duration = _ref4$duration === void 0 ? 150 : _ref4$duration,
      children = _ref4.children;
  return __jsx(_reactSpring.Transition, {
    items: isOpen,
    from: {
      opacity: 0,
      y: 10
    },
    enter: {
      opacity: 1,
      y: 0
    },
    leave: {
      opacity: 0,
      y: -10
    },
    config: {
      duration: duration
    }
  }, function (isTransOpen) {
    return isTransOpen && function (styles) {
      return children(styles);
    };
  });
};

exports.ModalTransition = ModalTransition;
//# sourceMappingURL=Modal.js.map