X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/7e6f6af46386e429be4b0ffbb388dad7d2267325..refs/pull/5676/head:/resources/js/wysiwyg/utils/nodes.ts diff --git a/resources/js/wysiwyg/utils/nodes.ts b/resources/js/wysiwyg/utils/nodes.ts index b5cc78955..116a3f4e5 100644 --- a/resources/js/wysiwyg/utils/nodes.ts +++ b/resources/js/wysiwyg/utils/nodes.ts @@ -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,46 @@ 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 $selectOrCreateAdjacent(node: LexicalNode, after: boolean): RangeSelection { + const nearestBlock = $getNearestNodeBlockParent(node) || node; + let target = after ? nearestBlock.getNextSibling() : nearestBlock.getPreviousSibling() + + if (!target) { + target = $createParagraphNode(); + if (after) { + nearestBlock.insertAfter(target) + } else { + nearestBlock.insertBefore(target); + } + } + + return after ? target.selectStart() : target.selectEnd(); +} + export function nodeHasAlignment(node: object): node is NodeHasAlignment { return '__alignment' in node; }