var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/pisellDraggable/index.tsx
var pisellDraggable_exports = {};
__export(pisellDraggable_exports, {
  SortableTree: () => SortableTree,
  default: () => pisellDraggable_default
});
module.exports = __toCommonJS(pisellDraggable_exports);
var import_core = require("@dnd-kit/core");
var import_sortable = require("@dnd-kit/sortable");
var import_react = __toESM(require("react"));
var import_react_dom = require("react-dom");
var import_utilities = require("@dnd-kit/utilities");
var import_components = require("./components");
var import_utilities2 = require("./utilities");
var initialItems = [
  {
    id: "Home",
    children: []
  },
  {
    id: "Collections",
    children: [
      { id: "Spring", children: [] },
      { id: "Summer", children: [] },
      { id: "Fall", children: [] },
      { id: "Winter", children: [], disabledDrop: true }
    ]
  },
  {
    id: "About Us",
    children: []
  },
  {
    id: "My Account",
    children: [
      { id: "Addresses", children: [] },
      { id: "Order History", children: [] }
    ]
  }
];
var measuring = {
  droppable: {
    strategy: import_core.MeasuringStrategy.Always
  }
};
var dropAnimationConfig = {
  keyframes({ transform }) {
    return [
      { opacity: 1, transform: import_utilities.CSS.Transform.toString(transform.initial) },
      {
        opacity: 0,
        transform: import_utilities.CSS.Transform.toString({
          ...transform.final,
          x: transform.final.x + 5,
          y: transform.final.y + 5
        })
      }
    ];
  },
  easing: "ease-out",
  sideEffects({ active }) {
    active.node.animate([{ opacity: 0 }, { opacity: 1 }], {
      duration: import_core.defaultDropAnimation.duration,
      easing: import_core.defaultDropAnimation.easing
    });
  }
};
function SortableTree({
  collapsible = true,
  value = initialItems,
  indicator = false,
  indentationWidth = 50,
  removable = true,
  renderItem,
  onChange,
  onRemoveBefore,
  __designMode,
  maxLevel = 3
}) {
  const [items, setItems] = (0, import_react.useState)([]);
  const [activeId, setActiveId] = (0, import_react.useState)(null);
  const [overId, setOverId] = (0, import_react.useState)(null);
  const [offsetLeft, setOffsetLeft] = (0, import_react.useState)(0);
  (0, import_react.useEffect)(() => {
    console.log("初始化", value);
    setItems(value);
  }, [value]);
  const flattenTreeData = (0, import_react.useMemo)(() => {
    return (0, import_utilities2.flattenTree)(items);
  }, [items]);
  const flattenedItems = (0, import_react.useMemo)(() => {
    const collapsedItems = flattenTreeData.reduce(
      (acc, { children = [], collapsed, id }) => collapsed && children.length ? [...acc, id] : acc,
      []
    );
    return (0, import_utilities2.removeChildrenOf)(
      flattenTreeData,
      activeId != null ? [activeId, ...collapsedItems] : collapsedItems
    );
  }, [activeId, flattenTreeData]);
  console.log("flattenedItems", flattenedItems);
  const projected = activeId && overId ? (0, import_utilities2.getProjection)(
    flattenedItems,
    activeId,
    overId,
    offsetLeft,
    indentationWidth
  ) : null;
  const sensorContext = (0, import_react.useRef)({
    items: flattenedItems,
    offset: offsetLeft
  });
  const sensors = (0, import_core.useSensors)((0, import_core.useSensor)(import_core.PointerSensor));
  const sortedIds = (0, import_react.useMemo)(
    () => flattenedItems.map(({ id }) => id),
    [flattenedItems]
  );
  const activeItem = activeId ? flattenedItems.find(({ id }) => id === activeId) : null;
  (0, import_react.useEffect)(() => {
    sensorContext.current = {
      items: flattenedItems,
      offset: offsetLeft
    };
  }, [flattenedItems, offsetLeft]);
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
  }, []);
  function checkSubtreeDepth(items2, itemId, baseDepth) {
    const item = items2.find((i) => i.id === itemId);
    if (!item)
      return false;
    if (baseDepth >= maxLevel)
      return true;
    const children = items2.filter((i) => i.parentId === itemId);
    if (baseDepth >= maxLevel - 1 && children.length > 0)
      return true;
    return children.some((child) => {
      const childNewDepth = baseDepth + 1;
      return childNewDepth >= maxLevel || checkSubtreeDepth(items2, child.id, childNewDepth);
    });
  }
  return /* @__PURE__ */ import_react.default.createElement(
    import_core.DndContext,
    {
      sensors,
      collisionDetection: import_core.closestCenter,
      measuring,
      onDragStart: handleDragStart,
      onDragMove: handleDragMove,
      onDragOver: handleDragOver,
      onDragEnd: handleDragEnd,
      onDragCancel: handleDragCancel
    },
    /* @__PURE__ */ import_react.default.createElement(import_sortable.SortableContext, { items: sortedIds, strategy: import_sortable.verticalListSortingStrategy }, flattenedItems.map((item) => {
      const { id, children, collapsed, depth } = item;
      return /* @__PURE__ */ import_react.default.createElement(
        import_components.SortableTreeItem,
        {
          key: id,
          id,
          item,
          depth: id === activeId && projected ? projected.depth : depth,
          indentationWidth,
          indicator,
          collapsed: Boolean(collapsed && (children == null ? void 0 : children.length)),
          onCollapse: collapsible && (children == null ? void 0 : children.length) ? () => handleCollapse(id) : void 0,
          onRemove: removable ? () => handleRemove(item) : void 0,
          renderItem,
          __designMode
        }
      );
    }), (0, import_react_dom.createPortal)(
      /* @__PURE__ */ import_react.default.createElement(
        import_core.DragOverlay,
        {
          dropAnimation: dropAnimationConfig,
          modifiers: indicator ? [adjustTranslate] : void 0
        },
        activeId && activeItem ? /* @__PURE__ */ import_react.default.createElement(
          import_components.SortableTreeItem,
          {
            id: activeId,
            depth: activeItem.depth,
            clone: true,
            childCount: (0, import_utilities2.getChildCount)(items, activeId) + 1,
            item: activeItem,
            indentationWidth,
            renderItem
          }
        ) : null
      ),
      document.body
    ))
  );
  function handleDragStart({ active: { id: activeId2 } }) {
    setActiveId(activeId2);
    setOverId(activeId2);
    document.body.style.setProperty("cursor", "grabbing");
  }
  function handleDragMove({ delta }) {
    setOffsetLeft(delta.x);
  }
  function handleDragOver({ over }) {
    if (!projected || !over) {
      setOverId((over == null ? void 0 : over.id) ?? null);
      return;
    }
    const targetParent = projected.parentId ? flattenedItems.find((item) => item.id === projected.parentId) : null;
    if (targetParent == null ? void 0 : targetParent.disabledDrop) {
      return;
    }
    if (projected.depth >= maxLevel) {
      return;
    }
    const willExceedLimit = checkSubtreeDepth(
      flattenTreeData,
      activeId,
      projected.depth
    );
    if (willExceedLimit) {
      return;
    }
    setOverId(over.id);
  }
  function handleDragEnd({ active, over }) {
    resetState();
    if (projected && over) {
      const { depth, parentId } = projected;
      const targetParent = parentId ? flattenedItems.find((item) => item.id === parentId) : null;
      if (targetParent == null ? void 0 : targetParent.disabledDrop) {
        return;
      }
      if (depth >= maxLevel) {
        return;
      }
      const willExceedLimit = checkSubtreeDepth(
        flattenTreeData,
        active.id,
        depth
      );
      if (willExceedLimit) {
        return;
      }
      const clonedItems = JSON.parse(
        JSON.stringify((0, import_utilities2.flattenTree)(items))
      );
      const overIndex = clonedItems.findIndex(({ id }) => id === over.id);
      const activeIndex = clonedItems.findIndex(({ id }) => id === active.id);
      const activeTreeItem = clonedItems[activeIndex];
      clonedItems[activeIndex] = { ...activeTreeItem, depth, parentId };
      const sortedItems = (0, import_sortable.arrayMove)(clonedItems, activeIndex, overIndex);
      const newItems = (0, import_utilities2.buildTree)(sortedItems);
      setItems(newItems);
      onChange == null ? void 0 : onChange(newItems);
    }
  }
  function handleDragCancel() {
    resetState();
  }
  function resetState() {
    setOverId(null);
    setActiveId(null);
    setOffsetLeft(0);
    document.body.style.setProperty("cursor", "");
  }
  async function handleRemove(item) {
    if (onRemoveBefore) {
      let res = await (onRemoveBefore == null ? void 0 : onRemoveBefore(item));
      if (!res) {
        return;
      }
    }
    setItems((items2) => (0, import_utilities2.removeItem)(items2, item.id));
    onChange == null ? void 0 : onChange(items);
  }
  function handleCollapse(id) {
    setItems(
      (items2) => (0, import_utilities2.setProperty)(items2, id, "collapsed", (value2) => {
        return !value2;
      })
    );
  }
}
var adjustTranslate = ({ transform }) => {
  return {
    ...transform,
    y: transform.y - 25
  };
};
var Demo = (props) => {
  return /* @__PURE__ */ import_react.default.createElement(SortableTree, { ...props });
};
var pisellDraggable_default = Demo;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SortableTree
});
