import { DATA_CELL_SELECTED } from "../data-hooks.js";
import { RicosCellSelection } from "../tiptap/plugins/cellselection.js";
import { findTable } from "../tiptap/utilities/find-table.js";
import { isRicosCellSelection } from "../tiptap/utilities/is-selection-type.js";
const findCellDomById = (editor, id) => {
  const dom = [...editor.view.dom.querySelectorAll("[data-node-id]")].find(
    (element) => element.getAttribute("data-node-id") === id
  );
  return dom instanceof HTMLElement ? dom : void 0;
};
const getCellElement = (editor, pos, id) => {
  const dom = editor.view.nodeDOM(pos);
  if (dom instanceof HTMLElement) {
    return dom;
  }
  return id ? findCellDomById(editor, id) : void 0;
};
const captureCellsById = (editor, selectedCellIds) => {
  if (!selectedCellIds?.length) {
    return null;
  }
  const selectedIds = new Set(selectedCellIds);
  const tableInfo = findTable(editor.state.selection);
  const cells = [];
  const visit = (node, basePos) => {
    node.descendants((child, offset) => {
      const id = child.attrs.id;
      if (id && selectedIds.has(id)) {
        cells.push({
          element: getCellElement(editor, basePos + offset, id),
          id,
          pos: basePos + offset
        });
      }
    });
  };
  if (tableInfo) {
    visit(tableInfo.node, tableInfo.start);
  } else {
    visit(editor.state.doc, 0);
  }
  return cells.length > 0 ? cells : null;
};
const captureCellsFromDom = (editor) => {
  const { view } = editor;
  const cells = [];
  for (const element of view.dom.querySelectorAll(`[${DATA_CELL_SELECTED}="true"]`)) {
    if (!(element instanceof HTMLElement) || !view.dom.contains(element)) {
      continue;
    }
    try {
      cells.push({
        element,
        id: element.getAttribute("data-node-id") ?? void 0,
        pos: view.posAtDOM(element, 0)
      });
    } catch {
    }
  }
  return cells.length > 0 ? cells : null;
};
const captureSelectedCellPositions = (editor, selectedCellIds) => {
  const { selection } = editor.state;
  if (isRicosCellSelection(selection)) {
    const cells = [];
    selection.forEachCell((node, pos) => {
      cells.push({ element: getCellElement(editor, pos, node.attrs.id), id: node.attrs.id, pos });
    });
    if (cells.length > 0) {
      return cells;
    }
  }
  return captureCellsFromDom(editor) ?? captureCellsById(editor, selectedCellIds);
};
const runWithTableCellSelection = (editor, capturedCells, run) => {
  if (!isRicosCellSelection(editor.state.selection) && capturedCells?.length) {
    const { state, view } = editor;
    try {
      const cells = capturedCells.map(({ pos }) => state.doc.resolve(pos));
      view.dispatch(
        state.tr.setSelection(new RicosCellSelection(cells, state.doc)).setMeta("addToHistory", false)
      );
    } catch {
    }
  }
  run();
};
export {
  captureSelectedCellPositions,
  runWithTableCellSelection
};
//# sourceMappingURL=capture-table-cell-selection.js.map
