# Selection collapses after focus() when a change replaces the selected text (Firefox)

**URL:** https://discuss.codemirror.net/t/selection-collapses-after-focus-when-a-change-replaces-the-selected-text-firefox/9920
**Category:** v6
**Created:** [October 19, 2026, 7:57pm UTC](https://discuss.codemirror.net/t/selection-collapses-after-focus-when-a-change-replaces-the-selected-text-firefox/9920 "2026-10-19T19:57:37Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![yacine.souadda](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/yacine.souadda/32/5566_2.png) [@yacine.souadda](https://discuss.codemirror.net/u/yacine.souadda)
#### Post date: [October 19, 2026, 7:57pm UTC](https://discuss.codemirror.net/t/selection-collapses-after-focus-when-a-change-replaces-the-selected-text-firefox/9920/1 "2026-10-19T19:57:37Z")

</div>

**Selection collapses after focus() when a change replaces the selected text (Firefox)**

Versions: @codemirror/view 6.43.14, @codemirror/state 6.7.6. Firefox 157.0 (Playwright 1.64 build, Linux).

Not reproduced in Chromium 156.

I also see it in WebKit 27.2 in a larger setup but not with the minimal page below.

```auto
<!doctype html>
  <textarea id="outside"></textarea>
  <div id="editor"></div>
  <button id="run">run</button>

  <script type="module">
    import { EditorState } from 'https://esm.sh/@codemirror/state@6.7.6';
    import { EditorView } from 'https://esm.sh/@codemirror/view@6.43.14';

    const view = new EditorView({
      parent: document.getElementById('editor'),
      state: EditorState.create({doc: '\nfoo bar foo\nfoo'}), // first line is empty
    });

    view.dispatch({selection: {anchor: 1, head: 4}});

    document.getElementById('run').addEventListener('click', () => {
      document.getElementById('outside').focus();

      setTimeout(() => {
        view.focus(); // Within 200 ms of the focus: replace the selected text and keep it selected.
        view.dispatch({
          changes: {from: 1, to: 4, insert: 'qux'},
          selection: {anchor: 1, head: 4},
        });

        setTimeout(() => console.log(JSON.stringify(view.state.selection.main)), 300);
      }, 100);
    });
  </script>

```

---

<div class="post-metadata">

### Author: ![marijn](https://discuss.codemirror.net/user_avatar/discuss.codemirror.net/marijn/32/136_2.png) [@marijn](https://discuss.codemirror.net/u/marijn)
#### Post date: [October 20, 2026, 3:36pm UTC](https://discuss.codemirror.net/t/selection-collapses-after-focus-when-a-change-replaces-the-selected-text-firefox/9920/2 "2026-10-20T15:36:06Z")

</div>

This patch seems to help.

> **[Don't force a selection update when already updating · 0ebe2c0652](https://code.haverbeke.berlin/codemirror/view/commit/0ebe2c0652fdc34cd53d5a28d21ef86b0c5489f8)**
>
> FIX: Fix an issue that could, when updating the editor right after focusing it,
> cause the selection to end up in the wrong place.
> 
> See...
