From f49f2eea1ae1b81c8e943b76a57ca787bfd46bf5 Mon Sep 17 00:00:00 2001 From: Marijn Haverbeke Date: Sun, 16 Apr 2023 11:28:28 +0200 Subject: [PATCH] Restore focus if manipulating the DOM selection moves it into the editor 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 --- src/docview.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/docview.ts b/src/docview.ts index abf1356..37d9222 100644 --- a/src/docview.ts +++ b/src/docview.ts @@ -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 @@ -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) } @@ -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)