Skip to content

Commit

Permalink
Restore focus if manipulating the DOM selection moves it into the editor
Browse files Browse the repository at this point in the history
FIX: Fix a bug where the editor could take focus when content changes required it to
restore the DOM selection.

See https://discuss.codemirror.net/t/how-to-add-decoration-without-focusing-the-editor-on-dispatch/6283
  • Loading branch information
marijnh committed Apr 16, 2023
1 parent 9fdf90a commit f49f2ee
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/docview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ export class DocView extends ContentView {
// Sync the DOM selection to this.state.selection
updateSelection(mustRead = false, fromPointer = false) {
if (mustRead || !this.view.observer.selectionRange.focusNode) this.view.observer.readSelectionRange()
if (!(fromPointer || this.mayControlSelection())) return
let activeElt = this.view.root.activeElement, focused = activeElt == this.dom
let selectionNotFocus = !focused &&
hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt))
if (!(focused || fromPointer || selectionNotFocus)) return
let force = this.forceSelection
this.forceSelection = false

Expand Down Expand Up @@ -210,6 +213,10 @@ export class DocView extends ContentView {
rawSel.removeAllRanges()
rawSel.addRange(range)
}
if (selectionNotFocus && this.view.root.activeElement == this.dom) {
this.dom.blur()
if (activeElt) (activeElt as HTMLElement).focus()
}
})
this.view.observer.setSelectionRange(anchor, head)
}
Expand Down Expand Up @@ -241,12 +248,6 @@ export class DocView extends ContentView {
sel.collapse(anchorNode, anchorOffset)
}

mayControlSelection() {
let active = this.view.root.activeElement
return active == this.dom ||
hasSelection(this.dom, this.view.observer.selectionRange) && !(active && this.dom.contains(active))
}

nearest(dom: Node): ContentView | null {
for (let cur: Node | null = dom; cur;) {
let domView = ContentView.get(cur)
Expand Down

0 comments on commit f49f2ee

Please sign in to comment.