function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
 * 拖动/缩放图元时的「边缘对齐吸附」：对照其他图元的 6 条候选线
 * （左/中/右 + 上/中/下），如果当前 rect 的对应边距离它们小于
 * 阈值（内容坐标），就把 rect 平移到精确贴合，并返回参考辅助线，
 * 供画布上渲染红色对齐线。
 *
 * 阈值应保持小（典型 4~8 px / scale），避免吞掉正常拖动手感。
 */

/** 拖动模式：x/y 两轴可独立平移；不改尺寸 */

/** 缩放模式：根据 handle 决定 left/right/top/bottom 哪条边可动 */

function getSelfEdgesX(rect) {
  return [{
    edge: 'left',
    value: rect.left
  }, {
    edge: 'centerX',
    value: rect.left + rect.width / 2
  }, {
    edge: 'right',
    value: rect.left + rect.width
  }];
}
function getSelfEdgesY(rect) {
  return [{
    edge: 'top',
    value: rect.top
  }, {
    edge: 'centerY',
    value: rect.top + rect.height / 2
  }, {
    edge: 'bottom',
    value: rect.top + rect.height
  }];
}
function getOtherEdgesX(rect) {
  return getSelfEdgesX(rect);
}
function getOtherEdgesY(rect) {
  return getSelfEdgesY(rect);
}

/**
 * 对一个 rect 做边对齐吸附。返回 snap 后的 rect + 实际命中的辅助线（0~2 条）。
 *
 * 算法：对 x、y 轴独立处理；每轴在所有「自身 3 边 × 所有 other 3 边」组合
 * 中选距离最小且 < threshold 的一对，把自身整体平移让它们贴齐；同时记录
 * 所有「平移后仍精确贴齐」的参考线（可能不止 1 条，例如 left 和 centerX
 * 同时与他人对齐时只有 1 条平移量但 2 条 guide）。
 */
export function snapRectToOthers(rect, others, options) {
  var _dx$delta, _dy$delta;
  var threshold = Math.max(0, options.threshold);
  if (threshold <= 0 || others.length === 0) {
    return {
      rect: stripId(rect),
      guides: []
    };
  }

  /** 1) 找最优偏移 dx / dy */
  var dx = findBestDelta(getSelfEdgesX(rect), others.flatMap(function (o) {
    return getOtherEdgesX(o).map(function (e) {
      return _objectSpread(_objectSpread({}, e), {}, {
        ownerId: o.id
      });
    });
  }), threshold, options.mode === 'resize' ? options.movableEdgesX : undefined);
  var dy = findBestDelta(getSelfEdgesY(rect), others.flatMap(function (o) {
    return getOtherEdgesY(o).map(function (e) {
      return _objectSpread(_objectSpread({}, e), {}, {
        ownerId: o.id
      });
    });
  }), threshold, options.mode === 'resize' ? options.movableEdgesY : undefined);

  /** 2) 根据 mode 把 dx/dy 应用到 rect（drag: 平移；resize: 只动可动边）*/
  var snapped = applyDelta(rect, (_dx$delta = dx === null || dx === void 0 ? void 0 : dx.delta) !== null && _dx$delta !== void 0 ? _dx$delta : 0, (_dy$delta = dy === null || dy === void 0 ? void 0 : dy.delta) !== null && _dy$delta !== void 0 ? _dy$delta : 0, options);

  /** 3) 重新计算所有边坐标，列出与 other 边精确相等的 guide（不限 1 条） */
  var guides = [];
  if (dx) {
    var _iterator = _createForOfIteratorHelper(getSelfEdgesX(snapped)),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var self = _step.value;
        var _iterator2 = _createForOfIteratorHelper(others),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var o = _step2.value;
            var _iterator3 = _createForOfIteratorHelper(getOtherEdgesX(o)),
              _step3;
            try {
              for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
                var oe = _step3.value;
                if (self.value === oe.value) {
                  var top = Math.min(snapped.top, o.top);
                  var bottom = Math.max(snapped.top + snapped.height, o.top + o.height);
                  guides.push({
                    orientation: 'v',
                    position: self.value,
                    start: top,
                    end: bottom,
                    selfEdge: self.edge,
                    otherEdge: oe.edge,
                    otherId: o.id
                  });
                }
              }
            } catch (err) {
              _iterator3.e(err);
            } finally {
              _iterator3.f();
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  }
  if (dy) {
    var _iterator4 = _createForOfIteratorHelper(getSelfEdgesY(snapped)),
      _step4;
    try {
      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
        var _self = _step4.value;
        var _iterator5 = _createForOfIteratorHelper(others),
          _step5;
        try {
          for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
            var _o = _step5.value;
            var _iterator6 = _createForOfIteratorHelper(getOtherEdgesY(_o)),
              _step6;
            try {
              for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
                var _oe = _step6.value;
                if (_self.value === _oe.value) {
                  var left = Math.min(snapped.left, _o.left);
                  var right = Math.max(snapped.left + snapped.width, _o.left + _o.width);
                  guides.push({
                    orientation: 'h',
                    position: _self.value,
                    start: left,
                    end: right,
                    selfEdge: _self.edge,
                    otherEdge: _oe.edge,
                    otherId: _o.id
                  });
                }
              }
            } catch (err) {
              _iterator6.e(err);
            } finally {
              _iterator6.f();
            }
          }
        } catch (err) {
          _iterator5.e(err);
        } finally {
          _iterator5.f();
        }
      }
    } catch (err) {
      _iterator4.e(err);
    } finally {
      _iterator4.f();
    }
  }
  return {
    rect: snapped,
    guides: guides
  };
}
/** 在所有 self×other 组合中选距离最小且 < threshold 的一组 */
function findBestDelta(selfEdges, otherEdges, threshold, movableFilter) {
  var best = null;
  var _iterator7 = _createForOfIteratorHelper(selfEdges),
    _step7;
  try {
    for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
      var self = _step7.value;
      /** resize 模式下：「centerX/centerY 不可动；left/right/top/bottom 必须在 movable 列表里」 */
      if (movableFilter) {
        if (self.edge === 'centerX' || self.edge === 'centerY') continue;
        if (!movableFilter.includes(self.edge)) continue;
      }
      var _iterator8 = _createForOfIteratorHelper(otherEdges),
        _step8;
      try {
        for (_iterator8.s(); !(_step8 = _iterator8.n()).done;) {
          var o = _step8.value;
          var dist = o.value - self.value;
          var ad = Math.abs(dist);
          if (ad > threshold) continue;
          if (!best || ad < best.absDist) {
            best = {
              delta: dist,
              absDist: ad
            };
          }
        }
      } catch (err) {
        _iterator8.e(err);
      } finally {
        _iterator8.f();
      }
    }
  } catch (err) {
    _iterator7.e(err);
  } finally {
    _iterator7.f();
  }
  return best ? {
    delta: best.delta
  } : null;
}
function applyDelta(rect, dx, dy, options) {
  var _options$movableEdges, _options$movableEdges2;
  if (options.mode === 'drag') {
    return {
      left: rect.left + dx,
      top: rect.top + dy,
      width: rect.width,
      height: rect.height
    };
  }
  /** resize：根据可动边把 dx/dy 应用到该边 */
  var left = rect.left,
    top = rect.top,
    width = rect.width,
    height = rect.height;
  var right = left + width;
  var bottom = top + height;
  var mx = (_options$movableEdges = options.movableEdgesX) !== null && _options$movableEdges !== void 0 ? _options$movableEdges : [];
  var my = (_options$movableEdges2 = options.movableEdgesY) !== null && _options$movableEdges2 !== void 0 ? _options$movableEdges2 : [];
  var newLeft = left;
  var newRight = right;
  var newTop = top;
  var newBottom = bottom;
  if (dx !== 0) {
    if (mx.includes('left')) newLeft = left + dx;else if (mx.includes('right')) newRight = right + dx;
  }
  if (dy !== 0) {
    if (my.includes('top')) newTop = top + dy;else if (my.includes('bottom')) newBottom = bottom + dy;
  }
  /** 保证 width/height >= 1，否则忽略该轴 snap */
  if (newRight - newLeft < 1) {
    newLeft = left;
    newRight = right;
  }
  if (newBottom - newTop < 1) {
    newTop = top;
    newBottom = bottom;
  }
  return {
    left: newLeft,
    top: newTop,
    width: newRight - newLeft,
    height: newBottom - newTop
  };
}
function stripId(rect) {
  return {
    left: rect.left,
    top: rect.top,
    width: rect.width,
    height: rect.height
  };
}