# Object Card (https://s3.dimah.dev/docs/ui/components/object-card)

Show a file you already stored, such as an attachment on a record.
`ObjectCard` renders its name, size, and type, with a download action and a
delete action. It shows the progress of each.

For a whole folder of files, use [Object List](https://s3.dimah.dev/docs/ui/components/object-list).

```tsx title="object-card-demo.tsx"
"use client";

import { useState } from "react";
import { RotateCcwIcon } from "lucide-react";
import { useDelete, useFetchDownload } from "@dimah-s3/react";
import { DeleteToasts, DownloadToasts, ObjectCard } from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";

const FILES = [
  {
    key: "uploads/3f1a/quarterly-report.pdf",
    size: 8 * 1024 * 1024,
    type: "application/pdf",
  },
  {
    key: "uploads/9b2e/brand-assets.zip",
    size: 24 * 1024 * 1024,
    type: "application/zip",
  },
  {
    key: "uploads/c47d/avatar.png",
    size: 180_000,
    type: "image/png",
    previewUrl: "/dimah-avatar.png",
  },
];

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

  return (
    <div className="mx-auto flex w-full max-w-md flex-col gap-2">
      {files.map((file) => (
        <ObjectCard
          key={file.key}
          objectKey={file.key}
          fileSize={file.size}
          contentType={file.type}
          previewUrl={file.previewUrl}
          download={download}
          delete={remove}
          onDeleted={(result) =>
            setFiles((current) =>
              current.filter((item) => !result.deleted.includes(item.key)),
            )
          }
        />
      ))}
      {files.length < FILES.length ? (
        <Button
          variant="ghost"
          size="sm"
          className="self-center"
          onClick={() => setFiles(FILES)}
        >
          <RotateCcwIcon data-icon="inline-start" />
          Restore the demo files
        </Button>
      ) : null}
      <DownloadToasts download={download} />
      <DeleteToasts delete={remove} />
    </div>
  );
}
```

## Installation [#installation]

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

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

Adds `@/components/dimah-s3/preview/object-card` with the download and delete
families.
</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, useFetchDownload } from "@dimah-s3/react";
import { DeleteToasts, DownloadToasts, ObjectCard } from "@dimah-s3/ui";

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

export function Attachments({
  files,
  onRemoved,
}: {
  files: Attachment[];
  onRemoved: (key: string) => void;
}) {
  const download = useFetchDownload({ route: "attachments" });
  const remove = useDelete({ route: "attachments" });

  return (
    <>
      {files.map((file) => (
        <ObjectCard
          key={file.key}
          objectKey={file.key}
          fileSize={file.size}
          contentType={file.type}
          download={download}
          delete={remove}
          onDeleted={(result) => {
            if (result.deleted.includes(file.key)) onRemoved(file.key);
          }}
        />
      ))}
      <DownloadToasts download={download} />
      <DeleteToasts delete={remove} />
    </>
  );
}
```

- Pass only the hooks for the actions you want. Many cards share one hook.
- The card stays after a delete. Remove it in `onDeleted`.
- Mount `DownloadToasts` and `DeleteToasts` once for the hooks.
- With `useFetchDownload`, the card shows the download progress and the action
  cancels.

## Examples [#examples]

### Your own actions [#your-own-actions]

`actions` render before the built-in ones. This Copy link action signs a URL
with the same download hook.

```tsx title="object-card-actions-demo.tsx"
"use client";

import { useState } from "react";
import { CheckIcon, LinkIcon } from "lucide-react";
import { useDownload } from "@dimah-s3/react";
import { AttachmentAction, DownloadToasts, ObjectCard } from "@dimah-s3/ui";

const KEY = "uploads/2c9a/price-list.pdf";

export function ObjectCardActionsDemo() {
  const download = useDownload({ route: "uploads" });
  const [copied, setCopied] = useState(false);

  async function copyLink() {
    // Signs a URL without saving the file.
    const outcome = await download.presign(KEY);
    if (outcome.status !== "success") return;
    await navigator.clipboard.writeText(outcome.data.url);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  }

  return (
    <div className="mx-auto w-full max-w-md">
      <ObjectCard
        objectKey={KEY}
        fileSize={512_000}
        contentType="application/pdf"
        description="Updated Oct 30 · 500 KB"
        download={download}
        actions={
          <AttachmentAction
            aria-label="Copy link to price-list.pdf"
            onClick={() => void copyLink()}
          >
            {copied ? <CheckIcon /> : <LinkIcon />}
          </AttachmentAction>
        }
      />
      <DownloadToasts download={download} />
    </div>
  );
}
```

## API Reference [#api-reference]

Also accepts the [`FileAttachment`](https://s3.dimah.dev/docs/ui/components/attachment) props it
does not set itself, such as `description`, `previewUrl`, `actions`, and
`trigger`.

| Prop          | Type                             | Default             | Description                                                            |
| ------------- | -------------------------------- | ------------------- | ---------------------------------------------------------------------- |
| `objectKey`   | `string`                         | required            | Key of the stored object                                               |
| `fileName`    | `string`                         | Last segment of key | Name shown, and the name the browser saves                             |
| `fileSize`    | `number \| null`                 | —                   | Size in bytes, shown on the second line                                |
| `contentType` | `string \| null`                 | —                   | MIME type. Picks the type glyph without a preview                      |
| `previewUrl`  | `string \| null`                 | —                   | Image thumbnail in place of the glyph                                  |
| `download`    | `AnyDownloadReturn`              | —                   | A `useDownload` or `useFetchDownload` return. Adds the download action |
| `delete`      | `UseDeleteReturn`                | —                   | Adds the delete action and its confirm dialog                          |
| `onDeleted`   | `(result: DeleteResult) => void` | —                   | Runs once a confirmed delete settles                                   |
| `description` | `ReactNode`                      | The size            | Replaces the second line                                               |
| `actions`     | `ReactNode`                      | —                   | Your own `AttachmentAction`s, before the built-in ones                 |