Skip to content

Commit cff46c4

Browse files
committed
fix(utils): focusElementsWithin correctly focuses container element as a fallback
1 parent 1d92472 commit cff46c4

2 files changed

Lines changed: 20 additions & 4 deletions

File tree

‎packages/utils/src/wia-aria/__tests__/focusElementWithin.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,4 +192,11 @@ describe("focusElementWithin", () => {
192192
);
193193
expect(scrollIntoView).not.toBeCalled();
194194
});
195+
196+
it("should fallback to focusing the container element if it is focusable", () => {
197+
const div = document.createElement("div");
198+
div.tabIndex = -1;
199+
200+
expect(() => focusElementWithin(div, "first", true)).not.toThrow();
201+
});
195202
});

‎packages/utils/src/wia-aria/focusElementWithin.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { scrollIntoView } from "../scrollIntoView";
22
import { getFocusableElements } from "./getFocusableElements";
3+
import { isFocusable } from "./isFocusable";
34

45
export type Focus = "first" | "last" | string;
56

@@ -12,21 +13,24 @@ export type Focus = "first" | "last" | string;
1213
* @param focus - Either the "first" or "last" string to focus the first or last
1314
* focusable element within the container or a query selector string to find a
1415
* focusable element within the container.
16+
* @param programmatic - Boolean if programmatically focusable elements should be
17+
* included as well.
1518
* @param preventScroll - Boolean if the focus event should not scroll the
1619
* element into view. This should normally remain `false`, but can be useful if
1720
* the element gets focused while offscreen during a transition.
18-
* @param progamatic - Boolean if programatically focusable elements should be
19-
* included as well.
21+
* @param elements - Optonal child elements to search
22+
* @remarks \@since 2.8.0 Supports focusing the container element if it is
23+
* focusable
2024
*/
2125
export function focusElementWithin(
2226
container: HTMLElement | Document,
2327
focus: Focus,
24-
programatic = false,
28+
programmatic = false,
2529
preventScroll = false,
2630
elements?: HTMLElement[]
2731
): void {
2832
if (!elements || !elements.length) {
29-
elements = getFocusableElements(container, programatic);
33+
elements = getFocusableElements(container, programmatic);
3034
}
3135

3236
let el: HTMLElement | null;
@@ -41,6 +45,11 @@ export function focusElementWithin(
4145
el = container.querySelector<HTMLElement>(focus);
4246
}
4347

48+
// just allow any focusable-type element
49+
if (!el && isFocusable(container, "programmatic")) {
50+
el = container;
51+
}
52+
4453
if (!el) {
4554
throw new Error("Unable to find a focusable element");
4655
}

0 commit comments

Comments
 (0)