Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(utils): useTabFocusWrap when only one element
This makes it so that if you click within the area and hit tab, the item
will be correctly focused.
  • Loading branch information
mlaursen committed Mar 22, 2021
1 parent c5daa47 commit 25178d7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
13 changes: 8 additions & 5 deletions packages/utils/src/wia-aria/__tests__/useTabFocusWrap.tsx
Expand Up @@ -8,13 +8,15 @@ interface Props {
disableFocusCache?: boolean;
onKeyDown?: React.KeyboardEventHandler<HTMLDivElement>;
count: 1 | 2 | 3;
tabIndex?: number;
}

function Test({
onKeyDown,
disableFocusCache,
disabled,
count,
tabIndex,
}: Props): ReactElement {
const handleKeyDown = useTabFocusWrap({
onKeyDown,
Expand All @@ -23,7 +25,7 @@ function Test({
});

return (
<div onKeyDown={handleKeyDown} data-testid="div">
<div onKeyDown={handleKeyDown} data-testid="div" tabIndex={tabIndex}>
{count >= 1 && <input data-testid="input-1" type="text" />}
{count >= 2 && <input data-testid="input-2" type="text" />}
{count >= 3 && <input data-testid="input-3" type="text" />}
Expand All @@ -33,16 +35,17 @@ function Test({

describe("useTabFocusWrap", () => {
it("should not focus a different element if there is only one focusable child", () => {
const { getByTestId } = render(<Test count={1} />);
const { getByTestId } = render(<Test count={1} tabIndex={-1} />);

const input = getByTestId("input-1");
input.focus();
expect(document.activeElement).toBe(input);

const inputFocus = jest.spyOn(input, "focus");

fireEvent.keyDown(input, { key: "Tab" });
expect(inputFocus).not.toBeCalled();
expect(document.activeElement).toBe(input);

const container = getByTestId("div");
fireEvent.keyDown(container, { key: "Tab" });
expect(document.activeElement).toBe(input);
});

Expand Down
1 change: 1 addition & 0 deletions packages/utils/src/wia-aria/useTabFocusWrap.ts
Expand Up @@ -60,6 +60,7 @@ export function useTabFocusWrap<E extends HTMLElement>({

if (l === 1) {
event.preventDefault();
elements[0].focus();
} else if (elements[0] === event.target && event.shiftKey) {
event.preventDefault();
elements[l - 1].focus();
Expand Down

0 comments on commit 25178d7

Please sign in to comment.