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(click): click no longer blurs when focus changes during onClick event #208

Merged
merged 1 commit into from Jan 23, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions __tests__/react/click.js
Expand Up @@ -198,6 +198,32 @@ describe("userEvent.click", () => {
expect(b).toHaveFocus();
});

it("does not lose focus when click updates focus", () => {
const FocusComponent = () => {
const inputRef = React.useRef();
const focusInput = () => inputRef.current.focus();

return (
<React.Fragment>
<input data-testid="input" ref={inputRef} />
<button onClick={focusInput}>Update Focus</button>
</React.Fragment>
);
};
const { getByTestId, getByText } = render(<FocusComponent />);

const input = getByTestId("input");
const button = getByText("Update Focus");

expect(input).not.toHaveFocus();

userEvent.click(button);
expect(input).toHaveFocus();

userEvent.click(button);
expect(input).toHaveFocus();
});

it.each(["input", "textarea"])(
"gives focus to <%s> when clicking a <label> with htmlFor",
type => {
Expand Down
15 changes: 12 additions & 3 deletions src/index.js
Expand Up @@ -99,6 +99,15 @@ function fireChangeEvent(event) {
event.target.removeEventListener("blur", fireChangeEvent);
}

function blurFocusedElement(element, focusedElement, wasAnotherElementFocused) {
if (
wasAnotherElementFocused &&
element.ownerDocument.activeElement === element
) {
focusedElement.blur();
}
}

const userEvent = {
click(element) {
const focusedElement = element.ownerDocument.activeElement;
Expand All @@ -123,7 +132,7 @@ const userEvent = {
clickElement(element);
}

wasAnotherElementFocused && focusedElement.blur();
blurFocusedElement(element, focusedElement, wasAnotherElementFocused);
},

dblClick(element) {
Expand All @@ -145,7 +154,7 @@ const userEvent = {
dblClickElement(element);
}

wasAnotherElementFocused && focusedElement.blur();
blurFocusedElement(element, focusedElement, wasAnotherElementFocused);
},

selectOptions(element, values) {
Expand All @@ -172,7 +181,7 @@ const userEvent = {
}
}

wasAnotherElementFocused && focusedElement.blur();
blurFocusedElement(element, focusedElement, wasAnotherElementFocused);
},

async type(element, text, userOpts = {}) {
Expand Down