From cfbd05c2f60f7cb90b4ab7039077ebd34efd9a8f Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Wed, 2 Aug 2023 02:23:16 +0200 Subject: [PATCH] Place cursor before uneditable element --- codejar.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/codejar.ts b/codejar.ts index 0926449..c7c009b 100644 --- a/codejar.ts +++ b/codejar.ts @@ -254,9 +254,39 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P [startNode, startOffset, endNode, endOffset] = [endNode, endOffset, startNode, startOffset] } + { + // If nodes not editable, create a text node. + const startEl = uneditable(startNode) + if (startEl) { + const node = document.createTextNode('') + startEl.parentNode?.insertBefore(node, startEl) + startNode = node + startOffset = 0 + } + const endEl = uneditable(endNode) + if (endEl) { + const node = document.createTextNode('') + endEl.parentNode?.insertBefore(node, endEl) + endNode = node + endOffset = 0 + } + } + s.setBaseAndExtent(startNode, startOffset, endNode, endOffset) } + function uneditable(node: Node): Element | undefined { + while (node && node !== editor) { + if (node.nodeType === Node.ELEMENT_NODE) { + const el = node as Element + if (el.getAttribute('contenteditable') == 'false') { + return el + } + } + node = node.parentNode! + } + } + function beforeCursor() { const s = getSelection() const r0 = s.getRangeAt(0)