Skip to content

Commit e05e521

Browse files
committed
Improve focus handling for setup
1 parent 67858c1 commit e05e521

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

tests/_helpers/setup.ts

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export function render<Elements extends Element | Element[] = HTMLElement>(
2828
if (typeof focus === 'string') {
2929
;(assertSingleNodeFromXPath(focus, div) as HTMLElement).focus()
3030
} else if (focus !== false) {
31-
const element: HTMLElement | null = getFocusableElement(div)
31+
const element: HTMLElement | null = findFocusable(div)
3232
element?.focus()
3333
}
3434

@@ -103,23 +103,14 @@ export function setup<Elements extends Element | Element[] = HTMLElement>(
103103
...render<Elements>(ui, {eventHandlers, focus, selection}),
104104
}
105105
}
106-
export function getFocusableElement(
107-
parent: Element | ShadowRoot,
108-
): HTMLElement | null {
109-
const possibleFocusableElement: HTMLElement | null =
110-
parent.querySelector(FOCUSABLE_SELECTOR)
111-
if (possibleFocusableElement) {
112-
return possibleFocusableElement
113-
}
114-
115-
const children = Array.from(parent.children)
116-
for (const child of children) {
117-
if ('shadowRoot' in child && child.shadowRoot) {
118-
const possibleFocusableChildElement = getFocusableElement(
119-
child.shadowRoot,
120-
)
121-
if (possibleFocusableChildElement) {
122-
return possibleFocusableChildElement
106+
function findFocusable(container: Element | ShadowRoot): HTMLElement | null {
107+
for (const el of Array.from(container.querySelectorAll('*'))) {
108+
if (el.matches(FOCUSABLE_SELECTOR)) {
109+
return el as HTMLElement
110+
} else if (el.shadowRoot) {
111+
const f = findFocusable(el.shadowRoot)
112+
if (f) {
113+
return f
123114
}
124115
}
125116
}

0 commit comments

Comments
 (0)