Skip to content

Commit

Permalink
fix(pointer): change selection before dispatching focus (#895)
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-fritsche committed Mar 31, 2022
1 parent dff6d54 commit 06f12a6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
12 changes: 5 additions & 7 deletions src/pointer/pointerPress.ts
Expand Up @@ -266,13 +266,6 @@ function mousedownDefaultBehavior({
node?: Node
offset?: number
}) {
// The closest focusable element is focused when a `mousedown` would have been fired.
// Even if there was no `mousedown` because the element was disabled.
// A `mousedown` that preventsDefault cancels this though.
focus(target)

// TODO: What happens if a focus event handler interfers?

// An unprevented mousedown moves the cursor to the closest character.
// We try to approximate the behavior for a no-layout environment.
if (!targetIsDisabled) {
Expand Down Expand Up @@ -326,6 +319,11 @@ function mousedownDefaultBehavior({
selection.addRange(range.cloneRange())
}
}

// The closest focusable element is focused when a `mousedown` would have been fired.
// Even if there was no `mousedown` because the element was disabled.
// A `mousedown` that preventsDefault cancels this though.
focus(target)
}

function getTextRange(
Expand Down
14 changes: 14 additions & 0 deletions tests/pointer/select.ts
Expand Up @@ -368,3 +368,17 @@ describe('focus control when clicking label', () => {
expect(input).not.toHaveFocus()
})
})

test('focus event handler can override selection', async () => {
const {element, user} = setup(`<input value="hello"/>`, {
focus: false,
})
element.addEventListener('focus', e =>
(e.target as HTMLInputElement).select(),
)

await user.click(element)

expect(element).toHaveProperty('selectionStart', 0)
expect(element).toHaveProperty('selectionEnd', 5)
})
2 changes: 1 addition & 1 deletion tests/utility/type.ts
Expand Up @@ -19,9 +19,9 @@ test('type into input', async () => {
input[value="foo"] - mousemove
input[value="foo"] - pointerdown
input[value="foo"] - mousedown: primary
input[value="foo"] - select
input[value="foo"] - focus
input[value="foo"] - focusin
input[value="foo"] - select
input[value="foo"] - pointerup
input[value="foo"] - mouseup: primary
input[value="foo"] - click: primary
Expand Down

0 comments on commit 06f12a6

Please sign in to comment.