"use strict";
const React = require("react");
const index = require("../ConfigProvider/index.js");
const classNames = require("../_util/classNames.js");
const is = require("../_util/is.js");
const resizeTrigger = require("./resize-trigger.js");
const dom = require("../_util/dom.js");
const omit = require("../_util/omit.js");
const emotionReactJsxRuntime_browser_esm = require("../../../../../../@emotion_react@11.10.4_3toe27fv7etiytxb5kxc7fxaw4/node_modules/@emotion/react/jsx-runtime/dist/emotion-react-jsx-runtime.browser.esm.js");
var __assign = globalThis && globalThis.__assign || function() {
  __assign = Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
      s = arguments[i];
      for (var p in s)
        if (Object.prototype.hasOwnProperty.call(s, p))
          t[p] = s[p];
    }
    return t;
  };
  return __assign.apply(this, arguments);
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p in s)
    if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
      t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
var __read = globalThis && globalThis.__read || function(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m)
    return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
      ar.push(r.value);
  } catch (error) {
    e = {
      error
    };
  } finally {
    try {
      if (r && !r.done && (m = i["return"]))
        m.call(i);
    } finally {
      if (e)
        throw e.error;
    }
  }
  return ar;
};
var __spreadArray = globalThis && globalThis.__spreadArray || function(to, from, pack) {
  if (pack || arguments.length === 2)
    for (var i = 0, l = from.length, ar; i < l; i++) {
      if (ar || !(i in from)) {
        if (!ar)
          ar = Array.prototype.slice.call(from, 0, i);
        ar[i] = from[i];
      }
    }
  return to.concat(ar || Array.prototype.slice.call(from));
};
var DIRECTION_HORIZONTAL = "horizontal";
var DIRECTION_VERTICAL = "vertical";
function SplitGroup(props, ref) {
  var _a, _b;
  var panes = props.panes, style = props.style, className = props.className, _c = props.component, component = _c === void 0 ? "div" : _c, _d = props.direction, direction = _d === void 0 ? "horizontal" : _d, icon = props.icon, rest = __rest(props, ["panes", "style", "className", "component", "direction", "icon"]);
  var _e = React.useContext(index.ConfigContext), getPrefixCls = _e.getPrefixCls, rtl = _e.rtl;
  var defaultOffset = 1 / panes.length;
  var wrapperRef = React.useRef();
  var recordRef = React.useRef(new Array(panes.length).fill({
    moving: false,
    startOffset: 0,
    startPosition: 0
  }));
  var paneContainers = React.useRef([]);
  var movingIndex = React.useRef(0);
  var prevOffsets = React.useRef([]);
  var _f = __read(React.useState(new Array(panes.length).fill(defaultOffset)), 2), offsets = _f[0], setOffsets = _f[1];
  var _g = __read(React.useState(false), 2), isMoving = _g[0], setIsMoving = _g[1];
  var _h = __read(React.useState(new Array(panes.length).fill(0)), 2), triggerSize = _h[0], setTriggerSize = _h[1];
  var _j = __read(React.useState(new Array(Math.max(panes.length - 1, 0)).fill({
    prev: false,
    next: false
  })), 2), collapsedStatus = _j[0], setCollapsedStatus = _j[1];
  var prefixCls = getPrefixCls("resizebox-split-group");
  var isHorizontal = direction === DIRECTION_HORIZONTAL;
  var rtlReverse = isHorizontal && rtl;
  var isTriggerHorizontal = !isHorizontal;
  var classNames$1 = classNames(prefixCls, prefixCls + "-" + (isHorizontal ? DIRECTION_HORIZONTAL : DIRECTION_VERTICAL), (_a = {}, _a[prefixCls + "-moving"] = isMoving, _a), (_b = {}, _b[prefixCls + "-rtl"] = rtl, _b), className);
  var Tag = component;
  var getInitialOffsets = function() {
    var newOffsets = [];
    panes.forEach(function(pane) {
      var size = pane.size;
      if (!is.isUndefined(size)) {
        newOffsets.push(formatSize(size));
      } else {
        newOffsets.push(void 0);
      }
    });
    var noSizeArr = newOffsets.filter(function(size) {
      return !size;
    });
    var remainPercent = 1 - newOffsets.reduce(function(a, b) {
      var formatA = a || 0;
      var formatB = b || 0;
      return formatA + formatB;
    }, 0);
    var averagePercent = remainPercent / noSizeArr.length;
    newOffsets = newOffsets.map(function(size) {
      if (!is.isUndefined(size)) {
        return size;
      }
      return averagePercent;
    });
    return newOffsets;
  };
  var getPaneSize = function(index2) {
    var prevTriggerSize = triggerSize[index2 - 1] || 0;
    var currentTriggerSize = triggerSize[index2];
    var baseVal = offsets[index2] * 100;
    var unit = "%";
    return "calc(" + baseVal + unit + " - " + (prevTriggerSize + currentTriggerSize) / 2 + "px)";
  };
  function formatSize(size) {
    var totalPX = isHorizontal ? wrapperRef.current.offsetWidth : wrapperRef.current.offsetHeight;
    if (!size || is.isNumber(size) && size < 0) {
      return 0;
    }
    var percent = is.isString(size) ? parseFloat(size) / totalPX : size;
    return Math.min(percent, 1);
  }
  var getMinAndMax = function(index2) {
    var next = Math.min(index2 + 1, panes.length - 1);
    var totalOffset = offsets[index2] + offsets[next];
    var currentMin = formatSize(panes[index2].min) || 0;
    var currentMax = formatSize(panes[index2].max) || totalOffset;
    var nextMin = formatSize(panes[next].min) || 0;
    var nextMax = formatSize(panes[next].max) || totalOffset;
    currentMax = Math.min(totalOffset - nextMin, currentMax);
    nextMax = Math.min(totalOffset - currentMin, nextMax);
    return {
      currentMin,
      currentMax,
      nextMin,
      nextMax
    };
  };
  var getNewOffsets = function(startOffset, startPosition, currentPosition) {
    var current = movingIndex.current;
    var next = current + 1;
    var newOffsets = __spreadArray([], __read(offsets), false);
    var ratio = rtlReverse ? -1 : 1;
    var currentPercent = offsets[current];
    var nextPercent = offsets[next];
    var totalPercent = currentPercent + nextPercent;
    var _a2 = getMinAndMax(current), minOffset = _a2.currentMin, maxOffset = _a2.currentMax;
    var moveOffset = startOffset + formatSize((currentPosition - startPosition) * ratio + "px");
    moveOffset = Math.max(minOffset, moveOffset);
    moveOffset = Math.min(maxOffset, moveOffset);
    newOffsets[current] = moveOffset;
    newOffsets[next] = totalPercent - moveOffset;
    return newOffsets;
  };
  function onTriggerResize(e, index2) {
    var contentRect = e[0].contentRect;
    var currentSize = contentRect[isTriggerHorizontal ? "height" : "width"];
    var newTriggerSize = __spreadArray([], __read(triggerSize), false);
    newTriggerSize[index2] = currentSize;
    setTriggerSize(newTriggerSize);
  }
  var getCollapsedConfig = function(index2) {
    var collapsible = panes[index2].collapsible;
    if (!is.isObject(collapsible)) {
      collapsible = !collapsible ? {} : {
        prev: true,
        next: true
      };
    }
    var prev = collapsible.prev, next = collapsible.next;
    if (!prev && !next) {
      return {};
    }
    if (!collapsedStatus[index2]) {
      return {};
    }
    var hasPrev = !!prev || !prev && collapsedStatus[index2].next;
    var hasNext = !!next || !next && collapsedStatus[index2].prev;
    return {
      hasPrev,
      hasNext
    };
  };
  function onTriggerMouseDown(e, index2) {
    props.onMovingStart && props.onMovingStart(index2);
    movingIndex.current = index2;
    var currentRecord = recordRef.current[index2];
    currentRecord.moving = true;
    currentRecord.startOffset = offsets[index2];
    currentRecord.startPosition = isHorizontal ? e.pageX : e.pageY;
    setIsMoving(true);
    dom.on(window, "mousemove", moving);
    dom.on(window, "touchmove", moving);
    dom.on(window, "mouseup", moveEnd);
    dom.on(window, "touchend", moveEnd);
    dom.on(window, "contextmenu", moveEnd);
    document.body.style.cursor = isTriggerHorizontal ? "row-resize" : "col-resize";
  }
  function moving(e) {
    var index2 = movingIndex.current;
    var currentRecord = recordRef.current[index2];
    var totalPX = isHorizontal ? wrapperRef.current.offsetWidth : wrapperRef.current.offsetHeight;
    if (currentRecord.moving) {
      var newOffsets = getNewOffsets(currentRecord.startOffset, currentRecord.startPosition, isHorizontal ? e.pageX : e.pageY);
      setOffsets(newOffsets);
      prevOffsets.current = newOffsets;
      props.onMoving && props.onMoving(e, newOffsets.map(function(value) {
        return value * totalPX + "px";
      }), index2);
    }
  }
  function moveEnd() {
    var index2 = movingIndex.current;
    recordRef.current[index2].moving = false;
    setIsMoving(false);
    dom.off(window, "mousemove", moving);
    dom.off(window, "touchmove", moving);
    dom.off(window, "mouseup", moveEnd);
    dom.off(window, "touchend", moveEnd);
    dom.off(window, "contextmenu", moveEnd);
    document.body.style.cursor = "default";
    props.onMovingEnd && props.onMovingEnd(index2);
  }
  function handleCollapsed(e, index2, status, callback) {
    var next = index2 + 1;
    var newOffset = __spreadArray([], __read(offsets), false);
    var currentOffset = offsets[index2];
    var nextOffset = offsets[next];
    var totalOffset = currentOffset + nextOffset;
    var totalPX = isHorizontal ? wrapperRef.current.offsetWidth : wrapperRef.current.offsetHeight;
    var _a2 = getMinAndMax(index2), currentMin = _a2.currentMin, nextMin = _a2.nextMin;
    var newCurrentOffset = prevOffsets.current[index2];
    var newNextOffset = prevOffsets.current[next];
    var collapsed = collapsedStatus[index2][status];
    if (status === "prev") {
      if (nextOffset !== nextMin || newNextOffset === nextMin) {
        newCurrentOffset = currentMin;
        newNextOffset = totalOffset - currentMin;
        collapsed = true;
      }
    } else if (currentOffset !== currentMin || newCurrentOffset === currentMin) {
      newCurrentOffset = totalOffset - nextMin;
      newNextOffset = nextMin;
      collapsed = true;
    }
    newOffset[index2] = newCurrentOffset;
    newOffset[next] = newNextOffset;
    props.onMoving && props.onMoving(e, newOffset.map(function(value) {
      return value * totalPX + "px";
    }), index2);
    props.onMovingEnd && props.onMovingEnd(index2);
    setOffsets(newOffset);
    if (is.isFunction(callback)) {
      callback(e, index2, status, collapsed);
    }
  }
  React.useEffect(function() {
    var offsets2 = getInitialOffsets();
    setOffsets(offsets2);
    prevOffsets.current = offsets2;
  }, [JSON.stringify(panes.map(function(item) {
    return item.size;
  }))]);
  React.useImperativeHandle(ref, function() {
    return wrapperRef.current;
  }, []);
  React.useEffect(function() {
    var newCollapsedStatus = [];
    offsets.forEach(function(offset, index2) {
      var currentCollapsedStatus = {
        prev: false,
        next: false
      };
      var next = index2 + 1;
      var _a2 = getMinAndMax(index2), currentMin = _a2.currentMin, nextMin = _a2.nextMin;
      if (offset === currentMin) {
        currentCollapsedStatus.prev = true;
      } else if (offsets[next] === nextMin) {
        currentCollapsedStatus.next = true;
      }
      newCollapsedStatus.push(currentCollapsedStatus);
    });
    setCollapsedStatus(newCollapsedStatus);
  }, [offsets]);
  return /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(Tag, {
    ...__assign({}, omit(rest, ["onMovingStart", "onPaneResize", "onMoving", "onMovingEnd"]), {
      style,
      className: classNames$1,
      ref: wrapperRef
    }),
    children: panes.map(function(pane, index2) {
      var content = pane.content, disabled = pane.disabled, trigger = pane.trigger, _a2 = pane.resizable, resizable = _a2 === void 0 ? true : _a2, _b2 = pane.collapsible, collapsible = _b2 === void 0 ? {} : _b2;
      var _c2 = getCollapsedConfig(index2), hasPrev = _c2.hasPrev, hasNext = _c2.hasNext;
      var prevConfig = is.isObject(collapsible) && is.isObject(collapsible.prev) ? collapsible.prev : {};
      var nextConfig = is.isObject(collapsible) && is.isObject(collapsible.next) ? collapsible.next : {};
      return /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsxs(emotionReactJsxRuntime_browser_esm.Fragment, {
        children: [/* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx("div", {
          className: prefixCls + "-pane",
          style: {
            flexBasis: getPaneSize(index2)
          },
          ref: function(el) {
            return paneContainers.current[index2] = el;
          },
          children: content
        }), !disabled && index2 !== panes.length - 1 && /* @__PURE__ */ emotionReactJsxRuntime_browser_esm.jsx(resizeTrigger, {
          className: prefixCls + "-trigger",
          direction: isTriggerHorizontal ? DIRECTION_HORIZONTAL : DIRECTION_VERTICAL,
          icon,
          onResize: function(e) {
            return onTriggerResize(e, index2);
          },
          onMouseDown: function(e) {
            return onTriggerMouseDown(e, index2);
          },
          collapsible: {
            prev: hasPrev ? {
              onClick: function(e) {
                return handleCollapsed(e, index2, "prev", prevConfig.onClick);
              },
              icon: prevConfig.icon,
              collapsed: collapsedStatus[index2].prev
            } : void 0,
            next: hasNext ? {
              onClick: function(e) {
                return handleCollapsed(e, index2, "next", nextConfig.onClick);
              },
              icon: nextConfig.icon,
              collapsed: collapsedStatus[index2].next
            } : void 0
          },
          resizable,
          renderChildren: trigger
        })]
      });
    })
  });
}
var SplitGroupComponent = React.forwardRef(SplitGroup);
SplitGroupComponent.displayName = "ResizeBoxSplitGroup";
const SplitGroup$1 = SplitGroupComponent;
module.exports = SplitGroup$1;
//# sourceMappingURL=split-group.js.map
