Files
ad/molodetz/static/js/components/Dialog.js
T

51 lines
1.6 KiB
JavaScript

// retoor <retoor@molodetz.nl>
import { Component } from "./Component.js";
export class Dialog extends Component {
static tag = "dp-dialog";
setup() {
this.className = "modal-overlay";
this.setAttribute("role", "alertdialog");
this.setAttribute("aria-modal", "true");
}
confirm(message, { okLabel = "Yes", cancelLabel = "Cancel" } = {}) {
return new Promise((resolve) => {
this.replaceChildren();
const box = document.createElement("div");
box.className = "modal";
const text = document.createElement("p");
text.textContent = message;
const actions = document.createElement("div");
actions.className = "actions";
const ok = document.createElement("button");
ok.type = "button";
ok.className = "button";
ok.textContent = okLabel;
const cancel = document.createElement("button");
cancel.type = "button";
cancel.className = "button ghost";
cancel.textContent = cancelLabel;
actions.append(cancel, ok);
box.append(text, actions);
this.append(box);
this.classList.add("visible");
const finish = (value) => {
this.classList.remove("visible");
document.removeEventListener("keydown", onKey);
resolve(value);
};
const onKey = (event) => {
if (event.key === "Escape") {
finish(false);
}
};
document.addEventListener("keydown", onKey);
ok.addEventListener("click", () => finish(true));
cancel.addEventListener("click", () => finish(false));
ok.focus();
});
}
}