]> BookStack Code Mirror - bookstack/blobdiff - resources/js/wysiwyg/utils/nodes.ts
Lexical: Made a range of selection improvements
[bookstack] / resources / js / wysiwyg / utils / nodes.ts
index b5cc789550cda2a0d82f10a09911aef306a54887..ebf01e39ddef50a291a5b5b00558b7e7d1bf1d9b 100644 (file)
@@ -6,7 +6,7 @@ import {
     $isTextNode,
     ElementNode,
     LexicalEditor,
-    LexicalNode
+    LexicalNode, RangeSelection
 } from "lexical";
 import {LexicalNodeMatcher} from "../nodes";
 import {$generateNodesFromDOM} from "@lexical/html";
@@ -94,6 +94,41 @@ export function $getNearestNodeBlockParent(node: LexicalNode): LexicalNode|null
     return $findMatchingParent(node, isBlockNode);
 }
 
+export function $sortNodes(nodes: LexicalNode[]): LexicalNode[] {
+    const idChain: string[] = [];
+    const addIds = (n: ElementNode) => {
+        for (const child of n.getChildren()) {
+            idChain.push(child.getKey())
+            if ($isElementNode(child)) {
+                addIds(child)
+            }
+        }
+    };
+
+    const root = $getRoot();
+    addIds(root);
+
+    const sorted = Array.from(nodes);
+    sorted.sort((a, b) => {
+        const aIndex = idChain.indexOf(a.getKey());
+        const bIndex = idChain.indexOf(b.getKey());
+        return aIndex - bIndex;
+    });
+
+    return sorted;
+}
+
+export function $insertAndSelectNewEmptyAdjacentNode(node: LexicalNode, after: boolean): RangeSelection {
+    const target = $createParagraphNode();
+    if (after) {
+        node.insertAfter(target)
+    } else {
+        node.insertBefore(target);
+    }
+
+    return target.select();
+}
+
 export function nodeHasAlignment(node: object): node is NodeHasAlignment {
     return '__alignment' in node;
 }