"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
});
exports.OuiFlyout = exports.PADDING_SIZES = exports.SIZES = exports.SIDES = exports.TYPES = void 0;

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

var _classnames = _interopRequireDefault(require("classnames"));

var _services = require("../../services");

var _common = require("../common");

var _focus_trap = require("../focus_trap");

var _overlay_mask = require("../overlay_mask");

var _button = require("../button");

var _i18n = require("../i18n");

var _resize_observer = require("../observer/resize_observer");

var _outside_click_detector = require("../outside_click_detector");

var _portal = require("../portal");

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

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(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

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; } /*
                                                                                                                                                                                                                                                                                                                     * SPDX-License-Identifier: Apache-2.0
                                                                                                                                                                                                                                                                                                                     *
                                                                                                                                                                                                                                                                                                                     * The OpenSearch Contributors require contributions made to
                                                                                                                                                                                                                                                                                                                     * this file be licensed under the Apache-2.0 license or a
                                                                                                                                                                                                                                                                                                                     * compatible open source license.
                                                                                                                                                                                                                                                                                                                     *
                                                                                                                                                                                                                                                                                                                     * Modifications Copyright OpenSearch Contributors. See
                                                                                                                                                                                                                                                                                                                     * GitHub history for details.
                                                                                                                                                                                                                                                                                                                     */ /*
                                                                                                                                                                                                                                                                                                                         * Licensed to Elasticsearch B.V. under one or more contributor
                                                                                                                                                                                                                                                                                                                         * license agreements. See the NOTICE file distributed with
                                                                                                                                                                                                                                                                                                                         * this work for additional information regarding copyright
                                                                                                                                                                                                                                                                                                                         * ownership. Elasticsearch B.V. licenses this file to you under
                                                                                                                                                                                                                                                                                                                         * the Apache License, Version 2.0 (the "License"); you may
                                                                                                                                                                                                                                                                                                                         * not use this file except in compliance with the License.
                                                                                                                                                                                                                                                                                                                         * You may obtain a copy of the License at
                                                                                                                                                                                                                                                                                                                         *
                                                                                                                                                                                                                                                                                                                         *    http://www.apache.org/licenses/LICENSE-2.0
                                                                                                                                                                                                                                                                                                                         *
                                                                                                                                                                                                                                                                                                                         * Unless required by applicable law or agreed to in writing,
                                                                                                                                                                                                                                                                                                                         * software distributed under the License is distributed on an
                                                                                                                                                                                                                                                                                                                         * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
                                                                                                                                                                                                                                                                                                                         * KIND, either express or implied.  See the License for the
                                                                                                                                                                                                                                                                                                                         * specific language governing permissions and limitations
                                                                                                                                                                                                                                                                                                                         * under the License.
                                                                                                                                                                                                                                                                                                                         */

var typeToClassNameMap = {
  push: 'ouiFlyout--push',
  overlay: null
};
var TYPES = (0, _common.keysOf)(typeToClassNameMap);
exports.TYPES = TYPES;
var sideToClassNameMap = {
  left: 'ouiFlyout--left',
  right: null
};
var SIDES = (0, _common.keysOf)(sideToClassNameMap);
exports.SIDES = SIDES;
var sizeToClassNameMap = {
  s: 'ouiFlyout--small',
  m: 'ouiFlyout--medium',
  l: 'ouiFlyout--large'
};
var SIZES = (0, _common.keysOf)(sizeToClassNameMap);
exports.SIZES = SIZES;

/**
 * Custom type checker for named flyout sizes since the prop
 * `size` can also be CSSProperties['width'] (string | number)
 */
function isOuiFlyoutSizeNamed(value) {
  return SIZES.includes(value);
}

var paddingSizeToClassNameMap = {
  none: 'ouiFlyout--paddingNone',
  s: 'ouiFlyout--paddingSmall',
  m: 'ouiFlyout--paddingMedium',
  l: 'ouiFlyout--paddingLarge'
};
var PADDING_SIZES = (0, _common.keysOf)(paddingSizeToClassNameMap); // Using ReactHTML rather than JSX.IntrinsicElements here because it does not include
// SVG element types which cause errors because they do not have all the attributes needed.

exports.PADDING_SIZES = PADDING_SIZES;
var OuiFlyout = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
  var className = _ref.className,
      children = _ref.children,
      _ref$as = _ref.as,
      Element = _ref$as === void 0 ? 'div' : _ref$as,
      _ref$hideCloseButton = _ref.hideCloseButton,
      hideCloseButton = _ref$hideCloseButton === void 0 ? false : _ref$hideCloseButton,
      closeButtonProps = _ref.closeButtonProps,
      closeButtonAriaLabel = _ref.closeButtonAriaLabel,
      _ref$closeButtonPosit = _ref.closeButtonPosition,
      closeButtonPosition = _ref$closeButtonPosit === void 0 ? 'inside' : _ref$closeButtonPosit,
      onClose = _ref.onClose,
      _ref$ownFocus = _ref.ownFocus,
      ownFocus = _ref$ownFocus === void 0 ? true : _ref$ownFocus,
      _ref$side = _ref.side,
      side = _ref$side === void 0 ? 'right' : _ref$side,
      _ref$size = _ref.size,
      size = _ref$size === void 0 ? 'm' : _ref$size,
      _ref$paddingSize = _ref.paddingSize,
      paddingSize = _ref$paddingSize === void 0 ? 'l' : _ref$paddingSize,
      _ref$maxWidth = _ref.maxWidth,
      maxWidth = _ref$maxWidth === void 0 ? false : _ref$maxWidth,
      style = _ref.style,
      maskProps = _ref.maskProps,
      _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'overlay' : _ref$type,
      _ref$outsideClickClos = _ref.outsideClickCloses,
      outsideClickCloses = _ref$outsideClickClos === void 0 ? false : _ref$outsideClickClos,
      _ref$role = _ref.role,
      role = _ref$role === void 0 ? 'dialog' : _ref$role,
      _ref$pushMinBreakpoin = _ref.pushMinBreakpoint,
      pushMinBreakpoint = _ref$pushMinBreakpoin === void 0 ? 'l' : _ref$pushMinBreakpoin,
      rest = _objectWithoutProperties(_ref, ["className", "children", "as", "hideCloseButton", "closeButtonProps", "closeButtonAriaLabel", "closeButtonPosition", "onClose", "ownFocus", "side", "size", "paddingSize", "maxWidth", "style", "maskProps", "type", "outsideClickCloses", "role", "pushMinBreakpoint"]);

  /**
   * Setting the initial state of pushed based on the `type` prop
   * and if the current window size is large enough (larger than `pushMinBreakpoint`)
   */
  var _useState = (0, _react.useState)((0, _services.isWithinMinBreakpoint)(typeof window === 'undefined' ? 0 : window.innerWidth, pushMinBreakpoint)),
      _useState2 = _slicedToArray(_useState, 2),
      windowIsLargeEnoughToPush = _useState2[0],
      setWindowIsLargeEnoughToPush = _useState2[1];

  var isPushed = type === 'push' && windowIsLargeEnoughToPush;
  /**
   * Watcher added to the window to maintain `isPushed` state depending on
   * the window size compared to the `pushBreakpoint`
   */

  var functionToCallOnWindowResize = (0, _services.throttle)(function () {
    if ((0, _services.isWithinMinBreakpoint)(window.innerWidth, pushMinBreakpoint)) {
      setWindowIsLargeEnoughToPush(true);
    } else {
      setWindowIsLargeEnoughToPush(false);
    } // reacts every 50ms to resize changes and always gets the final update

  }, 50);
  /**
   * Setting up the refs on the actual flyout element in order to
   * accommodate for the `isPushed` state by adding padding to the body equal to the width of the element
   */

  var _useState3 = (0, _react.useState)(null),
      _useState4 = _slicedToArray(_useState3, 2),
      resizeRef = _useState4[0],
      setResizeRef = _useState4[1];

  var setRef = (0, _services.useCombinedRefs)([setResizeRef, ref]); // TODO: Allow this hooke to be conditional

  var dimensions = (0, _resize_observer.useResizeObserver)(resizeRef);
  (0, _react.useEffect)(function () {
    // This class doesn't actually do anything by OUI, but is nice to add for consumers (JIC)
    document.body.classList.add('ouiBody--hasFlyout');
    /**
     * Accomodate for the `isPushed` state by adding padding to the body equal to the width of the element
     */

    if (type === 'push') {
      // Only add the event listener if we'll need to accommodate with padding
      window.addEventListener('resize', functionToCallOnWindowResize);

      if (isPushed) {
        if (side === 'right') {
          document.body.style.paddingRight = "".concat(dimensions.width, "px");
        } else if (side === 'left') {
          document.body.style.paddingLeft = "".concat(dimensions.width, "px");
        }
      }
    }

    return function () {
      document.body.classList.remove('ouiBody--hasFlyout');

      if (type === 'push') {
        window.removeEventListener('resize', functionToCallOnWindowResize);

        if (side === 'right') {
          document.body.style.paddingRight = '';
        } else if (side === 'left') {
          document.body.style.paddingLeft = '';
        }
      }
    };
  }, [type, side, dimensions, isPushed, functionToCallOnWindowResize]);
  /**
   * ESC key closes flyout (always?)
   */

  var onKeyDown = function onKeyDown(event) {
    if (!isPushed && event.key === _services.keys.ESCAPE) {
      event.preventDefault();
      onClose();
    }
  };

  var newStyle;
  var widthClassName;
  var sizeClassName; // Setting max-width

  if (maxWidth === true) {
    widthClassName = 'ouiFlyout--maxWidth-default';
  } else if (maxWidth !== false) {
    var value = typeof maxWidth === 'number' ? "".concat(maxWidth, "px") : maxWidth;
    newStyle = _objectSpread(_objectSpread({}, style), {}, {
      maxWidth: value
    });
  } // Setting size


  if (isOuiFlyoutSizeNamed(size)) {
    sizeClassName = sizeToClassNameMap[size];
  } else if (newStyle) {
    newStyle.width = size;
  } else {
    newStyle = _objectSpread(_objectSpread({}, style), {}, {
      width: size
    });
  }

  var classes = (0, _classnames.default)('ouiFlyout', typeToClassNameMap[type], sideToClassNameMap[side], sizeClassName, paddingSizeToClassNameMap[paddingSize], widthClassName, className);
  var closeButton;

  if (onClose && !hideCloseButton) {
    var closeButtonClasses = (0, _classnames.default)('ouiFlyout__closeButton', "ouiFlyout__closeButton--".concat(closeButtonPosition), closeButtonProps === null || closeButtonProps === void 0 ? void 0 : closeButtonProps.className);
    closeButton = /*#__PURE__*/_react.default.createElement(_i18n.OuiI18n, {
      token: "ouiFlyout.closeAriaLabel",
      default: "Close this dialog"
    }, function (closeAriaLabel) {
      return /*#__PURE__*/_react.default.createElement(_button.OuiButtonIcon, _extends({
        display: closeButtonPosition === 'outside' ? 'fill' : 'empty',
        iconType: "cross",
        color: "text",
        "aria-label": closeButtonAriaLabel || closeAriaLabel,
        "data-test-subj": "ouiFlyoutCloseButton"
      }, closeButtonProps, {
        className: closeButtonClasses,
        onClick: function onClick(e) {
          onClose();
          (closeButtonProps === null || closeButtonProps === void 0 ? void 0 : closeButtonProps.onClick) && closeButtonProps.onClick(e);
        }
      }));
    });
  }

  var flyoutContent =
  /*#__PURE__*/
  // @ts-expect-error JSX element without construct
  _react.default.createElement(Element, _extends({}, rest, {
    role: role,
    className: classes,
    tabIndex: -1,
    style: newStyle || style,
    ref: setRef
  }), closeButton, children);
  /*
   * Trap focus even when `ownFocus={false}`, otherwise closing
   * the flyout won't return focus to the originating button.
   *
   * Set `clickOutsideDisables={true}` when `ownFocus={false}`
   * to allow non-keyboard users the ability to interact with
   * elements outside the flyout.
   */


  var flyout = /*#__PURE__*/_react.default.createElement(_focus_trap.OuiFocusTrap, {
    disabled: isPushed,
    clickOutsideDisables: !ownFocus
  }, /*#__PURE__*/_react.default.createElement(_outside_click_detector.OuiOutsideClickDetector, {
    isDisabled: isPushed || !outsideClickCloses,
    onOutsideClick: function onOutsideClick() {
      return onClose();
    }
  }, flyoutContent)); // If ownFocus is set, wrap with an overlay and allow the user to click it to close it.


  if (ownFocus && !isPushed) {
    flyout = /*#__PURE__*/_react.default.createElement(_overlay_mask.OuiOverlayMask, _extends({
      onClick: onClose,
      headerZindexLocation: "below"
    }, maskProps), flyout);
  } else if (!isPushed) {
    // Otherwise still wrap within an OuiPortal so it appends (unless it is the push style)
    flyout = /*#__PURE__*/_react.default.createElement(_portal.OuiPortal, null, flyout);
  }

  return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_services.OuiWindowEvent, {
    event: "keydown",
    handler: onKeyDown
  }), flyout);
});
exports.OuiFlyout = OuiFlyout;
OuiFlyout.displayName = 'OuiFlyout';
/* OUI -> EUI Aliases: Build-Time */