Skip to content

Commit

Permalink
feat(elements): close drawer when pressing Escape
Browse files Browse the repository at this point in the history
Related to #3370
  • Loading branch information
hugo-vrijswijk committed Aug 20, 2024
1 parent 811f49e commit 6db2ee7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/elements/src/components/drawer/drawer.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
11 changes: 11 additions & 0 deletions packages/elements/test/unit/components/drawer.component.spec.ts
Original file line number Diff line number Diff line change
@@ -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<MutationTestReportDrawer>;
Expand Down Expand Up @@ -72,6 +73,16 @@ describe(MutationTestReportDrawer.name, () => {
const event = await sut.catchNativeEvent('click', () => sut.$<HTMLElement>('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 {
Expand Down

0 comments on commit 6db2ee7

Please sign in to comment.