Skip to content

Commit

Permalink
fix: recognize focused shadow root hosts (#1235)
Browse files Browse the repository at this point in the history
Co-authored-by: Philipp Fritsche <[email protected]>
  • Loading branch information
mattclough1 and ph-fritsche authored Feb 4, 2025
1 parent 481523e commit 0437f2e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
22 changes: 12 additions & 10 deletions src/utils/focus/getActiveElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@ export function getActiveElement(
const activeElement = document.activeElement

if (activeElement?.shadowRoot) {
return getActiveElement(activeElement.shadowRoot)
} else {
// Browser does not yield disabled elements as document.activeElement - jsdom does
if (isDisabled(activeElement)) {
return document.ownerDocument
// TODO: verify behavior in ShadowRoot
? /* istanbul ignore next */ document.ownerDocument.body
: document.body
const activeElementInShadowTree = getActiveElement(activeElement.shadowRoot)
if (activeElementInShadowTree) {
return activeElementInShadowTree
}

return activeElement
}
// Browser does not yield disabled elements as document.activeElement - jsdom does
if (isDisabled(activeElement)) {
return document.ownerDocument
// TODO: verify behavior in ShadowRoot
? /* istanbul ignore next */ document.ownerDocument.body
: document.body
}

return activeElement
}

export function getActiveElementOrBody(document: Document): Element {
Expand Down
25 changes: 25 additions & 0 deletions tests/keyboard/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,28 @@ test('disabling activeElement moves action to HTMLBodyElement', async () => {
body - keyup: c
`)
})

test('typing on focused element with shadow root', async () => {
const {user, eventWasFired} = setup(
'<focusable-custom-element></focusable-custom-element>',
)

await user.keyboard('[Space]')
expect(eventWasFired('keypress')).toBe(true)
})

customElements.define(
'focusable-custom-element',
class FocusableCustomElement extends HTMLElement {
constructor() {
super()
this.attachShadow({mode: 'open'})
}

connectedCallback() {
if (!this.hasAttribute('tabindex')) {
this.setAttribute('tabindex', '0')
}
}
},
)

0 comments on commit 0437f2e

Please sign in to comment.