Quellcode durchsuchen

Close modal on escape

JC Brand vor 1 Woche
Ursprung
Commit
79a241e23d

+ 17 - 0
src/plugins/modal/modal.js

@@ -33,6 +33,12 @@ class BaseModal extends CustomElement {
         this.tabIndex = -1;
         this.ariaHidden = 'true';
 
+        this.onKeyDown = /** @param {KeyboardEvent} ev */(ev) => {
+            if (ev.key === 'Escape' && this.ariaHidden === 'false') {
+                this.close();
+            }
+        }
+
         this.initialized = getOpenPromise();
 
         // Allow properties to be set via passed in options
@@ -47,6 +53,17 @@ class BaseModal extends CustomElement {
         });
     }
 
+    connectedCallback() {
+        super.connectedCallback();
+        window.addEventListener('keydown', this.onKeyDown);
+    }
+
+    disconnectedCallback() {
+        window.removeEventListener('resize', this.onKeyDown);
+        super.disconnectedCallback();
+    }
+
+
     get modal () {
         if (!this.#modal) {
             this.#modal = new Modal(this, {

+ 0 - 2
src/types/plugins/modal/confirm.d.ts

@@ -7,8 +7,6 @@ export default class Confirm extends BaseModal {
         resolve: (value: any) => void;
         reject: (reason?: any) => void;
     };
-    onKeyDown: (ev: KeyboardEvent) => void;
-    connectedCallback(): void;
     renderModal(): import("lit-html").TemplateResult<1>;
     getModalTitle(): any;
     renderModalFooter(): string;

+ 2 - 0
src/types/plugins/modal/modal.d.ts

@@ -13,6 +13,7 @@ declare class BaseModal extends CustomElement {
      */
     constructor(options: any);
     model: any;
+    onKeyDown: (ev: KeyboardEvent) => void;
     initialized: Promise<any> & {
         isResolved: boolean;
         isPending: boolean;
@@ -20,6 +21,7 @@ declare class BaseModal extends CustomElement {
         resolve: (value: any) => void;
         reject: (reason?: any) => void;
     };
+    connectedCallback(): void;
     get modal(): Modal;
     initialize(): void;
     /**