Skip to content

Commit

Permalink
Properly save selection state when the selection root is the editor (#82
Browse files Browse the repository at this point in the history
)

In cases where the cursor is at the beginning/end of the text or when all of the text is selected, window.getSelection() can specify the selection with respect to the editor instead of specific text nodes.
This change adds support for saving selection state in save() when this is the case.
Fixes #75
  • Loading branch information
moderatelyConfused committed Jul 31, 2022
1 parent 112370c commit f7e41cf
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions codejar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,15 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
let {anchorNode, anchorOffset, focusNode, focusOffset} = s
if (!anchorNode || !focusNode) throw 'error1'

// If the anchor and focus are the editor element, return either a full
// highlight or a start/end cursor position depending on the selection
if (anchorNode === editor && focusNode === editor) {
pos.start = (anchorOffset > 0 && editor.textContent) ? editor.textContent.length : 0
pos.end = (focusOffset > 0 && editor.textContent) ? editor.textContent.length : 0
pos.dir = (focusOffset >= anchorOffset) ? '->' : '<-'
return pos
}

// Selection anchor and focus are expected to be text nodes,
// so normalize them.
if (anchorNode.nodeType === Node.ELEMENT_NODE) {
Expand Down

0 comments on commit f7e41cf

Please sign in to comment.