NTP_V2/web/src/providers/ConfirmProvider.tsx

57 lines
1.7 KiB
TypeScript

import { createContext, useCallback, useContext, useRef, useState, type ReactNode } from 'react';
import { ConfirmDialog } from '@/components/ConfirmDialog';
import { useUi } from '@/i18n/useUi';
export interface ConfirmOptions {
title?: string;
message?: string;
confirmText?: string;
cancelText?: string;
danger?: boolean;
}
type ConfirmFn = (opts?: ConfirmOptions) => Promise<boolean>;
const Ctx = createContext<ConfirmFn | null>(null);
/** `const confirm = useConfirm(); if (await confirm({ message })) save();` */
export function ConfirmProvider({ children }: { children: ReactNode }) {
const { t } = useUi();
const [opts, setOpts] = useState<ConfirmOptions | null>(null);
const resolver = useRef<((v: boolean) => void) | null>(null);
const confirm = useCallback<ConfirmFn>((o) => {
return new Promise<boolean>((resolve) => {
resolver.current?.(false);
resolver.current = resolve;
setOpts(o ?? {});
});
}, []);
const finish = (v: boolean) => {
resolver.current?.(v);
resolver.current = null;
setOpts(null);
};
return (
<Ctx.Provider value={confirm}>
{children}
<ConfirmDialog
open={opts !== null}
title={opts?.title ?? t('confirm.title')}
message={opts?.message ?? t('confirm.save')}
confirmText={opts?.confirmText ?? t('confirm.yes')}
cancelText={opts?.cancelText ?? t('confirm.no')}
danger={opts?.danger}
onConfirm={() => finish(true)}
onCancel={() => finish(false)}
/>
</Ctx.Provider>
);
}
export function useConfirm(): ConfirmFn {
const v = useContext(Ctx);
if (!v) throw new Error('useConfirm must be used inside ConfirmProvider');
return v;
}