Skip to Content
dimah-s3v2.8.1

Object List

File browser for useObjectList, with folders, list and grid views, search, sort, selection, move, upload, thumbnails, previews, and a file menu.

A file browser for the files your app stores. ObjectList renders a useObjectList 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.

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

import { ObjectList } from "@dimah-s3/ui";

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

Usage

"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, shareObjectSource for a shared folder, or your own API. See useObjectList.

PropTurns on
selectionCheckboxes, the selection bar, Shift ranges, Ctrl+A, Escape, Space
uploadDrop and paste into the open folder, with progress under the header
downloadDownload in the file menu
shareCopy link, signed by a second useDownload such as an inline one
deleteDelete in the entry menu, bulk delete on the selection, and the Delete key
thumbnailsImage 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.

The list is the Upload, Download, and Delete root for its hooks, so their triggers work inside it without a root of their own.

Anatomy

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

<ObjectList list={list} selection={selection} upload={upload} delete={remove}>
  <ObjectListHeader>
    <ObjectListSearch />
    <ObjectListSortMenu />
    <ObjectListViewToggle />
    <UploadTrigger size="sm" />
  </ObjectListHeader>
  <ObjectListUsage />
  <ObjectListUploadStatus />
  <ObjectListContent />
</ObjectList>
PartDescription
ObjectListHeaderPath, select-all, New folder, and your controls. Turns into the search or selection bar
ObjectListBreadcrumbThe path. Shortens to fit, with a menu for the folders above
ObjectListSearchSearch button that opens a field across the header
ObjectListSearchBarWhere a search looks and how many results it found
ObjectListSortMenuName, size, and date order, or your own fields
ObjectListViewToggleList and grid buttons
ObjectListSelectAllThe select-all checkbox
ObjectListSelectionBarCount, your actions, Move, bulk delete, and Clear
ObjectListBulkMoveMove, for a selection bar of your own
ObjectListBulkDeleteBulk delete, for a selection bar of your own
ObjectListNewFolderNew folder, when the source can create folders
ObjectListUsageCatalog bytes and files, with a text-sized ring for the caps
ObjectListUsageMeterThe cap ring, for custom content inside ObjectListUsage
ObjectListUploadStatusUpload progress and errors
ObjectListContentRows or tiles, the loading, error, and empty states, and the next page
ObjectListEmptyThe empty state, with your own text or actions
ObjectListEntryMenuThe menu of one entry: download, copy link, rename, move, delete
ObjectListRow, ObjectListTileOne 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

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.

<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
  }
/>
PropReplaces
renderMetaNothing. Adds text beside the name, such as a badge
renderDescriptionThe second line: a file's size and date, or a folder's file count and size
renderActionsThe trailing controls. Return null to hide the menu
renderEntryThe 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

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

Thumbnails

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

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

Each image is signed with useObjectUrl 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

Pass preview with the route that signs downloads, and a file opens in ObjectPreviewDialog when it is clicked or opened with Enter:

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

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:

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

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:

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

When the source has searchScopes, users can search the open folder or everything.

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:

const selection = useObjectListSelection(list);

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

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:

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

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.

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

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:

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

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

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, and deleteFolder for folder deletes. Renaming and moving keep the object key.

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:

<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, and keep Download in the menu and the preview:

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

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

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

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

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

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

KeyAction
Tab / Shift+TabEnter the entries, move through an entry's controls, leave
ArrowUp / ArrowDownMove between entries (by row in the grid)
ArrowLeft / ArrowRightList: the row's checkbox, name, and menu. Grid: next tile
Home / EndFirst or last entry
EnterOpen the folder, the file's preview, or call onOpenItem
SpaceToggle the focused entry. With Shift: the range
Ctrl+A / Cmd+ASelect every loaded entry
EscapeClear the selection
Backspace / Alt+ArrowUpOpen the parent folder
Delete / Cmd+BackspaceDelete the selection, else the focused entry
F2Rename 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

ObjectList

PropTypeDefaultDescription
listUseObjectListReturnrequiredThe useObjectList return to render
selectionUseObjectListSelectionReturn—Adds selection
uploadUseUploadReturn—Adds drop, paste, and folder uploads
downloadAnyDownloadReturn—Adds Download to the file menu
shareUseDownloadReturn | false—Signs Copy link, else a useDownload download does. false leaves it out
deleteUseDeleteReturn—Adds Delete to the entry menu and the selection bar
toastsbooleantrueToasts 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
previewObjectListPreview—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
rootLabelstring"Files"Root breadcrumb label and the list's accessible name
breadcrumbbooleantrueShows the path in the default header
toolbarReactNode—Controls at the end of the default header
selectionActionsReactNode—Controls on the selection bar, beside Delete
emptyReactNode—Replaces the empty state
commandsObjectListCommands—Opens New folder and entry menus from outside
pagination"auto" | "button""auto"How later pages load
heightnumber | string—Fixed frame height. Entries scroll inside
maxHeightnumber | string—Largest frame height
renderEntry(entry) => ReactNode—Replaces the whole row or tile
renderActions(entry) => ReactNodeEntry menuReplaces the trailing controls
renderDescription(entry) => ReactNodeSize and date, or a folder's file count and sizeReplaces the second line. Text only
renderMeta(entry) => ReactNode—Text beside the name
classNamestring—Classes for the frame
childrenReactNode—Your own layout from the list parts

ObjectListHeader

PropTypeDefaultDescription
childrenReactNode—Trailing controls: search, sort, view, upload
breadcrumbbooleanThe list's breadcrumbShows the path
searchBarbooleantrueShows ObjectListSearchBar during a search
selectionActionsReactNodeThe list's selectionActionsControls on the selection bar

ObjectListSearch

PropTypeDefaultDescription
placeholderstringWhere it looksPlaceholder and accessible name
debounceMsnumber250Wait after typing before the list reloads
collapsiblebooleantrueIn a header, starts as a button that opens across the bar

ObjectListSortMenu

PropTypeDefaultDescription
options{ field, label, direction? }[]Name, size, dateThe choices

ObjectListEmpty

PropTypeDefaultDescription
titleReactNode"This folder is empty", or "No results"Heading
descriptionReactNode—Text under it
childrenReactNodeSearch actions while searchingActions below the text

ObjectListBulkMove and ObjectListBulkDelete

PropTypeDefaultDescription
classNamestring—Classes for the button

ObjectListUsage

PropTypeDefaultDescription
usageObjectListUsageData | nulllist.usageTotals to show. null hides the line
childrenReactNode | (state) => ReactNodeRing and summaryReplaces the ring and the summary. A function receives state
classNamestring—Classes for the row

state is ObjectListUsageState:

FieldDescription
usageThe 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
byteRatiototalBytes / maxBytes, or null
fileRatioobjectCount / maxFiles, or null
meterRatioWhat the ring draws. Bytes when maxBytes is set, otherwise files, or null
overA byte cap or a file cap is reached

ObjectListUsageMeter

PropTypeDefaultDescription
classNamestring—Classes for the ring

ObjectListEntryMenu

PropTypeDefaultDescription
objectKeystringThe entry's keyKey of the object
fileNamestringThe entry's fileName, else its nameDownload and Copy link name, and the delete dialog label
fileSizenumber | nullThe entry's sizeSize in the delete dialog
shareUseDownloadReturnThe list's shareSigns Copy link
expiresInnumber—Link lifetime in seconds, capped by the route
actionsObjectListEntryMenuAction[]—Rows { label, onClick, icon?, disabled?, destructive? } before Delete
childrenReactNode—ObjectListEntryMenuItems after actions

ObjectListRow and ObjectListTile

PropTypeDefaultDescription
entryObjectListEntryrequiredThe entry from renderEntry
mediaReactNodeGlyph or thumbnailReplaces the icon
metaReactNoderenderMetaBeside the name
descriptionReactNoderenderDescriptionThe second line
actionsReactNoderenderActionsThe trailing controls

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

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

const commands = useObjectListCommands();

<ObjectList list={list} commands={commands} />;
<Button onClick={() => commands.startNewFolder()}>New folder</Button>;
PropertyTypeDescription
startNewFolder() => voidOpens the New folder field
openMenu(entryKey: string) => voidOpens an entry's menu, when it is on screen

On this page