Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix integration with web components not working properly #589

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# [A11y Dialog](https://a11y-dialog.netlify.app)

This is a lightweight (1.4Kb) yet flexible script to create accessible dialog windows.
This is a lightweight (1.5Kb) yet flexible script to create accessible dialog windows.

- [Documentation ↗](https://a11y-dialog.netlify.app)
- [Demo on CodeSandbox ↗](https://codesandbox.io/s/a11y-dialog-v8-5gqfz8)
Expand Down
3 changes: 3 additions & 0 deletions cypress/e2e/focus.cy.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { shouldBeHidden } from './utils.js'

describe('Focus', { testIsolation: false }, () => {
before(() => cy.visit('/focus'))

Expand Down Expand Up @@ -34,6 +36,7 @@ describe('Focus', { testIsolation: false }, () => {

// Close the open dialog
cy.get('#close-my-dialog').click()
cy.get('.dialog').then(shouldBeHidden)
})

it('should properly handle focus with Shadow DOM children', () => {
Expand Down
22 changes: 17 additions & 5 deletions cypress/e2e/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ export function shouldBeVisible($subject) {
consoleProps: () => ({ $el: $subject }),
})

cy.wrap($subject, { log: false }).should('not.have.attr', 'aria-hidden')
cy.wrap($subject, { log: false })
if ($subject[0].shadowRoot) {
cy.wrap($subject, { log: false }).shadow().find('.dialog').as('subject')
} else {
cy.wrap($subject, { log: false }).as('subject')
}

cy.get('@subject').should('not.have.attr', 'aria-hidden')
cy.get('@subject')
.find('.dialog-content', { log: false })
.should('be.visible')
}
Expand All @@ -20,11 +26,17 @@ export function shouldBeHidden($subject) {
consoleProps: () => ({ $el: $subject }),
})

cy.wrap($subject, { log: false })
.should('have.attr', 'aria-hidden', 'true')
if ($subject[0].shadowRoot) {
cy.wrap($subject, { log: false }).shadow().find('.dialog').as('subject')
} else {
cy.wrap($subject, { log: false }).as('subject')
}

cy.get('@subject').should('have.attr', 'aria-hidden', 'true')
cy.get('@subject')
.find('.dialog-overlay', { log: false })
.should('not.be.visible')
cy.wrap($subject, { log: false })
cy.get('@subject')
.find('.dialog-content', { log: false })
.should('not.be.visible')
}
29 changes: 29 additions & 0 deletions cypress/e2e/webComponents.cy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { shouldBeHidden, shouldBeVisible } from './utils.js'

describe('Web Components', () => {
beforeEach(() => cy.visit('/web-components'))

it('should focus the dialog container on open', () => {
cy.get('my-dialog').shadow().find('[data-show]').click()
cy.get('my-dialog').then(shouldBeVisible)
cy.get('my-dialog').should('have.focus')
})

it('should close with ESC', () => {
cy.get('my-dialog').shadow().find('[data-show]').click()
cy.realPress('Escape')
cy.get('my-dialog').then(shouldBeHidden)
})

it('should close with close button', () => {
cy.get('my-dialog').shadow().find('[data-show]').click()
cy.get('my-dialog').shadow().find('.dialog-close').click()
cy.get('my-dialog').then(shouldBeHidden)
})

it('should restore focus to the previously focused element', () => {
cy.get('my-dialog').shadow().find('[data-show]').click()
cy.get('my-dialog').shadow().find('.dialog-close').click()
cy.get('my-dialog').shadow().find('[data-show]').should('have.focus')
})
})
49 changes: 49 additions & 0 deletions cypress/fixtures/web-components.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Tests — Web Components</title>
<link rel="stylesheet" href="../styles.css" />
</head>

<body>
<main>
<h1>Tests — Web Components</h1>

<my-dialog>
<template>
<button type="button" data-show>Open the dialog</button>
<div class="dialog" id="my-dialog" aria-labelledby="my-dialog-title" aria-hidden="true">
<div class="dialog-overlay" data-a11y-dialog-hide></div>
<div class="dialog-content" role="document">
<button data-a11y-dialog-hide class="dialog-close" aria-label="Close this dialog window">&times;</button>
<h1 id="my-dialog-title">Your dialog title</h1>
</div>
</div>
<link rel="stylesheet" href="../styles.css" />
</template>
</my-dialog>
</main>

<script src="./a11y-dialog.js"></script>
<script>
class MyDialog extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({ mode: 'open' });
const template = this.querySelector('template');
shadow.appendChild(template.content.cloneNode(true));

const container = this.shadowRoot.querySelector("#my-dialog");
const dialog = new A11yDialog(container);

const trigger = this.shadowRoot.querySelector('[data-show]');
trigger.addEventListener('click', () => dialog.show())
}
}

customElements.define("my-dialog", MyDialog);
</script>
</body>

</html>
23 changes: 19 additions & 4 deletions src/a11y-dialog.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { getActiveElement, moveFocusToDialog, trapTabKey } from './dom-utils'
import {
getActiveElement,
moveFocusToDialog,
trapTabKey,
closest,
} from './dom-utils'

export type A11yDialogEvent = 'show' | 'hide' | 'destroy'
export type A11yDialogInstance = InstanceType<typeof A11yDialog>
Expand Down Expand Up @@ -169,7 +174,16 @@ export default class A11yDialog {
* dialog are clicked, and call `show` or `hide`, respectively
*/
private handleTriggerClicks(event: Event) {
const target = event.target as HTMLElement
// This is a bit clumsy, but basically we want to account for being inside
// a web component *and* the target being a web component itself. In the
// 1st case, `event.target` ends up being the shadow root, so we need to use
// `event.composedPath()[0]` to get the actual click target. However in the
// case where the clicked element is a custom element (e.g. `<my-button>`),
// `event.composedPath()[0]` ends up being a `<slot>` element
// See: https://github.com/KittyGiraudel/a11y-dialog/issues/582
const target = [event.composedPath()[0], event.target].find(
node => (node as HTMLElement)?.tagName !== 'SLOT'
) as HTMLElement

// We use `.closest(..)` and not `.matches(..)` here so that clicking
// an element nested within a dialog opener does cause the dialog to open
Expand All @@ -192,8 +206,9 @@ export default class A11yDialog {
*/
private bindKeypress(event: KeyboardEvent) {
// This is an escape hatch in case there are nested open dialogs, so that
// only the top most dialog gets interacted with
if (document.activeElement?.closest('[aria-modal="true"]') !== this.$el) {
// only the top most dialog gets interacted with (`closest` is basically
// `Element.prototype.closest()` accounting for Shadow DOM subtrees)
if (closest('[aria-modal="true"]', getActiveElement()) !== this.$el) {
return
}

Expand Down
21 changes: 21 additions & 0 deletions src/dom-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,3 +213,24 @@ export function trapTabKey(el: HTMLElement, event: KeyboardEvent) {
event.preventDefault()
}
}

/**
* Find the closest element to the given element matching the given selector,
* accounting for Shadow DOM subtrees.
* @author Louis St-Amour
* @see: https://stackoverflow.com/a/56105394
*/
export function closest(selector: string, base: Element | null) {
function __closestFrom(
el: Element | Window | Document | null
): Element | null {
if (!el || el === document || el === window) return null
if ((el as Slottable).assignedSlot) el = (el as Slottable).assignedSlot
return (
(el as Element).closest(selector) ||
__closestFrom(((el as Element).getRootNode() as ShadowRoot).host)
)
}

return __closestFrom(base)
}