58 lines
2.2 KiB
JavaScript
58 lines
2.2 KiB
JavaScript
// ── Custom dialog system ──
|
|
|
|
import { $ } from './util.js';
|
|
|
|
const overlay = $('dialog');
|
|
const titleEl = $('dialog-title');
|
|
const msgEl = $('dialog-msg');
|
|
const inputEl = $('dialog-input');
|
|
const cancelBtn = $('dialog-cancel');
|
|
const okBtn = $('dialog-ok');
|
|
const closeBtn = $('dialog-close');
|
|
let resolve = null;
|
|
|
|
function canCancel() { return !cancelBtn.classList.contains('hidden'); }
|
|
|
|
function close(result) {
|
|
overlay.classList.remove('open');
|
|
if (resolve) { resolve(result); resolve = null; }
|
|
}
|
|
|
|
function submit() {
|
|
close(inputEl.classList.contains('hidden') ? true : inputEl.value);
|
|
}
|
|
|
|
export function showDialog({ title, message = '', input = false, placeholder = '', danger = false, okLabel = 'ok', cancelLabel = 'cancel' }) {
|
|
return new Promise(res => {
|
|
resolve = res;
|
|
titleEl.textContent = title;
|
|
msgEl.textContent = message;
|
|
msgEl.classList.toggle('hidden', !message);
|
|
inputEl.classList.toggle('hidden', input === false);
|
|
inputEl.value = '';
|
|
inputEl.placeholder = placeholder;
|
|
inputEl.type = input === 'password' ? 'password' : 'text';
|
|
okBtn.textContent = okLabel;
|
|
okBtn.classList.toggle('border-t-danger', danger);
|
|
okBtn.classList.toggle('text-t-danger', danger);
|
|
okBtn.classList.toggle('border-t-accent', !danger);
|
|
okBtn.classList.toggle('text-t-accent', !danger);
|
|
cancelBtn.textContent = cancelLabel;
|
|
cancelBtn.classList.toggle('hidden', !cancelLabel);
|
|
if (closeBtn) closeBtn.classList.toggle('hidden', !cancelLabel);
|
|
overlay.classList.add('open');
|
|
if (input) inputEl.focus(); else okBtn.focus();
|
|
});
|
|
}
|
|
|
|
export function isDialogOpen() { return overlay.classList.contains('open'); }
|
|
|
|
okBtn.addEventListener('click', submit);
|
|
cancelBtn.addEventListener('click', () => { if (canCancel()) close(null); });
|
|
if (closeBtn) closeBtn.addEventListener('click', () => { if (canCancel()) close(null); });
|
|
overlay.addEventListener('click', e => { if (e.target === overlay && canCancel()) close(null); });
|
|
overlay.addEventListener('keydown', e => {
|
|
if (e.key === 'Escape' && canCancel()) close(null);
|
|
if (e.key === 'Enter') submit();
|
|
});
|