Skip to content

Media library (for a site)

One page of one site's files, the same in Carrel and in every site admin.

<p>Arrow keys move through the files, Enter opens one, Esc clears the selection and then closes the details; <kbd>Ctrl</kbd> <kbd>K</kbd> finds a file by name. Open a file and its inspector reads where it is used; Move to Trash runs at once with Undo (<kbd>z</kbd>); a tag shows each file's outcome in the bar; Delete for good, from Trash, asks first and lists every file. The site here refuses to delete a file a post still uses.</p>
<div data-mount="editor"></div>

Installation

// package.json: "capsomer": "github:DrDustinEdwards/capsomer#v0.152.2"
import "capsomer/tokens.css";
import "capsomer/base.css";
import "capsomer/media-library.css";
import { dirOf, mediaHref, withMedia } from "capsomer/behavior/media-library";

Usage

<section class="cap-media-lib" data-cap="media-library" aria-label="Files">
  <nav class="cap-tabs-list cap-media-lib-tabs" aria-label="Files: library or Trash">...Library, Trash, with counts...</nav>
  <form class="cap-field-row" role="search" aria-label="Find files" method="get" action="/media">...Search, Show...</form>
  <nav class="cap-media-lib-chips" aria-label="Narrow the files">
    <ul class="cap-chips" aria-label="Tags"><li><a class="cap-chip" href="/media?tag=release" aria-current="true">release <span class="cap-chip-count">4</span></a></li></ul>
    <ul class="cap-chips" aria-label="Lenses">...</ul>
  </nav>
  <div class="cap-media-lib-bar"><p class="cap-media-lib-count">5 files</p><div class="cap-media-lib-tools"><nav class="cap-media-lib-layout" aria-label="Show as">...Grid, List...</nav></div></div>
  <ul class="cap-media-lib-withheld">...</ul>
  <!-- the toolbar ends with <a class="cap-btn cap-media-lib-upload-open" data-variant="primary" href="/media?upload=1">Upload</a> -->
  <dialog class="cap-dialog cap-media-upload" data-cap="dialog" data-cap-inline open aria-labelledby="...">...only on ?upload=1 with no script:
    <form class="cap-media-lib-upload" method="post" enctype="multipart/form-data" action="/media"><input type="hidden" name="intent" value="upload"> ...the drop zone (name="file"), Alt text (required), Upload, Upload as decorative (name="decorative" value="on", formnovalidate)...</form>
    ...Import from a web address (a disclosure with its own form)... <a class="cap-btn" data-cap-part="cancel" href="/media">Close</a>
  </dialog>
  <div class="cap-message cap-content-result" role="status">...</div>
  <form id="bulk" class="cap-media-lib-bulk-form" method="post" action="/media"></form>
  <div class="cap-bulk" data-cap="bulk-bar" ...>...submit buttons with form="bulk", the tag field, the outcome list...</div>
  <div class="cap-media" data-size="m" data-view="list"><div class="cap-media-layout"><div class="cap-media-main">...media's grid; each tile's link is ?inspect=, its box name="ids" form="bulk"...</div>
    <dialog class="cap-dialog cap-media-inspector" open>...media's inspector; in form mode form.cap-media-field-form per group of fields, and form.cap-media-act for each of Move to Trash, Restore, Delete for good; Close is a link...</dialog></div></div>
  <form class="cap-media-pick" data-cap-part="pick" method="post" action="/media">...picker mode: the alt step...</form>
  <nav class="cap-media-lib-pages" aria-label="Files pages">...First page, Next page...</nav>
</section>
import { MediaLibrary } from "capsomer/react/media-library";
<MediaLibrary data={data} action="/media" Form={Form} result={useActionData()} submit={fetcherSubmit} inspector="autosave" />
<MediaLibrary data={data} action="/media/pick" Form={Form} mode="picker" onPick={({ id, url, alt }) => editor.insertImage(url, alt)} />

Examples

A site with every media idea (site-api v0.13.0), with script: filters, import, duplicates, credit, turns, history, shrinking, suggestions and live updates

<p>Its addresses carry the size, so a quarter turn of a picture that is not square is saved as a new file. Upload a file with “bay” in its name and the site answers with the one it already holds. Open Filter for type and orientation, Suggest tags and alt to ask the site's model, and the Oversized lens to shrink every picture on the page. Changes made elsewhere (<code>mediaChange(key, alt)</code> at the console) arrive within 15 seconds.</p>
<div data-mount="ideas"></div>

The inspector in form mode, as delivered with no script: one form per field with its own Save

<div data-mount="form"></div>

Trash, as a list: Restore, and Delete for good

<div data-mount="trash"></div>

The picture tools in form mode, on a site that takes a replacement only at the original's size

<p>The focal point, the caption, Crop (with script: the crop is saved as a new file) and Replace, which asks for a file of the same size.</p>
<div data-mount="keeps-size"></div>

Grouped by folder, at the small tile size

<p>The headings come from each file's id, page by page; the Display controls are links, so the view is an address. Grid or List and the tile size are also remembered in this browser.</p>
<div data-mount="grouped"></div>

A list grouped by month, largest first, on a site that sorts only the page it sent

<div data-mount="by-month"></div>

A reader on a site with no tags, no Trash and no uploads, and why, in words

<div data-mount="limited"></div>

Picker mode: images only, then the alt text this use needs

<p>With script: choose an image, write its alt text (or insert it as decorative), and the host gets the file and the words.</p>
<div data-mount="picker"></div>
<p class="specimen-note" id="picked" role="status"></p>

The picker's alt step with the site's model asked (?pick= with suggest=1)

<p>The model's alt text is shown, never filled in: Use it puts it in the field to read and edit.</p>
<div data-mount="picker-suggest"></div>

The picker's alt step with no script (?pick=)

<div data-mount="picker-step"></div>

Empty: Trash, and no match for a search

<div data-mount="empty-trash"></div>
<div data-mount="empty-match"></div>

The delivered HTML: what a server sends, before any script runs

<p>Rendered to a string and put in the page as it is, with nothing attached: the search is a GET form, the tiles are links to <code>?inspect=</code>, their boxes post as <code>ids</code> with the bar's submit buttons, upload is a multipart form, and the inspector's fields are forms.</p>
<div id="media-static"></div>

The media ideas as delivered HTML, on the Oversized lens: every one a form or a link

<p>Import, credit, the turns, Shrink, Go back to a version, Suggest and the resize pass all post the content kit's own intents (or, for Suggest, link to <code>suggest=1</code>), so they work before any script runs.</p>
<div id="media-ideas-static"></div>

The upload dialog as delivered with no script (?upload=1): one file with its alt text, and Import

<p>With script, the toolbar's Upload opens the dialog in place: choose several files, write each one's alt text or tick Decorative, and each is posted as its own <code>upload</code>.</p>
<div id="media-upload-static"></div>

One chosen image: a share image set, and a feature image not yet chosen

<p>Choose another opens the library in picker mode in a dialog; the host puts its alt text field under the buttons.</p>
<div id="media-image-field"></div>

API reference

MediaLibrary

PropTypeRequiredDoes
dataMediaDataYesThe loader's view data: one page of one site's files.
actionstringYesWhere the forms post, and the library's own address: usually the route itself.
FormFormComponent
submitSubmitIntentThe script path: posts a form and resolves with the action's result. With it, outcomes, Undo, the confirm dialog and the inspector's autosave happen in place.
resultIntentResult | nullThe last result from the action, for the page that comes back after a post with no script.
labelsContentLabels
mode"library" | "picker""library" (the default) manages files; "picker" offers images to insert, with an alt step.
inspector"form" | "autosave"How the inspector saves: "form" (the default), one form per field with its own Save button, which works with no script; or "autosave" (needs submit), saving by itself as you type.
onPick(picked: PickedMedia) => voidPicker mode, with script: called with the file and the alt text written for this use, in place of posting intent=pick.
search(query: string, signal: AbortSignal) => Promise<MediaRecord[]>Quick search, with script: the files matching what was typed (the host asks the kit). With it, Ctrl K, Cmd K or "/" opens the command menu over those files; without it, the keys put focus in the search field.
shortcutsbooleanFalse leaves Ctrl K, Cmd K and "/" to the host (an app-wide command menu). True by default in library mode; the picker never takes them.
bytesHref(key: string) => stringA file's own bytes on the page's own origin (the host serves them), for the crop editor, whose canvas could not export a picture from another origin. Without it, or without submit, there is no Crop.
changes(cursor: string, signal: AbortSignal) => Promise<KitMediaChanges | { reload: true }>Live updates, with script, where the kit offers them (offers.live and page.changeCursor, site-api v0.13.0): what others changed since a cursor, as the kit's loadMediaChanges(source, cursor) answers it (the host serves it, say as a JSON route). The library asks every 15 seconds while the page is visible, at once again when more wait, puts changed files in place and takes deleted ones out; { reload: true } asks the person to load the page again. Without script, or without it, the page is as the server sent it.

Functions

FunctionSignatureDoes
dirOf(q: Pick<MediaQuery, "dir" | "sort">): "asc" | "desc"The direction a query sorts in: its own, or its sort's.
mediaHref(base: string, q: MediaQuery): stringThe library's address with a query, its keys in one fixed order and the empty or default ones left out, so the same view is always the same address. base is the route.
withMedia(q: MediaQuery, change: Partial<MediaQuery>): MediaQueryA filter, sort or view change starts again at the first page, with the inspector and the pick closed; opening a file (inspect, pick) and a display change (layout, size, grouping) keep the page it is on and the open file. A new sort starts in its own direction unless dir is given. The model's suggestions are for one file: anything but asking for them again leaves them behind.
mediaActions(data: Pick<MediaData, "offers" | "can" | "query">, labels?: ContentLabels | undefined): { bulk: OfferedAction[]; withheld: string[]; }The bulk actions this person may run on this view of this site, in the bar's order, and a sentence for each one held back. Trash and Restore are an editor's (reversible, as the kit says); Delete is for good and the delete role's: from Trash where the site has one, from the library only where it has none.
inspectorOffers(data: Pick<MediaData, "offers" | "can">): { alt: boolean; tags: boolean; trash: boolean; delete: boolean; focus: boolean; caption: boolean; replace: boolean; credit: boolean; ... 5 more ...; twins: boolean; }What a file's inspector may do here. Replacing a file's bytes changes every page that shows it and cannot be undone here, so it needs the delete role, as the content kit says. A turn, a revert and a shrink change every page that uses the file too (site-api v0.13.0), so they need the delete role as well; credit and the model's suggestions are an editor's.
countLine(data: Pick<MediaData, "rows" | "page" | "query">, labels?: ContentLabels | undefined): string--------------------------------------------------------------------------------------- Words. "24 files", "Showing 48 of 210 files", "3 files in Trash".
filtered(q: MediaQuery): boolean
emptyWords(q: MediaQuery, labels?: ContentLabels | undefined): { kind: "nothing-yet" | "no-match" | "all-clear"; title: string; text: string; }The empty state's title and line, naming what is not there.
uploadRules(limits: { maxBytes: number; types: string[]; }, imagesOnly?: boolean): { accept: string; hint: string; } | nullThe site's upload rules in words, for the drop zone's hint: "PNG, JPEG and WebP, up to 5 MB". The picker takes images only; null when the site takes none.
pickable(rows: readonly MediaRecord[]): MediaRecord[]The picker's files: images that are in the library and uploaded, nothing in Trash or on its way.
lensChips(data: Pick<MediaData, "offers" | "extra">): { id: string; label: string; hint?: string | undefined; count?: number | undefined; }[]The lens chips: the contract's lenses the site names, then a host's own, each once.
folderOf(key: string): stringThe folder a file's id puts it in: everything before its last "/", or "Top level".
monthOf(uploaded: string | undefined): stringThe month a file was uploaded, in UTC, so a heading does not move with the reader's time zone.
groupRows(rows: readonly MediaRecord[], group: "folder" | "month" | undefined): { label: string; items: MediaRecord[]; }[] | nullThe page's files under headings, each group in the order its first file came, so the sort still reads down the page. Page-local on purpose: a group never spans a page, and its count is this page's.
readMediaView(search: URLSearchParams): Pick<MediaQuery, "size" | "group" | "upload" | "layout">What the address says about drawing the page, which the content kit's readMediaQuery leaves to the component: the layout, the tile size, the grouping and the open upload dialog (upload=1). A host merges it into the kit's query.
recordOfKit(row: KitMediaRow, used?: UsedIn[] | undefined): MediaRecordA kit row as the media component's record: url is the site's own address for it (what Markdown and the copy snippets carry), thumb the absolute one a browser loads. A list has no usedBy, so its tiles carry no Unattached flag unless the site counts uses (usedCount, site-api v0.13.0).
mediaDataOfKit(kit: KitMediaData, options?: { usedHref?: ((use: MediaUse) => string) | undefined; view?: Pick<MediaQuery, "size" | "group" | "upload" | "layout" | "pick"> | undefined; }): MediaDataThe kit's page as MediaLibrary's data, so every host maps it the same way. usedHref is where a place that uses the file links (the host's editor); the page's tags, with their counts on this page, make the chip row, and the chosen tag stays in it even when no file here carries it. view is the drawing the address asks for (readMediaView) and pick the picker's chosen file. The inspected file brings its twins, its history and the model's suggestions where the kit read them.
applyChanges(rows: readonly MediaRecord[], changed: ReadonlyMap<string, MediaRecord | null>, q: MediaQuery): { rows: MediaRecord[]; elsewhere: number; updated: number; }The page's files with what others changed put in place: a changed file replaces its tile where it still belongs in this view and leaves where it does not (moved to Trash, restored, untagged); a file deleted for good leaves. A changed file not on this page is counted, never added, since where it would sort and whether the site's search would match it are the site's to say.
turnMakesCopy(item: Pick<MediaRecord, "orientation">, offers: Pick<MediaOffers, "replaceKeepsSize">): booleanTrue when a quarter turn saves the turned picture as a new file: a site whose addresses carry the size (offers.replaceKeepsSize) turns a picture that is not square that way (site-api v0.13.0), by the orientation the kit gives.
oversized(item: Pick<MediaRecord, "kind" | "width" | "height">, maxEdge: number | null): booleanTrue when a picture has an edge longer than the site keeps (the oversized lens's rule).
licenseEnded(licenseExpires: string | null | undefined, today?: Date): booleanTrue when a license's end day (YYYY-MM-DD) is before today's, in UTC, as the license-expired lens counts it.
filesToOpen(result: Pick<IntentResult, "outcomes"> | null | undefined): { id: string; why: "copy" | "duplicate" | "new"; }[]The files an upload, an import or a turn left to open, read from the kit's outcomes (site-api v0.13.0): a file already stored (duplicate, whose outcome is that file), a new file, and a turned copy (copyId).
dayWords(iso: string): stringA day as words, in UTC, so it reads the same in every zone: "May 1, 2026". The string itself when it holds no date.
momentWords(iso: string): stringA moment in UTC, as words: "Oct 29, 2026, 2:05 PM UTC".

Parts and data attributes

ClassIs
.cap-image-fieldits own class
.cap-image-field-actionsits own class
.cap-image-field-controlsits own class
.cap-image-field-rowits own class
.cap-image-field-thumbits own class
.cap-image-field-urlits own class
.cap-media-libthe root
.cap-media-lib-accepta part
.cap-media-lib-bara part
.cap-media-lib-chipsa part
.cap-media-lib-counta part
.cap-media-lib-displaya part
.cap-media-lib-extraa part
.cap-media-lib-historya part
.cap-media-lib-history-factsa part
.cap-media-lib-history-whata part
.cap-media-lib-keysa part
.cap-media-lib-layouta part
.cap-media-lib-notea part
.cap-media-lib-openeda part
.cap-media-lib-pagesa part
.cap-media-lib-reverta part
.cap-media-lib-tool-labela part
.cap-media-lib-toolsa part
.cap-media-lib-uploada part
.cap-media-lib-upload-actionsa part
.cap-media-lib-withhelda part
StateRead from
:emptythe platform
[aria-current]an attribute

Accessibility

KeyDoes
Ctrl K, Cmd K, /Find a file: the command menu over the host's matches, or focus in the search field
Esc, on a tileClears the selection; with nothing selected, closes the open file's details and keeps focus on the tile

The grid's and the inspector's keys are media's (arrow keys, Home, End, Enter to open, Space or x to select, Alt and an arrow from a field). The bulk bar's are the bulk bar's (Esc clears). z is Undo. In the picker, Enter on a tile opens the alt step. The library adds these, and lists them under Keyboard shortcuts:

  • The library is a region named by its noun ("Files"); the picker is "Choose an image".
  • The tags and lenses are labeled lists of links in a nav; the current one has aria-current and the pressed look.
  • Each tile's box names its file; the inspector is a dialog named by the file; each of its forms is named ("Alt text", "Tags").
  • The alt step's text field is required, so the browser says so; Insert as decorative skips the check on purpose.
  • Text reaches 4.5:1 and edges 3:1 in both themes.