Add closeOnOutsideClick and closeOnEsc

This commit is contained in:
trading_peter 2024-11-22 10:54:57 +01:00
parent d6326e3b5e
commit 9c2cede178
2 changed files with 39 additions and 1 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@tp/tp-dialog",
"version": "1.0.5",
"version": "1.1.0",
"description": "",
"main": "tp-dialog.js",
"scripts": {

View File

@ -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);