Make show() and showModal() return a promise that resolves with "confirmed" or "dismissed"

This commit is contained in:
trading_peter 2025-05-25 23:57:46 +02:00
parent 54f9f3cb5d
commit 52d2fc7d33
2 changed files with 51 additions and 1 deletions

View File

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

View File

@ -84,22 +84,35 @@ class TpDialog extends EventHelpers(LitElement) {
constructor() {
super();
this._handleEscKey = this._handleEscKey.bind(this);
this._currentPromise = null;
this._resolvePromise = null;
}
connectedCallback() {
super.connectedCallback();
this.listen(this, 'click', '_onDialogClick');
this.listen(this, 'dialog-close', 'close');
this.listen(this, 'confirmed', '_handleConfirmed');
this.listen(this, 'dismissed', '_handleDismissed');
}
disconnectedCallback() {
super.disconnectedCallback();
this.unlisten(this, 'click', '_onDialogClick');
this.unlisten(this, 'dialog-close', 'close');
this.unlisten(this, 'confirmed', '_handleConfirmed');
this.unlisten(this, 'dismissed', '_handleDismissed');
if (this.closeOnEsc) {
document.removeEventListener('keydown', this._handleEscKey);
}
// Clean up promise if dialog is removed while open
if (this._currentPromise && this._resolvePromise) {
this._resolvePromise('dismissed');
this._currentPromise = null;
this._resolvePromise = null;
}
}
show() {
@ -109,6 +122,13 @@ class TpDialog extends EventHelpers(LitElement) {
if (this.closeOnEsc) {
document.addEventListener('keydown', this._handleEscKey, { once: true });
}
// Create and return a new promise
this._currentPromise = new Promise((resolve) => {
this._resolvePromise = resolve;
});
return this._currentPromise;
}
showModal() {
@ -122,6 +142,13 @@ class TpDialog extends EventHelpers(LitElement) {
if (this.closeOnOutsideClick) {
this.addEventListener('click', this._handleOutsideClick, { once: true });
}
// Create and return a new promise
this._currentPromise = new Promise((resolve) => {
this._resolvePromise = resolve;
});
return this._currentPromise;
}
close(e) {
@ -133,6 +160,29 @@ class TpDialog extends EventHelpers(LitElement) {
this.dialog.close();
this.dispatchEvent(new CustomEvent('closed', { detail: null, bubbles: true, composed: true }));
this.open = false;
// If closed without explicit confirm/dismiss (like ESC key), treat as dismissed
if (this._currentPromise && this._resolvePromise) {
this._resolvePromise('dismissed');
this._currentPromise = null;
this._resolvePromise = null;
}
}
_handleConfirmed(event) {
if (this._currentPromise && this._resolvePromise) {
this._resolvePromise('confirmed');
this._currentPromise = null;
this._resolvePromise = null;
}
}
_handleDismissed(event) {
if (this._currentPromise && this._resolvePromise) {
this._resolvePromise('dismissed');
this._currentPromise = null;
this._resolvePromise = null;
}
}
_onDialogClick(event) {