/** * Confirm dialog and toasts for the admin app (instead of window.confirm/alert). * * const { confirm, toast, NotifyPortal } = useNotify(); * * if (await confirm({ message: 'Delete this?' })) { ... } * toast({ message: 'Saved.' }); */ import { useCallback, useEffect, useId, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; interface ConfirmOptions { title?: string; message: string; confirmLabel?: string; cancelLabel?: string; danger?: boolean; } interface ToastOptions { message: string; type?: 'success' | 'error' | 'info'; duration?: number; } interface ToastItem extends ToastOptions { id: number; } interface ConfirmState extends ConfirmOptions { resolve: (value: boolean) => void; } let toastId = 0; function ConfirmDialog({ state, onClose }: { state: ConfirmState; onClose: (value: boolean) => void }) { const titleId = useId(); const messageId = useId(); const returnFocus = useRef(document.activeElement); useEffect(() => { const previous = returnFocus.current; const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(false); }; document.addEventListener('keydown', onKey); return () => { document.removeEventListener('keydown', onKey); if (previous instanceof HTMLElement) previous.focus(); }; }, [onClose]); return ( onClose(false)}> event.stopPropagation()} > {state.title && {state.title}} {state.message} onClose(false)}> {state.cancelLabel ?? 'Cancel'} onClose(true)} autoFocus > {state.confirmLabel ?? 'Confirm'} ); } export function useNotify() { const [confirmState, setConfirmState] = useState(null); const [toasts, setToasts] = useState([]); const confirm = useCallback((options: ConfirmOptions): Promise => { return new Promise((resolve) => setConfirmState({ ...options, resolve })); }, []); const dismissToast = useCallback((id: number) => { setToasts((current) => current.filter((toast) => toast.id !== id)); }, []); const toast = useCallback((options: ToastOptions) => { const id = ++toastId; setToasts((current) => [...current, { ...options, id }]); const duration = options.duration ?? (options.type === 'error' ? 6000 : 3500); window.setTimeout(() => dismissToast(id), duration); }, [dismissToast]); const closeConfirm = useCallback((value: boolean) => { setConfirmState((current) => { current?.resolve(value); return null; }); }, []); const NotifyPortal = useCallback(() => createPortal( {confirmState && } {toasts.map((item) => ( {item.message} dismissToast(item.id)}> × ))} , document.body, ), [confirmState, toasts, closeConfirm, dismissToast]); return { confirm, toast, NotifyPortal }; }
{state.message}