UI

Files

A drag-and-drop file input with a drawn dashed edge, clipboard paste, inline refusal checks, and a host-driven upload list with progress, retry, and remove actions.

import { FileInput } from '@uthereal/ui/file-input'

File input playground

  • lounge-chair-hero.jpg1.8 MBUploaded
  • brand-guidelines.pdf2.4 MBUploading 62%
  • launch-video.mov8.6 MBFailed: Connection lost
Loading interactive preview…

Overview

FileInput renders a drop area with a drawn dashed border, three paper sheets, a label, a description, and an automatic constraint note. Users add files by dragging and dropping, opening the native picker, or pasting from the clipboard while hovering or focusing the field.

The component validates accept, maxFiles, and maxSize inline and never uploads files by itself. Your application owns upload side effects, either by controlling the list through items and onAction (uploadAction, removeAction) or by supplying an onUpload handler that reports progress and supports AbortSignal cancellation.

CapabilityBehavior
Declarative hostPass items (or defaultItems) with ready, uploading, done, or error states; handle uploadAction / removeAction.
React onUploadSupply onUpload(item, { onProgress, signal }) to drive the progress bar, done check, error reason, retry, and abort.
Inline refusalsInvalid types and count overflow show an alert under the drop area and shake once; oversized files join as failed rows.
List and foldingRender rows below or inside the dashed edge; set compactAt to fold the prompt into a slim bar once the list fills.
Single-file modeSet multiple={false} to take one file at a time; a valid pick aborts prior uploads and replaces the list.

Use FileInput for attachments, document imports, and multi-file upload queues. Use Avatar for circular cropped profile photos, and File for read-only attachment display.

Usage

'use client'
import { useState } from 'react'
import { FileInput, type FileInputHostItem } from '@uthereal/ui/file-input'

export function DocumentUploader() {
  const [items, setItems] = useState<FileInputHostItem[]>([])

  return (
    <FileInput
      label="Add files"
      description="PDF or PNG, up to 10 MB"
      accept=".pdf,image/png"
      maxSize={10 * 1024 * 1024}
      items={items}
      onItemsChange={setItems}
      onUpload={async (item, { onProgress, signal }) => {
        if (!item.file) return
        const body = new FormData()
        body.append('file', item.file)
        onProgress(35)
        const response = await fetch('/api/uploads', {
          method: 'POST',
          body,
          signal,
        })
        if (!response.ok) {
          throw new Error('Upload failed. Try again.')
        }
        onProgress(100)
      }}
    />
  )
}

Omit items for an uncontrolled list initialized from defaultItems. For declarative or AI-native hosts that drive uploads externally, omit onUpload, set uploadAction and removeAction, and update items as each file transitions from ready to uploading, done, or error.

Examples

Upload lifecycle states

Each row displays an extension-based icon (or a 40px thumbnail from preview, generated automatically for picked images), binary file size, and status. ready shows size only; uploading animates a spring progress bar and counted percentage; done draws a check mark once the bar reaches 100%; error displays the failure reason and a Retry pill unless retryable is false.

  • contract-final.pdf1.2 MBUploaded
  • appendix-tables.xlsx375 KBUploading 58%
  • review-notes.md18 KB
  • product-demo.mp48.6 MBFailed: Connection interrupted. Try again.
  • raw-archive.zip46 MBFailed: File is larger than 25 MB

Inside list, folding, and single-file constraints

Set listPlacement="inside" to render the file list inside the dashed border, and pair it with compactAt to fold the prompt into a slim bar once that many rows exist (dragging a file over the target expands the sheets again). Set multiple={false} with maxFiles={1} for single-file inputs where each accepted pick replaces the current file.

  • flight-invoice.pdf418 KBUploaded
  • hotel-folio.png1.8 MBUploaded
  • master-services-agreement.pdf598 KBUploaded

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
labelstringDefault: "Add files"Name of the field. In the drop area it is the bold first line (the field label stays for assistive technology).
hideLabelbooleanDefault: falseHide the label visually when the context already names the field. It is still announced.
descriptionstringDefault: "Drop files here or choose from your device"Line under the label inside the drop area. Drop files here or choose from your device.
errorstring—Validation message from your application. Setting it marks the field invalid; the message is linked to the field and announced politely. It replaces a refused-file message while set.
requiredbooleanDefault: falseMarks the field as required for assistive technology and shows an indicator. Your application validates the value.
readOnlybooleanDefault: falseShow the files without letting the user add, remove, or retry them.
disabledbooleanDefault: falseUnavailable: the drop area and the file actions cannot be used.
namestring—Native form field name of the hidden file input.
acceptstring—Accepted file types as one native accept string: MIME types ("image/*", "application/pdf") or extensions (".pdf"), comma-separated. Omit it to accept any file.
multiplebooleanDefault: trueTake several files (the default). false takes one file per pick, which replaces the list: replace your files with the accepted one.
maxFilesintegerDefault: 5Most files in the list, including the files already shown (5 by default). A pick adds as many files as fit; the rest are refused with the tooMany message.
maxSizeinteger—Largest accepted file in bytes, e.g. 10485760 for 10 MB. A larger file never reaches your application: it is listed as a failed row with the tooLarge reason, which the user can remove.
listPlacementbelow | insideDefault: "below"below: the file list sits under the drop area. inside: the list sits inside its edge.
notestring—The small line under the description. Omit it to show the accepted types, or the file limit.
noteLabelsFileInputNoteLabels—Templates of the automatic note: accepted ({accept}), limit ({maxFiles}) and limitOne.
dropLabelstring—The label while files are dragged over the drop area. Omit it to use dropLabels.
dropLabelsFileInputDropLabels—Templates of the automatic drop label: files (several files) and file (multiple false).
compactAtinteger—From this many files the prompt folds to a slim bar so the list has room; a file dragged over brings the illustration back. Omit it to keep the full prompt.
listLabelstringDefault: "Files"Accessible name of the file list.
defaultItemsFileInputItem[]Default: []Files present at mount, such as files added earlier, each with an ID, name, size in bytes, status (ready, a plain selection showing its size; uploading; done; error), progress in percent, an error message and retryable (false hides Retry). Later argument edits do not reset a mounted instance; your application owns the live list.
statusLabelsFileInputStatusLabels—Status text for each lifecycle state. An error message on the file replaces the error label.
rejectionLabelsFileInputRejectionLabels—Messages for refused files: invalidType (one picked file, {name}), invalidTypes (several), tooMany ({maxFiles}) and tooManyOne show as an alert under the drop area until the next pick or a removal (an error you set wins); tooLarge ({maxSize}) is the reason on the failed row of a file above maxSize.
removeActionstring—Name of an action registered by your application, sent to onAction with the file ID when the user removes a file.
uploadActionstring—Name of an action registered by your application, sent to onAction with the file ID when the host should upload a file (a retry, or an AI-native host driving the lifecycle). Without it, a picked file stays ready for the host to upload itself.
removeLabelstringDefault: "Remove {name}"Accessible name of each remove button. {name} is replaced with the file name.
retryLabelstringDefault: "Retry {name}"Accessible name of each retry button. {name} is replaced with the file name.
retryTextstringDefault: "Retry"Visible text and tooltip of the retry button; narrow lists show its icon only.
removeTextstringDefault: "Remove"Tooltip of each remove button.
progressLabelstringDefault: "Uploading {name}"Accessible name of each progress bar. {name} is replaced with the file name.
failedLabelstringDefault: "Failed: {reason}"How assistive technology reads a failed row; {reason} is replaced with its reason.
announcementsFileInputAnnouncementLabels—Polite announcements: added ({count}), addedOne, refused ({name}, {reason}, appended per file above maxSize), removed ({name}), uploaded ({name}), failed ({name}, {reason}) and retrying ({name}).
sizesm | md | lgDefault: "md"Text scale of the drop area and the rows.
recipestudio | softDefault: "studio"Visual treatment. Both recipes use the same interaction behavior.
themeFileInputTheme—Color mode, accent, and semantic tokens. See Theming for all keys and defaults.
motionnone | subtle | expressiveDefault: "subtle"Arc motion: the edge closes and glows toward a dragged file, the sheets fan out, rows land and fold, progress fills on a spring and failures shake. none changes at once; system reduced motion fades.
dirltr | rtl—Reading direction. Omit it to inherit the page direction.

Each FileInputItem has { id, name, size, status, progress?, error?, retryable, preview? }. status is 'ready' (default), 'uploading', 'done', or 'error'; size is in bytes; progress is 0 to 100; retryable defaults to true.

React integration

PropPurpose
items, onItemsChangeControlled list of FileInputHostItem rows (each extends FileInputItem with file?: File).
onFilesChange(files)Fires with the File[] of listed rows whenever files are added or removed.
onUpload(item, options)Async uploader receiving { onProgress, signal }. Removing a row or unmounting aborts signal.
onRetry(item)Fires when the user activates Retry on a failed row, before onUpload retries.
onRemove(item)Fires after a row is removed from the list.
onAction(action, itemId)Fires with uploadAction (on pick or retry) or removeAction (on removal) and the file ID.
idID of the hidden <input type="file">; label, trigger, description, error, and row IDs derive from it.
refRef to the root field <div>.
presetApplication defaults (such as translated statusLabels, rejectionLabels, and announcements).
tokensCSS custom properties (--ui-*) applied after the typed theme on the field root.
renderIcon(name, context)Custom icon renderer; context holds size and slot ('prompt', 'file', 'status', 'remove', 'retry').
className, styleApplied to the root field element, which carries the resolved --ui-* tokens.
Native attributesForwarded to the root field <div> (data-*, event handlers); aria-describedby merges onto the picker button.

Keyboard & accessibility

KeyInteraction
TabMoves focus to the drop-area trigger, then to each row's retry and remove buttons.
Enter, SpaceOn the drop-area trigger: open the file picker. On row buttons: retry or remove.
ArrowUp, ArrowDownIn the file list: move focus to the same action button on the adjacent row.
Delete, BackspaceIn the file list: remove the focused row (when not disabled or readOnly).
⌘V, Ctrl+VPaste clipboard files while hovering or focusing the field (skips text inputs).

The drop area exposes a native <button> labelled by label (plus dropLabel while dragging) and described by description, note, any active error or refusal message, and any consumer aria-describedby. When disabled or readOnly, the trigger sets aria-disabled="true" and blocks clicking, drag-and-drop, pasting, removing, and retrying.

Refusal and validation messages render in a role="alert" region. Picks, oversized refusals, removals, retries, and upload completions or failures announce through a pre-mounted role="status" (aria-live="polite", aria-atomic="true") region. Removing a row moves focus to the next row's remove button, the previous row, or back to the drop-area trigger; retrying moves focus to that row's remove button. Each uploading row exposes role="progressbar" with aria-valuenow and progressLabel. Layout spacing, file names (unicode-bidi: plaintext), and the progress fill direction adapt to dir="rtl". forced-colors: active preserves system borders, disabled text/stroke colors, progress bar contrast, error outlines, and focus rings.

Motion and theming

  • Drop area and drag state: hovering fans the three paper sheets; dragging a file over the target closes the dashed SVG perimeter into a solid accent border, tracks the pointer with a spring-driven edge glow and wash, spreads the sheets, and runs a 2.2s breathing scale.
  • Refusals and errors: invalid-type or count refusals shake the drop area (420ms) and open the error row on the smooth spring while changed words rise in through a soft blur.
  • Rows and progress: new rows stagger into view as their height opens on the smooth spring; uploading rows drive both the progress bar and formatted percentage from one smooth spring, hold until 100%, draw the Done check mark, and collapse the bar; failed rows shake once and spring open the Retry pill; removed rows fold to zero height.
  • Reduced motion: prefers-reduced-motion: reduce disables CSS transitions, breathing, shakes, travel, blur, height springs, and press scales while keeping 120ms opacity crossfades and immediate progress updates. motion="none" makes every update immediate (0ms).

theme accepts the core and control token groups, plus borderStrong, surfaceRadius (resting drop area), popupRadius (folded drop area), and success (finished check mark). An optional UtherealProvider supplies application-wide defaults.

Composition

FileInput is a leaf component. defaultItems seeds initial metadata at /fields/instance-<id>/items, while live upload states (uploading, done, error) and picked File objects stay owned by the host application. Register uploadAction and removeAction handlers in your host to drive uploads and removals from agent compositions. See Building with agents.

{
  "type": "FileInput",
  "props": {
    "label": "Add supporting documents",
    "description": "PDF or PNG, up to 10 MB",
    "accept": ".pdf,image/png",
    "maxSize": 10485760,
    "maxFiles": 5,
    "uploadAction": "upload_document",
    "removeAction": "remove_document"
  },
  "children": []
}

On this page