diff --git a/.changeset/real-clouds-accept.md b/.changeset/real-clouds-accept.md new file mode 100644 index 000000000..850177504 --- /dev/null +++ b/.changeset/real-clouds-accept.md @@ -0,0 +1,5 @@ +--- +'slate-dom': patch +--- + +Search backward and forward for leaf nodes in non contenteditable elements inside `toSlatePoint` diff --git a/packages/slate-dom/src/plugin/dom-editor.ts b/packages/slate-dom/src/plugin/dom-editor.ts index 065d5da28..ba2bdb329 100644 --- a/packages/slate-dom/src/plugin/dom-editor.ts +++ b/packages/slate-dom/src/plugin/dom-editor.ts @@ -697,7 +697,7 @@ export const DOMEditor: DOMEditorInterface = { searchDirection?: 'forward' | 'backward' } ): T extends true ? Point | null : Point => { - const { exactMatch, suppressThrow, searchDirection = 'backward' } = options + const { exactMatch, suppressThrow, searchDirection } = options const [nearestNode, nearestOffset] = exactMatch ? domPoint : normalizeDOMPoint(domPoint) @@ -812,20 +812,32 @@ export const DOMEditor: DOMEditorInterface = { '[data-slate-node="element"]' ) - if (searchDirection === 'forward') { - const leafNodes = [ - ...getLeafNodes(elementNode), - ...getLeafNodes(elementNode?.nextElementSibling), - ] - leafNode = - leafNodes.find(leaf => isAfter(nonEditableNode, leaf)) ?? null - } else { + if (searchDirection === 'backward' || !searchDirection) { const leafNodes = [ ...getLeafNodes(elementNode?.previousElementSibling), ...getLeafNodes(elementNode), ] + leafNode = leafNodes.findLast(leaf => isBefore(nonEditableNode, leaf)) ?? null + + if (leafNode) { + searchDirection === 'backward' + } + } + + if (searchDirection === 'forward' || !searchDirection) { + const leafNodes = [ + ...getLeafNodes(elementNode), + ...getLeafNodes(elementNode?.nextElementSibling), + ] + + leafNode = + leafNodes.find(leaf => isAfter(nonEditableNode, leaf)) ?? null + + if (leafNode) { + searchDirection === 'forward' + } } if (leafNode) {