From 9c2cede1780f35a0d1ba7aa3a69e525ad4cf2be5 Mon Sep 17 00:00:00 2001 From: pk Date: Fri, 22 Nov 2024 10:54:57 +0100 Subject: [PATCH] Add closeOnOutsideClick and closeOnEsc --- package.json | 2 +- tp-dialog.js | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 032c61c..a42b6d4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tp/tp-dialog", - "version": "1.0.5", + "version": "1.1.0", "description": "", "main": "tp-dialog.js", "scripts": { diff --git a/tp-dialog.js b/tp-dialog.js index cebbd4d..e9d0b76 100644 --- a/tp-dialog.js +++ b/tp-dialog.js @@ -67,6 +67,8 @@ class TpDialog extends EventHelpers(LitElement) { open: { type: Boolean, reflect: true }, showClose: { type: Boolean }, icon: { type: Object }, + closeOnEsc: { type: Boolean }, + closeOnOutsideClick: { type: Boolean }, }; } @@ -78,6 +80,11 @@ class TpDialog extends EventHelpers(LitElement) { return this.shadowRoot.querySelector('dialog'); } + constructor() { + super(); + this._handleEscKey = this._handleEscKey.bind(this); + } + connectedCallback() { super.connectedCallback(); this.listen(this, 'click', '_onDialogClick'); @@ -88,16 +95,32 @@ class TpDialog extends EventHelpers(LitElement) { super.disconnectedCallback(); this.unlisten(this, 'click', '_onDialogClick'); this.unlisten(this, 'dialog-close', 'close'); + + if (this.closeOnEsc) { + document.removeEventListener('keydown', this._handleEscKey); + } } show() { this.dialog.show(); this.open = true; + + if (this.closeOnEsc) { + document.addEventListener('keydown', this._handleEscKey, { once: true }); + } } showModal() { this.dialog.showModal(); this.open = true; + + if (this.closeOnEsc) { + document.addEventListener('keydown', this._handleEscKey, { once: true }); + } + + if (this.closeOnOutsideClick) { + this.addEventListener('click', this._handleOutsideClick, { once: true }); + } } close() { @@ -106,6 +129,15 @@ class TpDialog extends EventHelpers(LitElement) { } _onDialogClick(event) { + if (this.closeOnOutsideClick) { + const path = event.composedPath(); + if (!path.includes(this.dialog)) { + this.close(); + event.stopPropagation(); + return; + } + } + var rootTarget = event.composedPath()[0]; var target = closest(rootTarget, '[dialog-dismiss]', true) || closest(rootTarget, '[dialog-confirm]', true); while (target && target !== this) { @@ -127,6 +159,12 @@ class TpDialog extends EventHelpers(LitElement) { target = target.parentNode; } } + + _handleEscKey(event) { + if (event.key === 'Escape' && this.closeOnEsc) { + this.close(); + } + } } window.customElements.define('tp-dialog', TpDialog);