Skip to content

Commit

Permalink
Place cursor before uneditable element
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Aug 2, 2023
1 parent 61a2b38 commit cfbd05c
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions codejar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit cfbd05c

Please sign in to comment.