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

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.

<!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>

This patch seems to help.