<!-- generated by scripts/gen-docs.mjs from docs/system/image-field.md. Edit the source and rerun. -->
# ImageField

## Description

Lets a person choose the picture that stands for them or their organisation, such as a face, a logo or a cover, place it in its frame, and see it upload and save.

`import { ImageField, imageFieldLabels, type ImageUpload } from "@/components/cobalt/ui/image-field"`, source `registry/cobalt/ui/image-field.tsx`, status `ready-with-gaps`.
`import { centred, clampPlacement, coverScale, frameRatio, reach, sourceRect } from "@/lib/cobalt/image-crop"`, source `registry/cobalt/lib/image-crop.ts`.
Foundation: `hand-rolled`, over the native file input, the system `Dialog`, `Slider`, `Button`, `TextSwap` and the toaster through `useUndoable`. Traps checked: `trap/native-control`, `trap/field-label`, `trap/button-icon-name`, `trap/control-height`, `trap/toast-errors`, `trap/loading-layout-shift`, `trap/loading-label-swap`, `trap/submit-repeat`, `trap/disabled-drops-focus`, `trap/live-region-double`, `trap/color-only-status`, `trap/numbers-shift`, `trap/gesture-drag`, `trap/gesture-axes`, `trap/overlay-title`, `trap/overlay-pending-dismiss`, `trap/overlay-focus-return`, `trap/illustration-announced`, `trap/decor-pointer`, `trap/focus-ring-shape`, `trap/toast-timer`, `trap/touch-hover-flash` (n/a: nothing on the field changes on hover), `trap/reduced-motion-ignored`, `trap/demo-on-timers` (n/a: the examples' timers stand in for an upload's progress events, and no example steps through the field's own animation).

Where each trap is answered. `trap/native-control` in Foundation: the file input stays hidden and a real `Button` opens it. `trap/field-label` in ARIA: the field is a group named by its visible label. `trap/button-icon-name` n/a: every button has its words. `trap/control-height` in States: the buttons are the `sm` size side by side. `trap/toast-errors` in States: every refusal and failure is on the line under the label. `trap/loading-layout-shift` in States: the line holds its widest message and the buttons their widest words, so nothing moves through an upload. `trap/loading-label-swap` n/a: Remove sends no request while it is on screen; it answers at once and the server hears of it when the Undo window ends. `trap/submit-repeat` in States: Replace is disabled through Base UI's `focusableWhenDisabled` while an upload runs, Use picture takes `aria-disabled` and an early return while the crop is drawn, and Remove leaves with the picture, so it cannot be pressed twice. `trap/disabled-drops-focus` in Keyboard: Replace stays focusable while disabled, and a button that leaves with its state hands focus to Upload. `trap/live-region-double` in ARIA: the field's one status line speaks the upload, and the toast alone says "Picture removed", so the field's line stays silent for it. `trap/color-only-status` in States: every message is words, and a failed picture has the retry arrow. `trap/numbers-shift` in Tokens: the line uses tabular figures. `trap/gesture-drag` and `trap/gesture-axes` in Keyboard: the crop stage captures the pointer, keeps the grab offset, takes `touch-action: none`, and has the arrow keys and the slider as its other paths. `trap/overlay-title` and `trap/overlay-pending-dismiss` in ARIA: the crop window has its title, and while the crop is drawn Escape and the backdrop do nothing. `trap/overlay-focus-return` in Keyboard. `trap/focus-ring-shape` in Keyboard: the crop stage's ring is drawn around the stage on its 16px corner, and only after the Tab key. `trap/toast-timer` in Rules: Remove's window is `useUndoable`'s, held while its toast is pointed at or focused. `trap/illustration-announced` in ARIA: the picture is hidden unless it is the progress bar. `trap/decor-pointer` in Tokens: the drop tint and the face's circle take no pointer. `trap/reduced-motion-ignored` in Motion.

### Foundation

Not applicable: hand-rolled.

| Given by the foundation                                                                                                                                                                       | Added by the team                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The native `<input type="file">` with `accept`, the HTML drag and drop events, `Image.decode()`, the canvas and its `toBlob()`; `accepts()` from FileDrop; the system `Dialog`, `Slider`, `Button`, `TextSwap` and `AvatarSilhouette`; `useUndoable` and the toaster | The picture as it will appear, a 64px circle for `avatar`, a 64px square with the card's corner for `square`, or a 3:1 band across the field for `cover`, with the silhouette or a picture glyph while there is none; Upload, or Replace, and Remove beside it, each holding the width of its widest wording; a press on the picture opens the chooser, and a drop anywhere on the field takes the first file, with the picture tinted while a file is over it and no request is on its way; `accept`, `maxSize` and a picture that cannot be decoded refused at once on the line; the crop window, with the picture covering the frame, moved by a drag or the arrow keys and zoomed from 1 to 3 times by the slider or plus and minus, and a face's circle drawn over it; the framed part redrawn in the browser at `output.width`, 512px by default and 1500px for a cover, as JPEG, or PNG for a square PNG; the upload drawn on the picture, grey with its colour rising from the bottom as the share grows; failure kept as the grey picture under the retry arrow, with Retry and Cancel; the saved picture kept on screen until `value` has loaded, and a saved address that does not load said so on the line, over the silhouette or the picture glyph; one line under the label that holds every message in one cell; one status line; focus handed to Upload when the button pressed leaves with its state, such as Remove once the picture is gone; Remove through `useUndoable`, so the picture goes at once, a toast offers Undo for 10 seconds, and `onRemove` is sent only when the window ends, the toast is closed, a new picture is chosen or the field leaves the page; the crop stage's ring drawn only after the Tab key, read from `data-focus-source` (`registry/cobalt/lib/focus-source.ts`), since the stage takes the focus as the window opens after a drop or the file chooser, which a browser counts as keyboard focus; the share rounded down, so a picture still on its way never reads 100%; `imageFieldLabels`. `image-crop.ts` holds the placement arithmetic with no DOM: the cover scale, how far the picture may move and still cover the frame, and the part of the picture the frame keeps |

## Examples

A profile picture on an account page. Choose a picture, or drop one on the circle, place it in the crop window, and watch it upload, grey at first with its colour rising as it goes.

Real uses, 0 call sites (`rg -n "<ImageField\b" app registry --glob '!registry/cobalt/ui/*'`): no showcase page draws one outside its examples yet, and the examples folder does not count.

Uses inside the registry: none. `registry/cobalt/ui/image-field.test.tsx` renders it for the tests, `registry/cobalt/lib/image-crop.test.ts` tests the placement arithmetic, and `docs/system/stress/image-field.tsx` draws the three shapes with a German label and a picture that fails to load.

### Example files

| File                                              | Covers           | Caption                                                                                                                                                                         |
| ------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `docs/system/examples/image-field/default.tsx`    | default          | A profile picture on an account page. Choose a picture, or drop one on the circle, place it in the crop window, and watch it upload; Replace and Remove sit beside it            |
| `docs/system/examples/image-field/default.tsx`    | shape=avatar     | The face, a 64px circle with the crop window's circle drawn over the square frame                                                                                               |
| `docs/system/examples/image-field/shape-square.tsx` | shape=square   | A firm's logo, square with the card's corner, before one is chosen, so only Upload logo shows                                                                                   |
| `docs/system/examples/image-field/shape-cover.tsx` | shape=cover     | A research group's cover, 3:1 across the field; what is sent is the framed part at 1500 by 500                                                                                  |
| `docs/system/examples/image-field/shape-square.tsx` | state:empty    | No picture yet: the picture glyph and one button                                                                                                                                |
| `docs/system/examples/image-field/failed.tsx`     | state:failed     | An upload that does not go through. The new picture stays grey under the retry arrow, the line says so, and the buttons become Retry and Cancel. Every first try fails here     |
| `docs/system/examples/image-field/in-card.tsx`    | composition:Card | A profile card on an account page. The picture saves on its own once it is placed, and the name beside it saves with its own Save                                              |

Example: A profile picture on an account page. Choose a picture, or drop one on the circle, place it in the crop window, and watch it upload; Replace and Remove sit beside it (`docs/system/examples/image-field/default.tsx`)

```tsx
import { useState } from "react";

import { ImageField, type ImageUpload } from "@/components/cobalt/ui/image-field";

// Stands in for the upload: 12 percent every 150ms, then the saved address.
function upload(file: File, { progress, signal }: ImageUpload) {
  return new Promise<string>((resolve, reject) => {
    let share = 0;
    const timer = setInterval(() => {
      share += 12;
      progress(share);
      if (share >= 100) {
        clearInterval(timer);
        resolve(URL.createObjectURL(file));
      }
    }, 150);
    signal.addEventListener("abort", () => {
      clearInterval(timer);
      reject(new Error("cancelled"));
    });
  });
}

export default function Example() {
  const [picture, setPicture] = useState<string | null>("/photos/portrait-2.webp");
  return (
    <ImageField
      label="Profile picture"
      hint="PNG, JPEG or WebP, up to 20 MB"
      value={picture}
      onUpload={async (file, report) => setPicture(await upload(file, report))}
      onRemove={() => new Promise<void>((resolve) => setTimeout(() => (setPicture(null), resolve()), 700))}
    />
  );
}
```

Example: A profile card on an account page. The picture saves on its own once it is placed, and the name beside it saves with its own Save (`docs/system/examples/image-field/in-card.tsx`)

```tsx
import { useState } from "react";

import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import { Field, FieldError, FieldLabel } from "@/components/cobalt/ui/field";
import { ImageField, type ImageUpload } from "@/components/cobalt/ui/image-field";
import { Input } from "@/components/cobalt/ui/input";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after 900ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 900),
  );

// Stands in for the picture's upload: 15 percent every 150ms, then the saved address.
function upload(file: File, { progress, signal }: ImageUpload) {
  return new Promise<string>((resolve, reject) => {
    let share = 0;
    const timer = setInterval(() => {
      share += 15;
      progress(Math.min(share, 100));
      if (share >= 100) {
        clearInterval(timer);
        resolve(URL.createObjectURL(file));
      }
    }, 150);
    signal.addEventListener("abort", () => {
      clearInterval(timer);
      reject(new Error("cancelled"));
    });
  });
}

export default function Example() {
  const [picture, setPicture] = useState<string | null>("/photos/portrait-5.webp");
  const [name, setName] = useState("Priya Shah");
  const save = useAction(request);
  return (
    <Card className="w-full max-w-md">
      <CardHeader>
        <CardTitle>Profile</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col gap-6">
        <ImageField
          label="Profile picture"
          hint="PNG, JPEG or WebP, up to 20 MB"
          value={picture}
          onUpload={async (file, report) => setPicture(await upload(file, report))}
          onRemove={async () => {
            await request();
            setPicture(null);
          }}
        />
        <Field>
          <FieldLabel>Name</FieldLabel>
          <Input value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" />
          <FieldError reserve>
            {save.status === "failure" ? "Your name was not saved. Check your connection and try again." : ""}
          </FieldError>
        </Field>
      </CardContent>
      <CardFooter>
        <StateButton
          status={save.status}
          pendingLabel="Saving"
          successLabel="Saved"
          failureLabel="Not saved"
          onClick={() => void save.run()}
        >
          Save
        </StateButton>
      </CardFooter>
    </Card>
  );
}
```

## Variants

### shape

- `avatar`: the default, a person's face, drawn as a 64px circle beside the label, cropped square with a circle drawn over the crop window. Used at 0 call sites.
- `square`: an organisation's logo, a 64px square with the card's corner; a PNG stays PNG, so its transparent parts survive. Used at 0 call sites.
- `cover`: a banner across the top of a page, a 3:1 band across the field with the label and buttons under it, placed in a 3:1 window titled "Position cover" and sent at 1500 by 500. Used at 0 call sites.

Example: The face, a 64px circle with the crop window's circle drawn over the square frame (`docs/system/examples/image-field/default.tsx`)

```tsx
import { useState } from "react";

import { ImageField, type ImageUpload } from "@/components/cobalt/ui/image-field";

// Stands in for the upload: 12 percent every 150ms, then the saved address.
function upload(file: File, { progress, signal }: ImageUpload) {
  return new Promise<string>((resolve, reject) => {
    let share = 0;
    const timer = setInterval(() => {
      share += 12;
      progress(share);
      if (share >= 100) {
        clearInterval(timer);
        resolve(URL.createObjectURL(file));
      }
    }, 150);
    signal.addEventListener("abort", () => {
      clearInterval(timer);
      reject(new Error("cancelled"));
    });
  });
}

export default function Example() {
  const [picture, setPicture] = useState<string | null>("/photos/portrait-2.webp");
  return (
    <ImageField
      label="Profile picture"
      hint="PNG, JPEG or WebP, up to 20 MB"
      value={picture}
      onUpload={async (file, report) => setPicture(await upload(file, report))}
      onRemove={() => new Promise<void>((resolve) => setTimeout(() => (setPicture(null), resolve()), 700))}
    />
  );
}
```

Example: A firm's logo, square with the card's corner, before one is chosen, so only Upload logo shows (`docs/system/examples/image-field/shape-square.tsx`)

```tsx
import { useState } from "react";

import { ImageField } from "@/components/cobalt/ui/image-field";

export default function Example() {
  const [logo, setLogo] = useState<string | null>(null);
  return (
    <ImageField
      shape="square"
      label="Logo"
      hint="A square PNG keeps its transparent parts"
      value={logo}
      labels={{ upload: "Upload logo" }}
      // Stands in for an upload whose share is not known: 1.2 seconds, then the saved address.
      // Cancel stops it.
      onUpload={async (file, { signal }) => {
        await new Promise<void>((resolve, reject) => {
          const timer = setTimeout(resolve, 1200);
          signal.addEventListener("abort", () => {
            clearTimeout(timer);
            reject(new Error("cancelled"));
          });
        });
        setLogo(URL.createObjectURL(file));
      }}
      onRemove={async () => setLogo(null)}
    />
  );
}
```

Example: A research group's cover, 3:1 across the field; what is sent is the framed part at 1500 by 500 (`docs/system/examples/image-field/shape-cover.tsx`)

```tsx
import { useState } from "react";

import { ImageField, type ImageUpload } from "@/components/cobalt/ui/image-field";

// Stands in for the upload: 10 percent every 150ms, then the saved address. Cancel stops it.
function upload(file: File, { progress, signal }: ImageUpload) {
  return new Promise<string>((resolve, reject) => {
    let share = 0;
    const timer = setInterval(() => {
      share += 10;
      progress(share);
      if (share >= 100) {
        clearInterval(timer);
        resolve(URL.createObjectURL(file));
      }
    }, 150);
    signal.addEventListener("abort", () => {
      clearInterval(timer);
      reject(new Error("cancelled"));
    });
  });
}

export default function Example() {
  const [cover, setCover] = useState<string | null>("/photos/city-toronto.webp");
  return (
    <div className="w-full max-w-xl">
      <ImageField
        shape="cover"
        label="Cover"
        hint="At least 1500 by 500 pixels"
        value={cover}
        labels={{ upload: "Upload cover" }}
        onUpload={async (file, report) => setCover(await upload(file, report))}
        onRemove={async () => setCover(null)}
      />
    </div>
  );
}
```

## States

| State         | Trigger                                                                         | What the user can do                                                          | Shown by, besides color                                                                                                                                                                                                                                       | Checked by       |
| ------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| empty         | `value` is null and nothing is uploading                                        | press Upload or the picture, or drop a picture on the field                   | the silhouette for a face, or the picture glyph for a logo or a cover; one button, "Upload picture"; no Remove                                                                                                                                               | test             |
| idle          | `value` holds an address                                                        | press Replace or the picture, drop a picture, or press Remove when `onRemove` is passed | the picture as it will appear; Replace and Remove, both 79px wide (measured)                                                                                                                                                                          | test             |
| drag-over     | a file is dragged over the field, which is not `disabled` and has no request on its way | drop it                                                                       | the picture tinted with the accent's soft fill and a 2px accent ring inside its edge; the field stays 78px tall (measured)                                                                                                                                  | by hand          |
| refused       | the file fails `accept` or `maxSize`, or cannot be decoded                      | choose another picture                                                        | the reason on the line: "Not a picture this takes", "Over 20 MB, choose a smaller picture" or "Could not open this picture", read once (measured "Not a picture this takes" for a text file)                                                              | by hand          |
| placing       | a picture is taken and `crop` is on                                             | drag the picture, use the arrow keys, plus and minus or the slider, then Use picture or Cancel | the crop window titled "Crop picture", or "Position cover" for a cover, with the picture just covering the frame and centred (measured 464px in a 464px frame) and a face's circle drawn over it                                             | by hand          |
| uploading     | Use picture is pressed, or a picture is taken with `crop` off                   | wait, or press Cancel to put the saved picture back                           | the new picture grey with its colour rising from the bottom by the share (measured `inset(76% 0 0 0)` at 24 percent); "Uploading", then "Uploading, 24%"; `aria-busy`; Replace disabled at half opacity and still focusable, so it keeps its focus (measured `aria-disabled="true"`, opacity 0.5, focus kept), and Remove turned to Cancel; "Uploading" read once; no drop tint (measured opacity 0 during a drag) | by hand          |
| saved         | `onUpload` resolves                                                             | Replace, Remove                                                               | the new picture in full colour, kept until `value` has loaded; "Picture saved" read once; the line back to the hint                                                                                                                                          | by hand          |
| failed        | `onUpload` rejects                                                              | press Retry, or press Cancel to put the saved picture back                    | the new picture grey under the retry arrow; "Upload failed" on the line, read once; Replace turned to Retry and Remove to Cancel, each holding its width; the field 283px wide and 78px tall throughout (measured)                                         | by hand          |
| removing      | Remove is pressed                                                               | press Undo in the toast, for 10 seconds, held while the toast is pointed at or focused | the field as it is when empty, at once: the silhouette and "Upload picture", focus on it (measured); a toast "Picture removed" with Undo; `onRemove` is not called yet. Undo puts the picture back and the toaster returns the focus to the first button, which reads Replace again (measured at 1440 and 390, by pointer and by Enter) | by hand          |
| remove-failed | `onRemove`, sent when the Undo window ends, rejects                             | press Retry in the toast, which removes it again with a fresh window          | the picture back on the field with Replace and Remove; a toast that stays, "Could not remove the picture", with Retry and a close button; the field's line keeps the hint | test             |
| unloadable    | `value` holds an address that does not load                                     | press Replace, or Remove when `onRemove` is passed                            | the silhouette, or the picture glyph, in place of the picture; "Could not load the saved picture" on the line, not read (measured on /stress/image-field?data=worst) | by hand          |
| disabled      | `disabled`                                                                      | nothing                                                                       | half opacity; both buttons disabled; no tint and no drop; the picture opens nothing                                                                                                                                                                           | by hand          |

Example: No picture yet: the picture glyph and one button (`docs/system/examples/image-field/shape-square.tsx`)

```tsx
import { useState } from "react";

import { ImageField } from "@/components/cobalt/ui/image-field";

export default function Example() {
  const [logo, setLogo] = useState<string | null>(null);
  return (
    <ImageField
      shape="square"
      label="Logo"
      hint="A square PNG keeps its transparent parts"
      value={logo}
      labels={{ upload: "Upload logo" }}
      // Stands in for an upload whose share is not known: 1.2 seconds, then the saved address.
      // Cancel stops it.
      onUpload={async (file, { signal }) => {
        await new Promise<void>((resolve, reject) => {
          const timer = setTimeout(resolve, 1200);
          signal.addEventListener("abort", () => {
            clearTimeout(timer);
            reject(new Error("cancelled"));
          });
        });
        setLogo(URL.createObjectURL(file));
      }}
      onRemove={async () => setLogo(null)}
    />
  );
}
```

Example: An upload that does not go through. The new picture stays grey under the retry arrow, the line says so, and the buttons become Retry and Cancel. Every first try fails here (`docs/system/examples/image-field/failed.tsx`)

```tsx
import { useRef, useState } from "react";

import { ImageField, type ImageUpload } from "@/components/cobalt/ui/image-field";

export default function Example() {
  const [picture, setPicture] = useState<string | null>("/photos/portrait-4.webp");
  const tries = useRef(0);
  // Stands in for an upload that drops at 60 percent on every first try and goes through on the next.
  const upload = (file: File, { progress, signal }: ImageUpload) =>
    new Promise<string>((resolve, reject) => {
      const fails = (tries.current += 1) % 2 === 1;
      let share = 0;
      const timer = setInterval(() => {
        share += 15;
        progress(Math.min(share, 100));
        if (fails && share >= 60) {
          clearInterval(timer);
          reject(new Error("dropped"));
        } else if (share >= 100) {
          clearInterval(timer);
          resolve(URL.createObjectURL(file));
        }
      }, 150);
      signal.addEventListener("abort", () => {
        clearInterval(timer);
        reject(new Error("cancelled"));
      });
    });
  return (
    <ImageField
      label="Profile picture"
      hint="PNG, JPEG or WebP, up to 20 MB"
      value={picture}
      onUpload={async (file, report) => setPicture(await upload(file, report))}
      onRemove={async () => setPicture(null)}
    />
  );
}
```

### State precedence

- Refused and failed: refused wins on the line. The picture stays grey under the arrow, and Retry still sends the earlier picture.
- Refused and uploading: Not applicable: while an upload runs the chooser's button is disabled, the picture opens nothing and a drop is ignored.
- Unloadable and uploading: uploading wins. The new picture takes the empty box's place.
- Refused and removing: removing wins. Pressing Remove clears the reason, and the line shows the hint.
- Removing and a new picture: the new picture wins. Choosing one while Undo is offered closes the toast, which sends the removal at once, before the new picture is sent.
- Uploading and removing: Not applicable: while a picture is local, Remove is Cancel.
- Failed and remove-failed: both show. The failed upload keeps the field; the removal's toast stays until it is closed or retried.
- Placing and uploading: Not applicable: no picture can be taken while an upload runs, so the window cannot open.
- Drag-over and uploading: the upload wins. No tint shows and the drop is ignored until it ends. While a removal waits the field is empty and takes a drop, which ends the window as choosing does.
- Unloadable and refused: refused wins on the line, until the next picture is taken.
- Drag-over and disabled: disabled wins. No tint and no drop.
- Saved and a `value` that has not changed yet: `value` wins. The field loads whatever `value` holds when `onUpload` resolves and then shows it, so the new picture stays only when `value` already holds its address (`rule/image-field-value-before-resolve`).

### Motion

| Trigger                                          | Kind     | Preset                                                                                                         | Properties           | Reduced motion                                                     |
| ------------------------------------------------ | -------- | -------------------------------------------------------------------------------------------------------------- | -------------------- | ------------------------------------------------------------------ |
| an upload's share grows                          | announce | `duration-settle`, `--t-settle` 300ms, `ease-out` on `--curve`                                                 | clip-path            | none: the share jumps to its new height                            |
| an upload with no share yet                      | announce | `animate-pulse` on a wrapper around the grey picture, so it breathes from the picture's 45 percent to half of it and back (measured 0.225 to 0.45); on the picture itself the pulse only reached 0.5, from 0.45 | opacity              | none: the picture stays grey and still                             |
| a file is dragged over the field, or leaves      | input    | `duration-press`, `--t-press` 140ms on `--curve`                                                               | opacity              | the same fade                                                      |
| the line's message changes                       | announce | `TextSwap`: the old wording leaves on 70 percent of `--t-pop`, the new one arrives on `--t-icon` and `--curve-in-out` | opacity, color | the same fade                                                      |
| a button's words change, such as Replace to Retry | announce | `TextSwap`, as on the line                                                                                    | opacity              | the same fade                                                      |
| the removal's toast arrives and leaves           | announce | the toaster's own: Arrive on `--t-arrive`, Leave on `--t-leave`                                                | opacity, transform   | the toaster's fade                                                 |
| the crop window opens or closes                  | announce | `dialog-motion`                                                                                                | opacity              | the same fade                                                      |

## Props

<!-- Props generated from registry/cobalt/ui/image-field.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `label` | `string` |  | The field's name, shown beside the picture: "Profile picture". |
| `onUpload` | `(file: File, upload: ImageUpload) => Promise<unknown>` |  | Sends a picture. |
| `value` | `string` |  | The saved picture's address, or null when there is none. |
| `accept?` | `string` | `"image/png` | The kinds it opens, as an input's `accept`. |
| `className?` | `string` |  |  |
| `crop?` | `boolean` | `true` | Opens the crop window after a picture is chosen, for a face or a logo, or to place a cover. |
| `disabled?` | `boolean` | `false` |  |
| `hint?` | `ReactNode` |  | What it takes, under the label: "PNG or JPEG, up to 20 MB". |
| `labels?` | `Partial<{ upload: string; replace: string; remove: string; cancel: string; retry: string; progress: (percent: number) => string; uploaded: string; failed: string; removed: string; undo: string; removeFailed: string; unloadable: string; unreadable: string; tooLarge: (max: string) => string; wrongType: string; crop: string; position: string; cropHint: string; stage: string; zoom: string; use: string; }>` |  |  |
| `maxSize?` | `number` | `20_000_000` | The largest picture it opens, in bytes. |
| `onRemove?` | `() => Promise<unknown>` |  | Removes the saved picture, once Remove's Undo window ends without Undo, its toast is closed, or the field leaves the page. |
| `output?` | `{ width?: number; type?: "image/jpeg" \| "image/png" \| "image/webp"; quality?: number; }` |  | The size and format of the picture a crop sends. |
| `shape?` | `ImageShape` | `"avatar"` | `avatar` is a round face, `square` a logo with the card's corner, `cover` a 3:1 banner. |

`label` names the field, shown beside the picture, such as "Profile picture". `value` is the saved picture's address, or null when there is none. `onUpload(file, { progress, signal })` sends the picture: report the share sent through `progress`, abort on `signal`, which Cancel aborts, and resolve once `value` holds the new address, or reject when it is not saved. `onRemove` removes the saved picture, called once Remove's Undo window ends without Undo, its toast is closed, a new picture is chosen, or the field leaves the page; without it there is no Remove. A rejected `onRemove` puts the picture back with a toast that offers Retry. `shape` is `avatar`, `square` or `cover`. `crop`, on by default, opens the crop window before anything is sent; off, the file goes as it was chosen. `accept` is the kinds it opens, as an input's `accept`, PNG, JPEG, WebP and GIF by default. `maxSize` is the largest file it opens, in bytes, 20,000,000 by default. `hint` is the line under the label at rest. `output` sets the width, type and quality of the picture a crop sends. `disabled` turns the field off. `labels` replaces any string from `imageFieldLabels`. `className` is for placement. The lib's functions take sizes in pixels and a placement as a zoom and the centre's offset as a share of the frame.

## Usage

### When to use

- A person sets the picture that stands for them, such as a profile picture on an account page.
- An organisation sets its logo, or a group its cover, where the picture must fit a fixed frame and is sent already cropped.

### When not to use

- Files of any kind, or several at once, such as a booking's documents. Use FileDrop instead.
- Photos attached to a message. Use Composer instead.
- Someone's picture shown with no way to change it. Use Avatar instead.

### Rules

- `rule/image-field-value-before-resolve`: When `onUpload` succeeds, set `value` to the saved address inside it, before its promise resolves, such as `setPicture(await upload(file, report))`, instead of after it, because once it resolves the field loads whatever `value` holds and then shows it in place of the new picture, so a `value` set later puts the old picture back in between. Evidence: single use docs/system/examples/image-field/default.tsx:32, as are the other examples; principle heuristic: visibility of system status, the picture after "Picture saved" must be the saved one. Check: review of every `onUpload` passed to `ImageField`.
  - Don't: `onUpload={(file, report) => api.upload(file, report).then(refetchProfile)}`
  - Do: `onUpload={async (file, report) => setPicture(await api.upload(file, report))}`
- `rule/image-field-reject-on-failure`: When the upload fails, let `onUpload` reject instead of catching the error and calling `toast()`, because a rejection keeps the new picture grey under the retry arrow with Retry and Cancel, and a caught error resolves, so the field says "Picture saved". Evidence: person D39; principle heuristic: help users recognize, diagnose and recover from errors. Check: review of every `try` inside an `onUpload`.
  - Don't: `onUpload={async (file) => { try { await api.upload(file) } catch { toast("Upload failed") } }}`
  - Do: `onUpload={async (file, report) => setPicture(await api.upload(file, report))}`
- `rule/image-field-remove-is-the-request`: When passing `onRemove`, make it the server call alone, resolving once the picture is deleted and rejecting when it is not, instead of confirming first or showing a toast of your own, because the field already takes the picture away at once and offers Undo for 10 seconds, sends `onRemove` only when that window ends, and puts the picture back with Retry when it rejects; a question first or a second toast repeats what the field does. Evidence: person D39; app 2/2 source apps commit a removal late, Tag's pending delete and the TSA app's logo field (docs/research/2026-10-17-missing-parts.md, F4); single use registry/cobalt/ui/image-field.tsx:161, Remove through `useUndoable`. Check: test `use-undoable.test.ts` "Undo puts it back and the server never hears of it", and review of every `onRemove`.
  - Don't: `onRemove={async () => { if (!confirm("Remove your picture?")) return; await api.removeAvatar(); toast("Picture removed") }}`
  - Do: `onRemove={async () => { await api.removeAvatar(); setAvatar(null) }}`
- `rule/image-field-pass-the-signal`: When `onUpload` sends the file, pass `signal` to the request, and report its share through `progress` whenever the request knows it, instead of ignoring the second argument, because Cancel only aborts `signal`, so an upload that ignores it still lands after Cancel, and without `progress` the picture only breathes grey until the end. Evidence: single use docs/system/examples/image-field/default.tsx:18; principle heuristic: user control and freedom, Cancel stops what it cancels. Check: review of every `onUpload` passed to `ImageField`.
  - Don't: `onUpload={async (file) => setLogo(await api.upload(file))}`
  - Do: `onUpload={async (file, { progress, signal }) => setLogo(await api.upload(file, { onProgress: progress, signal }))}`

### Content

- Follows `rule/writing-button-verb`.
- Follows `rule/file-drop-hint-says-what-it-takes`.
- `rule/image-field-upload-names-the-picture`: When the picture is not a face, set `labels.upload` to "Upload" and the picture's name, such as "Upload logo" or "Upload cover", instead of the default "Upload picture", because the button is the keyboard's way in and the only words on it before a picture is chosen. Evidence: single use docs/system/examples/image-field/shape-square.tsx:14, and the cover example does the same; principle heuristic: match between system and the real world, the button names the thing the person is setting. Check: review of every `ImageField` with `shape="square"` or `shape="cover"`.
  - Don't: `<ImageField shape="square" label="Logo" value={logo} onUpload={upload} />`
  - Do: `<ImageField shape="square" label="Logo" value={logo} labels={{ upload: "Upload logo" }} onUpload={upload} />`

### Anti-slop

- `rule/image-field-not-a-raw-input`: When a person picks a picture that stands for them or their organisation, render `ImageField` instead of an `<input type="file">` beside an `img`, because the field crops to the frame and redraws at `output.width` before anything is sent, draws the upload on the picture, refuses a wrong file on its line, and keeps Replace, Remove and Retry in place. Evidence: person D39; principle heuristic: error prevention, a picture is placed in its frame before it goes. Check: review of every `type="file"` outside `registry/cobalt/ui/`.
  - Don't: `<input type="file" accept="image/*" onChange={(e) => upload(e.target.files[0])} /><img src={avatar} alt="" />`
  - Do: `<ImageField label="Profile picture" value={avatar} onUpload={upload} onRemove={remove} />`
- `rule/image-field-upload-on-the-picture`: When a picture uploads, let `ImageField` draw the share on the picture instead of a `Spinner` over it or a `Progress` bar under it, because the field keeps one box through the upload, and a spinner or a bar added to it changes its size or covers the picture being sent. Evidence: measured the field at 283px wide and 78px tall from idle through uploading, failed and saved (Playwright on /components/image-field); person D37. Check: review of every `Spinner` or `Progress` beside an `ImageField`.
  - Don't: `{uploading ? <Spinner /> : null}<ImageField label="Profile picture" value={avatar} onUpload={upload} />`
  - Do: `<ImageField label="Profile picture" value={avatar} onUpload={upload} />`

### Limits

- `rule/image-field-label-length`: When a `label` runs past 33 characters, shorten it, such as "Profile picture", instead of a phrase, because beside a 64px picture at 390px the label has one line of 230px, and a longer label wraps and makes the field taller than the fields beside it. Evidence: measured by setting the label's text on /stress/image-field?data=worst at 390 with Playwright: a 230px column, where "Profile picture for the directory", 33 characters, stays on one line with the field 78px tall, and 39 characters wrap to two lines and grow the field to 98px, as the page's own 50-character German label does. Check: review of every `label` passed to `ImageField`.
  - Don't: `<ImageField label="Profile picture shown across the whole company directory" value={avatar} onUpload={upload} />`
  - Do: `<ImageField label="Profile picture" value={avatar} onUpload={upload} />`

## Accessibility

Rests on the system `Button`, the toaster's Undo through `useUndoable`, the hidden native file input, the system `Dialog` and `Slider`, and a `role="group"` named by the label. The picture can be pressed with a pointer, and its keyboard path is the Upload or Replace button. Screen reader pass with VoiceOver: NEEDS REVIEW.

### Keyboard

| Key                  | Where focus is                      | Effect                                                                                     | Focus after                                                                                                                    | Checked by |
| -------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| Enter or Space       | Upload or Replace                   | opens the device's file chooser                                                            | the button                                                                                                                     | by hand    |
| none                 | the chooser returns a picture, or a picture is dropped | opens the crop window                                                         | the picture's stage in the window, with no ring unless the Tab key was the last way you moved (measured: no outline with `data-focus-source` unset or `pointer`, the outline after Tab then Shift+Tab) | by hand    |
| Arrow keys           | the stage                           | move the picture 2 percent of the frame, or 10 percent with Shift, never leaving an empty edge | the stage                                                                                                                  | by hand    |
| Plus, Equals, Minus  | the stage                           | zoom in or out by 0.1, between 1 and 3                                                     | the stage                                                                                                                      | by hand    |
| Arrow keys           | the zoom slider                     | zoom by 0.01                                                                               | the slider                                                                                                                     | by hand    |
| Enter                | Use picture                         | draws the framed part and sends it                                                         | Replace, which the window hands focus back to and which stays focusable while disabled for the upload (measured) | by hand    |
| Escape               | anywhere in the window              | closes it and sends nothing; does nothing while the crop is being drawn                    | the button that opened the chooser, such as Replace (measured)                                                                 | by hand    |
| Enter or Space       | Cancel, during an upload or after a failure | aborts the upload and puts the saved picture back                                   | stays on the button, which reads Remove again (measured)                                                                       | by hand    |
| Enter or Space       | Retry                               | sends the failed picture again                                                             | stays on the same button, which reads Replace and stays focusable while disabled for the upload (measured)                   | by hand    |
| Enter or Space       | Remove                              | takes the picture away at once and offers Undo in a toast for 10 seconds                   | Upload picture, since Remove leaves with the picture (measured)                                                                | by hand    |
| Enter or Space       | Undo, in the toast                  | puts the picture back; `onRemove` is never sent                                            | the field's first button, which reads Replace again: the toaster returns the focus to where it was before the toast (measured) | by hand    |

### ARIA

| Part                  | Role                 | Accessible name from                                         | States and properties                                                     | Announced                                                                                                                | Checked by        |
| --------------------- | -------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------- |
| field                 | group                | `aria-labelledby` the visible label                          | `aria-busy` while an upload runs                                           | the label, such as "Profile picture, group"                                                                             | test              |
| picture               | none, `aria-hidden`  | none                                                         | none                                                                      | nothing                                                                                                                  | by hand           |
| picture, uploading    | progressbar          | `aria-labelledby` the visible label                          | `aria-valuemin` 0, `aria-valuemax` 100, `aria-valuenow` once known        | "Profile picture" and the share, on request (measured name)                                                              | by hand           |
| Upload, Replace, Retry | button              | its words, the one wording shown                             | `aria-disabled` and `data-disabled` while an upload runs, through `focusableWhenDisabled`, so it keeps its tab stop; disabled with the field | "Replace, button"                                                                                                        | snapshot          |
| Remove, Cancel        | button               | its words                                                    | none                                                                      | "Remove, button"; the toast it opens reads "Picture removed", and the field's status line says nothing for it | snapshot          |
| status line           | status               | its text                                                     | visually hidden                                                           | "Uploading", "Picture saved", "Upload failed", or a refusal's reason, once each                                         | by hand           |
| crop window           | dialog               | its title, "Crop picture" or "Position cover"                | `aria-busy` while the crop is drawn; described by the hint                | the title and "Drag the picture to move it, and zoom with the slider."                                                  | by hand           |
| stage                 | group                | `aria-label` from `labels.stage`                             | `tabIndex` 0, `data-focus="custom"`; the ring on its wrapper after Tab                                                           | "Picture position. Arrow keys move it, plus and minus zoom."; a move is not read                                        | by hand           |
| zoom slider           | slider               | `aria-label` from `labels.zoom`                              | the value as a percent through `getAriaValueText`, such as "110%"         | "Zoom, 110%"                                                                                                             | by hand           |

## Tokens

| Part                  | State                    | Token                                                          |
| --------------------- | ------------------------ | -------------------------------------------------------------- |
| picture               | all                      | `--muted`, `--outline-image`, `--r-2xl` for a logo or a cover  |
| picture glyph         | empty                    | `--muted-foreground`                                           |
| drop tint             | drag-over                | `--primary-soft`, `--primary`                                  |
| retry arrow           | failed                   | `--on-photo` on black at 60 percent                            |
| line                  | hint, uploading          | `--muted-foreground`, tabular figures                          |
| line                  | refused, failed          | `--destructive`                                                |
| crop stage            | focus-visible, after Tab | `--ring`, `--line-focus`, `--focus-offset` on the stage's `--r-2xl` |
| buttons               | all                      | the Button's `sm` tokens: `--secondary` for Upload, ghost for Remove |
| crop window           | placing                  | the Dialog's tokens; `--muted` and `--r-2xl` for the stage     |
| fades and fills       | all                      | `--t-press`, `--t-settle`, `--t-pop`, `--t-icon`, `--curve`, `--curve-in-out` |

## Related

- Avatar: a person's picture shown, with no way to change it.
- FileDrop: files of any kind, several at once, each with its own upload.
- FileTile: one file with its upload drawn on its glyph, as this draws it on the picture.
- Dialog: the window the crop opens in.
- Toaster: where Remove's Undo shows, through `useUndoable` (documented on SettingsLayout).
