Skip to Content
dimah-s3v2.8.1

Object Preview

Show a stored image, video, audio file, PDF, or text file in the page or a dialog, without saving it.

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.

Pick an image, PDF, video, audio, or text file

Installation

import { ObjectPreview, ObjectPreviewDialog } from "@dimah-s3/ui";

Complete Installation first: the package or registry setup, the stylesheet, and one <Toaster /> in your layout.

Usage

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 decide who may read the file. The dialog signs a URL only while it is open. In ObjectList, pass preview instead.

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

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

What it shows

KindTypesShown with
Imageimage/*<img>
Videovideo/*<video> with the browser's controls
Audioaudio/*<audio> with the browser's controls
PDFapplication/pdfThe browser's PDF viewer in an <iframe>
Texttext/*, JSONThe first 256 KiB in a <pre>, set by maxTextBytes
OtherAnything elseA 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. 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 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 set up.
  • A file the browser cannot play, such as an MKV video, shows the panel.

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 and list thumbnails sign, so an image already on screen opens from the browser cache.

Preview only some kinds with kinds:

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

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.

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

render receives the useObjectPreview state. Return your own view, or undefined to keep the built-in one:

<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.

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

ObjectPreview

Also accepts every div prop except children.

PropTypeDefaultDescription
routestringrequiredRoute that signs the URL
objectKeystring | nullrequiredKey of the stored file. null shows nothing
fileNamestringKey's nameShown name and accessible name
contentTypestring | null—The file's type. A type without a preview signs nothing
fileSizenumber | null—Size in bytes, shown in the panel
kindsObjectPreviewKind[]Every kindKinds to preview. Others show the panel
maxTextBytesnumber262144Most bytes read from a text file
downloadAnyDownloadReturn—Adds Download to the panel
render(preview) => ReactNode | undefined—Your own view. undefined keeps the built-in one
apiS3Api—Signs the URL. Optional inside S3Provider

ObjectPreviewDialog

PropTypeDefaultDescription
routestringrequiredRoute that signs the URL
fileObjectPreviewFile | nullrequiredThe file to show. Open while set
onOpenChange(open) => voidrequiredRuns with false when the dialog asks to close
downloadAnyDownloadReturn—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"
kindsObjectPreviewKind[]Every kindKinds to preview. Others show the panel
maxTextBytesnumber262144Most bytes read from a text file
render(preview) => ReactNode | undefined—Your own view. undefined keeps the built-in one
actionsReactNode—More header controls, before Open in new tab and Download
finalFocus() => HTMLElement | null—Where focus goes on close. null keeps the opener
apiS3Api—Signs the URL. Optional inside S3Provider
classNamestring—Classes for the dialog

ObjectPreviewFile

Fields marked ? are optional.

PropertyTypeDescription
objectKeystringKey of the stored file
fileName?stringSaved name. Defaults to the key's
title?stringTitle and accessible name. Defaults to fileName
contentType?string | nullThe file's type, such as a listed object's
fileSize?number | nullSize 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

On this page