"use strict";
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);
var resize_utils_exports = {};
__export(resize_utils_exports, {
  domCellAround: () => domCellAround,
  edgeCell: () => edgeCell,
  getTableElement: () => getTableElement,
  resetHandle: () => resetHandle,
  updateColumns: () => updateColumns,
  updateHandle: () => updateHandle
});
module.exports = __toCommonJS(resize_utils_exports);
var import_lodash = __toESM(require("lodash"));
var import_queries = require("../commands/queries.js");
var import_tablemap = require("../tablemap.js");
function updateHandle(view, value, key) {
  view.dispatch(view.state.tr.setMeta(key, { setHandle: value }));
}
function resetHandle(view, key) {
  const pluginState = key.getState(view.state);
  if (pluginState.activeHandle > -1 && !pluginState.dragging) {
    updateHandle(view, -1, key);
  }
}
function domCellAround(target) {
  while (target && target.nodeName !== "TD" && target.nodeName !== "TH") {
    target = target.classList.contains("ProseMirror") ? null : target.parentNode;
  }
  return target;
}
function edgeCell(view, event, side, isVertical = false) {
  const found = view.posAtCoords({ left: event.clientX, top: event.clientY });
  if (!found) {
    return -1;
  }
  const { inside } = found;
  const $cell = (0, import_queries.cellAround)(view.state.doc.resolve(inside + 1));
  if (!$cell) {
    return -1;
  }
  const direction = isVertical ? "bottom" : "right";
  if (side === direction) {
    return $cell.pos;
  }
  const map = import_tablemap.TableMap.get($cell.node(-1));
  const start = $cell.start(-1);
  const index = map.map.indexOf($cell.pos - start);
  return index % map.width === 0 ? -1 : start + map.map[index - 1];
}
function updateColumns({
  node,
  colgroup,
  table,
  cellMinWidth,
  commands,
  overrideCol,
  overrideValue,
  shouldUpdateState
}) {
  let totalWidth = 0;
  let nextDOM = colgroup.firstChild;
  const colsWidthRatio = node.attrs.dimensions?.colsWidthRatio || [];
  const row = node.firstChild;
  let actualColumnCount = 0;
  if (row) {
    for (let i = 0; i < row.childCount; i++) {
      actualColumnCount += row.child(i).attrs.colspan || 1;
    }
  }
  if (colsWidthRatio.length > 0 && colsWidthRatio.length === actualColumnCount) {
    const spacing = node.attrs.tableData?.cellSpacing ?? 0;
    for (let col = 0; col < colsWidthRatio.length; col++) {
      const rawWidth = overrideCol === col ? overrideValue : colsWidthRatio[col];
      const baseWidth = rawWidth ? Math.max(rawWidth, cellMinWidth) : cellMinWidth;
      const hasWidth = col > 0 && spacing > 0 ? baseWidth + spacing : baseWidth;
      const cssWidth = hasWidth + "px";
      totalWidth += hasWidth;
      if (!nextDOM) {
        const colElement = document.createElement("col");
        colElement.style.width = cssWidth;
        colgroup.appendChild(colElement);
      } else {
        if (nextDOM.style.width !== cssWidth) {
          nextDOM.style.width = cssWidth;
        }
        nextDOM = nextDOM.nextSibling;
      }
    }
  } else {
    const spacing = node.attrs.tableData?.cellSpacing ?? 0;
    const row2 = node.firstChild;
    if (row2 === null) {
      return;
    }
    let fixedWidth = true;
    for (let i = 0, col = 0; i < row2.childCount; i++) {
      const { colspan, colwidth } = row2.child(i).attrs;
      for (let j = 0; j < colspan; j++, col++) {
        const rawWidth = overrideCol === col ? overrideValue : colwidth && colwidth[j];
        const baseWidth = rawWidth ? Math.max(rawWidth, cellMinWidth) : null;
        const hasWidth = baseWidth && col > 0 && spacing > 0 ? baseWidth + spacing : baseWidth;
        const cssWidth = hasWidth ? hasWidth + "px" : "";
        totalWidth += hasWidth || cellMinWidth;
        if (!hasWidth) {
          fixedWidth = false;
        }
        if (!(nextDOM instanceof HTMLElement)) {
          const colElement = document.createElement("col");
          colElement.style.width = cssWidth;
          colgroup.appendChild(colElement);
        } else {
          if (nextDOM.style.width !== cssWidth) {
            nextDOM.style.width = cssWidth;
          }
          nextDOM = nextDOM.nextSibling;
        }
      }
    }
    if (!fixedWidth) {
      table.style.width = "";
      table.style.minWidth = totalWidth + "px";
      while (nextDOM) {
        const after = nextDOM.nextSibling;
        if (nextDOM.parentNode) {
          nextDOM.parentNode.removeChild(nextDOM);
        }
        nextDOM = after;
      }
      if (shouldUpdateState) {
        updateColsWidthAttrs(colgroup, node, commands);
      }
      return;
    }
  }
  while (nextDOM) {
    const after = nextDOM.nextSibling;
    if (nextDOM.parentNode === null) {
      return;
    }
    nextDOM.parentNode.removeChild(nextDOM);
    nextDOM = after;
  }
  if (shouldUpdateState) {
    updateColsWidthAttrs(colgroup, node, commands);
  }
  table.style.width = totalWidth + "px";
  table.style.minWidth = "";
}
function updateColsWidthAttrs(colgroup, table, commands) {
  const spacing = table.attrs.tableData?.cellSpacing ?? 0;
  const colsWidth = Array.from(colgroup.children).map((col, index) => {
    const width = col.offsetWidth;
    return index > 0 && spacing > 0 ? width - spacing : width;
  });
  const colsMinWidth = colsWidth.map((width, index) => {
    const minBase = Math.min(width, 120);
    return index > 0 && spacing > 0 ? minBase : minBase;
  });
  if (!import_lodash.default.isEqual(table.attrs.dimensions?.colsWidthRatio, colsWidth) || !import_lodash.default.isEqual(table.attrs.dimensions?.colsMinWidth, colsMinWidth)) {
    try {
      commands.updateNodeAttrsById(table.attrs.id, {
        ...table.attrs,
        dimensions: {
          ...table.attrs.dimensions,
          colsWidthRatio: colsWidth,
          colsMinWidth
        }
      });
    } catch (e) {
      console.error("could not update node attributes by id", e);
    }
  }
}
const getTableElement = (view, tablePosition) => {
  try {
    const dom = view.domAtPos(tablePosition + 1).node;
    let element = dom;
    while (element && element.nodeName !== "TABLE") {
      element = element.parentNode;
    }
    return element;
  } catch {
    return null;
  }
};
//# sourceMappingURL=resize-utils.js.map
