var _excluded = ["as", "className", "children", "closeOnClickOutside", "disableContentStyle", "footer", "onClose", "open", "title", "closeButtonTitle", "onExitAnimationComplete", "onAnimationComplete", "disableInitialAnimation", "preventOnClickOutsideDataAttributes"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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; }
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useUIDSeed } from 'react-uid';
import FocusLock from 'react-focus-lock';
import { RemoveScroll } from 'react-remove-scroll';
import { AnimatePresence, useDragControls } from 'framer-motion';
import { fromKebabToCamelCase, isBoolean, isElement } from '../../common/utils';
import { useOnClickOutside } from '../../common/Hooks';
import { Icon, Portal, Typography, useKeyPress, useMedia } from '../..';
import { CloseButton, Container, Content, DragArea, Footer, H2, TitleWrapper } from './Drawer.styles';
var displayName = 'Drawer';
var PREVENT_CLICK_OUTSIDE_ATTRIBUTE = 'drawerPreventClickOutside';
var animationProps = {
  initial: {
    opacity: 0,
    x: '100%'
  },
  animate: {
    opacity: 1,
    x: '0%'
  },
  exit: {
    opacity: 0,
    x: '100%'
  },
  transition: {
    ease: 'easeInOut',
    duration: 0.2
  }
};
var noInitialAnimationProps = {
  initial: {
    opacity: 1,
    x: '0%'
  }
};
export var components = {
  CloseButton: CloseButton,
  Container: Container,
  Content: Content,
  Footer: Footer,
  TitleWrapper: TitleWrapper
};
var Title = function Title(_ref) {
  var title = _ref.title,
    uid = _ref.uid;
  var isDesktop = useMedia(function (t) {
    return t.media.greaterThan(t.breakpoints.sm);
  });
  return React.createElement("span", {
    id: uid
  }, isElement(title) ? title : React.createElement(Typography, {
    as: H2,
    type: isDesktop ? 'title3' : 'title1'
  }, title));
};
export var Drawer = React.forwardRef(function (_ref2, ref) {
  var as = _ref2.as,
    className = _ref2.className,
    children = _ref2.children,
    _ref2$closeOnClickOut = _ref2.closeOnClickOutside,
    closeOnClickOutside = _ref2$closeOnClickOut === void 0 ? true : _ref2$closeOnClickOut,
    disableContentStyle = _ref2.disableContentStyle,
    footer = _ref2.footer,
    onClose = _ref2.onClose,
    isOpenExternal = _ref2.open,
    title = _ref2.title,
    closeButtonTitle = _ref2.closeButtonTitle,
    onExitAnimationComplete = _ref2.onExitAnimationComplete,
    onAnimationComplete = _ref2.onAnimationComplete,
    disableInitialAnimation = _ref2.disableInitialAnimation,
    preventOnClickOutsideDataAttributes = _ref2.preventOnClickOutsideDataAttributes,
    rest = _objectWithoutProperties(_ref2, _excluded);
  var isControlled = isBoolean(isOpenExternal);
  var escapePress = useKeyPress('Escape');
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    isOpenInternal = _useState2[0],
    setIsOpenInternal = _useState2[1];
  var isOpen = isControlled ? isOpenExternal : isOpenInternal;
  var internalDrawerRef = useRef(null);
  var drawerRef = ref || internalDrawerRef;
  var isDesktop = useMedia(function (t) {
    return t.media.greaterThan(t.breakpoints.sm);
  }) || false;
  var seed = useUIDSeed();
  var uid = seed(displayName);
  var dragControls = useDragControls();
  var startDrag = useCallback(function (event) {
    dragControls.start(event, {
      snapToCursor: false
    });
  }, [dragControls]);
  var handleClose = useCallback(function () {
    setIsOpenInternal(false);
    if (onClose) {
      onClose();
    }
  }, [onClose]);
  var handleDragEnd = useCallback(function (event, info) {
    var _info$offset;
    if ((info === null || info === void 0 || (_info$offset = info.offset) === null || _info$offset === void 0 ? void 0 : _info$offset.x) > 100) {
      handleClose();
    }
  }, [handleClose]);
  useOnClickOutside(drawerRef, function (e) {
    if (!closeOnClickOutside) return;
    var preventingDataAttributes = [PREVENT_CLICK_OUTSIDE_ATTRIBUTE].concat(_toConsumableArray(preventOnClickOutsideDataAttributes || []));
    var preventOnClickOutside = e instanceof Event && e.composedPath().some(function (target) {
      if (!(target instanceof HTMLElement)) return false;
      return preventingDataAttributes.some(function (dataAttribute) {
        var _target$dataset;
        var formattedDataAttribute = fromKebabToCamelCase(dataAttribute.replace('data-', ''));
        return (_target$dataset = target.dataset) === null || _target$dataset === void 0 ? void 0 : _target$dataset[formattedDataAttribute];
      });
    });
    if (!preventOnClickOutside) handleClose();
  });
  useEffect(function () {
    if (isOpen && escapePress) {
      handleClose();
    }
  }, [escapePress, handleClose, isOpen]);
  return React.createElement(AnimatePresence, {
    onExitComplete: onExitAnimationComplete
  }, isOpen ? React.createElement(Portal, null, React.createElement(FocusLock, {
    disabled: isDesktop
  }, React.createElement(RemoveScroll, {
    enabled: !isDesktop
  }, React.createElement(Container, _extends({
    as: as,
    className: className,
    "aria-labelledby": uid
  }, animationProps, disableInitialAnimation ? noInitialAnimationProps : {}, {
    ref: drawerRef,
    dragControls: dragControls,
    dragListener: false,
    drag: "x",
    onDragEnd: handleDragEnd,
    dragConstraints: {
      right: 0,
      left: 0
    },
    onAnimationComplete: onAnimationComplete
  }, rest), React.createElement(TitleWrapper, {
    onTouchStart: startDrag
  }, title && React.createElement(Title, {
    title: title,
    uid: uid
  }), React.createElement(CloseButton, {
    onClick: handleClose
  }, React.createElement(Icon.Cross16, {
    title: closeButtonTitle
  }))), React.createElement(DragArea, {
    onTouchStart: startDrag
  }), disableContentStyle ? children : React.createElement(Content, null, children), footer && React.createElement(Footer, null, footer))))) : null);
});
Drawer.components = components;
Drawer.displayName = displayName;