Skip to content

Commit 01136f7

Browse files
Added delete handling (#372)
1 parent 8d4fb2d commit 01136f7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

packages/core/src/extensions/Blocks/nodes/BlockContainer.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,51 @@ export const BlockContainer = Node.create<{
485485
}),
486486
]);
487487

488+
const handleDelete = () =>
489+
this.editor.commands.first(({ commands }) => [
490+
// Deletes the selection if it's not empty.
491+
() => commands.deleteSelection(),
492+
// Merges block with the next one (at the same nesting level or lower),
493+
// if one exists, the block has no children, and the selection is at the
494+
// end of the block.
495+
() =>
496+
commands.command(({ state }) => {
497+
const { node, contentNode, depth, endPos } = getBlockInfoFromPos(
498+
state.doc,
499+
state.selection.from
500+
)!;
501+
502+
const blockAtDocEnd = false;
503+
const selectionAtBlockEnd =
504+
state.selection.$anchor.parentOffset ===
505+
contentNode.firstChild!.nodeSize;
506+
const selectionEmpty =
507+
state.selection.anchor === state.selection.head;
508+
const hasChildBlocks = node.childCount === 2;
509+
510+
if (
511+
!blockAtDocEnd &&
512+
selectionAtBlockEnd &&
513+
selectionEmpty &&
514+
!hasChildBlocks
515+
) {
516+
let oldDepth = depth;
517+
let newPos = endPos + 2;
518+
let newDepth = state.doc.resolve(newPos).depth;
519+
520+
while (newDepth < oldDepth) {
521+
oldDepth = newDepth;
522+
newPos += 2;
523+
newDepth = state.doc.resolve(newPos).depth;
524+
}
525+
526+
return commands.BNMergeBlocks(newPos - 1);
527+
}
528+
529+
return false;
530+
}),
531+
]);
532+
488533
const handleEnter = () =>
489534
this.editor.commands.first(({ commands }) => [
490535
// Removes a level of nesting if the block is empty & indented, while the selection is also empty & at the start
@@ -571,6 +616,7 @@ export const BlockContainer = Node.create<{
571616

572617
return {
573618
Backspace: handleBackspace,
619+
Delete: handleDelete,
574620
Enter: handleEnter,
575621
// Always returning true for tab key presses ensures they're not captured by the browser. Otherwise, they blur the
576622
// editor since the browser will try to use tab for keyboard navigation.

0 commit comments

Comments
 (0)