Add closeOnOutsideClick and closeOnEsc
This commit is contained in:
parent
d6326e3b5e
commit
9c2cede178
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@tp/tp-dialog",
|
||||
"version": "1.0.5",
|
||||
"version": "1.1.0",
|
||||
"description": "",
|
||||
"main": "tp-dialog.js",
|
||||
"scripts": {
|
||||
|
38
tp-dialog.js
38
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);
|
||||
|
Loading…
Reference in New Issue
Block a user