Skip to content

Commit 25178d7

Browse files
committed
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.
1 parent c5daa47 commit 25178d7

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

packages/utils/src/wia-aria/__tests__/useTabFocusWrap.tsx

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ interface Props {
88
disableFocusCache?: boolean;
99
onKeyDown?: React.KeyboardEventHandler<HTMLDivElement>;
1010
count: 1 | 2 | 3;
11+
tabIndex?: number;
1112
}
1213

1314
function Test({
1415
onKeyDown,
1516
disableFocusCache,
1617
disabled,
1718
count,
19+
tabIndex,
1820
}: Props): ReactElement {
1921
const handleKeyDown = useTabFocusWrap({
2022
onKeyDown,
@@ -23,7 +25,7 @@ function Test({
2325
});
2426

2527
return (
26-
<div onKeyDown={handleKeyDown} data-testid="div">
28+
<div onKeyDown={handleKeyDown} data-testid="div" tabIndex={tabIndex}>
2729
{count >= 1 && <input data-testid="input-1" type="text" />}
2830
{count >= 2 && <input data-testid="input-2" type="text" />}
2931
{count >= 3 && <input data-testid="input-3" type="text" />}
@@ -33,16 +35,17 @@ function Test({
3335

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

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

42-
const inputFocus = jest.spyOn(input, "focus");
43-
4444
fireEvent.keyDown(input, { key: "Tab" });
45-
expect(inputFocus).not.toBeCalled();
45+
expect(document.activeElement).toBe(input);
46+
47+
const container = getByTestId("div");
48+
fireEvent.keyDown(container, { key: "Tab" });
4649
expect(document.activeElement).toBe(input);
4750
});
4851

packages/utils/src/wia-aria/useTabFocusWrap.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ export function useTabFocusWrap<E extends HTMLElement>({
6060

6161
if (l === 1) {
6262
event.preventDefault();
63+
elements[0].focus();
6364
} else if (elements[0] === event.target && event.shiftKey) {
6465
event.preventDefault();
6566
elements[l - 1].focus();

0 commit comments

Comments
 (0)