{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "photo-upload-crop",
  "type": "registry:ui",
  "title": "Photo Upload Crop",
  "description": "The crop and turn dialog PhotoUpload opens for one photo. Lazy-loaded, so a form that never crops never loads it. Everything pointer-only has a keyboard twin: drag the frame or press the arrows (Shift for ten times as far), zoom with the range or `+` /…",
  "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/dialog.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/photo-upload-crop.tsx",
      "target": "components/ui/patterns/photo-upload-crop.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/photo-upload-crop v1.0.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/photo-upload-crop\n// What changed since: https://ds.interlace.tools/c/photo-upload-crop#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — PhotoCropper\n *\n * The crop and turn dialog PhotoUpload opens for one photo. Lazy-loaded, so a\n * form that never crops never loads it. Everything pointer-only has a keyboard\n * twin: drag the frame or press the arrows (Shift for ten times as far),\n * zoom with the range or `+` / `-`, turn a quarter with `[` / `]` or the two\n * buttons, Enter applies, Escape cancels. Arrow keys are physical: Left moves\n * the frame left, in right-to-left layouts too.\n *\n * The frame is a rectangle in fractions of the picture as shown, so it does\n * not depend on the preview's pixel size. `shape=\"round\"` masks the preview\n * only: the saved crop is the whole rectangle.\n */\n\nimport { RotateCcwIcon, RotateCwIcon } from 'lucide-react';\n\nimport { cn } from '@/lib/utils';\nimport { Button } from '@/components/ui/button';\nimport {\n  Dialog,\n  DialogContent,\n  DialogDescription,\n  DialogFooter,\n  DialogHeader,\n  DialogTitle,\n} from '@/components/ui/dialog';\nimport {\n  aspectAfter,\n  initialCrop,\n  panRect,\n  rotateQuarter,\n  zoomRect,\n  type CropRect,\n  type PhotoItem,\n  type Quarter,\n} from '@/components/ui/patterns/photo-upload-model';\n\ninterface PhotoCropperProps {\n  item: PhotoItem;\n  /** Pixel aspect (width / height) of the saved crop; null for the whole picture. */\n  aspect: number | null;\n  shape: 'rect' | 'round';\n  labels?: {\n    title?: string;\n    zoom?: string;\n    rotateLeft?: string;\n    rotateRight?: string;\n    apply?: string;\n    cancel?: string;\n  };\n  onApply: (crop: { rect: CropRect | null; quarter: Quarter }) => void;\n  onCancel: () => void;\n}\n\nconst MAX_ZOOM = 4;\n\nexport default function PhotoCropper({ item, aspect, shape, labels, onApply, onCancel }: PhotoCropperProps) {\n  const w = item.source.width ?? item.output?.width ?? 1;\n  const h = item.source.height ?? item.output?.height ?? 1;\n  const [quarter, setQuarter] = React.useState<Quarter>(item.crop.quarter);\n  const imageAspect = aspectAfter(w / h, quarter);\n  const [rect, setRect] = React.useState<CropRect>(() => item.crop.rect ?? initialCrop(aspect, aspectAfter(w / h, item.crop.quarter)));\n  const [zoom, setZoom] = React.useState(1);\n  const stage = React.useRef<HTMLDivElement>(null);\n  const frame = React.useRef<HTMLDivElement>(null);\n  const drag = React.useRef<{ x: number; y: number; rect: CropRect } | null>(null);\n  const words = {\n    title: labels?.title ?? 'Crop photo',\n    zoom: labels?.zoom ?? 'Zoom',\n    rotateLeft: labels?.rotateLeft ?? 'Turn left',\n    rotateRight: labels?.rotateRight ?? 'Turn right',\n    apply: labels?.apply ?? 'Apply',\n    cancel: labels?.cancel ?? 'Cancel',\n  };\n\n  React.useEffect(() => {\n    frame.current?.focus();\n  }, []);\n\n  const turn = (dir: 1 | -1) => {\n    const next = rotateQuarter(quarter, dir);\n    setQuarter(next);\n    setRect(initialCrop(aspect, aspectAfter(w / h, next)));\n    setZoom(1);\n  };\n  const zoomTo = (z: number) => {\n    const clamped = Math.min(MAX_ZOOM, Math.max(1, z));\n    setRect((r) => zoomRect(r, clamped / zoom));\n    setZoom(clamped);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const step = e.shiftKey ? 0.1 : 0.01;\n    const move = (dx: number, dy: number) => {\n      e.preventDefault();\n      setRect((r) => panRect(r, dx, dy));\n    };\n    if (e.key === 'ArrowLeft') move(-step, 0);\n    else if (e.key === 'ArrowRight') move(step, 0);\n    else if (e.key === 'ArrowUp') move(0, -step);\n    else if (e.key === 'ArrowDown') move(0, step);\n    else if (e.key === '+' || e.key === '=') {\n      e.preventDefault();\n      zoomTo(zoom + 0.25);\n    } else if (e.key === '-') {\n      e.preventDefault();\n      zoomTo(zoom - 0.25);\n    } else if (e.key === '[') {\n      e.preventDefault();\n      turn(-1);\n    } else if (e.key === ']') {\n      e.preventDefault();\n      turn(1);\n    } else if (e.key === 'Enter') {\n      e.preventDefault();\n      onApply({ rect, quarter });\n    }\n  };\n\n  const turnedBox = quarter === 90 || quarter === 270;\n\n  return (\n    <Dialog open onOpenChange={(open) => !open && onCancel()}>\n      <DialogContent data-slot=\"photo-cropper\" onKeyDown={(e) => e.target === e.currentTarget && onKeyDown(e)}>\n        <DialogHeader>\n          <DialogTitle>{words.title}</DialogTitle>\n          <DialogDescription>{item.name}</DialogDescription>\n        </DialogHeader>\n        <div\n          ref={stage}\n          className=\"bg-muted relative mx-auto w-full max-w-prose select-none overflow-hidden rounded-lg\"\n          style={{ aspectRatio: String(imageAspect) }}\n        >\n          {item.previewUrl ? (\n            <img\n              src={item.previewUrl}\n              alt=\"\"\n              draggable={false}\n              className=\"absolute top-1/2 left-1/2 max-w-none -translate-x-1/2 -translate-y-1/2\"\n              style={{\n                width: turnedBox ? `${100 / imageAspect}%` : '100%',\n                height: turnedBox ? `${100 * imageAspect}%` : '100%',\n                transform: `translate(-50%, -50%) rotate(${quarter}deg)`,\n              }}\n            />\n          ) : null}\n          <div\n            ref={frame}\n            role=\"application\"\n            aria-label={`${words.title}: arrow keys move, plus and minus zoom, brackets turn, Enter applies`}\n            tabIndex={0}\n            data-slot=\"photo-cropper-frame\"\n            onKeyDown={onKeyDown}\n            onPointerDown={(e) => {\n              e.currentTarget.setPointerCapture(e.pointerId);\n              drag.current = { x: e.clientX, y: e.clientY, rect };\n            }}\n            onPointerMove={(e) => {\n              const d = drag.current;\n              const box = stage.current?.getBoundingClientRect();\n              if (!d || !box) return;\n              setRect(panRect(d.rect, (e.clientX - d.x) / box.width, (e.clientY - d.y) / box.height));\n            }}\n            onPointerUp={() => {\n              drag.current = null;\n            }}\n            className={cn(\n              'border-primary focus-visible:ring-ring absolute cursor-move touch-none border-2 focus-visible:ring-2 focus-visible:outline-hidden forced-colors:border-[Highlight]',\n              shape === 'round' && 'rounded-full',\n            )}\n            style={{\n              left: `${rect.x * 100}%`,\n              top: `${rect.y * 100}%`,\n              width: `${rect.width * 100}%`,\n              height: `${rect.height * 100}%`,\n            }}\n          />\n        </div>\n        <div className=\"flex flex-wrap items-center gap-3\">\n          <Button type=\"button\" variant=\"outline\" size=\"icon\" onClick={() => turn(-1)} aria-label={words.rotateLeft}>\n            <RotateCcwIcon aria-hidden=\"true\" />\n          </Button>\n          <Button type=\"button\" variant=\"outline\" size=\"icon\" onClick={() => turn(1)} aria-label={words.rotateRight}>\n            <RotateCwIcon aria-hidden=\"true\" />\n          </Button>\n          <label className=\"flex flex-1 items-center gap-2 text-sm\">\n            {words.zoom}\n            <input\n              type=\"range\"\n              min={1}\n              max={MAX_ZOOM}\n              step={0.05}\n              value={zoom}\n              onChange={(e) => zoomTo(Number(e.target.value))}\n              className=\"flex-1\"\n            />\n          </label>\n        </div>\n        <DialogFooter>\n          <Button type=\"button\" variant=\"outline\" onClick={onCancel}>\n            {words.cancel}\n          </Button>\n          <Button type=\"button\" onClick={() => onApply({ rect, quarter })}>\n            {words.apply}\n          </Button>\n        </DialogFooter>\n      </DialogContent>\n    </Dialog>\n  );\n}\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"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": null,
    "loading": false,
    "version": "1.0.1",
    "since": "2.1.0"
  },
  "docs": "## @interlace/photo-upload-crop\n\nInstalled to `components/ui/patterns/photo-upload-crop.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/photo-upload-crop';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/photo-upload-crop\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
