85 lines
2.3 KiB
TypeScript
85 lines
2.3 KiB
TypeScript
// Imperative custom dialogs (item 10) replacing the browser's native
|
|
// confirm()/prompt(), which can't be styled and look out of place. A single
|
|
// <DialogHost/> 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<DialogState>({ 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<ConfirmRequest, 'kind' | 'resolve'>
|
|
): Promise<boolean> {
|
|
// 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<boolean>((resolve) => {
|
|
dialogStore.set({ current: { kind: 'confirm', ...opts, resolve } });
|
|
});
|
|
}
|
|
|
|
export function promptDialog(
|
|
opts: Omit<PromptRequest, 'kind' | 'resolve'>
|
|
): Promise<string | null> {
|
|
const pending = dialogStore.get().current;
|
|
if (pending) {
|
|
if (pending.kind === 'confirm') pending.resolve(false);
|
|
else pending.resolve(null);
|
|
}
|
|
return new Promise<string | null>((resolve) => {
|
|
dialogStore.set({ current: { kind: 'prompt', ...opts, resolve } });
|
|
});
|
|
}
|