Skip to content

Commit

Permalink
fix(click): click no longer blurs when focus changes during onClick e…
Browse files Browse the repository at this point in the history
…vent (#208)
  • Loading branch information
jmcriffey authored and Kent C. Dodds committed Jan 23, 2020
1 parent df282f9 commit 4bcab8c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
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

0 comments on commit 4bcab8c

Please sign in to comment.