// Imperative custom dialogs (item 10) replacing the browser's native // confirm()/prompt(), which can't be styled and look out of place. A single // mounted at the app root renders the active request; the // confirmDialog/promptDialog helpers return a promise that resolves when the // user answers, so call sites read like `if (await confirmDialog(...))`. import { Store } from './store'; export interface ConfirmRequest { kind: 'confirm'; title: string; message: string; confirmLabel?: string; cancelLabel?: string; danger?: boolean; resolve: (ok: boolean) => void; } export interface PromptRequest { kind: 'prompt'; title: string; message?: string; placeholder?: string; initial?: string; confirmLabel?: string; cancelLabel?: string; resolve: (value: string | null) => void; } export type DialogRequest = ConfirmRequest | PromptRequest; interface DialogState { current: DialogRequest | null; } export const dialogStore = new Store({ current: null }); // Resolve the active dialog and clear it. Guards against double-resolve (e.g. // clicking confirm and the backdrop in quick succession). function settle(value: boolean | string | null) { const req = dialogStore.get().current; if (!req) return; dialogStore.set({ current: null }); if (req.kind === 'confirm') { req.resolve(value === true); } else { req.resolve(typeof value === 'string' ? value : null); } } export function resolveConfirm(ok: boolean) { settle(ok); } export function resolvePrompt(value: string | null) { settle(value); } export function confirmDialog( opts: Omit ): Promise { // A pending dialog is cancelled if a new one opens (shouldn't overlap). const pending = dialogStore.get().current; if (pending) { if (pending.kind === 'confirm') pending.resolve(false); else pending.resolve(null); } return new Promise((resolve) => { dialogStore.set({ current: { kind: 'confirm', ...opts, resolve } }); }); } export function promptDialog( opts: Omit ): Promise { const pending = dialogStore.get().current; if (pending) { if (pending.kind === 'confirm') pending.resolve(false); else pending.resolve(null); } return new Promise((resolve) => { dialogStore.set({ current: { kind: 'prompt', ...opts, resolve } }); }); }