Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(pointer): change selection before dispatching focus #895

Merged
merged 2 commits into from
Mar 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions src/pointer/pointerPress.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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