]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/services/keyboard-handling.ts
Lexical: Added single node backspace/delete support
[bookstack] / resources / js / wysiwyg / services / keyboard-handling.ts
1 import {EditorUiContext} from "../ui/framework/core";
2 import {
3     $isDecoratorNode,
4     COMMAND_PRIORITY_LOW,
5     KEY_BACKSPACE_COMMAND,
6     KEY_DELETE_COMMAND,
7     LexicalEditor
8 } from "lexical";
9 import {$isImageNode} from "../nodes/image";
10 import {$isMediaNode} from "../nodes/media";
11 import {getLastSelection} from "../utils/selection";
12
13 function deleteSingleSelectedNode(editor: LexicalEditor) {
14     const selectionNodes = getLastSelection(editor)?.getNodes() || [];
15     if (selectionNodes.length === 1) {
16         const node = selectionNodes[0];
17         if ($isDecoratorNode(node) || $isImageNode(node) || $isMediaNode(node)) {
18             editor.update(() => {
19                 node.remove();
20             });
21         }
22     }
23 }
24
25 export function registerKeyboardHandling(context: EditorUiContext): () => void {
26     const unregisterBackspace = context.editor.registerCommand(KEY_BACKSPACE_COMMAND, (): boolean => {
27         deleteSingleSelectedNode(context.editor);
28         return false;
29     }, COMMAND_PRIORITY_LOW);
30
31     const unregisterDelete = context.editor.registerCommand(KEY_DELETE_COMMAND, (): boolean => {
32         deleteSingleSelectedNode(context.editor);
33         return false;
34     }, COMMAND_PRIORITY_LOW);
35
36     return () => {
37           unregisterBackspace();
38           unregisterDelete();
39     };
40 }