{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-field",
  "title": "ImageField",
  "description": "A field for one photo, shown large: the photo already saved (`src`) or the one just chosen, with Choose photo (Change photo once one shows) and Remove.",
  "registryDependencies": [
    "@ouro/button",
    "@ouro/file-field",
    "@ouro/image-cropper",
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-use-dev-messages",
    "@ouro/lib-use-field"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/image-field/image-field.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useId, useRef, useState, type ChangeEvent, type DragEvent, type JSX, type ReactNode, type Ref } from \"react\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { errorMessages, type ReadonlyErrorMessages } from \"@/registry/ouro/lib/ouro/use-field\";\nimport { Button } from \"@/registry/ouro/components/ouro/button/button\";\nimport { formatSize, matchesAccept } from \"@/registry/ouro/components/ouro/file-field/file-field-styles\";\nimport { ImageCropper } from \"@/registry/ouro/components/ouro/image-cropper/image-cropper\";\n\n/** How {@link ImageField} crops a chosen photo. */\nexport interface ImageFieldCrop {\n  /** The saved image's width in pixels. @default 1024 */\n  outputWidth?: number | undefined;\n  /** The saved image's format. @default \"image/jpeg\" */\n  type?: \"image/jpeg\" | \"image/png\" | \"image/webp\" | undefined;\n  /** The cropper's title. @default \"Crop photo\" */\n  title?: string | undefined;\n}\n\n/** Why a chosen file was turned away: not a type `accept` takes, over `maxSize`, or a photo the browser cannot open (such as HEIC outside Safari). */\nexport type ImageFieldRejection = \"type\" | \"size\" | \"unreadable\";\n\n/** Props for {@link ImageField}. */\nexport interface ImageFieldProps {\n  /** What the image is, above it and naming the field: \"Profile photo\". */\n  label: string;\n  /** Keeps the label for screen readers only. */\n  hideLabel?: boolean | undefined;\n  /** Supporting text under the label, such as the formats and size it takes. */\n  description?: ReactNode | undefined;\n  /** What is wrong, shown under the field in the destructive tone. */\n  error?: ReadonlyErrorMessages | undefined;\n  /** Marks the field as required: a mark after the label. Check that a photo was chosen when the form submits. */\n  required?: boolean | undefined;\n  /** Turns the field off. */\n  disabled?: boolean | undefined;\n  /** The form field name the chosen (and cropped) photo submits under. */\n  name?: string | undefined;\n  /** The photo the field shows until another is chosen, such as the one already saved. */\n  src?: string | null | undefined;\n  /** The photo's text alternative while it shows `src`. @default \"\" (the label names it) */\n  alt?: string | undefined;\n  /** The types it takes, as the file input's `accept`. @default \"image/*\" */\n  accept?: string | undefined;\n  /**\n   * The largest file it takes, in bytes.\n   *\n   * @claim \"The largest file it takes, in\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField > turns away a file that is not an image or is too large, keeping what showed, and says why)\n   */\n  maxSize?: number | undefined;\n  /** The preview's width divided by its height, and the crop's. @default 1 */\n  aspect?: number | undefined;\n  /** `circle` shows and crops a round photo, for a profile; `rect` a rounded rectangle. @default \"rect\" */\n  shape?: \"rect\" | \"circle\" | (string & { 'Use \"rect\" or \"circle\"': never }) | undefined;\n  /**\n   * Opens the cropper on every chosen photo, so it fits `aspect` and `shape`: `crop` or `crop={{ outputWidth: 512 }}`.\n   *\n   * @claim \"Opens the cropper on every chosen\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField > crops a chosen photo first with crop, and keeps the field as it was when the crop is cancelled)\n   * @claim \"Opens the cropper on every chosen\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField > crops with the defaults when crop is true)\n   */\n  crop?: boolean | ImageFieldCrop | undefined;\n  /** Called with the chosen photo (cropped, with `crop`), or `null` when it is removed. A photo comes here once the browser has opened it. */\n  onFileChange?: ((file: File | null) => void) | undefined;\n  /** Shows Remove while the field shows `src`, and is called when the person removes it. */\n  onRemove?: (() => void) | undefined;\n  /** The message for a file turned away, for apps in other languages. */\n  rejectMessage?: ((reason: ImageFieldRejection, file: File) => string) | undefined;\n  /**\n   * The choose button's label while no photo shows. @default \"Choose photo\"\n   *\n   * @claim \"The choose button's label while no\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField > is a group named by its label, with a placeholder, Choose photo and a hidden file input)\n   */\n  chooseLabel?: string | undefined;\n  /** The choose button's label while a photo shows. @default \"Change photo\" */\n  changeLabel?: string | undefined;\n  /** The remove button's label. @default \"Remove\" */\n  removeLabel?: string | undefined;\n  /** What the photo's frame says while a file is dragged over the field. @default \"Drop the photo here\" */\n  dropLabel?: string | undefined;\n  /**\n   * The words beside the choose button that say a photo can be dropped on the field, shown\n   * while it is enabled. An empty string leaves them out. @default \"or drop a photo here\"\n   *\n   * @claim \"The words beside the choose button\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField dropping a file > says beside the choose button that a photo can be dropped, in the app's words, and not while disabled)\n   */\n  dropHint?: string | undefined;\n  /** Layout only: margins, width (`mt-6`). Appearance classes warn in development. */\n  className?: string | undefined;\n  /** Reaches the file input. */\n  ref?: Ref<HTMLInputElement> | undefined;\n\n  /** Not a prop. The photo shown is `src`: `<ImageField src={user.photoUrl} />`. */\n  value?: { 'Use src={photoUrl}; the chosen file comes to onFileChange': never };\n  /** Not a prop. The photo shown is `src`: `<ImageField src={user.photoUrl} />`. */\n  defaultValue?: { 'Use src={photoUrl}': never };\n  /** Not a prop. Ouro UI says `onFileChange`: `<ImageField onFileChange={setPhoto} />`. */\n  onChange?: { 'Use onFileChange={(file) => ...}': never };\n  /** Not a prop. Ouro UI says `maxSize`, in bytes: `<ImageField maxSize={5 * 1024 * 1024} />`. */\n  maxFileSize?: { 'Use maxSize={5 * 1024 * 1024}': never };\n  /** Not a prop. Ouro UI says `crop`: `<ImageField crop />`. */\n  cropper?: { 'Use crop or crop={{ outputWidth: 512 }}': never };\n}\n\nfunction PhotoIcon(): JSX.Element {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className=\"size-8\">\n      <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\" />\n      <circle cx=\"9\" cy=\"9\" r=\"2\" />\n      <path d=\"m21 15-3.09-3.09a2 2 0 0 0-2.82 0L6 21\" />\n    </svg>\n  );\n}\n\n/**\n * Puts one file in the input, or none, so the form submits exactly what shows.\n *\n * @claim \"Puts one file in the input\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField > previews a chosen photo, puts it in the form, and removes it again)\n */\nfunction setInputFile(input: HTMLInputElement, file: File | null): void {\n  const data = new DataTransfer();\n  if (file) data.items.add(file);\n  input.files = data.files;\n}\n\n/**\n * A field for one photo, shown large: the photo already saved (`src`) or the one just chosen,\n * with Choose photo (Change photo once one shows) and Remove. With `crop`, a chosen photo\n * opens the cropper first, and the cropped image is what shows, what `onFileChange` gets and\n * what the form submits. A file of the wrong type, over `maxSize` or that the browser cannot\n * open as a photo is turned away, keeping what showed, with a message under the field that\n * screen readers announce. The photo is in a real file input, so a plain form submits it.\n *\n * A photo dragged onto the field lights its frame and says where to drop it; dropped, it goes\n * through the same checks, cropper and messages as one chosen with the button, which stays\n * the way to choose from the keyboard or a screen reader.\n *\n * Use `FileField` instead for other files or several files, and `ImageCropper` alone to crop\n * an image you already have.\n *\n * @group Forms\n * @see https://ui.ouroboros.bot/docs/image-field\n *\n * @example\n * <ImageField label=\"Profile photo\" name=\"photo\" src={user.photoUrl} shape=\"circle\" crop maxSize={5 * 1024 * 1024} onRemove={removePhoto} />\n * @claim \"A photo dragged onto the field lights\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField dropping a file > lights the frame while a file is over the field, and takes a dropped photo as if chosen)\n * @claim \"A photo dragged onto the field lights\" registry/ouro/components/ouro/image-field/image-field.test.tsx verify:testExists(registry/ouro/components/ouro/image-field/image-field.test.tsx::ImageField dropping a file > turns a dropped file away by type and size with the picker's messages, and crops a dropped photo with crop)\n */\nexport function ImageField(props: ImageFieldProps): JSX.Element {\n  const {\n    label,\n    hideLabel,\n    description,\n    error,\n    required,\n    disabled,\n    name,\n    src,\n    alt = \"\",\n    accept = \"image/*\",\n    maxSize,\n    aspect: aspectProp = 1,\n    shape: shapeProp = \"rect\",\n    crop,\n    onFileChange,\n    onRemove,\n    rejectMessage,\n    chooseLabel = \"Choose photo\",\n    changeLabel = \"Change photo\",\n    removeLabel = \"Remove\",\n    dropLabel = \"Drop the photo here\",\n    dropHint = \"or drop a photo here\",\n    className,\n    ref,\n    // Guard props (hint types), dropped here so they never reach the DOM.\n    value,\n    defaultValue,\n    onChange,\n    maxFileSize,\n    cropper,\n  } = props;\n  const aspect = aspectProp > 0 && Number.isFinite(aspectProp) ? aspectProp : 1;\n  const shape = shapeProp === \"circle\" ? \"circle\" : \"rect\";\n  useAppearanceClassNameCheck(\n    \"ImageField\",\n    className,\n    process.env.NODE_ENV !== \"production\"\n      ? (token: string) => `remove \"${token}\"; ImageField sets its own look from the theme`\n      : /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  useDevWarnings(\n    \"ImageField\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [\n          aspect !== aspectProp && [`aspect={${String(aspectProp)}} is not a ratio; it is the width over the height, above 0`, \"<ImageField aspect={16 / 9} />\"],\n          shape !== shapeProp && [`shape=\"${String(shapeProp)}\" is not a shape; use \"rect\" or \"circle\"`, '<ImageField shape=\"circle\" />'],\n          value !== undefined && [\"value is not a prop; the photo shown is src\", \"<ImageField src={photoUrl} onFileChange={setPhoto} />\"],\n          defaultValue !== undefined && [\"defaultValue is not a prop\", \"<ImageField src={photoUrl} />\"],\n          onChange !== undefined && [\"onChange is not a prop\", \"<ImageField onFileChange={(file) => {}} />\"],\n          maxFileSize !== undefined && [\"maxFileSize is not a prop\", `<ImageField maxSize={${typeof maxFileSize === \"number\" ? maxFileSize : \"5 * 1024 * 1024\"}} />`],\n          cropper !== undefined && [\"cropper is not a prop\", \"<ImageField crop />\"],\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n  const id = useId();\n  const input = useRef<HTMLInputElement | null>(null);\n  const setInput = useCallback(\n    (element: HTMLInputElement | null) => {\n      input.current = element;\n      if (typeof ref === \"function\") ref(element);\n      else if (ref) ref.current = element;\n    },\n    [ref],\n  );\n  const [file, setFile] = useState<File | null>(null);\n  const [pending, setPending] = useState<File | null>(null);\n  const [rejection, setRejection] = useState<string | null>(null);\n  // Counts the checks that open a chosen photo, so only the newest one, while mounted, takes effect.\n  const check = useRef(0);\n  // The frame that shows a turned-away file's message, after the status region has emptied.\n  const frame = useRef(0);\n  useEffect(\n    () => () => {\n      check.current++;\n      cancelAnimationFrame(frame.current);\n    },\n    [],\n  );\n\n  const attach = useCallback(\n    (image: HTMLImageElement | null) => {\n      /* istanbul ignore if @preserve -- React 19 calls a ref that returns a cleanup with the element only */\n      if (!image || !file) return;\n      const url = URL.createObjectURL(file);\n      image.src = url;\n      return () => URL.revokeObjectURL(url);\n    },\n    [file],\n  );\n\n  const take = (next: File | null) => {\n    setInputFile(input.current!, next);\n    setFile(next);\n    onFileChange?.(next);\n  };\n  const turnAway = (reason: ImageFieldRejection, chosen: File) => {\n    const fallback = () =>\n      reason === \"type\" ? `${chosen.name} is not an image this field takes.` : reason === \"size\" ? `${chosen.name} is larger than ${formatSize(maxSize!)}.` : `The browser can't read ${chosen.name} as a photo. Choose a JPEG or PNG photo instead.`;\n    setRejection(rejectMessage ? rejectMessage(reason, chosen) : fallback());\n  };\n  /** A photo from the picker or a drop: checked, opened (and, with crop, cropped), then shown. */\n  const consider = (chosen: File) => {\n    const ticket = ++check.current;\n    cancelAnimationFrame(frame.current);\n    // The input keeps what showed before until the photo is opened (and, with crop, cropped).\n    setInputFile(input.current!, file);\n    // Empty the status region first, so the same message for the same file is announced again.\n    setRejection(null);\n    const reason: ImageFieldRejection | null = !matchesAccept(chosen, accept) ? \"type\" : maxSize !== undefined && chosen.size > maxSize ? \"size\" : null;\n    if (reason) {\n      frame.current = requestAnimationFrame(() => turnAway(reason, chosen));\n      return;\n    }\n    if (crop) {\n      // The cropper opens the photo and says when it cannot.\n      setPending(chosen);\n      return;\n    }\n    const url = URL.createObjectURL(chosen);\n    const probe = new Image();\n    probe.src = url;\n    const opened = (ok: boolean) => {\n      URL.revokeObjectURL(url);\n      if (ticket !== check.current) return;\n      if (ok) take(chosen);\n      else turnAway(\"unreadable\", chosen);\n    };\n    probe.decode().then(\n      () => opened(true),\n      () => opened(false),\n    );\n  };\n  const choose = (event: ChangeEvent<HTMLInputElement>) => {\n    // Stryker disable next-line OptionalChaining: a file input's files is never null while it fires change; the type allows null.\n    const chosen = event.target.files?.[0];\n    if (chosen) consider(chosen);\n  };\n\n  // A file dragged over the field lights the photo's frame; dropped, it is taken as if chosen.\n  // Dropping never opens the file in the browser, so these always cancel the default; text or\n  // a link dragged over leaves the frame unlit, and a disabled field ignores what is dropped.\n  const [dragging, setDragging] = useState(false);\n  const dragOver = (event: DragEvent<HTMLDivElement>) => {\n    event.preventDefault();\n    if (!disabled && event.dataTransfer.types.includes(\"Files\")) setDragging(true);\n  };\n  const dragLeave = (event: DragEvent<HTMLDivElement>) => {\n    if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false);\n  };\n  const drop = (event: DragEvent<HTMLDivElement>) => {\n    event.preventDefault();\n    setDragging(false);\n    const dropped = event.dataTransfer.files[0];\n    if (!disabled && dropped) consider(dropped);\n  };\n  const remove = () => {\n    check.current++;\n    cancelAnimationFrame(frame.current);\n    setRejection(null);\n    if (file) take(null);\n    else onRemove?.();\n  };\n\n  const showing = file !== null || Boolean(src);\n  const errors = errorMessages(error);\n  const invalid = errors.length > 0 || rejection !== null;\n  const problems = [errors.length > 0 ? `${id}-error` : \"\", rejection ? `${id}-status` : \"\"];\n  const cropOptions = typeof crop === \"object\" ? crop : {};\n\n  return (\n    <div\n      data-ouro=\"image-field\"\n      role=\"group\"\n      aria-labelledby={`${id}-label`}\n      aria-describedby={[description != null ? `${id}-description` : \"\", ...problems].filter(Boolean).join(\" \") || undefined}\n      data-disabled={disabled ? \"\" : undefined}\n      data-invalid={invalid ? \"\" : undefined}\n      className={cn(\"grid min-w-0 justify-items-start gap-3\", className)}\n      onDragEnter={dragOver}\n      onDragOver={dragOver}\n      onDragLeave={dragLeave}\n      onDrop={drop}\n    >\n      <div data-ouro-label=\"\" data-ouro-required={required ? \"\" : undefined} className={cn(\"grid gap-1\", \"data-ouro-required:[&>span:first-child]:after:ms-0.5 data-ouro-required:[&>span:first-child]:after:text-destructive data-ouro-required:[&>span:first-child]:after:content-['*'] supports-[content:'*'_/_'']:data-ouro-required:[&>span:first-child]:after:content-['*'_/_'']\", hideLabel && \"sr-only\")}>\n        <span className=\"text-sm leading-5 font-medium text-foreground\">\n          <span id={`${id}-label`}>{label}</span>\n        </span>\n        {description != null ? (\n          <span id={`${id}-description`} className=\"text-sm leading-5 text-muted-foreground\">\n            {description}\n          </span>\n        ) : null}\n      </div>\n      <div\n        data-ouro-drop-zone=\"\"\n        data-dragging={dragging ? \"\" : undefined}\n        style={{ aspectRatio: aspect }}\n        className={cn(\n          \"relative flex items-center justify-center overflow-hidden border border-solid bg-muted text-muted-foreground\",\n          invalid ? \"border-destructive\" : \"border-border\",\n          \"transition-colors duration-(--ouro-duration-fast) ease-[ease] data-dragging:border-primary data-dragging:bg-primary/10 forced-colors:data-dragging:border-[Highlight]\",\n          shape === \"circle\" ? \"w-32 rounded-full\" : \"w-full max-w-xs rounded-ouro-lg\",\n        )}\n      >\n        {dragging ? (\n          <span aria-hidden=\"true\" className=\"absolute inset-0 z-1 flex items-center justify-center bg-background/85 p-2 text-center text-sm leading-5 font-medium text-foreground\">\n            {dropLabel}\n          </span>\n        ) : null}\n        {file ? (\n          <img ref={attach} alt=\"\" className=\"block size-full object-cover\" />\n        ) : src ? (\n          <img src={src} alt={alt} className=\"block size-full object-cover\" />\n        ) : (\n          <PhotoIcon />\n        )}\n      </div>\n      <div className=\"flex flex-wrap gap-2\">\n        <Button\n          data-ouro-control=\"image-field\"\n          data-ouro-part=\"choose\"\n          variant=\"outline\"\n          tone=\"secondary\"\n          size=\"sm\"\n          disabled={disabled}\n          aria-describedby={[`${id}-label`, ...problems].filter(Boolean).join(\" \")}\n          onClick={() => input.current!.click()}\n        >\n          {showing ? changeLabel : chooseLabel}\n        </Button>\n        {dropHint && !disabled ? <span className=\"self-center text-sm leading-5 text-muted-foreground\">{dropHint}</span> : null}\n        {file !== null || (src && onRemove) ? (\n          <Button data-ouro-control=\"image-field\" data-ouro-part=\"remove\" variant=\"plain\" tone=\"destructive\" size=\"sm\" disabled={disabled} aria-describedby={`${id}-label`} onClick={remove}>\n            {removeLabel}\n          </Button>\n        ) : null}\n      </div>\n      <input\n        ref={setInput}\n        data-ouro-control=\"image-field\"\n        data-ouro-part=\"input\"\n        type=\"file\"\n        name={name}\n        accept={accept}\n        disabled={disabled}\n        aria-labelledby={`${id}-label`}\n        tabIndex={-1}\n        hidden\n        onChange={choose}\n      />\n      <div className={cn(\"grid gap-1 text-sm leading-5 text-destructive\", !invalid && \"sr-only\")}>\n        {errors.length > 0 ? (\n          <div id={`${id}-error`} className=\"grid gap-1\">\n            {errors.map((message, index) => (\n              <p key={index} className=\"m-0\">\n                {message}\n              </p>\n            ))}\n          </div>\n        ) : null}\n        {/* Why a file was turned away: a polite status region from the first render, so screen\n            readers announce the message once when it appears; hidden while empty. */}\n        <p id={`${id}-status`} role=\"status\" className={cn(\"m-0\", !rejection && \"sr-only\")}>\n          {rejection}\n        </p>\n      </div>\n      {crop ? (\n        <ImageCropper\n          open={pending !== null}\n          // The cropper has no trigger, so it only ever asks to close.\n          onOpenChange={() => setPending(null)}\n          image={pending}\n          aspect={aspect}\n          shape={shape}\n          outputWidth={cropOptions.outputWidth}\n          type={cropOptions.type}\n          title={cropOptions.title}\n          onCrop={take}\n          onError={(reason) => {\n            if (reason !== \"open\") return;\n            turnAway(\"unreadable\", pending!);\n            setPending(null);\n          }}\n        />\n      ) : null}\n    </div>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/image-field/image-field.tsx"
    }
  ],
  "docs": "A field for one photo, shown large: the photo already saved (`src`) or the one just chosen, with Choose photo (Change photo once one shows) and Remove. Import: import { ImageField } from \"@/components/ouro/image-field/image-field\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: button, dialog, field, file-field, image-cropper, sheet, slider, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/image-field.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}