Skip to content

Commit

Permalink
sync indices
Browse files Browse the repository at this point in the history
  • Loading branch information
dimaanj committed Nov 15, 2023
1 parent 2b5f379 commit 8ee4a9e
Show file tree
Hide file tree
Showing 9 changed files with 109 additions and 91 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo } from 'react';
import { useEffect } from 'react';
import {
getPluginOptions,
useEditorRef,
Expand Down Expand Up @@ -59,45 +59,60 @@ export const useTableCellElementState = ({

const tableElement = useElement<TTableElement>(ELEMENT_TABLE);
const rowElement = useElement<TTableRowElement>(ELEMENT_TR);
const rowSizeOverrides = useTableStore().get.rowSizeOverrides();

const { _cellIndices } = useMemo(
() => getPluginOptions<TablePlugin>(editor as any, ELEMENT_TABLE),
[editor]
const { disableCellsMerging, _cellIndices } = getPluginOptions<TablePlugin>(
editor as any,
ELEMENT_TABLE
);
if (disableCellsMerging) {
const colIndex = getTableColumnIndex(editor, cellElement);
const rowIndex = getTableRowIndex(editor, cellElement);

const rowSize =
rowSizeOverrides.get(rowIndex) ?? rowElement?.size ?? undefined;

const isFirstCell = colIndex === 0;
const isFirstRow = tableElement.children?.[0] === rowElement;

const borders = getTableCellBorders(cellElement, {
isFirstCell,
isFirstRow,
});

return {
colIndex,
rowIndex,
readOnly: !ignoreReadOnly && readOnly,
selected: isCellSelected,
hovered: hoveredColIndex === colIndex,
hoveredLeft: isFirstCell && hoveredColIndex === -1,
rowSize,
borders,
isSelectingCell: !!selectedCells,
colSpan,
};
}

let x: { col: number; row: number };
const fromWeakMap = _cellIndices.get(cellElement);
// const cellContent = cellElement.children.map((i) => {
// return (i.children as any)[0].text;
// });
let result: { col: number; row: number };

// const spans = {
// colSpan: getColSpan(cellElement),
// rowSpan: getRowSpan(cellElement),
// };
const calculated =
_cellIndices.get(cellElement) ||
computeCellIndices(editor, tableElement, cellElement);

if (fromWeakMap) {
x = fromWeakMap;
// console.log('cellContent', cellContent, x);
if (calculated) {
result = calculated;
} else {
const x1 = computeCellIndices(editor, tableElement, cellElement);
if (x1) {
x = x1;
// console.log('computed', x, 'cellContent', cellContent, 'spans', spans);
} else {
const defaultColIndex = getTableColumnIndex(editor, cellElement);
const defaultRowIndex = getTableRowIndex(editor, cellElement);
x = { col: defaultColIndex, row: defaultRowIndex };
// console.log('get default', x, 'cellContent', cellContent);
}
const defaultColIndex = getTableColumnIndex(editor, cellElement);
const defaultRowIndex = getTableRowIndex(editor, cellElement);
result = { col: defaultColIndex, row: defaultRowIndex };
}
const colIndex = x.col;
const rowIndex = x.row;
const colIndex = result.col;
const rowIndex = result.row;

const endingRowIndex = rowIndex + rowSpan - 1;
const endingColIndex = colIndex + colSpan - 1;

const rowSizeOverrides = useTableStore().get.rowSizeOverrides();
const rowSize =
rowSizeOverrides.get(endingRowIndex) ?? rowElement?.size ?? undefined;

Expand Down
12 changes: 2 additions & 10 deletions packages/table/src/components/TableElement/useTableElement.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useEffect } from 'react';
import {
collapseSelection,
getPluginOptions,
Expand All @@ -7,7 +6,6 @@ import {
} from '@udecode/plate-common';

import { ELEMENT_TABLE } from '../../createTablePlugin';
import { computeAllCellIndices } from '../../merge/computeCellIndices';
import { useTableStore } from '../../stores/tableStore';
import { TablePlugin, TTableElement } from '../../types';
import { useSelectedCells } from './useSelectedCells';
Expand All @@ -30,10 +28,8 @@ export const useTableElementState = ({
} = {}): TableElementState => {
const editor = useEditorRef();

const { minColumnWidth, disableMarginLeft } = getPluginOptions<TablePlugin>(
editor,
ELEMENT_TABLE
);
const { minColumnWidth, disableMarginLeft, disableCellsMerging } =
getPluginOptions<TablePlugin>(editor, ELEMENT_TABLE);

const element = useElement<TTableElement>();
const selectedCells = useTableStore().get.selectedCells();
Expand All @@ -45,10 +41,6 @@ export const useTableElementState = ({

let colSizes = useTableColSizes(element);

useEffect(() => {
computeAllCellIndices(editor, element);
}, [editor, element]);

if (transformColSizes) {
colSizes = transformColSizes(colSizes);
}
Expand Down
25 changes: 2 additions & 23 deletions packages/table/src/merge/computeCellIndices.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import {
findNodePath,
getPluginOptions,
PlateEditor,
Value,
} from '@udecode/plate-common';
import { getPluginOptions, PlateEditor, Value } from '@udecode/plate-common';

import { ELEMENT_TABLE } from '../createTablePlugin';
import {
Expand Down Expand Up @@ -62,7 +57,7 @@ export function computeCellIndices<V extends Value>(
});

if (rowIndex === -1 || colIndex === -1) {
console.log('Invalid cell location.');
console.log('Invalid cell location.', rowIndex, colIndex);
return null;
}

Expand All @@ -78,34 +73,18 @@ export const computeAllCellIndices = <V extends Value>(
) => {
const options = getPluginOptions<TablePlugin, V>(editor, ELEMENT_TABLE);

// Initialize an array to store the indices of each cell
const cellIndicesArray = [];

// const tablePath = findNodePath(editor, tableNode)!;

// Iterate through the table rows
for (let r = 0; r < tableNode.children.length; r++) {
const row = tableNode.children[r] as TTableRowElement;
const rowIndicesArray = [];

// Iterate through the row cells
for (let c = 0; c < row.children.length; c++) {
const cell = row.children[c] as TTableCellElement;

// Get cell indices and store them in the row's array
// const cellPath = [r, c];

const indices = computeCellIndices(editor, tableNode, cell);
if (indices) {
options._cellIndices.set(cell, indices);
}
rowIndicesArray.push(indices);
}

// Push the rowIndicesArray to the cellIndicesArray
cellIndicesArray.push(rowIndicesArray);
// console.log('calculated array', cellIndicesArray);
}

return cellIndicesArray;
};
1 change: 1 addition & 0 deletions packages/table/src/merge/deleteRow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
TTableRowElement,
} from '../types';
import { getCellTypes } from '../utils';
import { computeAllCellIndices } from './computeCellIndices';
import { findCellByIndexes } from './findCellByIndexes';
import { getIndices } from './getIndices';

Expand Down
3 changes: 1 addition & 2 deletions packages/table/src/merge/findCellByIndexes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,20 @@ export const findCellByIndexes = <V extends Value>(
(current) => current.children
) as TTableCellElement[];

// console.log('searching for', searchRowIndex, searchColIndex);
const foundCell = allCells.find((cell) => {
const cellElement = cell as TTableCellElement;

const indices =
getIndices(options, cellElement) ||
computeCellIndices(editor, table, cellElement)!;
// getIndices(options, cellElement)!;

const { col: _startColIndex, row: _startRowIndex } = indices;
const { row: _endRowIndex, col: _endColIndex } = getIndicesWithSpans(
indices,
cellElement
);

// console.log('current', colIndex, endColIndex, rowIndex, endRowIndex);
if (
searchColIndex >= _startColIndex &&
searchColIndex <= _endColIndex &&
Expand Down
19 changes: 0 additions & 19 deletions packages/table/src/merge/mergeTableCells.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,24 +106,5 @@ export const mergeTableCells = <V extends Value = Value>(

// insert the new merged cell in place of the first cell in the selection
insertElements(editor, mergedCell, { at: cellEntries[0][1] });

// /**
// * Update cell indices in weak map
// */
// const tableEntry = findNode(editor, {
// at: cellEntries[0][1],
// match: { type: getPluginType(editor, ELEMENT_TABLE) },
// })!; // TODO: improve typing
// const cellEntry = findNode(editor, {
// at: cellEntries[0][1],
// match: { type: getCellTypes(editor) },
// })!; // TODO: improve typing

// const realTable = tableEntry[0] as TTableElement;
// const mC = cellEntry[0] as TTableCellElement;
// console.log('realTable', realTable, 'mC', mC);

// computeCellIndices(editor, realTable, mC);
// console.log('should be computed');
});
};
9 changes: 1 addition & 8 deletions packages/table/src/merge/unmergeTableCells.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,7 @@ import {
import { ELEMENT_TABLE, ELEMENT_TR } from '../createTablePlugin';
import { getTableGridAbove } from '../queries';
import { getColSpan } from '../queries/getColSpan';
import {
TablePlugin,
TTableCellElement,
TTableElement,
TTableRowElement,
} from '../types';
import { TablePlugin, TTableCellElement, TTableRowElement } from '../types';
import { getEmptyCellNode } from '../utils';

export const unmergeTableCells = <V extends Value = Value>(
Expand Down Expand Up @@ -73,12 +68,10 @@ export const unmergeTableCells = <V extends Value = Value>(
const { col: c } = options._cellIndices.get(item as TTableCellElement)!;
if (c === col - 1) {
newColPath = rowEl.children.indexOf(item) + 1;
// console.log('found first', newColPath);
break;
}
if (col + getColSpan(cellElem as TTableCellElement) === c - 1) {
newColPath = rowEl.children.indexOf(item);
// console.log('found last', newColPath);
break;
}
}
Expand Down
54 changes: 54 additions & 0 deletions packages/table/src/withMergedCells.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {
getBlockAbove,
getPluginType,
PlateEditor,
TElement,
Value,
} from '@udecode/plate-common';
import { BaseSelection } from 'slate';

import {
ELEMENT_TABLE,
ELEMENT_TD,
ELEMENT_TH,
ELEMENT_TR,
} from './createTablePlugin';
import { computeAllCellIndices } from './merge/computeCellIndices';
import { TTableElement } from './types';

export const withMergedCells = <
V extends Value = Value,
E extends PlateEditor<V> = PlateEditor<V>,
>(
editor: E
) => {
const { apply } = editor;

editor.apply = (op) => {
const needsSync =
op.type === 'insert_node' ||
op.type === 'merge_node' ||
op.type === 'move_node' ||
op.type === 'remove_node' ||
op.type === 'set_node';

const updateTable = (selection: BaseSelection) => {
const tableEntry = getBlockAbove(editor, {
at: selection?.anchor,
match: { type: getPluginType(editor, ELEMENT_TABLE) },
});
if (tableEntry) {
const realTable = tableEntry[0] as TTableElement;
computeAllCellIndices(editor, realTable);
}
};

if (needsSync) {
updateTable(editor.selection);
}

apply(op);
};

return editor;
};
4 changes: 4 additions & 0 deletions packages/table/src/withTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { withDeleteTable } from './withDeleteTable';
import { withGetFragmentTable } from './withGetFragmentTable';
import { withInsertFragmentTable } from './withInsertFragmentTable';
import { withInsertTextTable } from './withInsertTextTable';
import { withMergedCells } from './withMergedCells';
import { withNormalizeTable } from './withNormalizeTable';
import { withSelectionTable } from './withSelectionTable';
import { withSetFragmentDataTable } from './withSetFragmentDataTable';
Expand All @@ -16,6 +17,9 @@ export const withTable = <
editor: E,
plugin: WithPlatePlugin<TablePlugin<V>, V, E>
) => {
editor = plugin.options.disableCellsMerging
? editor
: withMergedCells<V, E>(editor);
editor = withNormalizeTable<V, E>(editor);
editor = withDeleteTable<V, E>(editor);
editor = withGetFragmentTable<V, E>(editor);
Expand Down

0 comments on commit 8ee4a9e

Please sign in to comment.