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

Show what a stored file looks like without saving it. `ObjectPreview` renders
the preview in your layout, and `ObjectPreviewDialog` opens it in a large
dialog with Download and Previous and Next. For images only, use
[`ObjectImage`](https://s3.dimah.dev/docs/ui/components/object-image).

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

import { useState } from "react";
import { EyeIcon } from "lucide-react";
import { useUpload } from "@dimah-s3/react";
import {
  ObjectPreview,
  ObjectPreviewDialog,
  Upload,
  UploadToasts,
  UploadTrigger,
  type ObjectPreviewFile,
} from "@dimah-s3/ui";
import { Button } from "@/components/ui/button";
import { rememberDemoFile } from "@/lib/demo/client-object-store";

export function ObjectPreviewDemo() {
  const [file, setFile] = useState<ObjectPreviewFile | null>(null);
  const [open, setOpen] = useState(false);
  const upload = useUpload({
    route: "previews",
    accept: ["image/*", "application/pdf", "video/*", "audio/*", "text/plain"],
    maxFileSize: 25 * 1024 * 1024,
    onSuccess: (result, picked) => {
      // Demo only: keep the bytes in the browser so the file can be shown.
      rememberDemoFile(result.key, picked);
      setFile({
        objectKey: result.key,
        fileName: picked.name,
        contentType: picked.type,
        fileSize: picked.size,
      });
    },
  });

  return (
    <div className="flex w-full max-w-xl flex-col gap-3">
      {file ? (
        <ObjectPreview
          route="previews"
          objectKey={file.objectKey}
          fileName={file.fileName}
          contentType={file.contentType}
          fileSize={file.fileSize}
          className="h-72 rounded-xl border bg-fd-muted/40"
        />
      ) : (
        <div className="flex h-72 items-center justify-center rounded-xl border border-dashed text-sm text-fd-muted-foreground">
          Pick an image, PDF, video, audio, or text file
        </div>
      )}
      <div className="flex flex-wrap items-center gap-2">
        <Upload upload={upload}>
          <UploadTrigger size="sm">Choose a file</UploadTrigger>
        </Upload>
        <Button
          size="sm"
          variant="outline"
          disabled={!file}
          onClick={() => setOpen(true)}
        >
          <EyeIcon data-icon="inline-start" />
          Open in a dialog
        </Button>
      </div>
      <ObjectPreviewDialog
        route="previews"
        file={open ? file : null}
        onOpenChange={setOpen}
      />
      <UploadToasts upload={upload} />
    </div>
  );
}
```

## Installation [#installation]

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

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

Adds `@/components/dimah-s3/preview/object-preview` and
`@/components/dimah-s3/preview/object-preview-dialog`, with the download parts
they use.
</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 title="components/file-viewer.tsx"
"use client";

import { useState } from "react";
import { useDownload } from "@dimah-s3/react";
import { ObjectPreviewDialog, type ObjectPreviewFile } from "@dimah-s3/ui";

export function FileViewer({ files }: { files: ObjectPreviewFile[] }) {
  const [open, setOpen] = useState<ObjectPreviewFile | null>(null);
  const download = useDownload({ route: "files" });

  return (
    <>
      {files.map((file) => (
        <button key={file.objectKey} onClick={() => setOpen(file)}>
          {file.fileName}
        </button>
      ))}
      <ObjectPreviewDialog
        route="files"
        file={open}
        onOpenChange={(isOpen) => !isOpen && setOpen(null)}
        download={download}
      />
    </>
  );
}
```

`route` must allow downloads, and its
[download hooks](https://s3.dimah.dev/docs/server/hooks/download) decide who may read the file. The
dialog signs a URL only while it is open. In
[`ObjectList`](https://s3.dimah.dev/docs/ui/components/object-list#preview), pass `preview` instead.

Render the preview in place, such as in a side panel, with `ObjectPreview`:

```tsx
<ObjectPreview
  route="files"
  objectKey={file.key}
  fileName={file.name}
  contentType={file.contentType}
  className="h-96 rounded-lg border"
/>
```

## What it shows [#what-it-shows]

| Kind  | Types             | Shown with                                                                |
| ----- | ----------------- | ------------------------------------------------------------------------- |
| Image | `image/*`         | `<img>`                                                                   |
| Video | `video/*`         | `<video>` with the browser's controls                                     |
| Audio | `audio/*`         | `<audio>` with the browser's controls                                     |
| PDF   | `application/pdf` | The browser's PDF viewer in an `<iframe>`                                 |
| Text  | `text/*`, JSON    | The first 256 KiB in a `<pre>`, set by `maxTextBytes`                     |
| Other | Anything else     | A panel with the file's icon, name, and size, and Download for `download` |

- **The server decides.** A file opens in the browser only when its type is on the route's [`inlineTypes`](https://s3.dimah.dev/docs/server/routes#download). Anything else shows the panel, even an image. SVG and HTML stay off the list unless you add them.
- **Preview PDFs in presign mode.** A route in [proxy mode](https://s3.dimah.dev/docs/server/file-proxy#inline-display) leaves `application/pdf` out of `inlineTypes`, and even when you list it, Safari shows an empty frame for a PDF from `/file`.
- **Mobile PDF.** A browser without an inline PDF viewer (`navigator.pdfViewerEnabled` is `false`) gets Open in new tab.
- **Text needs CORS.** The start of a text file is read with `fetch`, so in presign mode the bucket's CORS rules must allow `GET` from your app, as the [provider guides](https://s3.dimah.dev/docs/providers) set up.
- **A file the browser cannot play**, such as an MKV video, shows the panel.

## Cost [#cost]

A preview transfers bytes like a download does.

- `contentType` or a file name that rules out a preview, or a kind left out of `kinds`, signs and reads nothing.
- Video and audio load their metadata until you press play.
- A text file reads at most `maxTextBytes`.
- The URL is the one [`ObjectImage`](https://s3.dimah.dev/docs/ui/components/object-image) and list thumbnails sign, so an image already on screen opens from the browser cache.

Preview only some kinds with `kinds`:

```tsx
<ObjectPreviewDialog
  route="files"
  file={file}
  onOpenChange={onOpenChange}
  kinds={["image", "pdf"]}
/>
```

## Previous and Next [#previous-and-next]

Pass `onPrevious`, `onNext`, and `position`, and the header shows Previous,
Next, and "3 of 12". The arrow keys move too, except while a video or a field
has focus. Leave out a callback at the end of the set to disable it.

```tsx
const index = files.findIndex((file) => file.objectKey === open?.objectKey);

<ObjectPreviewDialog
  route="files"
  file={open}
  onOpenChange={(isOpen) => !isOpen && setOpen(null)}
  position={{ index, count: files.length }}
  onPrevious={index > 0 ? () => setOpen(files[index - 1]) : undefined}
  onNext={
    index < files.length - 1 ? () => setOpen(files[index + 1]) : undefined
  }
/>;
```

## Your own viewer [#your-own-viewer]

`render` receives the [`useObjectPreview`](https://s3.dimah.dev/docs/react/hooks/object-preview)
state. Return your own view, or `undefined` to keep the built-in one:

```tsx
<ObjectPreview
  route="files"
  objectKey={file.key}
  render={(preview) =>
    preview.kind === "pdf" && preview.url ? (
      <PdfJsViewer url={preview.url} />
    ) : undefined
  }
/>
```

For a type the browser cannot show, such as a Word file, return a component
that signs its own URL with [`useObjectUrl`](https://s3.dimah.dev/docs/react/hooks/object-url).

## Accessibility [#accessibility]

- The dialog is named by the file's `title`, else its name. Escape closes it, and focus goes back to the control that opened it, or to `finalFocus()`.
- The image's `alt`, the frame's `title`, and the player's name are the file name.
- The text is one tab stop, so the keyboard can scroll it. Its direction follows its first strong character.
- Previous and Next stay focusable when disabled, so focus does not jump at the ends of the set. In a right-to-left page, ArrowLeft goes to the next file.

## API Reference [#api-reference]

### ObjectPreview [#objectpreview]

Also accepts every `div` prop except `children`.

| Prop           | Type                                  | Default    | Description                                             |
| -------------- | ------------------------------------- | ---------- | ------------------------------------------------------- |
| `route`        | `string`                              | required   | Route that signs the URL                                |
| `objectKey`    | `string \| null`                      | required   | Key of the stored file. `null` shows nothing            |
| `fileName`     | `string`                              | Key's name | Shown name and accessible name                          |
| `contentType`  | `string \| null`                      | —          | The file's type. A type without a preview signs nothing |
| `fileSize`     | `number \| null`                      | —          | Size in bytes, shown in the panel                       |
| `kinds`        | `ObjectPreviewKind[]`                 | Every kind | Kinds to preview. Others show the panel                 |
| `maxTextBytes` | `number`                              | `262144`   | Most bytes read from a text file                        |
| `download`     | `AnyDownloadReturn`                   | —          | Adds Download to the panel                              |
| `render`       | `(preview) => ReactNode \| undefined` | —          | Your own view. `undefined` keeps the built-in one       |
| `api`          | `S3Api`                               | —          | Signs the URL. Optional inside `S3Provider`             |

### ObjectPreviewDialog [#objectpreviewdialog]

| Prop           | Type                                  | Default    | Description                                               |
| -------------- | ------------------------------------- | ---------- | --------------------------------------------------------- |
| `route`        | `string`                              | required   | Route that signs the URL                                  |
| `file`         | `ObjectPreviewFile \| null`           | required   | The file to show. Open while set                          |
| `onOpenChange` | `(open) => void`                      | required   | Runs with `false` when the dialog asks to close           |
| `download`     | `AnyDownloadReturn`                   | —          | Adds Download to the header and the panel                 |
| `onPrevious`   | `() => void`                          | —          | Shows the file before. Disabled when left out             |
| `onNext`       | `() => void`                          | —          | Shows the file after. Disabled when left out              |
| `position`     | `{ index, count }`                    | —          | Where the file sits in the set, from 0. Shows "3 of 12"   |
| `kinds`        | `ObjectPreviewKind[]`                 | Every kind | Kinds to preview. Others show the panel                   |
| `maxTextBytes` | `number`                              | `262144`   | Most bytes read from a text file                          |
| `render`       | `(preview) => ReactNode \| undefined` | —          | Your own view. `undefined` keeps the built-in one         |
| `actions`      | `ReactNode`                           | —          | More header controls, before Open in new tab and Download |
| `finalFocus`   | `() => HTMLElement \| null`           | —          | Where focus goes on close. `null` keeps the opener        |
| `api`          | `S3Api`                               | —          | Signs the URL. Optional inside `S3Provider`               |
| `className`    | `string`                              | —          | Classes for the dialog                                    |

### ObjectPreviewFile [#objectpreviewfile]

Fields marked `?` are optional.

| Property       | Type             | Description                                       |
| -------------- | ---------------- | ------------------------------------------------- |
| `objectKey`    | `string`         | Key of the stored file                            |
| `fileName?`    | `string`         | Saved name. Defaults to the key's                 |
| `title?`       | `string`         | Title and accessible name. Defaults to `fileName` |
| `contentType?` | `string \| null` | The file's type, such as a listed object's        |
| `fileSize?`    | `number \| null` | Size in bytes, shown under the title              |

Set `title` when the dialog shows a name other than the saved one, such as
"Site plan" for `site-plan.pdf`: the header and the panel show the title, and
Download saves `fileName`.

## Frequently asked questions [#frequently-asked-questions]

<Accordions>
<Accordion title="Why does a file show the panel instead of a preview?">
Its type is not on the route's `inlineTypes`, it is not a kind the browser
shows, or it is left out of `kinds`. Add the type to
[`download.inlineTypes`](https://s3.dimah.dev/docs/server/routes#download) to open it in the
browser.
</Accordion>

<Accordion title="Can it show Word, Excel, or PowerPoint files?">
Not built in: browsers do not render them, and online viewers need a public
URL. Render them with a library of your choice through `render`.
</Accordion>

<Accordion title="Can a user still save the file?">
Yes. A preview sends the file's bytes to the browser, so it does not stop a
user from saving them. Keep files private with your download hooks.
</Accordion>
</Accordions>