]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/helpers.ts
720f3c6d5dab9b820eee5974c2f405c6cc3c5142
[bookstack] / resources / js / wysiwyg / helpers.ts
1 import {$createParagraphNode, $getSelection, BaseSelection, LexicalEditor} from "lexical";
2 import {LexicalElementNodeCreator, LexicalNodeMatcher} from "./nodes";
3 import {$getNearestBlockElementAncestorOrThrow} from "@lexical/utils";
4 import {$setBlocksType} from "@lexical/selection";
5
6 export function selectionContainsNodeType(selection: BaseSelection|null, matcher: LexicalNodeMatcher): boolean {
7     if (!selection) {
8         return false;
9     }
10
11     for (const node of selection.getNodes()) {
12         if (matcher(node)) {
13             return true;
14         }
15
16         for (const parent of node.getParents()) {
17             if (matcher(parent)) {
18                 return true;
19             }
20         }
21     }
22
23     return false;
24 }
25
26 export function toggleSelectionBlockNodeType(editor: LexicalEditor, matcher: LexicalNodeMatcher, creator: LexicalElementNodeCreator) {
27     editor.update(() => {
28         const selection = $getSelection();
29         const blockElement = selection ? $getNearestBlockElementAncestorOrThrow(selection.getNodes()[0]) : null;
30         if (selection && matcher(blockElement)) {
31             $setBlocksType(selection, $createParagraphNode);
32         } else {
33             $setBlocksType(selection, creator);
34         }
35     });
36 }