"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.EuiResizableContainer = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _classnames = _interopRequireDefault(require("classnames"));
var _services = require("../../services");
var _resize_observer = require("../observer/resize_observer");
var _context = require("./context");
var _resizable_button = require("./resizable_button");
var _resizable_panel = require("./resizable_panel");
var _helpers = require("./helpers");
var _resizable_container = require("./resizable_container.styles");
var _react2 = require("@emotion/react");
var _excluded = ["direction", "children", "className", "onPanelWidthChange", "onToggleCollapsed", "onResizeStart", "onResizeEnd"];
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
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; }
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
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) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) 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; }
var initialState = {
  isDragging: false,
  currentResizerPos: -1,
  prevPanelId: null,
  nextPanelId: null,
  containerSize: 1,
  panels: {},
  resizers: {}
};
var EuiResizableContainer = function EuiResizableContainer(_ref) {
  var _ref$direction = _ref.direction,
    direction = _ref$direction === void 0 ? 'horizontal' : _ref$direction,
    children = _ref.children,
    className = _ref.className,
    onPanelWidthChange = _ref.onPanelWidthChange,
    onToggleCollapsed = _ref.onToggleCollapsed,
    onResizeStart = _ref.onResizeStart,
    onResizeEnd = _ref.onResizeEnd,
    rest = _objectWithoutProperties(_ref, _excluded);
  var containerRef = (0, _react.useRef)(null);
  var isHorizontal = direction === 'horizontal';
  var classes = (0, _classnames.default)('euiResizableContainer', className);
  var styles = (0, _resizable_container.euiResizableContainerStyles)();
  var cssStyles = [styles.euiResizableContainer, styles[direction]];
  var _useContainerCallback = (0, _helpers.useContainerCallbacks)({
      initialState: _objectSpread(_objectSpread({}, initialState), {}, {
        isHorizontal: isHorizontal
      }),
      containerRef: containerRef,
      onPanelWidthChange: onPanelWidthChange
    }),
    _useContainerCallback2 = _slicedToArray(_useContainerCallback, 2),
    actions = _useContainerCallback2[0],
    reducerState = _useContainerCallback2[1];
  var containerSize = (0, _resize_observer.useResizeObserver)(containerRef.current, isHorizontal ? 'width' : 'height');
  var initialize = (0, _react.useCallback)(function () {
    actions.initContainer(isHorizontal);
  }, [actions, isHorizontal]);
  (0, _react.useEffect)(function () {
    if (containerSize.width > 0 && containerSize.height > 0) {
      initialize();
    }
  }, [initialize, containerSize]);
  var resizeContext = (0, _react.useRef)({});
  var resizeEnd = (0, _react.useCallback)(function () {
    onResizeEnd === null || onResizeEnd === void 0 ? void 0 : onResizeEnd();
    resizeContext.current = {};
  }, [onResizeEnd]);
  var resizeStart = (0, _react.useCallback)(function (trigger, keyMoveDirection) {
    // If another resize starts while the previous one is still in progress
    // (e.g. user presses opposite arrow to change direction while the first
    // is still held down, or user presses an arrow while dragging with the
    // mouse), we want to signal the end of the previous resize first.
    if (resizeContext.current.trigger) {
      resizeEnd();
    }
    onResizeStart === null || onResizeStart === void 0 ? void 0 : onResizeStart(trigger);
    resizeContext.current = {
      trigger: trigger,
      keyMoveDirection: keyMoveDirection
    };
  }, [onResizeStart, resizeEnd]);
  var onMouseDown = (0, _react.useCallback)(function (event) {
    var currentTarget = event.currentTarget;
    var prevPanel = currentTarget.previousElementSibling;
    var nextPanel = currentTarget.nextElementSibling;
    if (!prevPanel || !nextPanel) return;
    var prevPanelId = prevPanel.id;
    var nextPanelId = nextPanel.id;
    var position = (0, _helpers.getPosition)(event, isHorizontal);
    resizeStart('pointer');
    actions.dragStart({
      position: position,
      prevPanelId: prevPanelId,
      nextPanelId: nextPanelId
    });
  }, [actions, isHorizontal, resizeStart]);
  var onMouseMove = (0, _react.useCallback)(function (event) {
    if (!reducerState.prevPanelId || !reducerState.nextPanelId || !reducerState.isDragging) return;
    var position = (0, _helpers.getPosition)(event, isHorizontal);
    actions.dragMove({
      position: position,
      prevPanelId: reducerState.prevPanelId,
      nextPanelId: reducerState.nextPanelId
    });
  }, [actions, isHorizontal, reducerState.prevPanelId, reducerState.nextPanelId, reducerState.isDragging]);
  var getKeyMoveDirection = (0, _react.useCallback)(function (key) {
    var direction = null;
    if (isHorizontal && key === _services.keys.ARROW_LEFT || !isHorizontal && key === _services.keys.ARROW_UP) {
      direction = 'backward';
    } else if (isHorizontal && key === _services.keys.ARROW_RIGHT || !isHorizontal && key === _services.keys.ARROW_DOWN) {
      direction = 'forward';
    }
    return direction;
  }, [isHorizontal]);
  var onKeyDown = (0, _react.useCallback)(function (event) {
    var key = event.key,
      currentTarget = event.currentTarget;
    var direction = getKeyMoveDirection(key);
    var prevPanelId = currentTarget.previousElementSibling.id;
    var nextPanelId = currentTarget.nextElementSibling.id;
    if (direction && prevPanelId && nextPanelId) {
      if (!event.repeat) {
        resizeStart('key', direction);
      }
      event.preventDefault();
      actions.keyMove({
        direction: direction,
        prevPanelId: prevPanelId,
        nextPanelId: nextPanelId
      });
    }
  }, [actions, getKeyMoveDirection, resizeStart]);
  var onKeyUp = (0, _react.useCallback)(function (_ref2) {
    var key = _ref2.key;
    // We only want to signal the end of a resize if the key that was released
    // is the same as the one that started the resize. This prevents the end
    // of a resize if the user presses one arrow key, then presses the opposite
    // arrow key to change direction, then releases the first arrow key.
    if (resizeContext.current.trigger === 'key' && resizeContext.current.keyMoveDirection === getKeyMoveDirection(key)) {
      resizeEnd();
    }
  }, [getKeyMoveDirection, resizeEnd]);
  var onMouseUp = (0, _react.useCallback)(function () {
    if (resizeContext.current.trigger === 'pointer') {
      resizeEnd();
    }
    actions.reset();
  }, [actions, resizeEnd]);
  var onBlur = (0, _react.useCallback)(function () {
    if (resizeContext.current.trigger === 'key') {
      resizeEnd();
    }
    actions.resizerBlur();
  }, [actions, resizeEnd]);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  var EuiResizableButton = (0, _react.useCallback)((0, _resizable_button.euiResizableButtonWithControls)({
    onKeyDown: onKeyDown,
    onKeyUp: onKeyUp,
    onMouseDown: onMouseDown,
    onTouchStart: onMouseDown,
    onFocus: actions.resizerFocus,
    onBlur: onBlur,
    isHorizontal: isHorizontal,
    registration: {
      register: actions.registerResizer,
      deregister: actions.deregisterResizer
    }
  }), [actions, isHorizontal]);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  var EuiResizablePanel = (0, _react.useCallback)((0, _resizable_panel.euiResizablePanelWithControls)({
    isHorizontal: isHorizontal,
    registration: {
      register: actions.registerPanel,
      deregister: actions.deregisterPanel
    },
    onToggleCollapsed: onToggleCollapsed,
    onToggleCollapsedInternal: actions.togglePanel
  }), [actions, isHorizontal]);
  var render = function render() {
    var DEFAULT = 'custom';
    var content = children(EuiResizablePanel, EuiResizableButton, {
      togglePanel: actions.togglePanel
    });
    var modes = /*#__PURE__*/_react.default.isValidElement(content) ? content.props.children.map(function (el) {
      return (0, _resizable_panel.getModeType)(el.props.mode) || DEFAULT;
    }) : null;
    if (modes && (['collapsible', 'main'].every(function (i) {
      return modes.includes(i);
    }) || modes.every(function (i) {
      return i === DEFAULT;
    }))) {
      return content;
    } else {
      throw new Error('Both `collapsible` and `main` mode panels are required.');
    }
  };
  return (0, _react2.jsx)(_context.EuiResizableContainerContextProvider, {
    registry: {
      panels: reducerState.panels,
      resizers: reducerState.resizers
    }
  }, (0, _react2.jsx)("div", _extends({
    css: cssStyles,
    className: classes,
    ref: containerRef,
    onMouseMove: reducerState.isDragging ? onMouseMove : undefined,
    onMouseUp: onMouseUp,
    onMouseLeave: onMouseUp,
    onTouchMove: onMouseMove,
    onTouchEnd: onMouseUp
  }, rest), render()));
};
exports.EuiResizableContainer = EuiResizableContainer;
EuiResizableContainer.propTypes = {
  /**
     * Specify the container direction
     */
  direction: _propTypes.default.oneOf(["vertical", "horizontal"]),
  /**
     * Pure function which accepts Panel and Resizer components in arguments
     * and returns a component tree
     */
  children: _propTypes.default.func.isRequired,
  /**
     * Pure function which accepts an object where keys are IDs of panels, which sizes were changed,
     * and values are actual sizes in percents
     */
  onPanelWidthChange: _propTypes.default.func,
  onToggleCollapsed: _propTypes.default.func,
  /**
     * Called when resizing starts
     */
  onResizeStart: _propTypes.default.func,
  /**
     * Called when resizing ends
     */
  onResizeEnd: _propTypes.default.func,
  style: _propTypes.default.any,
  className: _propTypes.default.string,
  "aria-label": _propTypes.default.string,
  "data-test-subj": _propTypes.default.string,
  css: _propTypes.default.any
};