import lodash from "lodash";
import React from "react";
import { NodeSelection } from "./../../tiptap/pm/state.js";
import { extractHeadingsFromPmDoc } from "../heading-extraction.js";
import { getScrollBehavior, TocView } from "../toc-view.js";
const Toc = ({ editor, node, getPos, selected }) => {
  const data = node.attrs;
  const includedLevelsKey = React.useMemo(
    () => (data.includedHeadings || []).join(","),
    [data.includedHeadings]
  );
  const [headings, setHeadings] = React.useState([]);
  React.useEffect(() => {
    const sync = () => {
      setHeadings(extractHeadingsFromPmDoc(editor.state.doc, data.includedHeadings));
    };
    const debouncedSync = lodash.debounce(sync, 60, { leading: true });
    sync();
    editor.on("update", debouncedSync);
    return () => {
      editor.off("update", debouncedSync);
      debouncedSync.cancel();
    };
  }, [editor, includedLevelsKey]);
  const wasSelectedRef = React.useRef(false);
  const onSelect = React.useCallback(() => {
    if (wasSelectedRef.current) {
      return false;
    }
    const pos = getPos();
    if (typeof pos === "number") {
      editor.view.dispatch(
        editor.state.tr.setSelection(NodeSelection.create(editor.state.doc, pos))
      );
    }
    return true;
  }, [editor, getPos]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      onMouseDownCapture: () => {
        wasSelectedRef.current = selected;
      }
    },
    /* @__PURE__ */ React.createElement(
      TocView,
      {
        tocId: String(node.attrs.id || ""),
        data,
        headings,
        mode: "editor",
        onSelect,
        onNavigate: (heading) => {
          const target = editor.view.dom.querySelector(
            `[data-ricos-id="${heading.nodeId}"]`
          );
          target?.scrollIntoView({ behavior: getScrollBehavior(), block: "start" });
        }
      }
    )
  );
};
export {
  Toc
};
//# sourceMappingURL=component.js.map
