'use client' import { useState, useCallback, useRef } from 'react' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, } from '@/components/ui/dialog' import { Button } from '@/components/ui/button' import { AlertTriangle, Loader2 } from 'lucide-react' import { cn } from '@/lib/utils' interface DestructiveConfirmDialogProps { open: boolean onOpenChange: (open: boolean) => void title: string description: string confirmLabel?: string cancelLabel?: string variant?: 'destructive' | 'warning' onConfirm: () => void | Promise } export function DestructiveConfirmDialog({ open, onOpenChange, title, description, confirmLabel = 'Bekräfta', cancelLabel = 'Avbryt', variant = 'destructive', onConfirm, }: DestructiveConfirmDialogProps) { const [isLoading, setIsLoading] = useState(false) const handleConfirm = async () => { setIsLoading(true) try { await onConfirm() } finally { setIsLoading(false) onOpenChange(false) } } return ( { if (isLoading) return onOpenChange(v) }} >
{title} {description}
) } interface ConfirmOptions { title: string description: string confirmLabel?: string cancelLabel?: string variant?: 'destructive' | 'warning' } interface UseDestructiveConfirmReturn { dialogProps: DestructiveConfirmDialogProps confirm: (options: ConfirmOptions) => Promise } /** * Hook that returns a `confirm()` function as a drop-in replacement for `window.confirm()`. * Returns `Promise` — true if user confirms, false if they cancel. * * Usage: * ``` * const { dialogProps, confirm } = useDestructiveConfirm() * * async function handleDelete() { * const ok = await confirm({ title: '...', description: '...' }) * if (!ok) return * // proceed with deletion * } * * return <> * ``` */ export function useDestructiveConfirm(): UseDestructiveConfirmReturn { const [open, setOpen] = useState(false) const [options, setOptions] = useState({ title: '', description: '', }) const resolveRef = useRef<((value: boolean) => void) | null>(null) const confirm = useCallback((opts: ConfirmOptions): Promise => { setOptions(opts) setOpen(true) return new Promise((resolve) => { resolveRef.current = resolve }) }, []) const handleOpenChange = useCallback((v: boolean) => { setOpen(v) if (!v && resolveRef.current) { resolveRef.current(false) resolveRef.current = null } }, []) const handleConfirm = useCallback(() => { if (resolveRef.current) { resolveRef.current(true) resolveRef.current = null } }, []) return { dialogProps: { open, onOpenChange: handleOpenChange, title: options.title, description: options.description, confirmLabel: options.confirmLabel, cancelLabel: options.cancelLabel, variant: options.variant, onConfirm: handleConfirm, }, confirm, } }