Skip to content

Commit

Permalink
Merge pull request #82 from oddbird/add-escape-to-dismiss
Browse files Browse the repository at this point in the history
Add escape to dismiss
  • Loading branch information
jgerigmeyer authored Mar 15, 2023
2 parents f4ae492 + fe8bcc0 commit a3798df
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- 🚀 NEW: Add support for Escape to dismiss auto popovers --
[#82](https://github.com/oddbird/popover-polyfill/pull/82)
- 🚀 NEW: Showing an `auto` popover closes other `auto` popovers --
[#83](https://github.com/oddbird/popover-polyfill/pull/83)
- 🚀 NEW: Add support for focus restoration on popover close --
Expand Down
8 changes: 8 additions & 0 deletions src/popover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,16 @@ export function apply() {
);
};

const onKeydown = (event: Event) => {
const key = (event as KeyboardEvent).key;
if (key === 'Escape' || key === 'Esc') {
hideOpenAutoPopovers();
}
};

const addOnClickEventListener = (root: Document | ShadowRoot) => {
root.addEventListener('click', onClick);
root.addEventListener('keydown', onKeydown);
};

observePopoversMutations(document);
Expand Down
27 changes: 27 additions & 0 deletions tests/dismiss.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,30 @@ test('showing an auto popover should close all other auto popovers', async ({
await expect(popover7).toBeVisible();
await expect(popover3).toBeHidden();
});

test('pressing Escape dismisses auto popovers', async ({ page }) => {
const popover7 = (await page.locator('#popover7')).nth(0);
await expect(
await popover7.evaluate((node) => node.showPopover()),
).toBeUndefined();
await expect(popover7).toBeVisible();

await page.keyboard.press('Escape');

await expect(popover7).toBeHidden();
});

test('pressing Escape focused in popover dismisses auto popovers', async ({
page,
}) => {
const popover3 = (await page.locator('#popover3')).nth(0);
await expect(
await popover3.evaluate((node) => node.showPopover()),
).toBeUndefined();
await expect(popover3).toBeVisible();
await page.locator('#popover3 a[href]').focus();

await page.keyboard.press('Escape');

await expect(popover3).toBeHidden();
});

0 comments on commit a3798df

Please sign in to comment.