From 6db2ee75d9672f456e837cb368b0b19eb47a6b02 Mon Sep 17 00:00:00 2001 From: Hugo van Rijswijk Date: Tue, 20 Aug 2024 17:59:17 +0200 Subject: [PATCH] feat(elements): close drawer when pressing Escape Related to #3370 --- .../src/components/drawer/drawer.component.ts | 16 ++++++++++++++++ .../unit/components/drawer.component.spec.ts | 11 +++++++++++ 2 files changed, 27 insertions(+) diff --git a/packages/elements/src/components/drawer/drawer.component.ts b/packages/elements/src/components/drawer/drawer.component.ts index 604d3859a..2b90507ec 100644 --- a/packages/elements/src/components/drawer/drawer.component.ts +++ b/packages/elements/src/components/drawer/drawer.component.ts @@ -63,6 +63,22 @@ export class MutationTestReportDrawer extends LitElement { event.stopImmediatePropagation(); }; + connectedCallback(): void { + super.connectedCallback(); + window.addEventListener('keydown', this.#handleKeyDown); + } + + disconnectedCallback(): void { + window.removeEventListener('keydown', this.#handleKeyDown); + super.disconnectedCallback(); + } + + #handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + this.mode = 'closed'; + } + }; + render() { const contentHeight = this.#contentHeightController.value; const styles = styleMap({ height: contentHeight ? `${contentHeight}px` : undefined }); diff --git a/packages/elements/test/unit/components/drawer.component.spec.ts b/packages/elements/test/unit/components/drawer.component.spec.ts index 3e63e4bc2..6a027d677 100644 --- a/packages/elements/test/unit/components/drawer.component.spec.ts +++ b/packages/elements/test/unit/components/drawer.component.spec.ts @@ -1,5 +1,6 @@ import { MutationTestReportDrawer } from '../../../src/components/drawer/drawer.component.js'; import { CustomElementFixture } from '../helpers/CustomElementFixture.js'; +import { userEvent } from '@vitest/browser/context'; describe(MutationTestReportDrawer.name, () => { let sut: CustomElementFixture; @@ -72,6 +73,16 @@ describe(MutationTestReportDrawer.name, () => { const event = await sut.catchNativeEvent('click', () => sut.$('header').click()); expect(event).undefined; }); + + it('should close when escape is pressed', async () => { + sut.element.mode = 'open'; + await sut.whenStable(); + + await userEvent.keyboard('{Escape}'); + await sut.whenStable(); + + expect(sut.element).toHaveProperty('mode', 'closed'); + }); }); function readMoreToggle(): HTMLElement {