Skip to content

Commit 0437f2e

Browse files
fix: recognize focused shadow root hosts (#1235)
Co-authored-by: Philipp Fritsche <[email protected]>
1 parent 481523e commit 0437f2e

File tree

2 files changed

+37
-10
lines changed

2 files changed

+37
-10
lines changed

src/utils/focus/getActiveElement.ts

+12-10
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,20 @@ export function getActiveElement(
66
const activeElement = document.activeElement
77

88
if (activeElement?.shadowRoot) {
9-
return getActiveElement(activeElement.shadowRoot)
10-
} else {
11-
// Browser does not yield disabled elements as document.activeElement - jsdom does
12-
if (isDisabled(activeElement)) {
13-
return document.ownerDocument
14-
// TODO: verify behavior in ShadowRoot
15-
? /* istanbul ignore next */ document.ownerDocument.body
16-
: document.body
9+
const activeElementInShadowTree = getActiveElement(activeElement.shadowRoot)
10+
if (activeElementInShadowTree) {
11+
return activeElementInShadowTree
1712
}
18-
19-
return activeElement
2013
}
14+
// Browser does not yield disabled elements as document.activeElement - jsdom does
15+
if (isDisabled(activeElement)) {
16+
return document.ownerDocument
17+
// TODO: verify behavior in ShadowRoot
18+
? /* istanbul ignore next */ document.ownerDocument.body
19+
: document.body
20+
}
21+
22+
return activeElement
2123
}
2224

2325
export function getActiveElementOrBody(document: Document): Element {

tests/keyboard/index.ts

+25
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,28 @@ test('disabling activeElement moves action to HTMLBodyElement', async () => {
165165
body - keyup: c
166166
`)
167167
})
168+
169+
test('typing on focused element with shadow root', async () => {
170+
const {user, eventWasFired} = setup(
171+
'<focusable-custom-element></focusable-custom-element>',
172+
)
173+
174+
await user.keyboard('[Space]')
175+
expect(eventWasFired('keypress')).toBe(true)
176+
})
177+
178+
customElements.define(
179+
'focusable-custom-element',
180+
class FocusableCustomElement extends HTMLElement {
181+
constructor() {
182+
super()
183+
this.attachShadow({mode: 'open'})
184+
}
185+
186+
connectedCallback() {
187+
if (!this.hasAttribute('tabindex')) {
188+
this.setAttribute('tabindex', '0')
189+
}
190+
}
191+
},
192+
)

0 commit comments

Comments
 (0)