| 1 | 'use client' |
| 2 | |
| 3 | import type { ReactNode } from 'react' |
| 4 | import { useEffect, useState |
| 5 | import { Button } |
| 6 | import { |
| 7 | Dialog, |
| 8 | DialogContent, |
| 9 | DialogDescription, |
| 10 | DialogFooter, |
| 11 | DialogHeader, |
| 12 | DialogTitle, |
| 13 | } from '@/components/ui/dialog' |
| 14 | import { Field } |
| 15 | import { Input } |
| 16 | import { Label } |
| 17 | |
| 18 | interface Props { |
| 19 | actionLabel?: string |
| 20 | /** |
| 21 | * When provided, the user must type this string to enable the action. |
| 22 | * Omit for a simple yes/no confirmation. |
| 23 | */ |
| 24 | confirmationText?: string |
| 25 | description: ReactNode |
| 26 | loading?: boolean |
| 27 | onConfirm: () |
| 28 | onOpenChange: (open |
| 29 | open: boolean |
| 30 | title: string |
| 31 | } |
| 32 | |
| 33 | export function ConfirmDeleteDialog({ |
| 34 | open, |
| 35 | onOpenChange, |
| 36 | title, |
| 37 | description, |
| 38 | confirmationText, |
| 39 | actionLabel = 'Delete' |
| 40 | loading = false, |
| 41 | onConfirm, |
| 42 | }: Props) |
| 43 | const [value, |
| 44 | |
| 45 | useEffect(() => |
| 46 | if (!open) |
| 47 | setValue('') |
| 48 | } |
| 49 | }, [open]) |
| 50 | |
| 51 | const matches = |
| 52 | |
| 53 | const handleSubmit = |
| 54 | e.preventDefault() |
| 55 | if (!matches) |
| 56 | return |
| 57 | } |
| 58 | await onConfirm() |
| 59 | } |
| 60 | |
| 61 | return ( |
| 62 | <Dialog onOpenChange={ |
| 63 | <DialogContent className=' |
| 64 | <DialogHeader> |
| 65 | <DialogTitle>{title} |
| 66 | <DialogDescription>{description} |
| 67 | </DialogHeader> |
| 68 | <form onSubmit={handleSubmit |
| 69 | {confirmationText && ( |
| 70 | <Field className=' |
| 71 | <Label> |
| 72 | Type |
| 73 | <span className='max-w-fit font-semibold |
| 74 | "{confirmationText}" |
| 75 | </span> |
| 76 | to confirm |
| 77 | </Label> |
| 78 | <Input |
| 79 | autoFocus |
| 80 | onChange={(e) |
| 81 | placeholder={confirmationText} |
| 82 | value={value} |
| 83 | /> |
| 84 | </Field> |
| 85 | )} |
| 86 | <DialogFooter className=' |
| 87 | <Button |
| 88 | onClick={() => |
| 89 | type='button' |
| 90 | variant='outline' |
| 91 | > |
| 92 | Cancel |
| 93 | </Button> |
| 94 | <Button |
| 95 | autoFocus={!confirmationText} |
| 96 | disabled={!matches} |
| 97 | loading={loading} |
| 98 | type='submit' |
| 99 | variant='destructive' |
| 100 | > |
| 101 | {actionLabel} |
| 102 | </Button> |
| 103 | </DialogFooter> |
| 104 | </form> |
| 105 | </DialogContent> |
| 106 | </Dialog> |
| 107 | ) |
| 108 | } |