Skip to content

Commit d274b80

Browse files
committed
Added shortcut to delete table while it's empty and all cells are selected
1 parent ac38a1b commit d274b80

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

packages/core/src/blocks/Table/block.ts

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Node, mergeAttributes } from "@tiptap/core";
22
import { DOMParser, Fragment, Node as PMNode, Schema } from "prosemirror-model";
3-
import { TableView } from "prosemirror-tables";
3+
import { CellSelection, TableMap, TableView } from "prosemirror-tables";
44
import { NodeView } from "prosemirror-view";
55
import { createBlockNoteExtension } from "../../editor/BlockNoteExtension.js";
66
import {
@@ -265,6 +265,59 @@ const TiptapTableParagraph = Node.create({
265265
group: "tableContent",
266266
content: "inline*",
267267

268+
addKeyboardShortcuts() {
269+
return {
270+
// If the table is empty while all cells are selected, deletes the table.
271+
Backspace: ({ editor }) => {
272+
if (!(editor.state.selection instanceof CellSelection)) {
273+
return false;
274+
}
275+
276+
const anchorCellColIndex = editor.state.selection.$anchorCell.index();
277+
const anchorCellRowIndex = editor.state.selection.$anchorCell.index(-1);
278+
const headCellColIndex = editor.state.selection.$headCell.index();
279+
const headCellRowIndex = editor.state.selection.$headCell.index(-1);
280+
281+
const minColIndex = Math.min(anchorCellColIndex, headCellColIndex);
282+
const maxColIndex = Math.max(anchorCellColIndex, headCellColIndex);
283+
const minRowIndex = Math.min(anchorCellRowIndex, headCellRowIndex);
284+
const maxRowIndex = Math.max(anchorCellRowIndex, headCellRowIndex);
285+
286+
const posBeforeTable = editor.state.selection.$anchorCell.before(-1);
287+
const tableNode = editor.state.doc.resolve(posBeforeTable).nodeAfter!;
288+
289+
const tableMap = TableMap.get(tableNode);
290+
291+
if (
292+
minColIndex !== 0 ||
293+
maxColIndex !== tableMap.width - 1 ||
294+
minRowIndex !== 0 ||
295+
maxRowIndex !== tableMap.height - 1
296+
) {
297+
return false;
298+
}
299+
300+
for (
301+
let cellIndex = 0;
302+
cellIndex < tableMap.height * tableMap.width;
303+
cellIndex++
304+
) {
305+
const posBeforeCell = posBeforeTable + tableMap.map[cellIndex] + 1;
306+
const cellNode = editor.state.doc.resolve(posBeforeCell).nodeAfter!;
307+
308+
if (cellNode.firstChild && cellNode.firstChild?.content.size > 0) {
309+
return false;
310+
}
311+
}
312+
313+
return editor.commands.deleteRange({
314+
from: posBeforeTable,
315+
to: posBeforeTable + tableNode.nodeSize,
316+
});
317+
},
318+
};
319+
},
320+
268321
parseHTML() {
269322
return [
270323
{

0 commit comments

Comments
 (0)