UI

Avatar

A profile photo input that expands into an in-place circular crop stage with drag pan, wheel and pinch zoom, progress ring, and host-driven or callback uploads.

import { AvatarInput } from '@uthereal/ui/avatar-input'

Avatar input playground

Profile photo

PNG, JPG or WebP, up to 5 MB

Loading interactive preview…

Overview

AvatarInput displays a circular avatar beside its label, status copy, and action buttons. Clicking or dropping an image onto the avatar validates file type and size before decoding, then grows the avatar into an in-place 184px circular crop stage with dimmed overflow. Users pan by dragging or pressing arrow keys, zoom with the wheel, pinch gestures, or slider, and save a square cropped image (outputSize, default 512px).

ModeHow it works
Declarative hostOmit onUpload. Receive cropped blobs via onCrop and/or uploadAction, and drive status, progress, and error props.
React onUploadPass onUpload(blob, { report, signal, original }). The component runs the progress ring, cancellation, settle, and retry.
Output encodingPNG inputs stay image/png to preserve transparency; all other accepted types encode as image/jpeg at 92% quality.
Refusal checksValidates accept MIME types and maxSize bytes before decoding, showing inline errors without creating a crop draft.

Use AvatarInput for profile photos, team member avatars, and circular workspace logos. Use Files when picking several files or documents at once, and Avatar when displaying a photo without editing.

Usage

'use client'
import { useState } from 'react'
import { AvatarInput } from '@uthereal/ui/avatar-input'

export function ProfilePhoto({
  user,
}: {
  user: { name: string; avatarUrl?: string }
}) {
  const [src, setSrc] = useState<string | undefined>(user.avatarUrl)

  return (
    <AvatarInput
      name={user.name}
      src={src}
      value={src}
      onValueChange={setSrc}
      removable
      onUpload={async (blob, { report, signal }) => {
        const res = await fetch('/api/avatar', {
          method: 'PUT',
          body: blob,
          signal,
        })
        report(100)
        if (!res.ok) {
          throw new Error('Upload failed. Your previous photo is unchanged.')
        }
        const { url } = (await res.json()) as { url: string }
        return url
      }}
      onRemove={() => {
        void fetch('/api/avatar', { method: 'DELETE' })
      }}
    />
  )
}

report accepts percentages from 0 to 100; until you call it, the progress ring spins in its waiting state. Resolve onUpload with the canonical URL to replace and revoke the local preview object URL, or resolve with undefined to keep displaying the local crop. For hosts without upload callbacks, omit onUpload and drive status, progress, and error declaratively.

Examples

Upload states

In declarative mode, your application reports the upload lifecycle with status (idle, uploading, done, error), progress (0 to 100), and error. While status="uploading", the photo scales down to 90% under a dim scrim inside the progress ring; omitting progress spins the ring until a value arrives. On status="error", the ring turns to --ui-danger and offers Try again and Discard.

Uploading photo

Uploading 64%

Uploading 50%

Saved photo

Photo updated

Upload failed

Connection interrupted. Try uploading again.

Constraints and read-only display

Configure size (48 to 160 px), accept, maxSize, and removable to match your backend limits; omitting hint and description generates the file-type and size hint automatically. Set readOnly to show the current avatar while blocking picking, dropping, removing, and keyboard triggers.

Workspace logo

PNG or WebP, up to 2 MB

Directory photo

Managed by your organization directory.

API reference

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

ArgumentType / defaultDescription
labelstringDefault: "Profile photo"Heading beside the avatar and accessible name of the group. In sentence case.
hideLabelbooleanDefault: falseHide the label visually when the context already names the field. It is still announced.
descriptionstring—Supporting copy under the heading when hint is omitted. Replaces the automatic file type and size hint.
errorstring—Upload failure message reported by your application, shown in place with Try again and Discard.
requiredbooleanDefault: falseMarks the field as required for assistive technology and shows an indicator. Your application validates the value.
readOnlybooleanDefault: falseDisplay the current photo without allowing picking, dropping, cropping, or removing.
disabledbooleanDefault: falseUnavailable: picking, dropping, and removing are blocked.
namestringDefault: "Alex Rivera"Person's name, used for the initials fallback when no photo is set.
srcstring—Current photo URL. Changing it replaces the shown photo; a stored upload value wins over later edits.
hintstring—Helper copy under the heading. Omit it to show description, or list the accepted types and size limit.
acceptstring[]Default: ["image/png","image/jpeg","image/webp"]Accepted image MIME types. The derived hint lists them, e.g. "PNG, JPG or WebP, up to 5 MB".
maxSizeintegerDefault: 5242880Largest file in bytes, checked before the image is decoded. Keep it in line with your backend.
sizeintegerDefault: 88Avatar diameter in px while not cropping; the crop circle is 184 px.
outputSizeintegerDefault: 512Side of the square cropped image, in px. PNGs stay PNG to keep transparency; everything else becomes JPEG at 92% quality.
statusidle | uploading | done | errorDefault: "idle"Upload phase reported by the host in declarative mode: uploading draws the ring, error colors it and offers retry, done settles it. With onUpload the component runs the lifecycle itself.
progressinteger—Upload progress in percent (0–100) to fill the ring. Omit while unknown so the ring spins without a value.
removablebooleanDefault: falseShow Remove when a photo is present; clears the photo and reports removeAction.
uploadActionstring—Host action run with the cropped image when no React onUpload callback drives the upload.
removeActionstring—Host action run when the photo is removed.
labelsAvatarInputLabels—Reader-facing copy: buttons, crop stage name and hint, zoom controls, and status messages.
errorCopyAvatarInputErrorCopy—Copy of each refusal, with {extension}, {types}, {size}, and {max} placeholders.
recipestudio | softDefault: "studio"Visual treatment. Both recipes use the same interaction behavior.
themeAvatarInputTheme—Color mode, accent, and semantic tokens. See Theming for all keys and defaults.
motionnone | subtle | expressiveDefault: "subtle"Crop-stage morph, drags, zooms, progress ring, and message motion. System reduced motion keeps a 120ms opacity crossfade; none makes every change immediate.
motionOptionsAvatarInputMotionOptions—Crop-stage morph transition (disclosure family; smooth spring by default). Durations are milliseconds.
dirltr | rtl—Reading direction. Omit to inherit the page direction.

React integration

PropPurpose
onUpload(image, context)Runs the full upload lifecycle inside the component. context gives { report, signal, original }; resolve with a stored URL or void.
onCrop(image, url, file)Fires with the cropped Blob, preview object URL, and original File when onUpload is omitted.
onRemove()Fires after the user activates Remove. Also enables the Remove button even when removable is false.
onError({ code, message })Fires whenever a type, size, decode, or upload refusal is displayed.
onAction(action)Fires with uploadAction or removeAction in declarative mode.
value, onValueChangeControlled photo URL and change callback fired on settled upload or removal in both modes.
refImperative AvatarInputHandle exposing open() (opens file picker) and selectFile(file) (validates and opens cropper).
presetApplication defaults (such as accept, maxSize, outputSize, and labels), overridden by explicit props.
tokensCSS custom properties (--ui-*) applied after the typed theme on the root group.
renderIcon(name, context)Replaces the hover camera or drag image-plus overlay icon; context provides { size: 20, slot: 'camera' | 'imagePlus' }.
className, styleApplied to the root group element, which carries the resolved --ui-* tokens.
Native attributesForwarded to the root role="group" container (id, lang, hidden, translate).

Keyboard & accessibility

KeyInteraction
Tab, Shift+TabIdle: avatar button, primary upload/replace button, remove button. Cropping: crop area, zoom out, slider, zoom in, save, cancel.
Enter, SpaceOn the avatar or primary button: opens the file picker.
Arrow keysIn the crop area: pans the photo by 2% of the circle diameter (10% while holding Shift).
+ / = and -In the crop area: zooms in or out by 20%.
0In the crop area: resets zoom to 100% and centers the photo.
EnterIn the crop area: crops and saves the photo.
EscapeIn the crop area: cancels cropping and returns focus to the primary button.

The root renders as role="group" named by label (visually hidden with hideLabel while remaining announced) and linked to the status message via aria-describedby. Entering crop mode moves focus to the crop area (role="group", aria-roledescription="crop area"), whose accessible name states the current zoom percentage and keyboard controls. Saving, canceling, and removing restore focus to the primary action button.

Status messages, validation refusals, and completion text announce in a role="status" (aria-live="polite", aria-atomic="true") region, while determinate upload progress announces in 25% increments in a dedicated hidden live region. All spacing, container queries, and the zoom range track fill mirror cleanly in dir="rtl", and forced-colors: active maps mask hairlines, progress rings, slider controls, disabled states, and focus outlines to system colors.

Motion and theming

  • Crop stage morph: opening and closing the cropper animates the avatar circle, backdrop, panel position, and container height on motionOptions.morph (Arc's smooth spring, 0.4s, bounce 0).
  • Elastic pan bounds: dragging past the photo edge stretches with resistance up to a quarter circle and springs back inside bounds on release.
  • Upload ring and settle: saving insets the photo to 90% on the smooth spring under a scrim while the 2px ring fills on the same spring. On completion, a second ring expands by 12% and fades over 480ms while the photo snaps back to 100% on the snappy spring.
  • Reduced motion: prefers-reduced-motion: reduce resizes the crop circle immediately, snaps pan bounds without bounce, skips the settle ring, disables active press scales, slows the waiting ring to 3s, and keeps 120ms opacity crossfades. motion="none" makes all updates immediate (0ms), disables press scales, and stops the waiting ring spin.

theme accepts the core and control token groups, plus borderStrong, popupRadius, accentStrong, success, track, controlFill, controlThumb, and shadowThumb. An optional UtherealProvider supplies application-wide defaults.

Composition

AvatarInput is a leaf component. Its photo URL (string | null) is host state at /fields/instance-<id>/value, initialized from src and preserved across configuration edits. Register uploadAction and removeAction as host actions when driving uploads declaratively. See Building with agents.

{
  "type": "AvatarInput",
  "props": {
    "label": "Profile photo",
    "name": "Alex Rivera",
    "removable": true,
    "uploadAction": "upload_avatar",
    "removeAction": "remove_avatar"
  },
  "children": []
}

On this page