"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var reorder_exports = {};
__export(reorder_exports, {
  moveColumns: () => moveColumns,
  moveRows: () => moveRows,
  reorderColumns: () => reorderColumns,
  reorderColumnsTr: () => reorderColumnsTr,
  reorderRows: () => reorderRows,
  reorderRowsTr: () => reorderRowsTr
});
module.exports = __toCommonJS(reorder_exports);
var import_prosemirror_state = require("prosemirror-state");
var import_cellselection = require("../plugins/cellselection.js");
var import_table_query = require("../table-query.js");
var import_tablemap = require("../tablemap.js");
var import_is_selection_type = require("../utilities/is-selection-type.js");
var import_queries = require("./queries.js");
function selectColumnsTr(tr, fromCol, toCol, tablePos) {
  const $tablePos = tr.doc.resolve(tablePos);
  const tempSelection = import_prosemirror_state.TextSelection.create(tr.doc, $tablePos.pos);
  const table = import_table_query.TableQuery.of(tempSelection);
  if (!table) {
    return;
  }
  const initialRect = { left: fromCol, right: toCol + 1, top: 0, bottom: table.map.height };
  const cells = (0, import_cellselection.getCellsInExpandedRect)(tr.doc, table.getStartPos(), table.map, initialRect);
  const selection = new import_cellselection.RicosCellSelection(cells, tr.doc);
  tr.setSelection(selection);
}
function selectRowsTr(tr, fromRow, toRow, tablePos) {
  const $tablePos = tr.doc.resolve(tablePos);
  const tempSelection = import_prosemirror_state.TextSelection.create(tr.doc, $tablePos.pos);
  const table = import_table_query.TableQuery.of(tempSelection);
  if (!table) {
    return;
  }
  const initialRect = { left: 0, right: table.map.width, top: fromRow, bottom: toRow + 1 };
  const cells = (0, import_cellselection.getCellsInExpandedRect)(tr.doc, table.getStartPos(), table.map, initialRect);
  const selection = new import_cellselection.RicosCellSelection(cells, tr.doc);
  tr.setSelection(selection);
}
function reorderRowsTr(tr, state, from, to) {
  const table = import_table_query.TableQuery.of(state.selection);
  if (!table) {
    return;
  }
  const tableStart = table.getStartPos();
  const tableNode = table.getNode();
  const hadHeaderRow = (0, import_queries.rowIsHeader)(table.map, tableNode, 0);
  const hadHeaderCol = hadHeaderRow && (0, import_queries.columnIsHeader)(table.map, tableNode, 0);
  const draggedRows = [];
  const rowsToDelete = [];
  tableNode.forEach((row, offset, index) => {
    if (index >= from.start && index <= from.end) {
      draggedRows.push(row);
      rowsToDelete.push({
        pos: tableStart + offset,
        node: row
      });
    }
  });
  let rowPos = tableStart;
  for (let i = 0; i < to; i++) {
    rowPos += tableNode.child(i).nodeSize;
  }
  tr.insert(rowPos, draggedRows);
  rowsToDelete.sort((a, b) => b.pos - a.pos).forEach(({ pos, node }) => {
    const mappedPos = tr.mapping.map(pos);
    tr.delete(mappedPos, mappedPos + node.nodeSize);
  });
  if (hadHeaderRow) {
    const tablePos = tr.mapping.map(tableStart - 1);
    const newTable = tr.doc.nodeAt(tablePos);
    const types = (0, import_queries.tableNodeTypes)(newTable.type.schema);
    const newMap = import_tablemap.TableMap.get(newTable);
    newMap.forEachCell((cellPos, placement) => {
      const cell = newTable.nodeAt(cellPos);
      const shouldBeHeader = placement.row === 0 || hadHeaderCol && placement.col === 0;
      const expected = shouldBeHeader ? types.header_cell : types.cell;
      if (cell.type !== expected) {
        tr.setNodeMarkup(tablePos + 1 + cellPos, expected, cell.attrs);
      }
    });
  }
}
function reorderColumnsTr(tr, state, from, to) {
  const table = import_table_query.TableQuery.of(state.selection);
  if (!table) {
    return;
  }
  const tableStart = table.getStartPos();
  const tableNode = table.getNode();
  const map = table.map;
  const hadHeaderCol = (0, import_queries.columnIsHeader)(map, tableNode, 0);
  const hadHeaderRow = hadHeaderCol && (0, import_queries.rowIsHeader)(map, tableNode, 0);
  let expandedStart = from.start;
  let expandedEnd = from.end;
  for (let row = 0; row < map.height; row++) {
    for (let col = from.start; col <= from.end; col++) {
      const cellPos = map.map[row * map.width + col];
      const placement = map.findCell(cellPos);
      if (placement.col < expandedStart) {
        expandedStart = placement.col;
      }
      if (placement.col + placement.colspan - 1 > expandedEnd) {
        expandedEnd = placement.col + placement.colspan - 1;
      }
    }
  }
  const dimensions = tableNode.attrs.dimensions;
  if (dimensions?.colsWidthRatio?.length > 0) {
    const colsWidthRatio = [...dimensions.colsWidthRatio];
    const colsMinWidth = dimensions.colsMinWidth ? [...dimensions.colsMinWidth] : [];
    const numColsToMove = expandedEnd - expandedStart + 1;
    const movedWidthRatios = colsWidthRatio.splice(expandedStart, numColsToMove);
    const movedMinWidths = colsMinWidth.splice(expandedStart, numColsToMove);
    const insertIndex = to > expandedStart ? to - numColsToMove : to;
    colsWidthRatio.splice(insertIndex, 0, ...movedWidthRatios);
    if (colsMinWidth.length > 0) {
      colsMinWidth.splice(insertIndex, 0, ...movedMinWidths);
    }
    const newDimensions = {
      ...dimensions,
      colsWidthRatio,
      colsMinWidth: colsMinWidth.length > 0 ? colsMinWidth : dimensions.colsMinWidth
    };
    tr.setNodeMarkup(tableStart - 1, null, {
      ...tableNode.attrs,
      dimensions: newDimensions
    });
  }
  const cellsToDelete = [];
  tableNode.forEach((row, rowOffset, rowIndex) => {
    const cellsToInsert = [];
    for (let col = expandedStart; col <= expandedEnd; col++) {
      const mapPos = map.map[rowIndex * map.width + col];
      const placement = map.findCell(mapPos);
      if (placement.col === col && placement.row === rowIndex) {
        const cellNode = tableNode.nodeAt(mapPos);
        if (cellNode) {
          cellsToInsert.push(cellNode);
          const cellPosInTable = mapPos;
          cellsToDelete.push({
            pos: tableStart + cellPosInTable,
            node: cellNode
          });
        }
      }
    }
    if (cellsToInsert.length > 0) {
      const dropPosRel = map.positionAt(rowIndex, to, tableNode);
      const insertPos = tr.mapping.map(tableStart + dropPosRel);
      tr.insert(insertPos, cellsToInsert);
    }
  });
  cellsToDelete.sort((a, b) => b.pos - a.pos).forEach(({ pos, node }) => {
    const mappedPos = tr.mapping.map(pos);
    tr.delete(mappedPos, mappedPos + node.nodeSize);
  });
  if (hadHeaderCol) {
    const tablePos = tr.mapping.map(tableStart - 1);
    const newTable = tr.doc.nodeAt(tablePos);
    const types = (0, import_queries.tableNodeTypes)(newTable.type.schema);
    const newMap = import_tablemap.TableMap.get(newTable);
    newMap.forEachCell((cellPos, placement) => {
      const cell = newTable.nodeAt(cellPos);
      const shouldBeHeader = placement.col === 0 || hadHeaderRow && placement.row === 0;
      const expected = shouldBeHeader ? types.header_cell : types.cell;
      if (cell.type !== expected) {
        tr.setNodeMarkup(tablePos + 1 + cellPos, expected, cell.attrs);
      }
    });
  }
}
const reorderRows = (from, to) => (state, dispatch) => {
  const table = import_table_query.TableQuery.of(state.selection);
  if (!table) {
    return false;
  }
  if (!dispatch) {
    return true;
  }
  const tr = state.tr;
  reorderRowsTr(tr, state, from, to);
  dispatch(tr);
  return true;
};
const reorderColumns = (from, to) => (state, dispatch) => {
  const table = import_table_query.TableQuery.of(state.selection);
  if (!table) {
    return false;
  }
  if (!dispatch) {
    return true;
  }
  const tr = state.tr;
  reorderColumnsTr(tr, state, from, to);
  dispatch(tr);
  return true;
};
const moveColumns = (direction) => (state, dispatch, view) => {
  const table = import_table_query.TableQuery.of(state.selection);
  if (!table || !(0, import_is_selection_type.isRicosCellSelection)(state.selection)) {
    return false;
  }
  const rect = (0, import_is_selection_type.isRicosCellSelection)(state.selection) ? state.selection.getRect() : (0, import_queries.selectedRect)(state);
  if (rect.top !== 0 || rect.bottom !== table.getHeight()) {
    return false;
  }
  const firstCol = rect.left;
  const lastCol = rect.right - 1;
  const colWidth = rect.right - rect.left;
  const targetCol = direction === "left" ? firstCol - 1 : lastCol + 1;
  const tableStart = table.getStartPos();
  if (targetCol < 0 || targetCol > table.getWidth()) {
    return false;
  }
  let newTargetCol = targetCol;
  if (targetCol > 0 && targetCol < table.map.width) {
    const cellColStartPos = targetCol;
    const cellColEndPos = table.map.width * (table.map.height - 1) + cellColStartPos;
    const targetRect = table.map.rectBetween(
      table.map.map[cellColStartPos],
      table.map.map[cellColEndPos]
    );
    newTargetCol = direction === "left" ? targetRect.left : targetRect.right;
  }
  const finalColStart = direction === "left" ? newTargetCol : newTargetCol - colWidth;
  const finalColEnd = finalColStart + colWidth - 1;
  if (!dispatch) {
    return true;
  }
  const tr = state.tr;
  reorderColumnsTr(tr, state, { start: firstCol, end: lastCol }, newTargetCol);
  selectColumnsTr(tr, finalColStart, finalColEnd, tableStart);
  dispatch(tr);
  view?.focus();
  return true;
};
const moveRows = (direction) => (state, dispatch, view) => {
  const table = import_table_query.TableQuery.of(state.selection);
  if (!table || !(0, import_is_selection_type.isRicosCellSelection)(state.selection)) {
    return false;
  }
  const rect = (0, import_is_selection_type.isRicosCellSelection)(state.selection) ? state.selection.getRect() : (0, import_queries.selectedRect)(state);
  if (rect.left !== 0 || rect.right !== table.getWidth()) {
    return false;
  }
  const firstRow = rect.top;
  const lastRow = rect.bottom - 1;
  const targetRow = direction === "up" ? firstRow - 1 : lastRow + 1;
  const rowHeight = rect.bottom - rect.top;
  const tableStart = table.getStartPos();
  if (targetRow < 0 || targetRow > table.getHeight()) {
    return false;
  }
  let newTargetRow = targetRow;
  if (targetRow < table.map.height) {
    const toRowStart = targetRow * table.map.width;
    const toRowEnd = toRowStart + table.map.width - 1;
    const toRect = table.map.rectBetween(table.map.map[toRowStart], table.map.map[toRowEnd]);
    newTargetRow = direction === "up" ? toRect.top : toRect.bottom;
  }
  const finalRowStart = direction === "up" ? newTargetRow : newTargetRow - rowHeight;
  const finalRowEnd = finalRowStart + rowHeight - 1;
  if (!dispatch) {
    return true;
  }
  const tr = state.tr;
  reorderRowsTr(tr, state, { start: firstRow, end: lastRow }, newTargetRow);
  selectRowsTr(tr, finalRowStart, finalRowEnd, tableStart);
  dispatch(tr);
  view?.focus();
  return true;
};
//# sourceMappingURL=reorder.js.map
