@atlaskit/editor-plugin-table
Version:
Table plugin for the @atlaskit/editor
62 lines (58 loc) • 2.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.updateCellsMarkup = exports.replaceCells = void 0;
// TODO: ED-26961 - move to prosemirror-utils
var replaceCells = exports.replaceCells = function replaceCells(tr, table, tablePos, modifyCell) {
var rows = [];
var modifiedCells = 0;
for (var rowIndex = 0; rowIndex < table.childCount; rowIndex++) {
var row = table.child(rowIndex);
var cells = [];
for (var colIndex = 0; colIndex < row.childCount; colIndex++) {
var cell = row.child(colIndex);
// TODO: ED-26961 - The rowIndex and colIndex are not accurate in a merged cell scenario
// e.g. table with 5 columns might have only one cell in a row, colIndex will be 1, where it should be 4
var node = modifyCell(cell, rowIndex, colIndex);
if (node.sameMarkup(cell) === false) {
modifiedCells++;
}
cells.push(node);
}
if (cells.length) {
rows.push(row.type.createChecked(row.attrs, cells, row.marks));
}
}
// Check if the table has changed before replacing.
// If no cells are modified our counter will be zero.
if (rows.length && modifiedCells !== 0) {
var newTable = table.type.createChecked(table.attrs, rows, table.marks);
return tr.replaceWith(tablePos, tablePos + table.nodeSize, newTable);
}
return tr;
};
/**
* Position-preserving alternative to `replaceCells`.
*
* Uses `setNodeMarkup` per cell instead of rebuilding the whole table with
* `replaceWith`, so document positions inside cells are never invalidated.
* This preserves any existing selection through `tr.mapping`.
*/
var updateCellsMarkup = exports.updateCellsMarkup = function updateCellsMarkup(tr, table, tablePos, modifyCell) {
var rowOffset = tablePos + 1;
for (var rowIndex = 0; rowIndex < table.childCount; rowIndex++) {
var row = table.child(rowIndex);
var cellOffset = rowOffset + 1;
for (var colIndex = 0; colIndex < row.childCount; colIndex++) {
var cell = row.child(colIndex);
var modified = modifyCell(cell, rowIndex, colIndex);
if (!modified.sameMarkup(cell)) {
tr.setNodeMarkup(cellOffset, modified.type, modified.attrs, modified.marks);
}
cellOffset += cell.nodeSize;
}
rowOffset += row.nodeSize;
}
return tr;
};