Skip to content

fix: reset document selection when focus moves per HTMLElement.focus() - #1344

Open
Enesuygurs wants to merge 6 commits into
testing-library:mainfrom
Enesuygurs:fix/reset-selection-on-programmatic-focus
Open

Enesuygurs wants to merge 6 commits into
testing-library:mainfrom
Enesuygurs:fix/reset-selection-on-programmatic-focus

Conversation

@Enesuygurs

Copy link
Copy Markdown

What

If an event handler moves focus into an <input> or <textarea> with HTMLElement.focus(), the document selection is left untouched. In the repro from the issue, the user drags to select text in a <div>, and the click handler on that <div> focuses an input. After the click, getSelection().toString() is still "ome tex".

document.body.innerHTML = `<div>Some text</div><input/>`
const [div, input] = document.body.children
div.addEventListener('click', () => input.focus())

await user.pointer([
  {keys: '[MouseLeft>]', target: div, offset: 1},
  {offset: 8},
  {keys: '[/MouseLeft]'},
])
document.getSelection().toString() // "ome tex", in the browser it is ""

Why

user-event already resets the document selection when focus moves into an element that has its own selection (updateSelectionOnFocus). It only does this in focusElement(), though, which means only when user-event moves the focus itself. When the page moves focus with .focus(), nothing updates the selection. A browser clears the selection in both cases, as the recording in the issue shows: the selected text goes away as soon as the input receives focus.

How

prepareDocument() now adds a capturing focus listener that calls updateSelectionOnFocus() for the newly focused element. That makes programmatic focus behave like focus moved by user-event. The listener skips focus events whose target is not document.activeElement, so a synthetic event such as fireEvent.focus() doesn't touch the selection. When focus moves through focusElement(), the function now runs twice, but it is idempotent.

I added a test to tests/event/selection/index.ts that follows the repro. It fails on main (isCollapsed is false) and passes with this change. It only checks that the selection is collapsed and empty, not which node holds it, so it doesn't depend on the TODO in updateSelectionOnFocus about where Chrome puts the caret. The full jest suite, lint and typecheck pass. I didn't run the toolbox (browser) tests locally.

Fixes #1204

Checklist

  • Documentation N/A
  • Tests
  • Ready to be merged

@snowystinger snowystinger left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is introducing a regression
https://jsfiddle.net/0zw6ku1d/9/

Some additional tests for consideration
  test('retain own selection of an element focused per `HTMLElement.focus()`', () => {
    const {
      elements: [div, input],
    } = setup<[HTMLDivElement, HTMLInputElement]>(
      `<div>Some text</div><input value="hello world"/>`,
      {focus: false},
    )
    input.setSelectionRange(2, 7)
    setSelection({
      focusNode: div.firstChild as Text,
      anchorOffset: 1,
      focusOffset: 8,
    })

    input.focus()

    expect(input).toHaveFocus()
    expect(input).toHaveProperty('selectionStart', 2)
    expect(input).toHaveProperty('selectionEnd', 7)
  })

  test('do not alter document selection on `focus` event for already focused element', () => {
    const {
      elements: [div, input],
    } = setup<[HTMLDivElement, HTMLInputElement]>(
      `<div>Some text</div><input value="hello world"/>`,
    )
    expect(input).toHaveFocus()
    setSelection({
      focusNode: div.firstChild as Text,
      anchorOffset: 1,
      focusOffset: 8,
    })

    input.dispatchEvent(new FocusEvent('focus'))

    expect(input).toHaveFocus()
    expect(document.getSelection()?.toString()).toBe('ome tex')
  })

  test('do not alter own selection on `focus` event for already focused element', () => {
    const {element} = setup<HTMLInputElement>(`<input value="hello world"/>`)
    expect(element).toHaveFocus()
    element.setSelectionRange(1, 3)

    element.dispatchEvent(new FocusEvent('focus'))

    expect(element).toHaveProperty('selectionStart', 1)
    expect(element).toHaveProperty('selectionEnd', 3)
  })

@Enesuygurs

Copy link
Copy Markdown
Author

Thanks for catching this and for the tests! The listener reacted to every focus event on the active element, so a synthetic focus dispatched on an already focused element also reset the document selection. It now keeps track of the focused element and only updates the selection when focus actually moved there; I added your three tests and they pass along with the rest of the suite.

Enesuygurs and others added 3 commits November 20, 2026 10:45
A synthetic `focus` event on an element that already has focus no longer
resets the document selection. Adds the tests suggested in review.
@snowystinger

Copy link
Copy Markdown
Contributor

I tested the fiddle in Safari and FF as well
In Safari, it doesn't work like this. Firefox did work like chrome. Can you point to any spec defining how this should work?

I also just looked through the toolbox tests, a bunch of the new ones are failing in Chrome.
There are also some typescript errors, if you wouldn't mind fixing those so that it works across versions of React.

There are other failures in the toolbox, I'll work on cleaning those up or annotating them later, just focus on the tests in this PR.

@Enesuygurs

Copy link
Copy Markdown
Author

I'm not aware of any normative spec text for this. The HTML focusing steps don't say what happens to the document selection, and the Selection API leaves the relationship between the selection and input/textarea selections open, so this is browser behaviour: Chrome and Firefox move the document selection into the text control on focus, Safari doesn't. user-event already models this in updateSelectionOnFocus for focus it moves itself, so the change only applies the same handling when focus is moved per HTMLElement.focus(). If you'd rather not rely on behaviour that isn't consistent across browsers, I understand and I'm fine with closing this.
In Chrome, moving the document selection onto the input reset the input's own selection, which broke "retain own selection of an element focused per HTMLElement.focus()". The listener now restores the element's programmatic selection after updating the document selection. Running the selection tests in headless Chrome, all four new tests pass now; the three contenteditable tests in that file fail on main as well. tsc on src and on tests didn't show errors in the files this PR touches (only existing ones in src/setup/setup.ts, tests/event/input.ts and tests/keyboard/index.ts), so could you point me to the TypeScript errors you saw?

@snowystinger

Copy link
Copy Markdown
Contributor
Screenshot 2026-11-27 at 7 19 34 pm

@Enesuygurs

Copy link
Copy Markdown
Author

Thanks for the screenshot. The selectionStart failure in Chrome was fixed by 85e40a1, which came after the commit in that run. FocusEvent is not defined came from creating the event with the global constructor, so those two tests now use the element's window (getWindow(el).FocusEvent), like other code in the repo does.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Selection not cleared when input is focused

2 participants