forked from udecode/plate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
withTable.ts
55 lines (42 loc) · 1.35 KB
/
withTable.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { isCollapsed } from 'common/queries/isCollapsed';
import { Editor, Point } from 'slate';
import { TableType, WithTableOptions } from './types';
export const withTable = ({
typeTable = TableType.TABLE,
typeTd = TableType.CELL,
}: WithTableOptions = {}) => <T extends Editor>(editor: T) => {
const { deleteBackward, deleteForward, insertBreak } = editor;
const preventDeleteCell = (operation: any, pointCallback: any) => (
unit: any
) => {
const { selection } = editor;
if (isCollapsed(selection)) {
const [cell] = Editor.nodes(editor, {
match: (n) => n.type === typeTd,
});
if (cell) {
const [, cellPath] = cell;
const start = pointCallback(editor, cellPath);
if (selection && Point.equals(selection.anchor, start)) {
return;
}
}
}
operation(unit);
};
// prevent deleting cells with deleteBackward
editor.deleteBackward = preventDeleteCell(deleteBackward, Editor.start);
// prevent deleting cells with deleteForward
editor.deleteForward = preventDeleteCell(deleteForward, Editor.end);
editor.insertBreak = () => {
const { selection } = editor;
if (selection) {
const [table] = Editor.nodes(editor, {
match: (n) => n.type === typeTable,
});
if (table) return;
}
insertBreak();
};
return editor;
};