Skip to content

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

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

Enesuygurs wants to merge 1 commit 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)
  })

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