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

A file browser for the files your app stores. `ObjectList` renders a
[`useObjectList`](https://s3.dimah.dev/docs/react/hooks/object-list) catalog with folders, list
and grid views, search, sort, and paging. Each hook you pass turns on a
feature: selection, upload, download, share, and delete.

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

import { useState } from "react";
import { s3Error } from "@dimah-s3/core";
import {
  useDelete,
  useDownload,
  useObjectList,
  useObjectListSelection,
  useUpload,
  type ObjectListFolder,
  type ObjectListSource,
} from "@dimah-s3/react";
import { memoryObjectSource } from "@dimah-s3/react/engine";
import {
  ObjectList,
  ObjectListContent,
  ObjectListHeader,
  ObjectListSearch,
  ObjectListSortMenu,
  ObjectListUploadStatus,
  ObjectListUsage,
  ObjectListViewToggle,
  UploadTrigger,
} from "@dimah-s3/ui";
import {
  getDemoFileUrl,
  rememberDemoFile,
} from "@/lib/demo/client-object-store";

type LibraryFile = {
  id: string;
  name: string;
  /** `/`-separated folder path, or `null` for the root. */
  folder: string | null;
  size: number;
  type: string;
  updatedAt: string;
  key?: string;
};

const FILES: LibraryFile[] = [
  {
    id: "brand",
    name: "Brand-guidelines-final-approved-for-print-and-web-Q4-2026-do-not-rename.pdf",
    folder: null,
    size: 2_481_152,
    type: "application/pdf",
    updatedAt: "2026-06-08",
  },
  {
    id: "cover",
    name: "Cover.png",
    folder: null,
    size: 1_843_200,
    type: "image/png",
    updatedAt: "2026-02-15",
  },
  {
    id: "notes",
    name: "Launch notes.md",
    folder: null,
    size: 4_096,
    type: "text/markdown",
    updatedAt: "2026-07-22",
  },
  {
    id: "roadmap",
    name: "Roadmap.pdf",
    folder: null,
    size: 860_160,
    type: "application/pdf",
    updatedAt: "2026-03-01",
  },
  {
    id: "pricing",
    name: "Pricing.xlsx",
    folder: null,
    size: 48_128,
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    updatedAt: "2026-08-08",
  },
  {
    id: "kickoff",
    name: "Kickoff.mp4",
    folder: null,
    size: 4_194_304,
    type: "video/mp4",
    updatedAt: "2026-04-15",
  },
  {
    id: "contract",
    name: "Contract.docx",
    folder: null,
    size: 92_160,
    type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    updatedAt: "2026-09-22",
  },
  {
    id: "spec",
    name: "Product spec.md",
    folder: null,
    size: 18_432,
    type: "text/markdown",
    updatedAt: "2026-05-01",
  },
  {
    id: "budget",
    name: "Q4 budget.xlsx",
    folder: null,
    size: 61_440,
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    updatedAt: "2026-01-08",
  },
  {
    id: "team",
    name: "Team.jpg",
    folder: null,
    size: 1_572_864,
    type: "image/jpeg",
    updatedAt: "2026-06-15",
  },
  {
    id: "release",
    name: "Release notes.txt",
    folder: null,
    size: 6_144,
    type: "text/plain",
    updatedAt: "2026-02-22",
  },
  {
    id: "proposal",
    name: "Proposal.pdf",
    folder: null,
    size: 737_280,
    type: "application/pdf",
    updatedAt: "2026-07-01",
  },
  {
    id: "film",
    name: "Brand film.mp4",
    folder: null,
    size: 6_291_456,
    type: "video/mp4",
    updatedAt: "2026-03-08",
  },
  {
    id: "a11y",
    name: "Accessibility.md",
    folder: null,
    size: 9_216,
    type: "text/markdown",
    updatedAt: "2026-08-15",
  },
  {
    id: "q1",
    name: "Q1.pdf",
    folder: "Invoices",
    size: 524_288,
    type: "application/pdf",
    updatedAt: "2026-04-22",
  },
  {
    id: "q2",
    name: "Q2.pdf",
    folder: "Invoices",
    size: 610_304,
    type: "application/pdf",
    updatedAt: "2026-09-01",
  },
  {
    id: "q3",
    name: "Q3.pdf",
    folder: "Invoices",
    size: 487_424,
    type: "application/pdf",
    updatedAt: "2026-05-08",
  },
  {
    id: "q4",
    name: "Q4.pdf",
    folder: "Invoices",
    size: 552_960,
    type: "application/pdf",
    updatedAt: "2026-01-15",
  },
  {
    id: "receipt",
    name: "Receipt.png",
    folder: "Invoices/2026",
    size: 184_320,
    type: "image/png",
    updatedAt: "2026-06-22",
  },
  {
    id: "january",
    name: "January.pdf",
    folder: "Invoices/2026/January",
    size: 90_112,
    type: "application/pdf",
    updatedAt: "2026-02-01",
  },
  {
    id: "hero",
    name: "Hero.png",
    folder: "Images",
    size: 3_200_000,
    type: "image/png",
    updatedAt: "2026-07-08",
  },
  {
    id: "logo",
    name: "Logo.svg",
    folder: "Images",
    size: 12_288,
    type: "image/svg+xml",
    updatedAt: "2026-03-15",
  },
  {
    id: "icon",
    name: "Icon.png",
    folder: "Images",
    size: 24_576,
    type: "image/png",
    updatedAt: "2026-08-22",
  },
  {
    id: "social",
    name: "Social.png",
    folder: "Images",
    size: 409_600,
    type: "image/png",
    updatedAt: "2026-04-01",
  },
  {
    id: "texture",
    name: "Texture.jpg",
    folder: "Images",
    size: 890_880,
    type: "image/jpeg",
    updatedAt: "2026-09-08",
  },
  {
    id: "wordmark",
    name: "Wordmark.svg",
    folder: "Images",
    size: 8_192,
    type: "image/svg+xml",
    updatedAt: "2026-05-15",
  },
  {
    id: "portrait",
    name: "Portrait.jpg",
    folder: "Images",
    size: 1_245_184,
    type: "image/jpeg",
    updatedAt: "2026-01-22",
  },
  {
    id: "pattern",
    name: "Pattern.png",
    folder: "Images",
    size: 327_680,
    type: "image/png",
    updatedAt: "2026-06-01",
  },
];

const PAGE_SIZE = 6;
const PAGE_DELAY_MS = 400;
const LIMITS = {
  maxBytes: 32 * 1024 * 1024,
  maxFiles: 40,
};

function fileObjectKey(file: LibraryFile) {
  return file.key ?? `uploads/${file.id}/${file.name}`;
}

function isInFolder(path: string | null, folder: string) {
  return path === folder || (path?.startsWith(`${folder}/`) ?? false);
}

/** Folder ids are paths. A rename rewrites that path and everything inside it. */
function rewriteFolderPath(path: string, from: string, to: string) {
  if (path === from) return to;
  const prefix = `${from}/`;
  if (!path.startsWith(prefix)) return path;
  return to + path.slice(from.length);
}

/** A folder name as the demo takes it, else `FOLDER_INVALID`. */
function folderName(input: string) {
  const name = input.trim();
  if (!name || name === "." || name === ".." || name.includes("/")) {
    throw s3Error("FOLDER_INVALID");
  }
  return name;
}

/** The demo's records. Uploads, deletes, renames, moves, and New folder edit them. */
function createCatalog() {
  let files = FILES;
  /** Folders made with New folder. They stay listed while empty. */
  let folders = new Set<string>();
  return {
    files: () => files,
    add(file: LibraryFile) {
      files = [...files, file];
    },
    remove(objectKey: string) {
      files = files.filter((file) => fileObjectKey(file) !== objectKey);
    },
    /** Created folders that sit directly in `parent`. */
    emptyFolders(parent: string | null): ObjectListFolder[] {
      const prefix = parent ? `${parent}/` : "";
      return [...folders]
        .filter((id) => id.startsWith(prefix))
        .map((id) => ({ id, name: id.slice(prefix.length) }))
        .filter((folder) => !folder.name.includes("/"));
    },
    renameFile(id: string, name: string): LibraryFile {
      const current = files.find((file) => file.id === id);
      if (!current) throw s3Error("OBJECT_NOT_FOUND");
      // Pin the key before the name changes, so download still finds the blob.
      const next: LibraryFile = {
        ...current,
        name,
        key: current.key ?? fileObjectKey(current),
      };
      files = files.map((file) => (file.id === id ? next : file));
      return next;
    },
    renameFolder(id: string, input: string): ObjectListFolder {
      const name = folderName(input);
      const parent = id.includes("/") ? id.slice(0, id.lastIndexOf("/")) : null;
      return placeFolder(id, parent, name);
    },
    moveFolder(id: string, parent: string | null) {
      if (parent === id || (parent?.startsWith(`${id}/`) ?? false)) {
        throw s3Error("FOLDER_INVALID");
      }
      placeFolder(id, parent, id.slice(id.lastIndexOf("/") + 1));
    },
    moveFile(id: string, parent: string | null) {
      files = files.map((file) =>
        file.id === id ? { ...file, folder: parent } : file,
      );
    },
    createFolder(parent: string | null, input: string): ObjectListFolder {
      const name = folderName(input);
      const id = parent ? `${parent}/${name}` : name;
      if (exists(id)) throw s3Error("FOLDER_EXISTS");
      folders = new Set(folders).add(id);
      return { id, name };
    },
    /** Drops a folder and the empty ones below it once their files are gone. */
    deleteFolder(id: string) {
      if (files.some((file) => isInFolder(file.folder, id))) {
        throw s3Error("FOLDER_NOT_EMPTY");
      }
      folders = new Set([...folders].filter((path) => !isInFolder(path, id)));
    },
  };

  function exists(id: string) {
    return folders.has(id) || files.some((file) => isInFolder(file.folder, id));
  }

  /** Renames or moves folder `id` to `name` inside `parent`, with what it holds. */
  function placeFolder(
    id: string,
    parent: string | null,
    name: string,
  ): ObjectListFolder {
    const nextId = parent ? `${parent}/${name}` : name;
    if (nextId === id) return { id, name };
    if (!exists(id)) throw s3Error("FOLDER_NOT_FOUND");
    if (exists(nextId)) throw s3Error("FOLDER_EXISTS");
    files = files.map((file) =>
      file.folder == null
        ? file
        : { ...file, folder: rewriteFolderPath(file.folder, id, nextId) },
    );
    folders = new Set(
      [...folders].map((folderId) => rewriteFolderPath(folderId, id, nextId)),
    );
    return { id: nextId, name };
  }
}

type Catalog = ReturnType<typeof createCatalog>;

/**
 * The list source. `memoryObjectSource` reads folders from the records, so
 * this adds the created folders that hold no file yet, renames, moves, and
 * deletes files and folders, uploads into the open folder or the folder a
 * file is dropped on, and makes later pages wait a moment so the next-page
 * spinner shows.
 */
function createSource(catalog: Catalog): ObjectListSource<LibraryFile> {
  const source = memoryObjectSource(catalog.files, {
    getId: (file) => file.id,
    getFile: (file) => ({
      name: file.name,
      objectKey: fileObjectKey(file),
      size: file.size,
      contentType: file.type,
      updatedAt: file.updatedAt,
      previewUrl: file.type.startsWith("image/")
        ? getDemoFileUrl(fileObjectKey(file))
        : null,
    }),
    getFolder: (file) => file.folder,
    pageSize: PAGE_SIZE,
    limits: LIMITS,
  });

  return {
    ...source,
    async query(input) {
      if (input.cursor) await delay(input.signal);
      const page = await source.query(input);
      if (!page.folders) return page;
      const search = input.search.toLowerCase();
      const listed = new Set(page.folders.map((folder) => folder.id));
      const extra = catalog
        .emptyFolders(input.parent)
        .filter((folder) => !listed.has(folder.id))
        .filter((folder) => folder.name.toLowerCase().includes(search));
      if (extra.length === 0) return page;
      const folders = [...page.folders, ...extra].sort((a, b) =>
        a.name.localeCompare(b.name, undefined, { numeric: true }),
      );
      if (input.sort?.field === "name" && input.sort.direction === "desc") {
        folders.reverse();
      }
      return { ...page, folders };
    },
    // Sent as `clientMetadata`. A real route reads it in `object()`.
    uploadOptions: (parent) => ({ clientMetadata: { folder: parent ?? "" } }),
    createFolder: async ({ parent, name }) =>
      catalog.createFolder(parent, name),
    renameFile: async ({ item, name }) => catalog.renameFile(item.id, name),
    renameFolder: async ({ folder, name }) =>
      catalog.renameFolder(folder.id, name),
    moveFile: async ({ item, parent }) => catalog.moveFile(item.id, parent),
    moveFolder: async ({ folder, parent }) =>
      catalog.moveFolder(folder.id, parent),
    // `listFolderKeys` comes from `memoryObjectSource`.
    deleteFolder: async ({ folder }) => catalog.deleteFolder(folder.id),
  };
}

function delay(signal: AbortSignal) {
  return new Promise<void>((resolve, reject) => {
    if (signal.aborted) {
      reject(abortError());
      return;
    }
    const timer = window.setTimeout(finish, PAGE_DELAY_MS);
    function finish() {
      signal.removeEventListener("abort", onAbort);
      resolve();
    }
    function onAbort() {
      window.clearTimeout(timer);
      reject(abortError());
    }
    signal.addEventListener("abort", onAbort, { once: true });
  });
}

function abortError() {
  return new DOMException("The operation was aborted.", "AbortError");
}

export function ObjectListDemo() {
  const [catalog] = useState(createCatalog);
  const [source] = useState(() => createSource(catalog));
  const list = useObjectList(source);
  const selection = useObjectListSelection(list);
  const upload = useUpload({
    route: "uploads",
    maxFiles: 8,
    append: true,
    onSuccess: (result, file) => {
      rememberDemoFile(result.key, file);
      // The demo API echoes the request metadata, so the folder comes back.
      const folder = result.metadata.folder || null;
      catalog.add({
        id: result.key,
        key: result.key,
        name: result.name ?? file.name,
        folder,
        size: result.size,
        type: result.type || "application/octet-stream",
        updatedAt: result.lastModified ?? new Date().toISOString(),
      });
    },
  });
  const download = useDownload({ route: "uploads" });
  const share = useDownload({ route: "uploads", disposition: "inline" });
  const remove = useDelete({
    route: "uploads",
    onSuccess: (_data, key) => catalog.remove(key),
  });

  return (
    <ObjectList
      list={list}
      selection={selection}
      upload={upload}
      download={download}
      share={share}
      delete={remove}
      onOpenItem={(file) => {
        void share
          .presign(fileObjectKey(file), { fileName: file.name })
          .then((outcome) => {
            if (outcome.status !== "success") return;
            window.open(outcome.data.url, "_blank", "noopener,noreferrer");
          });
      }}
      className="mx-auto max-w-2xl"
      height="28rem"
    >
      <ObjectListHeader>
        <ObjectListSearch />
        <ObjectListSortMenu />
        <ObjectListViewToggle />
        <UploadTrigger size="sm" />
      </ObjectListHeader>
      <ObjectListUsage />
      <ObjectListUploadStatus />
      <ObjectListContent />
    </ObjectList>
  );
}
```

The preview keeps its files in memory. Search, sort, switch to the grid,
select with Shift-click or Ctrl+A, drop a file or a folder onto it, drag a row
onto a folder, or open a row's menu.

## Installation [#installation]

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

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

The parts land in `components/dimah-s3/list/`, such as
`@/components/dimah-s3/list/object-list`, with the upload, download, and
delete families 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
"use client";

import {
  useDelete,
  useDownload,
  useObjectList,
  useObjectListSelection,
  useUpload,
  type ObjectListSource,
} from "@dimah-s3/react";
import { ObjectList, UploadTrigger } from "@dimah-s3/ui";

type LibraryFile = { id: string; key: string; name: string; size: number };

export function Library({ source }: { source: ObjectListSource<LibraryFile> }) {
  const list = useObjectList(source);
  const selection = useObjectListSelection(list);
  const upload = useUpload({ route: "docs", maxFiles: 8, append: true });
  const download = useDownload({ route: "docs" });
  const remove = useDelete({ route: "docs" });

  return (
    <ObjectList
      list={list}
      selection={selection}
      upload={upload}
      download={download}
      delete={remove}
      toolbar={<UploadTrigger size="sm" />}
    />
  );
}
```

The component never fetches. `source` decides where the rows come from:
`memoryObjectSource` for records you hold, `dbObjectSource` with the
[database plugin](https://s3.dimah.dev/docs/db), `shareObjectSource` for a
[shared folder](https://s3.dimah.dev/docs/share/visitor-page), or your own API. See
[useObjectList](https://s3.dimah.dev/docs/react/hooks/object-list).

| Prop         | Turns on                                                                   |
| ------------ | -------------------------------------------------------------------------- |
| `selection`  | Checkboxes, the selection bar, Shift ranges, Ctrl+A, Escape, Space         |
| `upload`     | Drop and paste into the open folder, with progress under the header        |
| `download`   | Download in the file menu                                                  |
| `share`      | Copy link, signed by a second `useDownload` such as an inline one          |
| `delete`     | Delete in the entry menu, bulk delete on the selection, and the Delete key |
| `thumbnails` | Image thumbnails, signed as rows come into view                            |

What the source can do turns on the rest: **New folder**, **Rename**,
**Move to…**, and Delete on folders. See [Folders](#folders).

The list is the [`Upload`](https://s3.dimah.dev/docs/ui/components/upload),
[`Download`](https://s3.dimah.dev/docs/ui/components/download), and
[`Delete`](https://s3.dimah.dev/docs/ui/components/delete) root for its hooks, so their triggers
work inside it without a root of their own.

## Anatomy [#anatomy]

Pass children to arrange the parts yourself. Without children, the list
renders a header, the usage, the upload status, and the content.

```tsx
<ObjectList list={list} selection={selection} upload={upload} delete={remove}>
  <ObjectListHeader>
    <ObjectListSearch />
    <ObjectListSortMenu />
    <ObjectListViewToggle />
    <UploadTrigger size="sm" />
  </ObjectListHeader>
  <ObjectListUsage />
  <ObjectListUploadStatus />
  <ObjectListContent />
</ObjectList>
```

| Part                              | Description                                                                             |
| --------------------------------- | --------------------------------------------------------------------------------------- |
| `ObjectListHeader`                | Path, select-all, New folder, and your controls. Turns into the search or selection bar |
| `ObjectListBreadcrumb`            | The path. Shortens to fit, with a menu for the folders above                            |
| `ObjectListSearch`                | Search button that opens a field across the header                                      |
| `ObjectListSearchBar`             | Where a search looks and how many results it found                                      |
| `ObjectListSortMenu`              | Name, size, and date order, or your own fields                                          |
| `ObjectListViewToggle`            | List and grid buttons                                                                   |
| `ObjectListSelectAll`             | The select-all checkbox                                                                 |
| `ObjectListSelectionBar`          | Count, your actions, Move, bulk delete, and Clear                                       |
| `ObjectListBulkMove`              | Move, for a selection bar of your own                                                   |
| `ObjectListBulkDelete`            | Bulk delete, for a selection bar of your own                                            |
| `ObjectListNewFolder`             | New folder, when the source can create folders                                          |
| `ObjectListUsage`                 | Catalog bytes and files, with a text-sized ring for the caps                            |
| `ObjectListUsageMeter`            | The cap ring, for custom content inside `ObjectListUsage`                               |
| `ObjectListUploadStatus`          | Upload progress and errors                                                              |
| `ObjectListContent`               | Rows or tiles, the loading, error, and empty states, and the next page                  |
| `ObjectListEmpty`                 | The empty state, with your own text or actions                                          |
| `ObjectListEntryMenu`             | The menu of one entry: download, copy link, rename, move, delete                        |
| `ObjectListRow`, `ObjectListTile` | One entry, for `renderEntry`                                                            |

Render the header's controls as its direct children, so the search and New
folder fields can take the bar from them.

## Customize entries [#customize-entries]

Change part of every entry with a `render*` prop. Each receives the entry:
`entry.kind` is `"file"` or `"folder"`, `entry.item` is your record, and
`entry.file` is what the source's `getFile` returned.

```tsx
<ObjectList
  list={list}
  onOpenItem={(file) => openDetails(file)}
  renderMeta={(entry) =>
    entry.kind === "file" && entry.item.shared ? <Badge>Shared</Badge> : null
  }
  renderDescription={(entry) =>
    entry.kind === "file" ? `${entry.item.owner} · ${entry.item.size}` : null
  }
  renderActions={(entry) =>
    entry.kind === "file" ? (
      <ObjectListEntryMenu
        actions={[{ label: "Details", onClick: () => openDetails(entry.item) }]}
      />
    ) : null
  }
/>
```

| Prop                | Replaces                                                                                         |
| ------------------- | ------------------------------------------------------------------------------------------------ |
| `renderMeta`        | Nothing. Adds text beside the name, such as a badge                                              |
| `renderDescription` | The second line: a file's size and date, or a folder's file count and size                       |
| `renderActions`     | The trailing controls. Return `null` to hide the menu                                            |
| `renderEntry`       | The whole row or tile. Return `ObjectListRow` or `ObjectListTile` to keep selection and keyboard |

`onOpenItem` runs when a file is opened; folders always open in place. Define
`render*` functions outside the component, or wrap them in `useCallback`, so
your renders do not redraw every entry.

## Views [#views]

`defaultView="grid"` starts in the grid. Pass `view` and `onViewChange` to
keep the view in your own state, such as the URL.

## Thumbnails [#thumbnails]

Pass `thumbnails` with the route that signs downloads, and image files show
their picture in rows and tiles:

```tsx
<ObjectList list={list} thumbnails={{ route: "files" }} />
```

Each image is signed with [`useObjectUrl`](https://s3.dimah.dev/docs/react/hooks/object-url) once
its row or tile comes into view, and signed again before the URL expires. Its
type, or its extension, decides: PNG, JPEG, GIF, WebP, AVIF, SVG, BMP, and
ICO. A `previewUrl` from `getFile` wins. Pass `api` with the route when there
is no `S3Provider`.

## Preview [#preview]

Pass `preview` with the route that signs downloads, and a file opens in
[`ObjectPreviewDialog`](https://s3.dimah.dev/docs/ui/components/object-preview) when it is clicked
or opened with Enter:

```tsx
<ObjectList
  list={list}
  download={download}
  thumbnails={{ route: "files" }}
  preview={{ route: "files" }}
/>
```

Previous, Next, and the arrow keys move through the loaded files, and the
dialog's Download uses `download`. Closing it focuses the row of the file it
showed last. `preview` also takes the dialog's `kinds`, `maxTextBytes`, and
`render`. A file opens one way: pass `preview` or `onOpenItem`, not both.

The dialog's title is the file's `name`, and Download saves its
[`fileName`](#titles-and-file-names). A `useDownload` `download` also adds
Copy link to the file menu: pass `share={false}` to keep the dialog's Download
without it, as [Entry menu](#entry-menu) shows.

## Titles and file names [#titles-and-file-names]

A row can show a title over the stored file, such as "Site plan" for
`site-plan.pdf`. Return the title as `name` and the stored file's name as
`fileName` from `getFile`:

```tsx
const list = useObjectList({
  query,
  getId: (file) => file.id,
  getFile: (file) => ({
    name: file.title,
    fileName: file.fileName,
    objectKey: file.objectKey,
    size: file.size,
    contentType: file.contentType,
  }),
});
```

The row, the preview dialog's title, and the delete confirmation show `name`.
Download, Copy link, and the preview save the file as `fileName`, and the
file's icon reads its extension. Without `fileName`, they use `name`. Rename
edits `name`.

## Search and sort [#search-and-sort]

`ObjectListSearch` and `ObjectListSortMenu` set `list.search` and `list.sort`,
which reload the first page. The source decides what they mean:

- `memoryObjectSource` matches names in the open folder and every folder
  below it, and sorts by name, size, date, or `sortValue`.
- `dbObjectSource` does the same on the server.
- Your own query receives `search`, `searchScope`, and `sort`.

Pass your own sort fields with `options`:

```tsx
<ObjectListSortMenu
  options={[
    { field: "name", label: "Name" },
    { field: "owner", label: "Owner" },
    { field: "updatedAt", label: "Modified", direction: "desc" },
  ]}
/>
```

When the source has [`searchScopes`](https://s3.dimah.dev/docs/react/hooks/object-list#search),
users can search the open folder or everything.

## Selection [#selection]

Pass `useObjectListSelection(list)` as `selection`. Files can be selected by
default, and folders too when the source can delete or move them. Put your own
bulk actions in `selectionActions`:

```tsx
const selection = useObjectListSelection(list);

<ObjectList
  list={list}
  selection={selection}
  selectionActions={
    <Button size="sm" onClick={() => share(selection.selectedItems)}>
      Share
    </Button>
  }
/>;
```

## Delete [#delete]

`onDeleted` receives the result of each confirmed delete. Delete, or
Cmd+Backspace on a Mac, deletes the selection, else the focused entry, after
the same confirmation.

Folders can be deleted when the source has `deleteFolder`. After the dialog is
confirmed, `listFolderKeys` names the files in each folder, `delete` removes
them with the selected files in one request, and `deleteFolder` removes each
folder whose files all went. A folder with a file that failed stays.
`dbObjectSource` sets both; with your own source:

```tsx
const list = useObjectList({
  ...source,
  listFolderKeys: ({ folder, signal }) => api.keysUnder(folder.id, { signal }),
  deleteFolder: ({ folder }) => api.deleteFolder(folder.id),
});
```

Without `deleteFolder`, folders have no Delete, and selected folders stay out
of a bulk delete.

## Move [#move]

When the source has `moveFile` or `moveFolder`, entries have **Move to…** in
their menu, the selection bar has **Move**, and a row dragged onto a folder,
or onto the root or the parent in the path, moves there. The dialog opens in
the open folder: browse to another and choose **Move here**.

```tsx
const list = useObjectList({
  ...source,
  moveFile: ({ item, parent }) => api.moveFile(item.id, parent),
  moveFolder: ({ folder, parent }) => api.moveFolder(folder.id, parent),
});
```

A dragged row that is selected takes the selection with it. Moved entries
leave the open folder at once, and the list reloads. A folder cannot be
opened in the dialog while it moves, so nothing moves into itself.
`dbObjectSource` sets both.

## Upload into folders [#upload-into-folders]

With `upload`, the list takes drops and pastes into the open folder. For a
file picker, add an `UploadTrigger` to the `toolbar` or the empty state:

```tsx
<ObjectList
  list={list}
  upload={upload}
  empty={
    <ObjectListEmpty>
      <UploadTrigger size="sm" />
    </ObjectListEmpty>
  }
/>
```

The source's `uploadOptions(parent)` decides where files land.
`dbObjectSource` sets it for you. A dropped folder keeps its folders when the
source has `createFolder`: each one is found by name below the folder it lands
in, or created as its first file starts, and its files upload there. With your own source, send the folder as
`clientMetadata` and read it in the server's upload hook:

```tsx
const list = useObjectList({
  ...source,
  uploadOptions: (parent) => ({ clientMetadata: { folderId: parent ?? "" } }),
});
```

## Folders [#folders]

`ObjectList` lists the folders the source returns on the first page.

- `memoryObjectSource` builds folders from `/`-separated paths with
  `getFolder`.
- `dbObjectSource` lists, creates, and renames the folders `db()` stores.
- Your own source returns folders from its query. Add `createFolder` to show
  **New folder**, `renameFile` or `renameFolder` to show **Rename**,
  `moveFile` or `moveFolder` for [Move](#move), and `deleteFolder` for
  [folder deletes](#delete). Renaming and moving keep the object key.

## Entry menu [#entry-menu]

`ObjectListEntryMenu` is the default trailing control, with **Download**,
**Copy link**, **Rename**, **Move to…**, and **Delete** when the list can do
them. Add your
own rows with `actions`, or with children:

```tsx
<ObjectListEntryMenu>
  <ObjectListEntryMenuItem onClick={() => star(entry.item)}>
    <StarIcon />
    Star
  </ObjectListEntryMenuItem>
</ObjectListEntryMenu>
```

Copy link signs a URL through `share`, else through a `useDownload`
`download`. Pass `share={false}` to leave Copy link out, such as when files
are shared through [share links](https://s3.dimah.dev/docs/share), and keep Download in the menu
and the preview:

```tsx
<ObjectList
  list={list}
  download={download}
  share={false}
  preview={{ route: "files" }}
/>
```

## Frame and paging [#frame-and-paging]

Pass `height` to keep the header in place and scroll the entries, or
`maxHeight` to let the list grow up to a cap. Later pages load as the user
scrolls; `pagination="button"` shows **Load more** instead.

## Storage usage [#storage-usage]

Return `usage` from the source's query. `ObjectListUsage` shows the bytes
and the file count on one line. For `dbObjectSource` and
`memoryObjectSource` that is the whole catalog, the same number in every
folder, against the [`db()` quota](https://s3.dimah.dev/docs/db/api#quota). A folder's own size
is on its row. A cap adds a ring the size of the text: the byte cap when
`maxBytes` is set, and the file cap when it is not. Hover, focus, or click
the ring for the percent. The line uses the destructive color when either
cap is reached.

Pass `usage` to show another total, such as the open folder. Pass `children`
to replace the ring and the line. A function receives the state on screen,
and `ObjectListUsageMeter` is the ring.

```tsx
<ObjectListUsage usage={folderUsage}>
  {(state) => (
    <>
      <ObjectListUsageMeter />
      <span>
        {state.bytesLabel} · {state.filesLabel}
      </span>
    </>
  )}
</ObjectListUsage>
```

## Toasts [#toasts]

The list shows toasts for its hooks by default, so it needs no
`UploadToasts`, `DownloadToasts`, or `DeleteToasts`. Pass `toasts={false}` to
turn them off.

## Keyboard [#keyboard]

The entries are one tab stop, so a long folder takes one Tab.

| Key                     | Action                                                     |
| ----------------------- | ---------------------------------------------------------- |
| Tab / Shift+Tab         | Enter the entries, move through an entry's controls, leave |
| ArrowUp / ArrowDown     | Move between entries (by row in the grid)                  |
| ArrowLeft / ArrowRight  | List: the row's checkbox, name, and menu. Grid: next tile  |
| Home / End              | First or last entry                                        |
| Enter                   | Open the folder, the file's preview, or call `onOpenItem`  |
| Space                   | Toggle the focused entry. With Shift: the range            |
| Ctrl+A / Cmd+A          | Select every loaded entry                                  |
| Escape                  | Clear the selection                                        |
| Backspace / Alt+ArrowUp | Open the parent folder                                     |
| Delete / Cmd+Backspace  | Delete the selection, else the focused entry               |
| F2                      | Rename the focused entry                                   |
| /                       | Open the search field                                      |

Give your own controls in `renderActions` `tabIndex={-1}`, as the built-in
checkbox and menu have, so Tab stays on the entry.

## API Reference [#api-reference]

### ObjectList [#objectlist]

| Prop                | Type                             | Default                                          | Description                                                                  |
| ------------------- | -------------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------------- |
| `list`              | `UseObjectListReturn`            | required                                         | The `useObjectList` return to render                                         |
| `selection`         | `UseObjectListSelectionReturn`   | —                                                | Adds selection                                                               |
| `upload`            | `UseUploadReturn`                | —                                                | Adds drop, paste, and folder uploads                                         |
| `download`          | `AnyDownloadReturn`              | —                                                | Adds Download to the file menu                                               |
| `share`             | `UseDownloadReturn \| false`     | —                                                | Signs Copy link, else a `useDownload` `download` does. `false` leaves it out |
| `delete`            | `UseDeleteReturn`                | —                                                | Adds Delete to the entry menu and the selection bar                          |
| `toasts`            | `boolean`                        | `true`                                           | Toasts for the hooks above                                                   |
| `view`              | `"list" \| "grid"`               | —                                                | Controlled view, with `onViewChange`                                         |
| `defaultView`       | `"list" \| "grid"`               | `"list"`                                         | Starting view                                                                |
| `onViewChange`      | `(view) => void`                 | —                                                | Runs when the view changes                                                   |
| `onOpenItem`        | `(item) => void`                 | —                                                | Runs when a file is clicked or opened with Enter                             |
| `preview`           | `ObjectListPreview`              | —                                                | Opens files in a preview dialog. Not with `onOpenItem`                       |
| `thumbnails`        | `{ route, api? }`                | —                                                | Signs image thumbnails through this route                                    |
| `onDeleted`         | `(result: DeleteResult) => void` | —                                                | Runs after each confirmed delete                                             |
| `rootLabel`         | `string`                         | `"Files"`                                        | Root breadcrumb label and the list's accessible name                         |
| `breadcrumb`        | `boolean`                        | `true`                                           | Shows the path in the default header                                         |
| `toolbar`           | `ReactNode`                      | —                                                | Controls at the end of the default header                                    |
| `selectionActions`  | `ReactNode`                      | —                                                | Controls on the selection bar, beside Delete                                 |
| `empty`             | `ReactNode`                      | —                                                | Replaces the empty state                                                     |
| `commands`          | `ObjectListCommands`             | —                                                | Opens New folder and entry menus from outside                                |
| `pagination`        | `"auto" \| "button"`             | `"auto"`                                         | How later pages load                                                         |
| `height`            | `number \| string`               | —                                                | Fixed frame height. Entries scroll inside                                    |
| `maxHeight`         | `number \| string`               | —                                                | Largest frame height                                                         |
| `renderEntry`       | `(entry) => ReactNode`           | —                                                | Replaces the whole row or tile                                               |
| `renderActions`     | `(entry) => ReactNode`           | Entry menu                                       | Replaces the trailing controls                                               |
| `renderDescription` | `(entry) => ReactNode`           | Size and date, or a folder's file count and size | Replaces the second line. Text only                                          |
| `renderMeta`        | `(entry) => ReactNode`           | —                                                | Text beside the name                                                         |
| `className`         | `string`                         | —                                                | Classes for the frame                                                        |
| `children`          | `ReactNode`                      | —                                                | Your own layout from the list parts                                          |

### ObjectListHeader [#objectlistheader]

| Prop               | Type        | Default                       | Description                                   |
| ------------------ | ----------- | ----------------------------- | --------------------------------------------- |
| `children`         | `ReactNode` | —                             | Trailing controls: search, sort, view, upload |
| `breadcrumb`       | `boolean`   | The list's `breadcrumb`       | Shows the path                                |
| `searchBar`        | `boolean`   | `true`                        | Shows `ObjectListSearchBar` during a search   |
| `selectionActions` | `ReactNode` | The list's `selectionActions` | Controls on the selection bar                 |

### ObjectListSearch [#objectlistsearch]

| Prop          | Type      | Default        | Description                                               |
| ------------- | --------- | -------------- | --------------------------------------------------------- |
| `placeholder` | `string`  | Where it looks | Placeholder and accessible name                           |
| `debounceMs`  | `number`  | `250`          | Wait after typing before the list reloads                 |
| `collapsible` | `boolean` | `true`         | In a header, starts as a button that opens across the bar |

### ObjectListSortMenu [#objectlistsortmenu]

| Prop      | Type                             | Default          | Description |
| --------- | -------------------------------- | ---------------- | ----------- |
| `options` | `{ field, label, direction? }[]` | Name, size, date | The choices |

### ObjectListEmpty [#objectlistempty]

| Prop          | Type        | Default                                 | Description            |
| ------------- | ----------- | --------------------------------------- | ---------------------- |
| `title`       | `ReactNode` | "This folder is empty", or "No results" | Heading                |
| `description` | `ReactNode` | —                                       | Text under it          |
| `children`    | `ReactNode` | Search actions while searching          | Actions below the text |

### ObjectListBulkMove and ObjectListBulkDelete [#objectlistbulkmove-and-objectlistbulkdelete]

| Prop        | Type     | Default | Description            |
| ----------- | -------- | ------- | ---------------------- |
| `className` | `string` | —       | Classes for the button |

### ObjectListUsage [#objectlistusage]

| Prop        | Type                                | Default          | Description                                                    |
| ----------- | ----------------------------------- | ---------------- | -------------------------------------------------------------- |
| `usage`     | `ObjectListUsageData \| null`       | `list.usage`     | Totals to show. `null` hides the line                          |
| `children`  | `ReactNode \| (state) => ReactNode` | Ring and summary | Replaces the ring and the summary. A function receives `state` |
| `className` | `string`                            | —                | Classes for the row                                            |

`state` is `ObjectListUsageState`:

| Field        | Description                                                                   |
| ------------ | ----------------------------------------------------------------------------- |
| `usage`      | The totals on screen                                                          |
| `bytesLabel` | "1.2 MB", or "1.2 MB of 10 MB" when `maxBytes` is set                         |
| `filesLabel` | "3 files", or "3 of 4 files" when `maxFiles` is set                           |
| `byteRatio`  | `totalBytes / maxBytes`, or `null`                                            |
| `fileRatio`  | `objectCount / maxFiles`, or `null`                                           |
| `meterRatio` | What the ring draws. Bytes when `maxBytes` is set, otherwise files, or `null` |
| `over`       | A byte cap or a file cap is reached                                           |

### ObjectListUsageMeter [#objectlistusagemeter]

| Prop        | Type     | Default | Description          |
| ----------- | -------- | ------- | -------------------- |
| `className` | `string` | —       | Classes for the ring |

### ObjectListEntryMenu [#objectlistentrymenu]

| Prop        | Type                          | Default                               | Description                                                             |
| ----------- | ----------------------------- | ------------------------------------- | ----------------------------------------------------------------------- |
| `objectKey` | `string`                      | The entry's key                       | Key of the object                                                       |
| `fileName`  | `string`                      | The entry's `fileName`, else its name | Download and Copy link name, and the delete dialog label                |
| `fileSize`  | `number \| null`              | The entry's size                      | Size in the delete dialog                                               |
| `share`     | `UseDownloadReturn`           | The list's `share`                    | Signs Copy link                                                         |
| `expiresIn` | `number`                      | —                                     | Link lifetime in seconds, capped by the route                           |
| `actions`   | `ObjectListEntryMenuAction[]` | —                                     | Rows `{ label, onClick, icon?, disabled?, destructive? }` before Delete |
| `children`  | `ReactNode`                   | —                                     | `ObjectListEntryMenuItem`s after `actions`                              |

### ObjectListRow and ObjectListTile [#objectlistrow-and-objectlisttile]

| Prop          | Type              | Default             | Description                  |
| ------------- | ----------------- | ------------------- | ---------------------------- |
| `entry`       | `ObjectListEntry` | required            | The entry from `renderEntry` |
| `media`       | `ReactNode`       | Glyph or thumbnail  | Replaces the icon            |
| `meta`        | `ReactNode`       | `renderMeta`        | Beside the name              |
| `description` | `ReactNode`       | `renderDescription` | The second line              |
| `actions`     | `ReactNode`       | `renderActions`     | The trailing controls        |

### useObjectListContext [#useobjectlistcontext]

Returns the list's state inside `ObjectList`, for parts of your own:
`list`, `selection`, `upload`, `download`, `share`, `delete`, `toasts`,
`view`, `setView`, `rootLabel`, and the commands `startNewFolder()`,
`startRename(key)`, `revealEntry(entry)`, `startMove(entries, { trigger? })`,
and `announce(feedback)`. Inside an entry, `useObjectListEntry()` returns that
entry.

### useObjectListCommands [#useobjectlistcommands]

Opens list UI from your own shortcuts. Pass the result to `ObjectList` as
`commands`.

```tsx
const commands = useObjectListCommands();

<ObjectList list={list} commands={commands} />;
<Button onClick={() => commands.startNewFolder()}>New folder</Button>;
```

| Property         | Type                         | Description                                 |
| ---------------- | ---------------------------- | ------------------------------------------- |
| `startNewFolder` | `() => void`                 | Opens the New folder field                  |
| `openMenu`       | `(entryKey: string) => void` | Opens an entry's menu, when it is on screen |