{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "photo-upload",
  "type": "registry:ui",
  "title": "Photo Upload",
  "description": "Photos from the five places people get them (pick, drag, paste, camera), made small and clean on the device, then handed to ONE function the app provides, `onUpload`. The component never opens a connection: it has no `fetch`, no `XMLHttpRequest`, no…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "form",
    "pattern"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/button.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/progress.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/photo-upload.tsx",
      "target": "components/ui/patterns/photo-upload.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/photo-upload v1.0.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/photo-upload\n// What changed since: https://ds.interlace.tools/c/photo-upload#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — PhotoUpload\n *\n * Photos from the five places people get them (pick, drag, paste, camera),\n * made small and clean on the device, then handed to ONE function the app\n * provides, `onUpload`. The component never opens a connection: it has no\n * `fetch`, no `XMLHttpRequest`, no destination. What reaches `onUpload` has\n * no location, camera, time or embedded thumbnail inside it.\n *\n * ## Anatomy\n *\n *   PhotoUpload                    (div role=group — data-slot=\"photo-upload\", data-state, data-count)\n *     ├─ span                      (data-slot=\"photo-upload-label\": the visible name)\n *     ├─ div                       (data-slot=\"photo-upload-dropzone\", data-drag idle|over, data-full)\n *     │   ├─ label > input file    (data-slot=\"photo-upload-pick\": the real control, laid over its label at opacity 0 so it stays focusable)\n *     │   ├─ label > input file    (data-slot=\"photo-upload-camera\": touch devices only, after mount)\n *     │   └─ p                     (data-slot=\"photo-upload-hint\")\n *     ├─ p role=status             (data-slot=\"photo-upload-rejections\")\n *     ├─ ul                        (data-slot=\"photo-upload-list\")\n *     │   └─ li                    (data-slot=\"photo-upload-item\", data-status)\n *     │       ├─ img | span        (data-slot=\"photo-upload-thumb\")\n *     │       ├─ div               (data-slot=\"photo-upload-meta\": name, size, \"Location removed\")\n *     │       ├─ Progress          (data-slot=\"photo-upload-progress\", only while working)\n *     │       ├─ p                 (data-slot=\"photo-upload-message\": the state in words; role=alert on error)\n *     │       ├─ input text        (data-slot=\"photo-upload-alt\", with `altText`)\n *     │       └─ div               (data-slot=\"photo-upload-actions\": Crop, Try again, Cancel, Remove)\n *     ├─ Button                    (data-slot=\"photo-upload-submit\": `manual` with ready photos)\n *     └─ p aria-live=polite        (data-slot=\"photo-upload-announce\", sr-only)\n *\n * ## Where the photos go\n *\n * `onUpload(photo, ctx)` is the whole backend surface. `ctx.onProgress(0..1)`\n * reports progress, `ctx.signal` aborts on cancel, remove and unmount. Throw\n * `PhotoUploadError({ retryable: true })` for a failure worth retrying (up to\n * `retries`, 1 s, 2 s, 4 s with jitter); any other failure shows Try again.\n * `xhrUploader` (subpath `photo-upload-xhr`) is one ready-made adapter.\n *\n * ## States\n *\n * Component: empty, drag-over, has-items, full, partial-failure, all-done,\n * disabled, read-only, offline-waiting. Item: queued, reading, processing,\n * ready, uploading, done, error, canceled. Each is words and an icon, never\n * colour alone. With JavaScript off the dropzone is a labelled native file\n * input (give it a `name`).\n *\n * ## Source of the API\n *\n * react-dropzone (https://react-dropzone.js.org): `accept`, `maxFiles` keep\n * its names. Uppy (https://uppy.io) and FilePond (https://pqina.nl/filepond):\n * the queue, progress and retry model. Diverges on purpose: `maxFileBytes`\n * names its unit, `onUpload` is an adapter (no destination), no plugin system\n * (the adapter and `runtime` are the extension points).\n *\n * | Rule | Concept              | Where                                   |\n * | ---- | -------------------- | --------------------------------------- |\n * | R5   | data-testid required | `PhotoUploadProps['data-testid']`       |\n * | R6   | data-slot per part   | every part above                        |\n * | R8   | booleans default off | `manual`, `altText`                     |\n * | R14  | controlled + not     | `value` / `defaultValue`                |\n * | R25  | lazy client part     | the cropper loads on first use          |\n * | R26  | A11y                 | native input, one announcement per change |\n */\n\nimport {\n  AlertCircleIcon,\n  CameraIcon,\n  CheckCircleIcon,\n  CropIcon,\n  ImagePlusIcon,\n  LoaderCircleIcon,\n  RotateCcwIcon,\n  XIcon,\n} from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport { Progress, ProgressIndicator, ProgressTrack } from '@/components/ui/progress';\nimport {\n  announcements,\n  DEFAULT_ACCEPT,\n  DEFAULT_ERROR_TEXT,\n  fingerprintOf,\n  formatBytes,\n  HEAD_BYTES,\n  isLive,\n  nextToUpload,\n  PhotoUploadError,\n  planIntake,\n  planProcessing,\n  qualityLadder,\n  readHeader,\n  reduce,\n  retryDelay,\n  shouldAutoRetry,\n  stripMetadata,\n  type CropRect,\n  type PhotoAction,\n  type PhotoError,\n  type PhotoErrorCode,\n  type PhotoItem,\n  type PhotoMime,\n  type PhotoProcessing,\n  type PhotoUploader,\n  type ProcessedPhoto,\n  type Quarter,\n} from '@/components/ui/patterns/photo-upload-model';\nimport { browserRuntime, type ImageRuntime } from '@/components/ui/patterns/photo-upload-runtime';\n\nexport type { PhotoItem, PhotoMime, PhotoProcessing, PhotoUploader, ProcessedPhoto };\nexport { PhotoUploadError } from '@/components/ui/patterns/photo-upload-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nconst PhotoCropper = React.lazy(() => import('./photo-upload-crop.js'));\n\nexport interface PhotoCrop {\n  /** width / height; null for free. @default null */\n  aspect?: number | null;\n  /** `round` masks the preview only; the output is the full rectangle. @default 'rect' */\n  shape?: 'rect' | 'round';\n  /** Open the cropper for every added photo before processing. @default false */\n  required?: boolean;\n}\n\ntype Text<A extends unknown[] = []> = string | ((...args: A) => string);\nexport interface PhotoUploadLabels {\n  /** @default 'Photos' */\n  label?: string;\n  /** @default 'Choose photos' (singular with maxFiles 1) */\n  choose?: string;\n  /** @default 'Take photo' */\n  camera?: string;\n  /** @default 'or drag photos here, or paste' */\n  hint?: string;\n  /** @default 'Upload' */\n  upload?: string;\n  /** @default 'Crop' */\n  crop?: string;\n  /** @default 'Try again' */\n  retry?: string;\n  /** @default 'Cancel' */\n  cancel?: string;\n  /** @default 'Remove' */\n  remove?: string;\n  /** @default 'Describe this photo' */\n  alt?: string;\n  /** @default 'Location removed' */\n  locationRemoved?: string;\n  /** @default 'Details removed' */\n  detailsRemoved?: string;\n  /** @default 'You have added the most photos allowed.' */\n  full?: string;\n  /** @default 'Waiting for a connection' */\n  offline?: string;\n  /** Per-status words. */\n  status?: Partial<Record<PhotoItem['status'], string>>;\n  /** Per-error words. */\n  errors?: Partial<Record<PhotoErrorCode, string>>;\n  /** @default (added, skipped) => '2 added. 1 skipped: not a photo' */\n  rejections?: Text<[number, string]>;\n  cropper?: {\n    title?: string;\n    zoom?: string;\n    rotateLeft?: string;\n    rotateRight?: string;\n    apply?: string;\n    cancel?: string;\n  };\n}\n\nexport interface PhotoChangeDetails {\n  reason: 'added' | 'removed' | 'status' | 'alt' | 'crop' | 'retry' | 'cancel' | 'rejected';\n  id: string | null;\n  rejected: readonly { name: string; error: PhotoError }[];\n}\n\nexport interface PhotoItemProps {\n  item: PhotoItem;\n  index: number;\n  total: number;\n  labels: Required<Pick<PhotoUploadLabels, 'crop' | 'retry' | 'cancel' | 'remove' | 'alt' | 'locationRemoved' | 'detailsRemoved'>>;\n  actions: {\n    crop?: () => void;\n    retry?: () => void;\n    cancel?: () => void;\n    remove?: () => void;\n    setAlt?: (alt: string) => void;\n  };\n  message: string;\n  altText: boolean;\n}\n\nexport interface PhotoUploadProps\n  extends Omit<React.ComponentPropsWithoutRef<'div'>, 'onChange' | 'defaultValue' | 'children'> {\n  'data-testid': string;\n  /** The whole backend surface. Required: the component has no default destination. */\n  onUpload: PhotoUploader;\n  value?: readonly PhotoItem[];\n  defaultValue?: readonly PhotoItem[];\n  onValueChange?: (items: readonly PhotoItem[], details: PhotoChangeDetails) => void;\n  /** @default ['image/jpeg', 'image/png', 'image/webp'] */\n  accept?: readonly PhotoMime[];\n  /** @default 10 */\n  maxFiles?: number;\n  /** Largest input file, in bytes, before any processing. @default 26214400 */\n  maxFileBytes?: number;\n  /** Largest input in pixels, read from the header before decoding. @default 40000000 */\n  maxPixels?: number;\n  /** `false` skips resize and re-encode but never skips the metadata strip. */\n  processing?: PhotoProcessing | false;\n  /** `false` hides the Crop action. @default false */\n  crop?: PhotoCrop | false;\n  /** Adds a \"Take photo\" button that opens the camera on a touch device. */\n  capture?: 'environment' | 'user';\n  /** Wait for an Upload button instead of uploading once a photo is processed. @default false */\n  manual?: boolean;\n  /** @default 3 */\n  concurrency?: number;\n  /** Automatic tries after a retryable failure. @default 2 */\n  retries?: number;\n  /** Show a \"Describe this photo\" field per photo. @default false */\n  altText?: boolean;\n  disabled?: boolean;\n  readOnly?: boolean;\n  /** Makes it a real form field: the native input posts the chosen files with JavaScript off. */\n  name?: string;\n  labels?: PhotoUploadLabels;\n  /** Substitute the browser: tests, an agent, a worker, a HEIC decoder. @default browserRuntime */\n  runtime?: ImageRuntime;\n  random?: () => number;\n  makeId?: () => string;\n  dropzoneProps?: React.ComponentPropsWithoutRef<'div'>;\n  itemComponent?: React.ComponentType<PhotoItemProps>;\n}\n\nconst STATUS_WORDS: Record<PhotoItem['status'], string> = {\n  queued: 'Waiting',\n  reading: 'Reading',\n  processing: 'Getting it ready',\n  ready: 'Ready to upload',\n  uploading: 'Uploading',\n  done: 'Uploaded',\n  error: 'Failed',\n  canceled: 'Canceled',\n};\n\nconst wordsOf = (t: Text<[number, string]> | undefined, added: number, skipped: string, fallback: string) =>\n  typeof t === 'function' ? t(added, skipped) : (t ?? fallback);\n\nconst STATE_OF = (items: readonly PhotoItem[], max: number, disabled: boolean, readOnly: boolean, online: boolean) => {\n  if (disabled) return 'disabled';\n  if (readOnly) return 'read-only';\n  if (!online) return 'offline-waiting';\n  if (items.length === 0) return 'empty';\n  if (items.some((i) => i.status === 'error')) return 'partial-failure';\n  if (items.every((i) => i.status === 'done')) return 'all-done';\n  if (items.filter((i) => isLive(i.status) || i.status === 'done').length >= max) return 'full';\n  return 'has-items';\n};\n\nfunction DefaultItem({ item, index, total, labels, actions, message, altText }: PhotoItemProps) {\n  const working = item.status === 'processing' || item.status === 'uploading';\n  const removed = item.output?.metadataRemoved ?? [];\n  const Icon = item.status === 'done' ? CheckCircleIcon : item.status === 'error' ? AlertCircleIcon : null;\n  return (\n    <li\n      data-slot=\"photo-upload-item\"\n      data-status={item.status}\n      data-id={item.id}\n      className=\"border-border bg-background grid grid-cols-[3.5rem_1fr] gap-x-3 gap-y-2 rounded-lg border p-3 motion-safe:animate-in motion-safe:slide-in-from-bottom-1 motion-safe:duration-(--duration-base)\"\n    >\n      {item.previewUrl ? (\n        <img\n          data-slot=\"photo-upload-thumb\"\n          src={item.previewUrl}\n          alt={altText ? item.alt : ''}\n          width={56}\n          height={56}\n          className=\"bg-muted aspect-square size-14 rounded-md object-cover\"\n        />\n      ) : (\n        <span data-slot=\"photo-upload-thumb\" className=\"bg-muted aspect-square size-14 rounded-md\" aria-hidden=\"true\" />\n      )}\n      <div className=\"grid min-w-0 gap-1\">\n        <div data-slot=\"photo-upload-meta\" className=\"min-w-0 text-sm\">\n          <p className=\"truncate font-medium\">{item.name}</p>\n          <p className=\"text-muted-foreground\">\n            {item.output && item.output.bytes < item.source.bytes\n              ? `${formatBytes(item.output.bytes)}, was ${formatBytes(item.source.bytes)}`\n              : formatBytes(item.output?.bytes ?? item.source.bytes)}\n            {removed.length > 0\n              ? `. ${removed.includes('gps') ? labels.locationRemoved : labels.detailsRemoved}`\n              : ''}\n          </p>\n        </div>\n        {working ? (\n          <Progress\n            data-slot=\"photo-upload-progress\"\n            value={Math.round(item.progress * 100)}\n            aria-label={`${item.name}: ${message}`}\n            aria-valuetext={`${Math.round(item.progress * 100)} percent, ${message.toLowerCase()}`}\n          >\n            <ProgressTrack>\n              <ProgressIndicator />\n            </ProgressTrack>\n          </Progress>\n        ) : null}\n        <p\n          data-slot=\"photo-upload-message\"\n          role={item.status === 'error' ? 'alert' : undefined}\n          className={cn('flex items-center gap-1.5 text-sm', item.status === 'error' ? 'text-destructive' : 'text-muted-foreground')}\n        >\n          {Icon ? <Icon aria-hidden=\"true\" className=\"size-4 shrink-0\" /> : null}\n          {item.status === 'processing' || item.status === 'uploading' || item.status === 'reading' ? (\n            <LoaderCircleIcon aria-hidden=\"true\" className=\"size-4 shrink-0 motion-safe:animate-spin\" />\n          ) : null}\n          <span>{message}</span>\n        </p>\n        {altText && actions.setAlt ? (\n          <input\n            data-slot=\"photo-upload-alt\"\n            type=\"text\"\n            aria-label={`${labels.alt}: ${item.name}`}\n            placeholder={labels.alt}\n            value={item.alt}\n            onChange={(e) => actions.setAlt?.(e.target.value)}\n            className=\"border-input bg-background h-control-sm w-full rounded-md border px-2 text-sm\"\n          />\n        ) : null}\n        <div data-slot=\"photo-upload-actions\" className=\"flex flex-wrap gap-2\">\n          {actions.crop ? (\n            <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={actions.crop} data-action=\"crop\">\n              <CropIcon aria-hidden=\"true\" />\n              {labels.crop}\n              <span className=\"sr-only\">{`: ${item.name}`}</span>\n            </Button>\n          ) : null}\n          {actions.retry ? (\n            <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={actions.retry} data-action=\"retry\">\n              <RotateCcwIcon aria-hidden=\"true\" />\n              {labels.retry}\n              <span className=\"sr-only\">{`: ${item.name}`}</span>\n            </Button>\n          ) : null}\n          {actions.cancel ? (\n            <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={actions.cancel} data-action=\"cancel\">\n              {labels.cancel}\n              <span className=\"sr-only\">{`: ${item.name}`}</span>\n            </Button>\n          ) : null}\n          {actions.remove ? (\n            <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={actions.remove} data-action=\"remove\">\n              <XIcon aria-hidden=\"true\" />\n              {labels.remove}\n              <span className=\"sr-only\">{`: ${item.name} (${index + 1} of ${total})`}</span>\n            </Button>\n          ) : null}\n        </div>\n      </div>\n    </li>\n  );\n}\n\nfunction PhotoUpload({\n  onUpload,\n  value,\n  defaultValue,\n  onValueChange,\n  accept = DEFAULT_ACCEPT,\n  maxFiles = 10,\n  maxFileBytes = 26_214_400,\n  maxPixels = 40_000_000,\n  processing,\n  crop = false,\n  capture,\n  manual = false,\n  concurrency = 3,\n  retries = 2,\n  altText = false,\n  disabled = false,\n  readOnly = false,\n  name,\n  labels,\n  runtime = browserRuntime,\n  random = Math.random,\n  makeId,\n  dropzoneProps,\n  itemComponent: Item = DefaultItem,\n  className,\n  ...rest\n}: PhotoUploadProps) {\n  const baseId = React.useId();\n  const nextId = React.useRef(0);\n  const newId = makeId ?? (() => `${baseId}-${++nextId.current}`);\n  const [inner, setInner] = React.useState<readonly PhotoItem[]>(defaultValue ?? []);\n  const items = value ?? inner;\n  const itemsRef = React.useRef(items);\n  itemsRef.current = items;\n  const files = React.useRef(new Map<string, File>());\n  const controllers = React.useRef(new Map<string, AbortController>());\n  const timers = React.useRef(new Set<ReturnType<typeof setTimeout>>());\n  const live = React.useRef(true);\n  const [rejections, setRejections] = React.useState<{ added: number; skipped: string[] } | null>(null);\n  const [drag, setDrag] = React.useState<'idle' | 'over'>('idle');\n  const [online, setOnline] = React.useState(true);\n  const wasOnline = React.useRef(true);\n  const [released, setReleased] = React.useState(false);\n  const [announce, setAnnounce] = React.useState('');\n  const [touch, setTouch] = React.useState(false);\n  const [cropping, setCropping] = React.useState<string | null>(null);\n  const cropButton = React.useRef<HTMLElement | null>(null);\n  const prev = React.useRef<readonly PhotoItem[] | null>(null);\n  const buffer = React.useRef<string[]>([]);\n  const flush = React.useRef<ReturnType<typeof setTimeout> | null>(null);\n  const chooseRef = React.useRef<HTMLInputElement>(null);\n  const t = labels ?? {};\n  const words = {\n    label: t.label ?? 'Photos',\n    choose: t.choose ?? (maxFiles === 1 ? 'Choose a photo' : 'Choose photos'),\n    camera: t.camera ?? 'Take photo',\n    hint: t.hint ?? 'or drag photos here, or paste',\n    upload: t.upload ?? 'Upload',\n    crop: t.crop ?? 'Crop',\n    retry: t.retry ?? 'Try again',\n    cancel: t.cancel ?? 'Cancel',\n    remove: t.remove ?? 'Remove',\n    alt: t.alt ?? 'Describe this photo',\n    full: t.full ?? 'You have added the most photos allowed.',\n    offline: t.offline ?? 'Waiting for a connection',\n    locationRemoved: t.locationRemoved ?? 'Location removed',\n    detailsRemoved: t.detailsRemoved ?? 'Details removed',\n  };\n  const errorText = (code: PhotoErrorCode) => t.errors?.[code] ?? DEFAULT_ERROR_TEXT[code];\n  const cropOpts = crop === false ? null : crop;\n\n  const commit = React.useCallback(\n    (action: PhotoAction, reason: PhotoChangeDetails['reason'], id: string | null, rejected: PhotoChangeDetails['rejected'] = []) => {\n      const next = reduce(itemsRef.current, action);\n      if (next === itemsRef.current && rejected.length === 0) return;\n      itemsRef.current = next;\n      if (value === undefined) setInner(next);\n      onValueChange?.(next, { reason, id, rejected });\n    },\n    [onValueChange, value],\n  );\n\n  const release = React.useCallback(\n    (id: string) => {\n      const url = itemsRef.current.find((i) => i.id === id)?.previewUrl;\n      if (url) runtime.revokeObjectURL(url);\n    },\n    [runtime],\n  );\n\n  // Processing: read, plan, strip or re-encode, thumbnail. The model decides; the runtime draws.\n  const process = React.useCallback(\n    async (id: string) => {\n      const file = files.current.get(id);\n      const item = itemsRef.current.find((i) => i.id === id);\n      if (!file || !item) return;\n      const controller = controllers.current.get(id) ?? new AbortController();\n      controllers.current.set(id, controller);\n      const { signal } = controller;\n      const fail = (code: PhotoErrorCode, detail?: string) =>\n        commit({ type: 'failed', id, error: { code, retryable: code !== 'unsupported-format', detail } }, 'status', id);\n      commit({ type: 'reading', id }, 'status', id);\n      try {\n        const bytes = new Uint8Array(await file.arrayBuffer());\n        if (signal.aborted) return;\n        const type = (item.source.type as PhotoMime) ?? 'image/jpeg';\n        const header = readHeader(bytes, type);\n        if (!header) return fail('decode-failed');\n        commit({ type: 'processing', id, progress: 0.2 }, 'status', id);\n        const plan = planProcessing(header, processing, item.crop);\n        const stripped = stripMetadata(bytes, type);\n        const edge = processing === false ? Infinity : (processing?.maxEdge ?? 2048);\n        const hint = header.width && header.height ? { width: header.width, height: header.height } : undefined;\n        const decoded = await runtime.decode(new Blob([bytes as BlobPart], { type }), {\n          maxEdge: plan.kind === 'strip-only' ? 320 : edge,\n          signal,\n          hint:\n            hint && header.orientation >= 5\n              ? { width: hint.height, height: hint.width }\n              : hint,\n        });\n        if (signal.aborted) {\n          if (decoded) runtime.dispose?.(decoded);\n          return;\n        }\n        if (!decoded) return fail('unsupported-format');\n        let blob: Blob;\n        let outType: PhotoMime = type;\n        // Both branches below assign these before they are read.\n        let width: number;\n        let height: number;\n        let removed = stripped.removed;\n        const strippedBlob = new Blob([stripped.bytes as BlobPart], { type });\n        if (plan.kind === 'strip-only') {\n          blob = strippedBlob;\n          width = header.width ?? decoded.width;\n          height = header.height ?? decoded.height;\n        } else {\n          let best: Blob | null = null;\n          for (const quality of qualityLadder(processing)) {\n            if (signal.aborted) return;\n            best = await runtime.encode(decoded, { ...plan, quality }, signal);\n            const target = processing === false ? undefined : processing?.targetBytes;\n            if (!target || best.size <= target) break;\n          }\n          blob = best as Blob;\n          outType = plan.type;\n          width = plan.width || decoded.width;\n          height = plan.height || decoded.height;\n          removed = header.metadata.length ? [...header.metadata] : [];\n          // A resize never makes a file bigger: keep the stripped original when it is smaller and unchanged in look.\n          if (\n            plan.crop === null &&\n            plan.quarter === 0 &&\n            header.orientation === 1 &&\n            header.width !== null &&\n            blob.size >= strippedBlob.size &&\n            plan.type === type\n          ) {\n            blob = strippedBlob;\n            outType = type;\n            width = header.width;\n            height = header.height ?? height;\n            removed = stripped.removed;\n          }\n        }\n        const thumb = await runtime.thumbnail(decoded, 320);\n        runtime.dispose?.(decoded);\n        if (signal.aborted) return;\n        const previewUrl = runtime.createObjectURL(thumb);\n        const output: ProcessedPhoto = {\n          blob,\n          type: outType,\n          width,\n          height,\n          bytes: blob.size,\n          metadataRemoved: removed,\n          alt: item.alt,\n        };\n        if (!live.current) return runtime.revokeObjectURL(previewUrl);\n        const old = itemsRef.current.find((i) => i.id === id)?.previewUrl;\n        if (old) runtime.revokeObjectURL(old);\n        commit({ type: 'processed', id, output, previewUrl }, 'status', id);\n      } catch (e) {\n        if (signal.aborted) return;\n        fail('encode-failed', e instanceof Error ? e.message : undefined);\n      }\n    },\n    [commit, processing, runtime],\n  );\n\n  const startUpload = React.useCallback(\n    (id: string) => {\n      const item = itemsRef.current.find((i) => i.id === id);\n      if (!item?.output) return;\n      const controller = new AbortController();\n      controllers.current.set(id, controller);\n      commit({ type: 'upload', id }, 'status', id);\n      onUpload(item.output, {\n        id,\n        signal: controller.signal,\n        attempt: item.attempt,\n        onProgress: (value) => {\n          if (!controller.signal.aborted) commit({ type: 'progress', id, value }, 'status', id);\n        },\n      }).then(\n        (result) => {\n          if (!controller.signal.aborted) commit({ type: 'resolved', id, result }, 'status', id);\n        },\n        (e: unknown) => {\n          if (controller.signal.aborted) return;\n          // `retryable` on the error means \"Try again is offered\": always, for a failed upload.\n          // Trying again by itself is for the adapter to ask for, with `PhotoUploadError({ retryable: true })`.\n          const byItself = e instanceof PhotoUploadError && e.options.retryable;\n          const error: PhotoError = {\n            code: 'upload-failed',\n            retryable: true,\n            detail: e instanceof Error ? e.message : undefined,\n          };\n          commit({ type: 'failed', id, error }, 'status', id);\n          if (shouldAutoRetry({ ...error, retryable: byItself }, item.attempt, retries)) {\n            const timer = setTimeout(() => {\n              timers.current.delete(timer);\n              if (live.current) commit({ type: 'retry', id }, 'retry', id);\n            }, retryDelay(item.attempt, random));\n            timers.current.add(timer);\n          }\n        },\n      );\n    },\n    [commit, onUpload, random, retries],\n  );\n\n  // Uploads start when a slot is free, the network is up, and (manual) the person said go.\n  React.useEffect(() => {\n    for (const id of nextToUpload(items, { concurrency, online, manual, released })) startUpload(id);\n    if (manual && released && !items.some((i) => i.status === 'ready' || i.status === 'uploading')) setReleased(false);\n  }, [items, concurrency, online, manual, released, startUpload]);\n\n  // Online and touch are read after mount, so the server and first client render agree.\n  React.useEffect(() => {\n    setTouch(typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0);\n    setOnline(typeof navigator === 'undefined' ? true : navigator.onLine !== false);\n    const up = () => setOnline(true);\n    const down = () => setOnline(false);\n    window.addEventListener('online', up);\n    window.addEventListener('offline', down);\n    return () => {\n      window.removeEventListener('online', up);\n      window.removeEventListener('offline', down);\n    };\n  }, []);\n\n  // One announcement per change, coalesced over 400 ms. Nothing on the first render.\n  React.useEffect(() => {\n    const said = announcements(prev.current, items, { online, wasOnline: wasOnline.current, text: t.errors });\n    prev.current = items;\n    wasOnline.current = online;\n    if (said.length === 0) return;\n    buffer.current.push(...said);\n    if (flush.current) clearTimeout(flush.current);\n    flush.current = setTimeout(() => {\n      setAnnounce(buffer.current.join('. '));\n      buffer.current = [];\n      flush.current = null;\n    }, 400);\n  });\n\n  // Unmount aborts every item, clears timers and revokes every preview.\n  React.useEffect(() => {\n    live.current = true;\n    const ctrl = controllers.current;\n    const tm = timers.current;\n    return () => {\n      live.current = false;\n      for (const c of ctrl.values()) c.abort();\n      for (const timer of tm) clearTimeout(timer);\n      if (flush.current) clearTimeout(flush.current);\n      for (const i of itemsRef.current) if (i.previewUrl) runtime.revokeObjectURL(i.previewUrl);\n    };\n  }, [runtime]);\n\n  const addFiles = React.useCallback(\n    async (list: File[]) => {\n      if (disabled || readOnly || list.length === 0) return;\n      const heads = await Promise.all(\n        list.map(async (f) => ({\n          name: f.name,\n          size: f.size,\n          lastModified: f.lastModified,\n          head: new Uint8Array(await f.slice(0, HEAD_BYTES).arrayBuffer()),\n        })),\n      );\n      const intake = planIntake(heads, itemsRef.current, { accept, maxFiles, maxFileBytes, maxPixels });\n      const made: PhotoItem[] = intake.accepted.map((a) => {\n        const f = list[a.index] as File;\n        const id = newId();\n        files.current.set(id, f);\n        return {\n          id,\n          name: f.name,\n          status: 'queued',\n          progress: 0,\n          attempt: 0,\n          source: { bytes: f.size, type: a.type, width: a.header.width, height: a.header.height },\n          output: null,\n          previewUrl: null,\n          alt: '',\n          crop: { rect: null, quarter: 0 },\n          error: null,\n          result: null,\n          fingerprint: fingerprintOf({ name: f.name, size: f.size, lastModified: f.lastModified }),\n        };\n      });\n      const rejected = intake.rejected.map((r) => ({ name: r.name, error: r.error }));\n      setRejections(\n        rejected.length || made.length\n          ? { added: made.length, skipped: [...new Set(rejected.map((r) => errorText(r.error.code)))] }\n          : null,\n      );\n      if (made.length > 0) commit({ type: 'add', items: made }, 'added', made[0]?.id ?? null, rejected);\n      else if (rejected.length > 0) {\n        onValueChange?.(itemsRef.current, { reason: 'rejected', id: null, rejected });\n      }\n      for (const m of made) {\n        if (cropOpts?.required) setCropping((c) => c ?? m.id);\n        else void process(m.id);\n      }\n    },\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [accept, commit, cropOpts?.required, disabled, maxFileBytes, maxFiles, maxPixels, onValueChange, process, readOnly],\n  );\n\n  const onPick = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const picked = Array.from(e.target.files ?? []);\n    if (!name) e.target.value = '';\n    void addFiles(picked);\n  };\n  const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer?.types ?? []).includes('Files');\n  const fullNow = items.filter((i) => i.status !== 'canceled' && i.status !== 'error').length >= maxFiles;\n  const state = STATE_OF(items, maxFiles, disabled, readOnly, online);\n  const interactive = !disabled && !readOnly;\n\n  const remove = (id: string) => {\n    const order = itemsRef.current.map((i) => i.id);\n    const at = order.indexOf(id);\n    controllers.current.get(id)?.abort();\n    release(id);\n    files.current.delete(id);\n    commit({ type: 'remove', id }, 'removed', id);\n    const target = order[at + 1] ?? order[at - 1];\n    queueMicrotask(() => {\n      const root = document.querySelector<HTMLElement>(`[data-photo-upload=\"${baseId}\"]`);\n      const btn = target\n        ? root?.querySelector<HTMLElement>(`[data-id=\"${target}\"] [data-action=\"remove\"]`)\n        : chooseRef.current;\n      btn?.focus();\n    });\n  };\n  const cancel = (id: string) => {\n    controllers.current.get(id)?.abort();\n    commit({ type: 'cancel', id }, 'cancel', id);\n  };\n  const messageOf = (item: PhotoItem) => {\n    if (item.status === 'error' && item.error) {\n      const why = errorText(item.error.code);\n      return item.error.detail && item.error.code === 'upload-failed' ? `${why}: ${item.error.detail}` : why;\n    }\n    return t.status?.[item.status] ?? STATUS_WORDS[item.status];\n  };\n\n  const cropTarget = cropping ? items.find((i) => i.id === cropping) : undefined;\n  const restart = (id: string, next: PhotoItem['crop']) => {\n    commit({ type: 'crop', id, crop: next }, 'crop', id);\n    const item = itemsRef.current.find((i) => i.id === id);\n    if (item?.status === 'ready' || item?.status === 'error') {\n      itemsRef.current = itemsRef.current.map((i) => (i.id === id ? { ...i, status: 'queued', output: null, error: null } : i));\n    }\n    void process(id);\n  };\n  const readyCount = items.filter((i) => i.status === 'ready').length;\n\n  return (\n    <div\n      role=\"group\"\n      aria-labelledby={`${baseId}-label`}\n      data-slot=\"photo-upload\"\n      data-photo-upload={baseId}\n      data-state={state}\n      data-count={items.length}\n      data-min-viewport={String(MIN_VIEWPORT)}\n      className={cn('@container grid gap-3', className)}\n      onPaste={(e) => {\n        const pasted = Array.from(e.clipboardData?.files ?? []).filter((f) => f.type.startsWith('image/'));\n        if (pasted.length > 0 && interactive) {\n          e.preventDefault();\n          void addFiles(pasted);\n        }\n      }}\n      {...rest}\n    >\n      <span id={`${baseId}-label`} data-slot=\"photo-upload-label\" className=\"text-sm font-medium\">\n        {words.label}\n      </span>\n      <div\n        data-slot=\"photo-upload-dropzone\"\n        data-drag={drag}\n        data-full={fullNow ? '' : undefined}\n        {...dropzoneProps}\n        onDragEnter={(e) => {\n          dropzoneProps?.onDragEnter?.(e);\n          if (interactive && !fullNow && hasFiles(e)) setDrag('over');\n        }}\n        onDragOver={(e) => {\n          dropzoneProps?.onDragOver?.(e);\n          if (interactive && hasFiles(e)) e.preventDefault();\n        }}\n        onDragLeave={(e) => {\n          dropzoneProps?.onDragLeave?.(e);\n          setDrag('idle');\n        }}\n        onDrop={(e) => {\n          dropzoneProps?.onDrop?.(e);\n          setDrag('idle');\n          if (!interactive || !hasFiles(e)) return;\n          e.preventDefault();\n          void addFiles(Array.from(e.dataTransfer.files));\n        }}\n        className={cn(\n          'border-border bg-muted/40 grid min-h-32 place-items-center gap-2 rounded-lg border border-dashed p-4 text-center motion-safe:transition-colors',\n          drag === 'over' && 'border-primary bg-primary/10',\n          // Only the controls dim (has-[:disabled]:opacity-50 on them): dimming the whole zone took the hint below 4.5:1.\n          dropzoneProps?.className,\n        )}\n      >\n        <div className=\"flex flex-wrap items-center justify-center gap-2\">\n          <label\n            data-slot=\"photo-upload-pick\"\n            className=\"has-[:focus-visible]:ring-ring relative border-input bg-background hover:bg-accent inline-flex h-control cursor-pointer items-center gap-2 rounded-lg border px-4 text-sm font-medium has-[:focus-visible]:ring-2 has-[:disabled]:pointer-events-none has-[:disabled]:opacity-50\"\n          >\n            <ImagePlusIcon aria-hidden=\"true\" className=\"size-4\" />\n            {words.choose}\n            <input\n              ref={chooseRef}\n              type=\"file\"\n              name={name}\n              accept={accept.join(',')}\n              multiple={maxFiles > 1}\n              disabled={disabled || readOnly || fullNow}\n              onChange={onPick}\n              className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n            />\n          </label>\n          {capture && touch ? (\n            <label\n              data-slot=\"photo-upload-camera\"\n              className=\"has-[:focus-visible]:ring-ring relative border-input bg-background hover:bg-accent inline-flex h-control cursor-pointer items-center gap-2 rounded-lg border px-4 text-sm font-medium has-[:focus-visible]:ring-2 has-[:disabled]:pointer-events-none has-[:disabled]:opacity-50\"\n            >\n              <CameraIcon aria-hidden=\"true\" className=\"size-4\" />\n              {words.camera}\n              <input\n                type=\"file\"\n                accept=\"image/*\"\n                capture={capture}\n                disabled={disabled || readOnly || fullNow}\n                onChange={onPick}\n                className=\"absolute inset-0 size-full cursor-pointer opacity-0 disabled:cursor-not-allowed\"\n              />\n            </label>\n          ) : null}\n        </div>\n        <p data-slot=\"photo-upload-hint\" className=\"text-muted-foreground text-sm\">\n          {fullNow ? words.full : !online ? words.offline : words.hint}\n        </p>\n      </div>\n      {rejections && (rejections.skipped.length > 0 || rejections.added > 0) ? (\n        <p role=\"status\" data-slot=\"photo-upload-rejections\" className=\"text-muted-foreground text-sm\">\n          {rejections.skipped.length === 0\n            ? null\n            : wordsOf(\n                t.rejections,\n                rejections.added,\n                rejections.skipped.join(', '),\n                `${rejections.added} added. Skipped: ${rejections.skipped.join(', ')}`,\n              )}\n        </p>\n      ) : null}\n      {items.length > 0 ? (\n        <ul data-slot=\"photo-upload-list\" aria-label={words.label} className=\"grid gap-2\">\n          {items.map((item, index) => {\n            const canCrop = cropOpts && interactive && (item.status === 'ready' || item.status === 'error' || item.status === 'queued');\n            return (\n              <Item\n                key={item.id}\n                item={item}\n                index={index}\n                total={items.length}\n                altText={altText}\n                message={messageOf(item)}\n                labels={{\n                  crop: words.crop,\n                  retry: words.retry,\n                  cancel: words.cancel,\n                  remove: words.remove,\n                  alt: words.alt,\n                  locationRemoved: words.locationRemoved,\n                  detailsRemoved: words.detailsRemoved,\n                }}\n                actions={{\n                  crop: canCrop\n                    ? () => {\n                        cropButton.current = document.activeElement as HTMLElement;\n                        setCropping(item.id);\n                      }\n                    : undefined,\n                  retry:\n                    item.status === 'error' && item.error?.retryable && interactive\n                      ? () => {\n                          commit({ type: 'retry', id: item.id }, 'retry', item.id);\n                          if (!itemsRef.current.find((i) => i.id === item.id)?.output) void process(item.id);\n                        }\n                      : undefined,\n                  cancel:\n                    interactive && ['queued', 'reading', 'processing', 'uploading'].includes(item.status)\n                      ? () => cancel(item.id)\n                      : undefined,\n                  remove: interactive ? () => remove(item.id) : undefined,\n                  setAlt: interactive ? (alt) => commit({ type: 'alt', id: item.id, alt }, 'alt', item.id) : undefined,\n                }}\n              />\n            );\n          })}\n        </ul>\n      ) : null}\n      {manual && readyCount > 0 && interactive ? (\n        <Button type=\"button\" data-slot=\"photo-upload-submit\" onClick={() => setReleased(true)}>\n          {words.upload}\n        </Button>\n      ) : null}\n      <p data-slot=\"photo-upload-announce\" aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n        {announce}\n      </p>\n      {cropTarget && cropOpts !== null ? (\n        <React.Suspense fallback={null}>\n          <PhotoCropper\n            item={cropTarget}\n            aspect={cropOpts.aspect ?? null}\n            shape={cropOpts.shape ?? 'rect'}\n            labels={t.cropper}\n            onApply={(next: { rect: CropRect | null; quarter: Quarter }) => {\n              const id = cropTarget.id;\n              setCropping(null);\n              if (cropOpts.required && cropTarget.status === 'queued' && !cropTarget.output) {\n                commit({ type: 'crop', id, crop: next }, 'crop', id);\n                void process(id);\n              } else restart(id, next);\n              cropButton.current?.focus();\n            }}\n            onCancel={() => {\n              const id = cropTarget.id;\n              setCropping(null);\n              if (cropOpts.required && cropTarget.status === 'queued' && !cropTarget.output) remove(id);\n              cropButton.current?.focus();\n            }}\n          />\n        </React.Suspense>\n      ) : null}\n    </div>\n  );\n}\n\nexport { PhotoUpload };\n"
    },
    {
      "path": "registry/interlace-ui/patterns/photo-upload-model.ts",
      "target": "components/ui/patterns/photo-upload-model.ts",
      "type": "registry:ui",
      "content": "export type PhotoMime = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/avif';\nexport type PhotoStatus =\n  | 'queued'\n  | 'reading'\n  | 'processing'\n  | 'ready'\n  | 'uploading'\n  | 'done'\n  | 'error'\n  | 'canceled';\nexport type MetadataKind = 'exif' | 'gps' | 'xmp' | 'iptc' | 'text' | 'thumbnail';\nexport type Quarter = 0 | 90 | 180 | 270;\n/** Fractions (0..1) of the image as shown: oriented, then turned by `quarter`. */\nexport interface CropRect {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\nexport type PhotoErrorCode =\n  | 'type-not-allowed'\n  | 'too-many'\n  | 'file-too-large'\n  | 'too-many-pixels'\n  | 'duplicate'\n  | 'decode-failed'\n  | 'unsupported-format'\n  | 'encode-failed'\n  | 'upload-failed'\n  | 'canceled';\nexport interface PhotoError {\n  code: PhotoErrorCode;\n  retryable: boolean;\n  detail?: string;\n}\nexport interface ProcessedPhoto {\n  blob: Blob;\n  type: PhotoMime;\n  width: number;\n  height: number;\n  bytes: number;\n  /** What was found and removed. Empty when the file had none. */\n  metadataRemoved: readonly MetadataKind[];\n  alt: string;\n}\nexport interface PhotoItem {\n  id: string;\n  name: string;\n  status: PhotoStatus;\n  progress: number;\n  attempt: number;\n  source: { bytes: number; type: string; width: number | null; height: number | null };\n  output: ProcessedPhoto | null;\n  previewUrl: string | null;\n  alt: string;\n  crop: { rect: CropRect | null; quarter: Quarter };\n  error: PhotoError | null;\n  result: unknown;\n  /** name + size + lastModified, the duplicate key. */\n  fingerprint: string;\n}\nexport interface EncodePlan {\n  /** Output size in pixels. */\n  width: number;\n  height: number;\n  /** EXIF orientation 1..8 of the source. */\n  orientation: number;\n  quarter: Quarter;\n  crop: CropRect | null;\n  type: 'image/jpeg' | 'image/png' | 'image/webp';\n  quality: number;\n}\n\nexport interface UploadContext {\n  id: string;\n  /** Aborted on cancel, remove and unmount. The adapter must stop work when it fires. */\n  signal: AbortSignal;\n  /** 0..1. Ignored after the signal aborts. */\n  onProgress: (fraction: number) => void;\n  /** 0 on the first try. */\n  attempt: number;\n}\nexport type PhotoUploader = (photo: ProcessedPhoto, ctx: UploadContext) => Promise<unknown>;\n\n/** Throw this from `onUpload` to say what happened. Any other error is shown as `upload-failed` and is not retried by itself. */\nexport class PhotoUploadError extends Error {\n  readonly options: { retryable: boolean; code?: 'network' | 'server' | 'rejected' | 'auth' };\n  constructor(message: string, options: { retryable: boolean; code?: 'network' | 'server' | 'rejected' | 'auth' }) {\n    super(message);\n    this.name = 'PhotoUploadError';\n    this.options = options;\n  }\n}\n\nexport const DEFAULT_ACCEPT: readonly PhotoMime[] = ['image/jpeg', 'image/png', 'image/webp'];\nexport const HEAD_BYTES = 256 * 1024;\n\n/* ------------------------------------------------------------------ sniff */\n\nconst startsWith = (b: Uint8Array, sig: readonly number[], at = 0) =>\n  b.length >= at + sig.length && sig.every((v, i) => b[at + i] === v);\nconst ascii = (b: Uint8Array, at: number, len: number) => {\n  let s = '';\n  for (let i = at; i < Math.min(at + len, b.length); i++) s += String.fromCharCode(b[i] as number);\n  return s;\n};\n\n/** The image type a file really is, from its first bytes; null for anything else (SVG, GIF, empty). */\nexport function sniffImage(b: Uint8Array): PhotoMime | null {\n  if (startsWith(b, [0xff, 0xd8, 0xff])) return 'image/jpeg';\n  if (startsWith(b, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'image/png';\n  if (ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 4) === 'WEBP') return 'image/webp';\n  if (ascii(b, 4, 4) === 'ftyp' && /avi[fs]/.test(ascii(b, 8, 24))) return 'image/avif';\n  return null;\n}\n\n/* ------------------------------------------------------------------- scan */\n\ninterface Segment {\n  /** Byte range [start, end) in the file. */\n  start: number;\n  end: number;\n  /** Kinds this segment holds; empty for a segment we keep. */\n  kinds: MetadataKind[];\n  drop: boolean;\n}\ninterface Scan {\n  width: number | null;\n  height: number | null;\n  orientation: number;\n  hasAlpha: boolean;\n  segments: Segment[];\n  /** Where the image data begins, for JPEG. */\n  tail: number;\n}\n\nconst u16 = (b: Uint8Array, at: number, little = false) =>\n  little ? (b[at] as number) | ((b[at + 1] as number) << 8) : ((b[at] as number) << 8) | (b[at + 1] as number);\nconst u32 = (b: Uint8Array, at: number, little = false) =>\n  little\n    ? ((b[at] as number) | ((b[at + 1] as number) << 8) | ((b[at + 2] as number) << 16) | ((b[at + 3] as number) << 24)) >>> 0\n    : (((b[at] as number) << 24) | ((b[at + 1] as number) << 16) | ((b[at + 2] as number) << 8) | (b[at + 3] as number)) >>> 0;\n\n/** What an Exif block (a TIFF structure) holds: orientation, GPS, and an IFD1 thumbnail. */\nfunction readTiff(b: Uint8Array, base: number, end: number) {\n  const out = { orientation: 1, gps: false, thumbnail: false };\n  if (end - base < 8) return out;\n  const order = ascii(b, base, 2);\n  if (order !== 'II' && order !== 'MM') return out;\n  const little = order === 'II';\n  const ifd0 = u32(b, base + 4, little);\n  const walk = (offset: number, first: boolean): number => {\n    const at = base + offset;\n    if (offset < 8 || at + 2 > end) return 0;\n    const n = u16(b, at, little);\n    for (let i = 0; i < n && at + 2 + (i + 1) * 12 <= end; i++) {\n      const e = at + 2 + i * 12;\n      const tag = u16(b, e, little);\n      if (first && tag === 0x0112) out.orientation = u16(b, e + 8, little);\n      if (first && tag === 0x8825) out.gps = true;\n    }\n    const next = at + 2 + n * 12;\n    return next + 4 <= end ? u32(b, next, little) : 0;\n  };\n  const next = walk(ifd0, true);\n  if (next) {\n    out.thumbnail = true;\n    walk(next, false);\n  }\n  if (out.orientation < 1 || out.orientation > 8) out.orientation = 1;\n  return out;\n}\n\nfunction scanJpeg(b: Uint8Array): Scan | null {\n  if (!startsWith(b, [0xff, 0xd8])) return null;\n  const scan: Scan = { width: null, height: null, orientation: 1, hasAlpha: false, segments: [], tail: b.length };\n  let at = 2;\n  while (at + 4 <= b.length) {\n    if (b[at] !== 0xff) return scan.width === null ? null : scan;\n    const marker = b[at + 1] as number;\n    if (marker === 0xff) {\n      at += 1;\n      continue;\n    }\n    if (marker === 0xda) {\n      scan.tail = at;\n      break;\n    }\n    if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7) || marker === 0x01) {\n      at += 2;\n      continue;\n    }\n    const len = u16(b, at + 2);\n    if (len < 2 || at + 2 + len > b.length) return scan.width === null ? null : scan;\n    const start = at;\n    const end = at + 2 + len;\n    const kinds: MetadataKind[] = [];\n    if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {\n      scan.height = u16(b, at + 5);\n      scan.width = u16(b, at + 7);\n    } else if (marker === 0xe1 && ascii(b, at + 4, 6) === 'Exif\\0\\0') {\n      const t = readTiff(b, at + 10, end);\n      scan.orientation = t.orientation;\n      kinds.push('exif');\n      if (t.gps) kinds.push('gps');\n      if (t.thumbnail) kinds.push('thumbnail');\n    } else if (marker === 0xe1 && ascii(b, at + 4, 28).startsWith('http://ns.adobe.com/xap/1.0/')) {\n      kinds.push('xmp');\n    } else if (marker === 0xed) {\n      kinds.push('iptc');\n    } else if (marker === 0xfe) {\n      kinds.push('text');\n    }\n    scan.segments.push({ start, end, kinds, drop: kinds.length > 0 });\n    at = end;\n  }\n  return scan.width === null ? null : scan;\n}\n\nfunction scanPng(b: Uint8Array): Scan | null {\n  if (!startsWith(b, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) || b.length < 33) return null;\n  if (ascii(b, 12, 4) !== 'IHDR') return null;\n  const colour = b[25] as number;\n  const scan: Scan = {\n    width: u32(b, 16),\n    height: u32(b, 20),\n    orientation: 1,\n    hasAlpha: colour === 4 || colour === 6,\n    segments: [],\n    tail: b.length,\n  };\n  let at = 8;\n  while (at + 12 <= b.length) {\n    const len = u32(b, at);\n    const type = ascii(b, at + 4, 4);\n    const end = at + 12 + len;\n    if (end > b.length) break;\n    const kinds: MetadataKind[] = [];\n    if (type === 'tRNS') scan.hasAlpha = true;\n    if (type === 'eXIf') {\n      const t = readTiff(b, at + 8, at + 8 + len);\n      scan.orientation = t.orientation;\n      kinds.push('exif');\n      if (t.gps) kinds.push('gps');\n      if (t.thumbnail) kinds.push('thumbnail');\n    } else if (type === 'tEXt' || type === 'zTXt' || type === 'tIME') kinds.push('text');\n    else if (type === 'iTXt') kinds.push(ascii(b, at + 8, 17) === 'XML:com.adobe.xmp' ? 'xmp' : 'text');\n    scan.segments.push({ start: at, end, kinds, drop: kinds.length > 0 });\n    at = end;\n    if (type === 'IEND') break;\n  }\n  return scan;\n}\n\nfunction scanWebp(b: Uint8Array): Scan | null {\n  if (ascii(b, 0, 4) !== 'RIFF' || ascii(b, 8, 4) !== 'WEBP') return null;\n  const scan: Scan = { width: null, height: null, orientation: 1, hasAlpha: false, segments: [], tail: b.length };\n  let at = 12;\n  while (at + 8 <= b.length) {\n    const type = ascii(b, at, 4);\n    const len = u32(b, at + 4, true);\n    const data = at + 8;\n    const end = data + len + (len % 2);\n    const kinds: MetadataKind[] = [];\n    if (type === 'VP8X' && data + 10 <= b.length) {\n      scan.hasAlpha = ((b[data] as number) & 0x10) !== 0;\n      scan.width = 1 + ((b[data + 4] as number) | ((b[data + 5] as number) << 8) | ((b[data + 6] as number) << 16));\n      scan.height = 1 + ((b[data + 7] as number) | ((b[data + 8] as number) << 8) | ((b[data + 9] as number) << 16));\n    } else if (type === 'VP8 ' && scan.width === null && data + 10 <= b.length && startsWith(b, [0x9d, 0x01, 0x2a], data + 3)) {\n      scan.width = u16(b, data + 6, true) & 0x3fff;\n      scan.height = u16(b, data + 8, true) & 0x3fff;\n    } else if (type === 'VP8L' && scan.width === null && data + 5 <= b.length && b[data] === 0x2f) {\n      const bits = u32(b, data + 1, true);\n      scan.width = (bits & 0x3fff) + 1;\n      scan.height = ((bits >>> 14) & 0x3fff) + 1;\n      scan.hasAlpha = ((bits >>> 28) & 1) === 1;\n    } else if (type === 'EXIF') {\n      const skip = ascii(b, data, 6) === 'Exif\\0\\0' ? 6 : 0;\n      const t = readTiff(b, data + skip, Math.min(data + len, b.length));\n      scan.orientation = t.orientation;\n      kinds.push('exif');\n      if (t.gps) kinds.push('gps');\n      if (t.thumbnail) kinds.push('thumbnail');\n    } else if (type === 'XMP ') kinds.push('xmp');\n    else if (type === 'ALPH') scan.hasAlpha = true;\n    scan.segments.push({ start: at, end: Math.min(end, b.length), kinds, drop: kinds.length > 0 });\n    at = end;\n  }\n  return scan.width === null ? null : scan;\n}\n\nfunction scanOf(b: Uint8Array, type: PhotoMime): Scan | null {\n  if (type === 'image/jpeg') return scanJpeg(b);\n  if (type === 'image/png') return scanPng(b);\n  if (type === 'image/webp') return scanWebp(b);\n  return null;\n}\n\nexport interface PhotoHeader {\n  type: PhotoMime;\n  width: number | null;\n  height: number | null;\n  /** EXIF orientation 1..8 (1 when absent). */\n  orientation: number;\n  hasAlpha: boolean;\n  metadata: readonly MetadataKind[];\n}\n\nconst KIND_ORDER: readonly MetadataKind[] = ['exif', 'gps', 'thumbnail', 'xmp', 'iptc', 'text'];\nconst kindsOf = (scan: Scan): MetadataKind[] => {\n  const present = new Set(scan.segments.flatMap((s) => s.kinds));\n  return KIND_ORDER.filter((k) => present.has(k));\n};\n\n/** Width, height, orientation, alpha and the metadata kinds a file carries; null when the header cannot be read. */\nexport function readHeader(b: Uint8Array, type: PhotoMime): PhotoHeader | null {\n  if (type === 'image/avif') return { type, width: null, height: null, orientation: 1, hasAlpha: false, metadata: [] };\n  const scan = scanOf(b, type);\n  if (!scan) return null;\n  return {\n    type,\n    width: scan.width,\n    height: scan.height,\n    orientation: scan.orientation,\n    hasAlpha: scan.hasAlpha,\n    metadata: kindsOf(scan),\n  };\n}\n\nconst concat = (parts: Uint8Array[]) => {\n  const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));\n  let at = 0;\n  for (const p of parts) {\n    out.set(p, at);\n    at += p.length;\n  }\n  return out;\n};\n\n/** The same image with its metadata segments cut out. A file with none comes back unchanged. */\nexport function stripMetadata(b: Uint8Array, type: PhotoMime): { bytes: Uint8Array; removed: MetadataKind[] } {\n  const scan = scanOf(b, type);\n  if (!scan) return { bytes: b, removed: [] };\n  const removed = kindsOf(scan);\n  const drops = scan.segments.filter((s) => s.drop);\n  if (drops.length === 0) return { bytes: b, removed: [] };\n  const parts: Uint8Array[] = [];\n  let at = 0;\n  for (const d of drops) {\n    parts.push(b.subarray(at, d.start));\n    at = d.end;\n  }\n  parts.push(b.subarray(at));\n  const out = concat(parts);\n  if (type === 'image/webp') {\n    const size = out.length - 8;\n    out[4] = size & 0xff;\n    out[5] = (size >>> 8) & 0xff;\n    out[6] = (size >>> 16) & 0xff;\n    out[7] = (size >>> 24) & 0xff;\n    if (ascii(out, 12, 4) === 'VP8X') out[20] = (out[20] as number) & ~0x0c; // EXIF and XMP flags\n  }\n  return { bytes: out, removed };\n}\n\n/* ------------------------------------------------------------------- plan */\n\nexport interface PhotoProcessing {\n  maxEdge?: number;\n  quality?: number;\n  type?: 'auto' | 'image/jpeg' | 'image/webp';\n  targetBytes?: number;\n  minQuality?: number;\n}\nexport const PROCESSING_DEFAULTS = { maxEdge: 2048, quality: 0.82, minQuality: 0.5 } as const;\n\nexport type ProcessingPlan = { kind: 'strip-only' } | ({ kind: 'reencode' } & EncodePlan);\n\nconst swaps = (orientation: number) => orientation >= 5 && orientation <= 8;\n\n/** The size of the oriented source, before any crop. */\nexport function orientedSize(header: Pick<PhotoHeader, 'width' | 'height' | 'orientation'>) {\n  const w = header.width ?? 0;\n  const h = header.height ?? 0;\n  return swaps(header.orientation) ? { width: h, height: w } : { width: w, height: h };\n}\n\n/** Strip the bytes when the file already fits; otherwise resize, orient, crop and encode. */\nexport function planProcessing(\n  header: PhotoHeader,\n  processing: PhotoProcessing | false | undefined,\n  crop: { rect: CropRect | null; quarter: Quarter } = { rect: null, quarter: 0 },\n): ProcessingPlan {\n  const opts = processing === false ? null : { ...PROCESSING_DEFAULTS, ...processing };\n  const base = orientedSize(header);\n  const cropped = crop.rect !== null || crop.quarter !== 0;\n  const needsOrient = header.orientation !== 1;\n  // The crop rectangle lives in the image as the person sees it: oriented, then turned.\n  const turned = crop.quarter === 90 || crop.quarter === 270;\n  const src = turned ? { width: base.height, height: base.width } : base;\n  const w = crop.rect ? Math.max(1, Math.round(src.width * crop.rect.width)) : src.width;\n  const h = crop.rect ? Math.max(1, Math.round(src.height * crop.rect.height)) : src.height;\n  const maxEdge = opts?.maxEdge ?? Infinity;\n  const scale = Math.min(1, maxEdge / Math.max(w, h, 1));\n  const convert = processing !== false && processing?.type && processing.type !== 'auto';\n  const unknownSize = header.width === null; // AVIF: the bytes cannot be stripped here, so the pixels are redrawn\n  if (!cropped && !needsOrient && scale === 1 && !convert && !unknownSize) return { kind: 'strip-only' };\n  const wanted = processing === false ? 'auto' : (processing?.type ?? 'auto');\n  const type: EncodePlan['type'] =\n    wanted !== 'auto'\n      ? header.hasAlpha && wanted === 'image/jpeg'\n        ? 'image/png'\n        : wanted\n      : header.type === 'image/png'\n        ? 'image/png'\n        : header.type === 'image/jpeg'\n          ? 'image/jpeg'\n          : 'image/webp';\n  return {\n    kind: 'reencode',\n    width: unknownSize ? 0 : Math.max(1, Math.round(w * scale)),\n    height: unknownSize ? 0 : Math.max(1, Math.round(h * scale)),\n    orientation: header.orientation,\n    quarter: crop.quarter,\n    crop: crop.rect,\n    type,\n    quality: opts?.quality ?? PROCESSING_DEFAULTS.quality,\n  };\n}\n\n/** Qualities to try, at most three, never below `minQuality`, for a `targetBytes` goal. */\nexport function qualityLadder(processing: PhotoProcessing | false | undefined): number[] {\n  const o = processing === false ? undefined : processing;\n  const start = o?.quality ?? PROCESSING_DEFAULTS.quality;\n  const floor = o?.minQuality ?? PROCESSING_DEFAULTS.minQuality;\n  if (!o?.targetBytes) return [start];\n  const ladder = [start, start - (start - floor) / 2, floor].map((q) => Math.round(Math.max(floor, q) * 100) / 100);\n  return [...new Set(ladder)];\n}\n\n/* ----------------------------------------------------------------- intake */\n\nexport interface IntakeFile {\n  name: string;\n  size: number;\n  lastModified: number;\n  /** The first HEAD_BYTES bytes. */\n  head: Uint8Array;\n}\nexport interface IntakeOptions {\n  accept: readonly PhotoMime[];\n  maxFiles: number;\n  maxFileBytes: number;\n  maxPixels: number;\n}\nexport interface Intake {\n  accepted: { index: number; type: PhotoMime; header: PhotoHeader; fingerprint: string }[];\n  rejected: { index: number; name: string; error: PhotoError }[];\n}\n\nexport const fingerprintOf = (f: Pick<IntakeFile, 'name' | 'size' | 'lastModified'>) =>\n  `${f.name}:${f.size}:${f.lastModified}`;\n\n/** Decide, file by file, what becomes an item. One bad file never rejects the batch. */\nexport function planIntake(files: readonly IntakeFile[], existing: readonly PhotoItem[], opts: IntakeOptions): Intake {\n  const out: Intake = { accepted: [], rejected: [] };\n  const live = existing.filter((i) => i.status !== 'canceled' && i.status !== 'error');\n  const seen = new Set(existing.filter((i) => i.status !== 'canceled').map((i) => i.fingerprint));\n  let count = live.length;\n  files.forEach((f, index) => {\n    const reject = (code: PhotoErrorCode, detail?: string) =>\n      out.rejected.push({ index, name: f.name, error: { code, retryable: false, detail } });\n    const type = sniffImage(f.head);\n    if (!type || !opts.accept.includes(type)) return reject('type-not-allowed');\n    if (count >= opts.maxFiles) return reject('too-many');\n    if (f.size > opts.maxFileBytes) return reject('file-too-large');\n    const header = readHeader(f.head, type);\n    if (!header) return reject('decode-failed');\n    if (header.width !== null && header.height !== null && header.width * header.height > opts.maxPixels)\n      return reject('too-many-pixels');\n    const fingerprint = fingerprintOf(f);\n    if (seen.has(fingerprint)) return reject('duplicate');\n    seen.add(fingerprint);\n    count += 1;\n    out.accepted.push({ index, type, header, fingerprint });\n  });\n  return out;\n}\n\n/* ------------------------------------------------------------------- crop */\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));\n\n/** Keep a rectangle inside 0..1 with a size that cannot vanish. */\nconst MIN_CROP = 0.05;\nexport function clampRect(r: CropRect, minSize = MIN_CROP): CropRect {\n  const width = clamp(r.width, minSize, 1);\n  const height = clamp(r.height, minSize, 1);\n  return { x: clamp(r.x, 0, 1 - width), y: clamp(r.y, 0, 1 - height), width, height };\n}\n\n/**\n * The largest centred rectangle with the pixel aspect `aspect` (width / height)\n * inside an image of `imageAspect`; the whole image when `aspect` is null.\n */\nexport function initialCrop(aspect: number | null, imageAspect: number): CropRect {\n  if (!aspect || !Number.isFinite(aspect) || !Number.isFinite(imageAspect) || imageAspect <= 0) {\n    return { x: 0, y: 0, width: 1, height: 1 };\n  }\n  const width = aspect < imageAspect ? aspect / imageAspect : 1;\n  const height = aspect < imageAspect ? 1 : imageAspect / aspect;\n  return { x: (1 - width) / 2, y: (1 - height) / 2, width, height };\n}\n\nexport const panRect = (r: CropRect, dx: number, dy: number): CropRect => clampRect({ ...r, x: r.x + dx, y: r.y + dy }, 0);\n\n/** Scale about the centre; `factor` > 1 zooms in. The aspect of the rectangle is kept, and it stays inside the image. */\nexport function zoomRect(r: CropRect, factor: number): CropRect {\n  const smallest = Math.min(r.width, r.height);\n  const k = clamp(1 / clamp(factor, 0.1, 10), MIN_CROP / smallest, Math.min(1 / r.width, 1 / r.height));\n  const width = r.width * k;\n  const height = r.height * k;\n  return clampRect({ x: r.x + (r.width - width) / 2, y: r.y + (r.height - height) / 2, width, height }, 0);\n}\n\nexport const rotateQuarter = (q: Quarter, dir: 1 | -1): Quarter => ((q + (dir === 1 ? 90 : 270)) % 360) as Quarter;\n\n/** The image aspect after a quarter turn. */\nexport const aspectAfter = (imageAspect: number, q: Quarter) => (q === 90 || q === 270 ? 1 / imageAspect : imageAspect);\n\n/* ---------------------------------------------------------------- reducer */\n\nexport type PhotoAction =\n  | { type: 'add'; items: readonly PhotoItem[] }\n  | { type: 'reading'; id: string }\n  | { type: 'processing'; id: string; progress?: number }\n  | { type: 'processed'; id: string; output: ProcessedPhoto; previewUrl: string | null }\n  | { type: 'upload'; id: string }\n  | { type: 'progress'; id: string; value: number }\n  | { type: 'resolved'; id: string; result: unknown }\n  | { type: 'failed'; id: string; error: PhotoError }\n  | { type: 'retry'; id: string }\n  | { type: 'cancel'; id: string }\n  | { type: 'remove'; id: string }\n  | { type: 'alt'; id: string; alt: string }\n  | { type: 'crop'; id: string; crop: PhotoItem['crop'] };\n\nconst LIVE: readonly PhotoStatus[] = ['queued', 'reading', 'processing', 'ready', 'uploading', 'error'];\n\n/** The next state of the list. An action for an item that is gone or canceled changes nothing. */\nexport function reduce(items: readonly PhotoItem[], action: PhotoAction): readonly PhotoItem[] {\n  if (action.type === 'add') return [...items, ...action.items];\n  if (action.type === 'remove') return items.filter((i) => i.id !== action.id);\n  const index = items.findIndex((i) => i.id === action.id);\n  const item = items[index];\n  if (!item) return items;\n  const set = (patch: Partial<PhotoItem>) => items.map((i, n) => (n === index ? { ...i, ...patch } : i));\n  if (action.type === 'cancel') {\n    return item.status === 'done' || item.status === 'canceled'\n      ? items\n      : set({ status: 'canceled', progress: 0, error: { code: 'canceled', retryable: false } });\n  }\n  if (item.status === 'canceled') return items;\n  switch (action.type) {\n    case 'alt':\n      return set({ alt: action.alt, output: item.output ? { ...item.output, alt: action.alt } : null });\n    case 'crop':\n      return set({ crop: action.crop });\n    case 'reading':\n      return item.status === 'queued' ? set({ status: 'reading', progress: 0 }) : items;\n    case 'processing':\n      return item.status === 'queued' || item.status === 'reading' || item.status === 'processing'\n        ? set({ status: 'processing', progress: action.progress ?? item.progress })\n        : items;\n    case 'processed':\n      return item.status === 'processing' || item.status === 'reading' || item.status === 'queued'\n        ? set({\n            status: 'ready',\n            progress: 0,\n            output: { ...action.output, alt: item.alt },\n            previewUrl: action.previewUrl ?? item.previewUrl,\n            error: null,\n          })\n        : items;\n    case 'upload':\n      return item.status === 'ready' ? set({ status: 'uploading', progress: 0, error: null }) : items;\n    case 'progress':\n      return item.status === 'uploading' || item.status === 'processing'\n        ? set({ progress: clamp(action.value, 0, 1) })\n        : items;\n    case 'resolved':\n      return item.status === 'uploading' ? set({ status: 'done', progress: 1, result: action.result, error: null }) : items;\n    case 'failed':\n      return item.status === 'uploading' || item.status === 'processing' || item.status === 'reading'\n        ? set({ status: 'error', progress: 0, error: action.error })\n        : items;\n    default: {\n      // retry\n      if (item.status !== 'error' || !item.error) return items;\n      const back: PhotoStatus = item.output ? 'ready' : 'queued';\n      return set({ status: back, progress: 0, attempt: item.attempt + 1, error: null });\n    }\n  }\n}\n\n/** Ready items to start now: free slots only, none while offline, none in `manual` until released. */\nexport function nextToUpload(\n  items: readonly PhotoItem[],\n  opts: { concurrency: number; online: boolean; manual: boolean; released: boolean },\n): string[] {\n  if (!opts.online || (opts.manual && !opts.released)) return [];\n  const busy = items.filter((i) => i.status === 'uploading').length;\n  return items\n    .filter((i) => i.status === 'ready')\n    .slice(0, Math.max(0, opts.concurrency - busy))\n    .map((i) => i.id);\n}\n\nexport const isLive = (status: PhotoStatus) => LIVE.includes(status);\n\n/** 1 s, 2 s, 4 s ... with up to 25% jitter. `random` is injected, so a test can pin it. */\nexport function retryDelay(attempt: number, random: () => number): number {\n  return Math.round(1000 * 2 ** Math.max(0, attempt) * (1 + 0.25 * clamp(random(), 0, 1)));\n}\n\n/** Only an upload that said it is retryable is retried, and only up to `retries` times. */\nexport const shouldAutoRetry = (error: PhotoError, attempt: number, retries: number) =>\n  error.code === 'upload-failed' && error.retryable && attempt < retries;\n\n/* ---------------------------------------------------------------- words */\n\nconst KB = 1024;\nexport function formatBytes(n: number): string {\n  if (n < KB) return `${n} B`;\n  if (n < KB * KB) return `${Math.round(n / KB)} KB`;\n  return `${(n / KB / KB).toFixed(1)} MB`;\n}\n\nexport const DEFAULT_ERROR_TEXT: Record<PhotoErrorCode, string> = {\n  'type-not-allowed': 'not a photo we can take',\n  'too-many': 'too many photos',\n  'file-too-large': 'the file is too large',\n  'too-many-pixels': 'the picture is too large',\n  duplicate: 'already added',\n  'decode-failed': 'the photo could not be read',\n  'unsupported-format': 'this browser cannot open that format',\n  'encode-failed': 'the photo could not be prepared',\n  'upload-failed': 'the connection dropped',\n  canceled: 'canceled',\n};\n\nexport interface AnnounceContext {\n  online: boolean;\n  wasOnline: boolean;\n  text?: Partial<Record<PhotoErrorCode, string>>;\n}\n\n/** What a screen reader hears for a change of state. Nothing on the first render; no per-percent text. */\nexport function announcements(\n  prev: readonly PhotoItem[] | null,\n  next: readonly PhotoItem[],\n  ctx: AnnounceContext,\n): string[] {\n  if (prev === null) return [];\n  const out: string[] = [];\n  const before = new Map(prev.map((i) => [i.id, i]));\n  const added = next.filter((i) => !before.has(i.id)).length;\n  if (added > 0) out.push(`${added} photo${added === 1 ? '' : 's'} added`);\n  next.forEach((item, index) => {\n    const old = before.get(item.id);\n    if (!old || old.status === item.status) return;\n    if (item.status === 'done') out.push(`Photo ${index + 1} of ${next.length} uploaded`);\n    if (item.status === 'error' && item.error) {\n      const why = ctx.text?.[item.error.code] ?? DEFAULT_ERROR_TEXT[item.error.code];\n      out.push(`Photo ${index + 1} failed: ${why}. Try again is available`);\n    }\n  });\n  if (!ctx.online && ctx.wasOnline) out.push('Waiting for a connection');\n  return out;\n}\n\n/**\n * @interlace/ui — PhotoUpload model\n *\n * Everything PhotoUpload decides, with no DOM, no React and no clock: what a\n * file is (by its bytes, never its name), what it says about its owner and\n * how to remove that, whether it needs resizing, the crop maths, the item\n * reducer, the retry delay and what a screen reader is told. The component\n * and the browser runtime only carry out what this file plans.\n *\n * Metadata is removed byte for byte (JPEG APP1 Exif/XMP, APP13 IPTC, COM;\n * PNG eXIf, tEXt, zTXt, iTXt, tIME; WebP EXIF, XMP). Colour profiles stay, so\n * colour does not shift.\n */\n"
    },
    {
      "path": "registry/interlace-ui/patterns/photo-upload-runtime.ts",
      "target": "components/ui/patterns/photo-upload-runtime.ts",
      "type": "registry:ui",
      "content": "import type { CropRect, EncodePlan, Quarter } from '@/components/ui/patterns/photo-upload-model';\n\n/**\n * @interlace/ui — PhotoUpload runtime\n *\n * The only file that touches the browser's image APIs. `ImageRuntime` is the\n * seam: the component and its tests talk to the type, so a test substitutes a\n * fake, an agent a headless one, an app a HEIC decoder or a worker.\n *\n * A canvas redraw carries no metadata by construction, which is why every\n * re-encoded photo leaves with none. Nothing here makes a network request.\n */\n\n/** A decoded picture, opaque to everyone but the runtime that made it. */\nexport interface DecodedImage {\n  /** Pixels of the image as shown: already oriented. */\n  width: number;\n  height: number;\n  /** The runtime's own handle (an `ImageBitmap` in the browser). */\n  handle: unknown;\n}\n\nexport interface ImageRuntime {\n  /** Reads and orients a picture. Resolves null when this browser cannot decode the type. */\n  decode(\n    blob: Blob,\n    opts: { maxEdge: number; signal: AbortSignal; hint?: { width: number; height: number } },\n  ): Promise<DecodedImage | null>;\n  /** Draws the oriented, turned, cropped, resized image and encodes it. */\n  encode(img: DecodedImage, plan: EncodePlan, signal: AbortSignal): Promise<Blob>;\n  /** A small preview, longest edge `edge`. */\n  thumbnail(img: DecodedImage, edge: number): Promise<Blob>;\n  createObjectURL(blob: Blob): string;\n  revokeObjectURL(url: string): void;\n  /** Release the decoded pixels. */\n  dispose?(img: DecodedImage): void;\n}\n\ntype Canvas2D = OffscreenCanvasRenderingContext2D | CanvasRenderingContext2D;\ninterface Surface {\n  ctx: Canvas2D;\n  toBlob(type: string, quality: number): Promise<Blob>;\n}\n\nfunction surface(width: number, height: number): Surface {\n  if (typeof OffscreenCanvas !== 'undefined') {\n    const canvas = new OffscreenCanvas(width, height);\n    const ctx = canvas.getContext('2d');\n    if (ctx) return { ctx, toBlob: (type, quality) => canvas.convertToBlob({ type, quality }) };\n  }\n  const canvas = document.createElement('canvas');\n  canvas.width = width;\n  canvas.height = height;\n  const ctx = canvas.getContext('2d');\n  if (!ctx) throw new Error('no 2d canvas');\n  return {\n    ctx,\n    toBlob: (type, quality) =>\n      new Promise((resolve, reject) =>\n        canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encode failed'))), type, quality),\n      ),\n  };\n}\n\nconst bitmapOf = (img: DecodedImage) => img.handle as ImageBitmap;\nconst turned = (q: Quarter) => q === 90 || q === 270;\n\n/** The image turned by `quarter`, on its own surface (the bitmap itself when it is not turned). */\nfunction rotated(img: DecodedImage, quarter: Quarter): { source: CanvasImageSource; width: number; height: number } {\n  if (quarter === 0) return { source: bitmapOf(img), width: img.width, height: img.height };\n  const w = turned(quarter) ? img.height : img.width;\n  const h = turned(quarter) ? img.width : img.height;\n  const s = surface(w, h);\n  s.ctx.translate(w / 2, h / 2);\n  s.ctx.rotate((quarter * Math.PI) / 180);\n  s.ctx.drawImage(bitmapOf(img), -img.width / 2, -img.height / 2);\n  // `surface` hides the canvas; draw it back through a bitmap-free path.\n  return { source: (s.ctx.canvas as CanvasImageSource), width: w, height: h };\n}\n\nfunction draw(img: DecodedImage, quarter: Quarter, crop: CropRect | null, width: number, height: number, flatten: boolean) {\n  const s = surface(width, height);\n  if (flatten) {\n    s.ctx.fillStyle = '#fff';\n    s.ctx.fillRect(0, 0, width, height);\n  }\n  const r = rotated(img, quarter);\n  const c = crop ?? { x: 0, y: 0, width: 1, height: 1 };\n  s.ctx.drawImage(r.source, c.x * r.width, c.y * r.height, c.width * r.width, c.height * r.height, 0, 0, width, height);\n  return s;\n}\n\nexport const browserRuntime: ImageRuntime = {\n  async decode(blob, { maxEdge, signal, hint }) {\n    if (typeof createImageBitmap !== 'function') return null;\n    try {\n      const scale = hint ? Math.min(1, maxEdge / Math.max(hint.width, hint.height, 1)) : 1;\n      const options: ImageBitmapOptions = { imageOrientation: 'from-image' };\n      if (hint && scale < 1) {\n        options.resizeWidth = Math.max(1, Math.round(hint.width * scale));\n        options.resizeHeight = Math.max(1, Math.round(hint.height * scale));\n        options.resizeQuality = 'high';\n      }\n      const bitmap = await createImageBitmap(blob, options);\n      if (signal.aborted) {\n        bitmap.close();\n        return null;\n      }\n      return { width: bitmap.width, height: bitmap.height, handle: bitmap };\n    } catch {\n      return null;\n    }\n  },\n  async encode(img, plan, signal) {\n    const width = plan.width || img.width;\n    const height = plan.height || img.height;\n    const s = draw(img, plan.quarter, plan.crop, width, height, plan.type === 'image/jpeg');\n    if (signal.aborted) throw new DOMException('aborted', 'AbortError');\n    return s.toBlob(plan.type, plan.quality);\n  },\n  async thumbnail(img, edge) {\n    const k = Math.min(1, edge / Math.max(img.width, img.height, 1));\n    const s = draw(img, 0, null, Math.max(1, Math.round(img.width * k)), Math.max(1, Math.round(img.height * k)), true);\n    return s.toBlob('image/jpeg', 0.7);\n  },\n  createObjectURL: (blob) => URL.createObjectURL(blob),\n  revokeObjectURL: (url) => URL.revokeObjectURL(url),\n  dispose(img) {\n    (img.handle as ImageBitmap | undefined)?.close?.();\n  },\n};\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.1",
    "since": "2.1.0"
  },
  "docs": "## @interlace/photo-upload\n\nInstalled to `components/ui/patterns/photo-upload.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/photo-upload';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/photo-upload\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
