Skip to content

Commit

Permalink
allow keyboard events on shadow root hosts
Browse files Browse the repository at this point in the history
  • Loading branch information
mattclough1 committed Sep 24, 2024
1 parent d036279 commit 1aaed3d
Show file tree
Hide file tree
Showing 2 changed files with 39 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 activeShadowRootElement = getActiveElement(activeElement.shadowRoot)
if (activeShadowRootElement) {
return activeShadowRootElement
}

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
27 changes: 27 additions & 0 deletions tests/keyboard/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,30 @@ test('disabling activeElement moves action to HTMLBodyElement', async () => {
body - keyup: c
`)
})

test('typing on focused element with shadow root', async () => {
const keypressHandler = mocks.fn()
class CustomElement extends HTMLElement {
constructor() {
super()

this.attachShadow({mode: 'open'})
this.addEventListener('keypress', keypressHandler)
}
}

customElements.define('custom-element', CustomElement)

const {element, user} = setup(
'<custom-element tabindex="0"></custom-element>',
)

// Tab to body
await user.tab()
// Tab to custom element
await user.tab()
expect(element).toHaveFocus()

await user.keyboard('[Space]')
expect(keypressHandler).toHaveBeenCalled()
})

0 comments on commit 1aaed3d

Please sign in to comment.