# Delete (https://s3.dimah.dev/docs/ui/components/delete)

Delete stored files after a confirmation. `Delete` holds one
[`useDelete`](https://s3.dimah.dev/docs/react/hooks/delete) hook and one confirm dialog. Every
`DeleteTrigger` inside it asks the root, which confirms, deletes, and reports
the result.

```tsx title="delete-demo.tsx"
"use client";

import { useState } from "react";
import { RotateCcwIcon, Trash2Icon } from "lucide-react";
import { useDelete } from "@dimah-s3/react";
import {
  Delete,
  DeleteToasts,
  DeleteTrigger,
  FileAttachment,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

const FILES = [
  {
    key: "uploads/4d1e/meeting-notes.docx",
    name: "meeting-notes.docx",
    size: 48_000,
  },
  { key: "uploads/8a7c/old-logo.png", name: "old-logo.png", size: 220_000 },
  { key: "uploads/b6f0/draft-v1.pdf", name: "draft-v1.pdf", size: 1_350_000 },
];

export function DeleteDemo() {
  const remove = useDelete({ route: "uploads" });
  const [files, setFiles] = useState(FILES);

  return (
    <div className="mx-auto w-full max-w-md">
      <Delete
        delete={remove}
        onDeleted={(result) =>
          setFiles((current) =>
            current.filter((file) => !result.deleted.includes(file.key)),
          )
        }
      >
        {files.length > 0 ? (
          <ul className="flex flex-col gap-2">
            {files.map((file) => (
              <li key={file.key}>
                <FileAttachment
                  state="done"
                  fileName={file.name}
                  fileSize={file.size}
                  actions={
                    <DeleteTrigger
                      objectKey={file.key}
                      fileName={file.name}
                      fileSize={file.size}
                      variant="ghost"
                      size="icon-xs"
                      aria-label={`Delete ${file.name}`}
                      tooltip="Delete"
                    >
                      <Trash2Icon />
                    </DeleteTrigger>
                  }
                />
              </li>
            ))}
          </ul>
        ) : (
          <div className="flex flex-col items-center gap-2 text-sm text-muted-foreground">
            All files deleted.
            <Button variant="outline" size="sm" onClick={() => setFiles(FILES)}>
              <RotateCcwIcon data-icon="inline-start" />
              Restore the demo files
            </Button>
          </div>
        )}
      </Delete>
      <DeleteToasts delete={remove} />
    </div>
  );
}
```

## Installation [#installation]

<Tabs items={["npm","shadcn"]}>
<Tab value="npm">
```tsx
import { Delete, DeleteToasts, DeleteTrigger } from "@dimah-s3/ui";
```
</Tab>

<Tab value="shadcn">
```npm
npx shadcn@latest add @dimah-s3/delete
```

The parts land in `components/dimah-s3/delete/`, one file each, such as
`@/components/dimah-s3/delete/delete-trigger`.
</Tab>
</Tabs>

Complete [Installation](https://s3.dimah.dev/docs/ui/installation) first: the package or registry
setup, the stylesheet, and one `<Toaster />` in your layout.

## Usage [#usage]

```tsx
"use client";

import { useDelete } from "@dimah-s3/react";
import { Delete, DeleteToasts, DeleteTrigger } from "@dimah-s3/ui";

type Attachment = { key: string; name: string; size: number };

export function AttachmentList({
  attachments,
  onRemoved,
}: {
  attachments: Attachment[];
  onRemoved: (keys: string[]) => void;
}) {
  const remove = useDelete({ route: "attachments" });

  return (
    <>
      <Delete delete={remove} onDeleted={(result) => onRemoved(result.deleted)}>
        <ul>
          {attachments.map((file) => (
            <li key={file.key}>
              {file.name}
              <DeleteTrigger
                objectKey={file.key}
                fileName={file.name}
                fileSize={file.size}
                size="sm"
              />
            </li>
          ))}
        </ul>
      </Delete>
      <DeleteToasts delete={remove} />
    </>
  );
}
```

`onDeleted` gets the keys that were `deleted`, `failed`, or `blocked`. Remove
the deleted rows there.

## Anatomy [#anatomy]

```tsx
<Delete delete={remove}>
  <DeleteTrigger objectKey={key} />
</Delete>
<DeleteToasts delete={remove} />
```

| Part                  | Description                                                          |
| --------------------- | -------------------------------------------------------------------- |
| `Delete`              | Root. Holds the hook and renders one confirm dialog for its triggers |
| `DeleteTrigger`       | A destructive `Button` that asks the root to delete one object       |
| `DeleteConfirmDialog` | The default dialog. Pass it to `dialog` with your own copy           |
| `DeleteToasts`        | Success and error toasts. Mount once per hook                        |

## Examples [#examples]

### Triggers and dialogs [#triggers-and-dialogs]

`note` on a trigger adds a line to the dialog. `dialog` on the root replaces
its copy, and `confirm={false}` deletes on click.

```tsx title="delete-variants-demo.tsx"
"use client";

import { Trash2Icon } from "lucide-react";
import { useDelete } from "@dimah-s3/react";
import {
  Delete,
  DeleteConfirmDialog,
  DeleteToasts,
  DeleteTrigger,
} from "@dimah-s3/ui";

const FILE = {
  objectKey: "uploads/71ce/contract-signed.pdf",
  fileName: "contract-signed.pdf",
  fileSize: 2_400_000,
};

export function DeleteVariantsDemo() {
  const remove = useDelete({ route: "uploads" });

  return (
    <div className="flex flex-wrap items-center justify-center gap-2">
      {/* The default dialog names the file and its size. */}
      <Delete delete={remove}>
        <DeleteTrigger {...FILE} />
        <DeleteTrigger {...FILE} variant="outline" />
        <DeleteTrigger
          {...FILE}
          variant="ghost"
          size="icon"
          aria-label="Delete contract-signed.pdf"
          tooltip="Delete"
        >
          <Trash2Icon />
        </DeleteTrigger>
        <DeleteTrigger
          {...FILE}
          variant="outline"
          note="The signed copy is also kept by the client."
        >
          With a note
        </DeleteTrigger>
      </Delete>

      {/* Your own copy in the dialog. */}
      <Delete
        delete={remove}
        dialog={
          <DeleteConfirmDialog
            title="Remove the signed contract?"
            description="Both parties lose access to this copy."
            confirmLabel="Remove contract"
            cancelLabel="Keep it"
          />
        }
      >
        <DeleteTrigger {...FILE} variant="outline">
          Custom dialog
        </DeleteTrigger>
      </Delete>

      {/* No dialog: the delete starts on click. */}
      <Delete delete={remove} confirm={false}>
        <DeleteTrigger {...FILE} variant="outline">
          Without confirm
        </DeleteTrigger>
      </Delete>

      <DeleteToasts delete={remove} />
    </div>
  );
}
```

### Delete several files [#delete-several-files]

A trigger of your own calls `request` from `useDeleteContext()` with every
target. One dialog asks for all of them.

```tsx title="delete-bulk-demo.tsx"
"use client";

import { useState } from "react";
import { Trash2Icon } from "lucide-react";
import { useDelete } from "@dimah-s3/react";
import {
  Delete,
  DeleteToasts,
  FileAttachment,
  useDeleteContext,
  type DeleteTarget,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

const FILES: DeleteTarget[] = [
  { objectKey: "uploads/e1/scan-001.pdf", fileName: "scan-001.pdf" },
  { objectKey: "uploads/e2/scan-002.pdf", fileName: "scan-002.pdf" },
  { objectKey: "uploads/e3/scan-003.pdf", fileName: "scan-003.pdf" },
];

export function DeleteBulkDemo() {
  const remove = useDelete({ route: "uploads" });
  const [files, setFiles] = useState(FILES);

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-3">
      <Delete
        delete={remove}
        onDeleted={(result) =>
          setFiles((current) =>
            current.filter((file) => !result.deleted.includes(file.objectKey)),
          )
        }
      >
        <ul className="flex flex-col gap-2">
          {files.map((file) => (
            <li key={file.objectKey}>
              <FileAttachment state="done" fileName={file.fileName ?? ""} />
            </li>
          ))}
        </ul>
        {files.length > 0 ? (
          <DeleteAllButton targets={files} />
        ) : (
          <Button variant="outline" size="sm" onClick={() => setFiles(FILES)}>
            Restore the demo files
          </Button>
        )}
      </Delete>
      <DeleteToasts delete={remove} />
    </div>
  );
}

/** A trigger of your own: one confirm for every target. */
function DeleteAllButton({ targets }: { targets: DeleteTarget[] }) {
  const { request, delete: remove } = useDeleteContext();

  return (
    <Button
      variant="destructive"
      className="self-start"
      disabled={remove.isPending}
      onClick={(event) => request(targets, { trigger: event.currentTarget })}
    >
      <Trash2Icon data-icon="inline-start" />
      Delete all {targets.length} files
    </Button>
  );
}
```

## Confirmation [#confirmation]

Replace the dialog's copy with `dialog`:

```tsx
<Delete
  delete={remove}
  dialog={
    <DeleteConfirmDialog
      title="Remove profile picture?"
      description="Your profile goes back to the default avatar."
      confirmLabel="Remove"
    />
  }
>
  <DeleteTrigger objectKey={avatarKey} />
</Delete>
```

For a dialog of your own, read `confirmation` and `isDeleting` from
`useDeleteContext()`, and call `confirm()` and `dismiss()`.

## Your own triggers [#your-own-triggers]

`request` takes one target or a list, so one confirmation covers a bulk
delete:

```tsx
function DeleteSelected({ files }: { files: Attachment[] }) {
  const { request } = useDeleteContext();

  return (
    <Button
      variant="destructive"
      onClick={(event) =>
        request(
          files.map((file) => ({ objectKey: file.key, fileName: file.name })),
          { trigger: event.currentTarget },
        )
      }
    >
      Delete {files.length} files
    </Button>
  );
}
```

## Focus [#focus]

When a deleted row unmounts with its trigger, focus goes to the nearest
`[data-dimah-s3-focus-root]`. Mark the list:

```tsx
<ul data-dimah-s3-focus-root tabIndex={-1}>
  {/* rows with DeleteTrigger */}
</ul>
```

## Toasts [#toasts]

Mount `DeleteToasts` once per hook. It shows one result toast per call.

## Accessibility [#accessibility]

- The dialog is an alert dialog with initial focus on Cancel.
- At an icon size the trigger keeps "Delete" as its accessible name.

## API Reference [#api-reference]

### Delete [#delete]

| Prop           | Type                                               | Default                   | Description                                              |
| -------------- | -------------------------------------------------- | ------------------------- | -------------------------------------------------------- |
| `delete`       | `UseDeleteReturn`                                  | required                  | The `useDelete` return                                   |
| `confirm`      | `boolean`                                          | `true`                    | Asks before deleting                                     |
| `dialog`       | `ReactNode`                                        | `<DeleteConfirmDialog />` | Replaces the confirm dialog                              |
| `onDeleted`    | `(result: DeleteResult) => void`                   | —                         | Runs once per confirmed delete, before the dialog closes |
| `restoreFocus` | `(targets: DeleteTarget[]) => HTMLElement \| null` | —                         | Where focus goes after the dialog closes                 |
| `children`     | `ReactNode`                                        | required                  | The triggers                                             |

### DeleteTrigger [#deletetrigger]

Also accepts every `Button` prop. `variant` defaults to `"destructive"`.

| Prop        | Type             | Default             | Description                   |
| ----------- | ---------------- | ------------------- | ----------------------------- |
| `objectKey` | `string`         | required            | Key of the object to delete   |
| `fileName`  | `string`         | Last segment of key | Name in the dialog and toasts |
| `fileSize`  | `number \| null` | —                   | Size shown in the dialog      |
| `note`      | `ReactNode`      | —                   | Extra line in the dialog      |
| `tooltip`   | `ReactNode`      | —                   | Tooltip on hover and focus    |
| `children`  | `ReactNode`      | Icon and "Delete"   | Replaces the icon and label   |

### DeleteConfirmDialog [#deleteconfirmdialog]

Each prop replaces the default copy.

| Prop           | Type        | Description          |
| -------------- | ----------- | -------------------- |
| `title`        | `ReactNode` | Dialog title         |
| `description`  | `ReactNode` | Dialog description   |
| `confirmLabel` | `ReactNode` | Confirm button label |
| `cancelLabel`  | `ReactNode` | Cancel button label  |

### DeleteToasts [#deletetoasts]

| Prop     | Type              | Default  | Description               |
| -------- | ----------------- | -------- | ------------------------- |
| `delete` | `UseDeleteReturn` | required | The hook return to report |

### useDeleteContext [#usedeletecontext]

Returns the root's state inside `Delete`.

| Property       | Type                                               | Description                                                       |
| -------------- | -------------------------------------------------- | ----------------------------------------------------------------- |
| `delete`       | `UseDeleteReturn`                                  | The root's hook                                                   |
| `confirmation` | `{ targets, title?, description?, note? } \| null` | The request the dialog asks about, or `null` while it is closed   |
| `isDeleting`   | `boolean`                                          | The confirmed request is deleting                                 |
| `request`      | `(targets, options?) => void`                      | Asks to delete one target or a list. Replaces a waiting request   |
| `confirm`      | `() => Promise<DeleteResult>`                      | Deletes the targets of `confirmation`, then closes. Never rejects |
| `dismiss`      | `() => void`                                       | Closes the dialog without deleting                                |

A target is `{ objectKey, fileName?, fileSize? }`. `request` options:

| Option        | Type                                | Description                                                                                                                                  |
| ------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`       | `ReactNode`                         | The dialog's title for this request                                                                                                          |
| `description` | `ReactNode`                         | The dialog's description for this request                                                                                                    |
| `note`        | `ReactNode`                         | Extra line in the dialog                                                                                                                     |
| `run`         | `(remove) => Promise<DeleteResult>` | Deletes in place of the targets, such as a folder and its files. `remove(targets)` deletes with the root's hook. `targets` may then be empty |
| `trigger`     | `HTMLElement \| null`               | Where focus returns. Defaults to the focused element                                                                                         |
| `onDeleted`   | `(result: DeleteResult) => void`    | Runs after the root's `onDeleted`, once this request settles                                                                                 |
| `onDismissed` | `() => void`                        | Runs when the request ends without deleting                                                                                                  |