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; const Ctx = createContext(null); /** `const confirm = useConfirm(); if (await confirm({ message })) save();` */ export function ConfirmProvider({ children }: { children: ReactNode }) { const { t } = useUi(); const [opts, setOpts] = useState(null); const resolver = useRef<((v: boolean) => void) | null>(null); const confirm = useCallback((o) => { return new Promise((resolve) => { resolver.current?.(false); resolver.current = resolve; setOpts(o ?? {}); }); }, []); const finish = (v: boolean) => { resolver.current?.(v); resolver.current = null; setOpts(null); }; return ( {children} finish(true)} onCancel={() => finish(false)} /> ); } export function useConfirm(): ConfirmFn { const v = useContext(Ctx); if (!v) throw new Error('useConfirm must be used inside ConfirmProvider'); return v; }