"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useResize = useResize;
var _react = require("react");
var _throttle = _interopRequireDefault(require("lodash/throttle"));
var _collapsibleSidebar = require("./collapsible-sidebar");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function useResize({
  panelElement,
  onWidthChange,
  sideBarPlacement,
  isResizeEnabled,
  isMinimized
}) {
  const [isResizing, setIsResizing] = (0, _react.useState)(false);
  const moveHandlerRef = (0, _react.useRef)(new AbortController());
  const upHandlerRef = (0, _react.useRef)(new AbortController());
  const shouldToggleOnClick = (0, _react.useRef)(true);
  const onMouseMoveHandler = event => {
    event.preventDefault();
    event.stopPropagation();
    shouldToggleOnClick.current = false;
    const sidePanelBoundingRect = panelElement.current.getBoundingClientRect();
    const delta = sideBarPlacement === _collapsibleSidebar.TOGGLE_BUTTON_PLACEMENTS.right ? Math.round(event.clientX - sidePanelBoundingRect.right) : Math.round(sidePanelBoundingRect.left - event.clientX);
    const newWidth = sidePanelBoundingRect.width + delta;
    onWidthChange?.(newWidth);
  };
  const throttledMoveHandler = (0, _react.useRef)((0, _throttle.default)(onMouseMoveHandler, 20)).current;
  const onMouseUpHandler = () => {
    if (isResizeEnabled) {
      moveHandlerRef?.current?.abort();
      setIsResizing(false);
    }
  };

  // subscribe to moseup handler which will cancel move listener
  (0, _react.useEffect)(() => {
    document.addEventListener('mouseup', onMouseUpHandler, {
      signal: upHandlerRef.current.signal
    });
    return () => {
      moveHandlerRef?.current?.abort();
      upHandlerRef.current.abort();
    };
  }, []);
  const onMouseDownHandler = () => {
    // we add mousemove listener to the whole document only on mousedown on border.
    // we unsubscribe in the mouseup handler.
    // this is neede so that user can drag mouse anywhere on the screen as long as the mouse is clicked and sidebar panl would respond respectively
    if (isResizeEnabled && !isMinimized) {
      shouldToggleOnClick.current = true;
      moveHandlerRef.current = new AbortController();
      document.addEventListener('mousemove', throttledMoveHandler, {
        signal: moveHandlerRef.current.signal
      });
      setIsResizing(true);
    }
  };
  return {
    isResizing,
    shouldRespondToBorderClick: shouldToggleOnClick.current,
    onMouseDownHandler
  };
}