# Shared View (https://s3.dimah.dev/docs/ui/components/shared-view)

Render the public page of a [share link](https://s3.dimah.dev/docs/share) in one component.
`SharedView` asks for the password when the link has one, then offers the
shared file, or lists the shared folder in a read-only
[`ObjectList`](https://s3.dimah.dev/docs/ui/components/object-list) with search, sort, and a
download per file. A link that does not open says why. To build the page
yourself, follow [The shared page](https://s3.dimah.dev/docs/share/visitor-page).

```tsx title="shared-view-demo.tsx"
"use client";

import { useState } from "react";
import { s3Error } from "@dimah-s3/core";
import type {
  ShareListSharedInput,
  ShareVisitorFolder,
  ShareVisitorObject,
} from "@dimah-s3/share/client";
import { useShareVisit, type ShareVisitorActions } from "@dimah-s3/share/react";
import { SharedView } from "@dimah-s3/ui/share";

const PASSWORD = "demo";
const ROOT: ShareVisitorFolder = {
  id: "drawings",
  name: "Project drawings",
  parentId: null,
};
const FOLDERS: ShareVisitorFolder[] = [
  { id: "details", name: "Details", parentId: null },
];
const FILES: ShareVisitorObject[] = [
  {
    id: "plan",
    name: "Ground-floor-plan.pdf",
    size: 3_145_728,
    contentType: "application/pdf",
    updatedAt: "2026-11-02T10:00:00.000Z",
    folderId: null,
  },
  {
    id: "render",
    name: "Courtyard-render.png",
    size: 1_572_864,
    contentType: "image/png",
    updatedAt: "2026-11-10T10:00:00.000Z",
    folderId: null,
  },
  {
    id: "stair",
    name: "Stair-section.dwg",
    size: 524_288,
    contentType: null,
    updatedAt: "2026-10-28T10:00:00.000Z",
    folderId: "details",
  },
];

/** The visitor actions of one password-protected folder link, in memory. */
function demoShare(): ShareVisitorActions {
  let downloadsLeft = 10;
  const wait = () => new Promise((resolve) => setTimeout(resolve, 200));
  // Read in the calls, never while rendering.
  const expiresAt = () => new Date(Date.now() + 5 * 86_400_000).toISOString();
  return {
    async openLink({ access }) {
      await wait();
      const base = {
        passwordProtected: true,
        expiresAt: expiresAt(),
        downloadsLeft,
      };
      return access === "demo-access"
        ? { link: { ...base, type: "folder", locked: false, folder: ROOT } }
        : { link: { ...base, type: "folder", locked: true } };
    },
    async unlockLink({ password }) {
      await wait();
      if (password !== PASSWORD) throw s3Error("SHARE_PASSWORD_INVALID");
      return { access: "demo-access", expiresAt: expiresAt() };
    },
    async listShared(input: ShareListSharedInput) {
      await wait();
      const folderId = input.folderId || null;
      const search = input.search?.toLowerCase();
      const objects = FILES.filter((file) =>
        search
          ? file.name.toLowerCase().includes(search)
          : file.folderId === folderId,
      );
      return {
        objects,
        nextCursor: null,
        folders: search || folderId ? [] : FOLDERS,
        trail: FOLDERS.filter((folder) => folder.id === folderId),
      };
    },
    async downloadShared() {
      await wait();
      if (downloadsLeft === 0) throw s3Error("SHARE_LINK_EXHAUSTED");
      downloadsLeft -= 1;
      return {
        // A real link sends the browser to a short-lived file URL.
        url: "#shared-view-demo",
        mode: "presign",
        expiresIn: 300,
        disposition: "attachment",
        downloadsLeft,
      };
    },
  };
}

export function SharedViewDemo() {
  const [share] = useState(demoShare);
  const visit = useShareVisit(share, "demo");
  return (
    <div id="shared-view-demo" className="flex w-full flex-col gap-3">
      <p className="text-sm text-fd-muted-foreground">
        The password is <code>{PASSWORD}</code>.
      </p>
      <SharedView visit={visit} height="20rem" />
    </div>
  );
}
```

## Installation [#installation]

<Tabs items={["npm","shadcn"]}>
<Tab value="npm">
```npm
npm i @dimah-s3/share
```

```tsx
import { useShareVisit } from "@dimah-s3/share/react";
import { SharedView } from "@dimah-s3/ui/share";
```
</Tab>

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

Adds `@/components/dimah-s3/share/shared-view` with the `ObjectList` files it
renders, and installs `@dimah-s3/share`.
</Tab>
</Tabs>

## Usage [#usage]

Render it on the page `share({ url })` points at. It takes
[`useShareVisit`](https://s3.dimah.dev/docs/share/api#usesharevisit) for the token in the URL, as
`ObjectList` takes `useObjectList`:

```tsx title="app/s/[token]/page.tsx"
import { SharedPage } from "./shared-page";

export default async function Page({
  params,
}: {
  params: Promise<{ token: string }>;
}) {
  const { token } = await params;
  return <SharedPage token={token} />;
}
```

```tsx title="app/s/[token]/shared-page.tsx"
"use client";

import type { ShareVisitorLink } from "@dimah-s3/share/client";
import { useShareVisit } from "@dimah-s3/share/react";
import { SharedView } from "@dimah-s3/ui/share";
import { s3Client } from "@/lib/s3-client";

export function SharedPage({
  token,
  link,
}: {
  token: string;
  link?: ShareVisitorLink;
}) {
  const visit = useShareVisit(s3Client.share, token, { link });
  return <SharedView visit={visit} />;
}
```

Visitors have no session: let the public share actions through your guard
with [`isSharePublicAction`](https://s3.dimah.dev/docs/share#let-visitors-through-your-guard-step).

## Open the link on the server [#open-the-link-on-the-server]

Pass `link` from `s3.share.api.openLink` to `useShareVisit` to render the file
or folder without a round trip. A locked link still shows the password form.

```tsx title="app/s/[token]/page.tsx"
import { getS3 } from "@/lib/s3";

const { link } = await getS3().share.api.openLink({ token });
return <SharedPage token={token} link={link} />;
```

## Header [#header]

The default header shows the name, the expiry, and the downloads left, and
counts down after each download. Pass `header` to render your own, such as
who sent the link:

```tsx
<SharedView
  visit={visit}
  header={(link) => (
    <h1>{link.type === "folder" ? link.folder.name : link.object.name}</h1>
  )}
/>
```

## Errors [#errors]

Every refusal reads through [`useFormatError`](https://s3.dimah.dev/docs/react/helpers#errors), so
`SHARE_LINK_EXPIRED` reads "This link has expired", in your
[translations](https://s3.dimah.dev/docs/i18n). A link that stops opening while the page is open,
such as one revoked or out of downloads, turns into that message on the next
download or listing. One whose password proof expired asks for the password
again. Any other refused download, such as `TOO_MANY_REQUESTS`, shows above
the file, and a network error offers **Try again**.

## Accessibility [#accessibility]

- The password field is labelled "This file needs a password" or "This folder
  needs a password". A wrong password is announced with `role="alert"`, and
  focus returns to the field with the text selected.
- Once the password opens the link, focus moves to what it opened.
- Each file's download button in a folder is named after the file, and is
  busy while its download starts.
- "Download started" is announced in a polite live region once the browser
  has the file's URL, and the button shows a check for two seconds.
- The downloads left are read out when a download changes them.

## API Reference [#api-reference]

### SharedView [#sharedview]

| Prop        | Type                                        | Default           | Description                                     |
| ----------- | ------------------------------------------- | ----------------- | ----------------------------------------------- |
| `visit`     | `UseShareVisitReturn`                       | required          | `useShareVisit` for the token in the page URL   |
| `header`    | `(link: ShareVisitorOpenLink) => ReactNode` | —                 | Replaces the default header once the link opens |
| `rootLabel` | `string`                                    | the folder's name | The top of a shared folder in its breadcrumb    |
| `height`    | `string`                                    | `"32rem"`         | Height of a shared folder's list                |
| `className` | `string`                                    | —                 | Classes on the outer element                    |