Files
WebHooker/app/composables/useConfirm.ts
T
翅膀 24f5d0477c feat(console): add in-app destructive-action confirmation
Deleting a route or a group used `window.confirm`, which blocks the page
and ignores the console theme. A promise-based `useConfirm()` now drives
one <ConfirmDialog /> built on the reka-ui AlertDialog that
@elysola/ui ships; reka-ui is pre-bundled so dev keeps a single copy and
the dialog stacks with the Rc dialogs.

A request never outlives its asker: one made after the asking component
unmounted resolves false, and one still open when it unmounts is
cancelled.
2026-10-17 00:12:36 +08:00

64 lines
2.1 KiB
TypeScript

export interface ConfirmOptions {
/** The question, shown as the dialog title. */
title: string;
/** Optional consequence text under the title. */
description?: string;
/** Label of the destructive button (defaults to "Delete"). */
confirmText?: string;
}
interface ConfirmRequest extends ConfirmOptions {
resolve: (confirmed: boolean) => void;
}
/**
* Promise-based destructive-action confirmation shared by the whole console.
* <ConfirmDialog /> (mounted once by ConsolePage) renders the pending request;
* `confirm()` resolves true on confirm and false on cancel / Escape.
*/
export function useConfirm() {
const pending = useState<ConfirmRequest | null>("wh-confirm", () => null);
const hosts = useState<number>("wh-confirm-hosts", () => 0);
// The component that asks; a request it makes after unmounting is refused,
// and one still on screen when it unmounts is cancelled.
const owner = getCurrentInstance();
let asked: ConfirmRequest | null = null;
if (owner) {
onBeforeUnmount(() => {
// Only our own request: another component's newer one stays open.
if (asked && toRaw(pending.value) === asked) settle(false);
asked = null;
});
}
function confirm(options: ConfirmOptions): Promise<boolean> {
// Nobody can answer, or the asker is gone (the console was left while the
// request was being prepared): never resume a stale destructive action.
if (!hosts.value || owner?.isUnmounted) return Promise.resolve(false);
// A newer request supersedes (and cancels) one still on screen.
pending.value?.resolve(false);
return new Promise((resolve) => {
asked = { ...options, resolve };
pending.value = asked;
});
}
function settle(confirmed: boolean): void {
const request = pending.value;
if (!request) return;
pending.value = null;
request.resolve(confirmed);
}
/** Register the dialog that renders requests; the returned detach cancels any pending one. */
function attachHost(): () => void {
hosts.value++;
return () => {
hosts.value--;
settle(false);
};
}
return { pending, confirm, settle, attachHost };
}