"use strict";

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); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "useModal", {
  enumerable: true,
  get: function get() {
    return _useModal.useModal;
  }
});
exports.Modal = exports.ModalRemove = exports.ModalText = exports.ModalContent = exports.ModalHeader = exports.ModalBackground = void 0;

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

var _reactDom = _interopRequireDefault(require("react-dom"));

var _styledComponents = _interopRequireDefault(require("styled-components"));

var _behaviors = require("../../behaviors");

var _patchworkThemeProvider = require("../../../themes/patchwork-theme-provider");

var _primitives = require("../../../primitives");

var _typography = require("../../typography");

var _icon = require("../../icon");

var _useFocusTrap = require("./use-focus-trap");

var _modal = require("./modal.css-rules");

var _useModal = require("./use-modal");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var ModalBackground = (0, _styledComponents["default"])(_primitives.Box).withConfig({
  displayName: "ModalBackground",
  componentId: "sc-10e2l11-0"
})(["display:block;position:fixed;z-index:1;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:", ";"], _modal.getBackgroundColor);
exports.ModalBackground = ModalBackground;
var ModalHeader = (0, _styledComponents["default"])(_primitives.Box).withConfig({
  displayName: "ModalHeader",
  componentId: "sc-10e2l11-1"
})(["height:", ";position:relative;text-align:center;"], _modal.getModalHeaderPadding);
exports.ModalHeader = ModalHeader;
var ModalContent = (0, _styledComponents["default"])(_primitives.Box).withConfig({
  displayName: "ModalContent",
  componentId: "sc-10e2l11-2"
})(["max-width:", ";background-color:", ";box-shadow:0 5px 15px 0 ", ";border:solid 1px ", ";border-radius:15px;z-index:2;margin:15vh auto;width:80%;&:focus{outline:none;}"], _modal.getModalWidth, _modal.getContentBackground, _modal.getContentBoxShadowColor, _modal.getBorderColor);
exports.ModalContent = ModalContent;
var ModalText = (0, _styledComponents["default"])(_typography.Head5).withConfig({
  displayName: "ModalText",
  componentId: "sc-10e2l11-3"
})(["top:0;padding-top:30px;padding-left:42px;padding-right:42px;position:absolute;line-height:1;"]);
exports.ModalText = ModalText;
var ModalRemove = (0, _styledComponents["default"])(_behaviors.UnstyledButton).withConfig({
  displayName: "ModalRemove",
  componentId: "sc-10e2l11-4"
})(["line-height:14px;padding:30px;position:absolute;right:0;top:0;"]);
exports.ModalRemove = ModalRemove;

function getBody() {
  var documentElement = typeof document !== 'undefined' ? document : undefined;
  return documentElement ? documentElement.body : null;
}

function lockBodyOverflow() {
  var body = getBody();

  if (body !== null && body.dataset.initialOverflow === undefined) {
    body.dataset.initialOverflow = body.style.overflow;
    body.style.overflow = 'hidden';
  }
}

function unlockBodyOverflow() {
  var body = getBody();

  if (body !== null && body.dataset.initialOverflow !== undefined) {
    body.style.overflow = body.dataset.initialOverflow;
    delete body.dataset.initialOverflow;
  }
}

var Modal = function Modal(_ref) {
  var show = _ref.show,
      _ref$persistent = _ref.persistent,
      persistent = _ref$persistent === void 0 ? false : _ref$persistent,
      onClose = _ref.onClose,
      _ref$size = _ref.size,
      size = _ref$size === void 0 ? 'lg' : _ref$size,
      children = _ref.children,
      _ref$className = _ref.className,
      className = _ref$className === void 0 ? '' : _ref$className,
      spacing = _ref.spacing,
      headerText = _ref.headerText,
      _ref$hideHeader = _ref.hideHeader,
      hideHeader = _ref$hideHeader === void 0 ? false : _ref$hideHeader,
      refToRestoreFocus = _ref.refToRestoreFocus,
      stacked = _ref.stacked,
      align = _ref.align,
      justify = _ref.justify,
      wrap = _ref.wrap,
      dataQa = _ref['data-qa'],
      dataCy = _ref['data-cy'],
      id = _ref.id,
      props = _objectWithoutProperties(_ref, ["show", "persistent", "onClose", "size", "children", "className", "spacing", "headerText", "hideHeader", "refToRestoreFocus", "stacked", "align", "justify", "wrap", "data-qa", "data-cy", "id"]);

  var modalRef = (0, _useFocusTrap.useFocusTrap)({
    show: show,
    refToRestoreFocus: refToRestoreFocus
  });
  var body = getBody();
  (0, _react.useEffect)(function () {
    if (body) {
      return function () {
        unlockBodyOverflow();
      };
    }
  }, [body]);
  var handleBackgroundClick = (0, _react.useCallback)(function (event) {
    event.preventDefault();

    if (!persistent) {
      onClose();
    }
  }, [onClose, persistent]);
  var handleContentClick = (0, _react.useCallback)(function (event) {
    event.stopPropagation();
  }, []);
  var handleCloseClick = (0, _react.useCallback)(function (event) {
    event.stopPropagation();
    onClose();
  }, [onClose]);
  var handleKeyPress = (0, _react.useCallback)(function (event) {
    if (show && !persistent && event.code === 'Escape') {
      onClose();
    }
  }, [onClose, show, persistent]);
  (0, _react.useEffect)(function () {
    if (show && !persistent) {
      window.addEventListener('keydown', handleKeyPress);
    }

    return function () {
      window.removeEventListener('keydown', handleKeyPress);
    };
  }, [handleKeyPress, show, persistent]);
  if (body == null) return null;

  if (show) {
    lockBodyOverflow();
  } else {
    unlockBodyOverflow();
  }

  return show && /*#__PURE__*/_reactDom["default"].createPortal( /*#__PURE__*/_react["default"].createElement(_patchworkThemeProvider.Resets, {
    face: "sans"
  }, /*#__PURE__*/_react["default"].createElement(ModalBackground, {
    onClick: handleBackgroundClick
  }, /*#__PURE__*/_react["default"].createElement(ModalContent, _extends({
    onClick: handleContentClick,
    size: size,
    className: className,
    ref: modalRef,
    role: "dialog",
    "aria-modal": "true",
    "data-cy": dataCy,
    "data-qa": dataQa,
    id: id
  }, props), !hideHeader && /*#__PURE__*/_react["default"].createElement(ModalHeader, {
    stacked: "row",
    justify: "center",
    align: "center",
    size: size
  }, headerText != null && /*#__PURE__*/_react["default"].createElement(ModalText, {
    fontSize: "f0"
  }, headerText), !persistent && /*#__PURE__*/_react["default"].createElement(ModalRemove, {
    insetFocus: true,
    onClick: handleCloseClick,
    "aria-label": "close"
  }, /*#__PURE__*/_react["default"].createElement(_icon.Remove, {
    size: 12,
    color: "greyscale-dark"
  }))), /*#__PURE__*/_react["default"].createElement(_primitives.Box, _extends({
    spacing: spacing || ['ph6', 'pb4']
  }, {
    stacked: stacked,
    align: align,
    justify: justify,
    wrap: wrap
  }), children)))), body);
};

exports.Modal = Modal;