{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-cropper",
  "title": "ImageCropper",
  "description": "A dialog for cropping a photo to a shape before it is used: drag the photo (or move it the way the arrow keys point) to choose what shows in the frame, zoom with the slider (or Plus and Minus), and Save hands the cropped image to `onCrop` as a `File`, ready for a form or an upload.",
  "registryDependencies": [
    "@ouro/button",
    "@ouro/dialog",
    "@ouro/lib-cn",
    "@ouro/lib-env",
    "@ouro/lib-use-dev-messages",
    "@ouro/slider"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/image-cropper/image-cropper-styles.ts",
      "content": "export { clampOffset, coverScale, cropRect, MAX_ZOOM, MIN_ZOOM, STEP };\nexport type { Offset, Size };\n\n// The export list comes first because the shadcn CLI drops comments before a file's\n// first statement, which would take the JSDoc below with it.\n\n/** A width and a height in pixels. */\ninterface Size {\n  width: number;\n  height: number;\n}\n\n/** How far the image's centre sits from the frame's, in screen pixels. */\ninterface Offset {\n  x: number;\n  y: number;\n}\n\n/** The scale at which the image just covers the frame. */\nfunction coverScale(image: Size, frame: Size): number {\n  return Math.max(frame.width / image.width, frame.height / image.height);\n}\n\n/**\n * An offset kept within the image's edges, so the frame never shows past them.\n *\n * @claim \"An offset kept within the image's\" registry/ouro/components/ouro/image-cropper/image-cropper.test.tsx verify:testExists(registry/ouro/components/ouro/image-cropper/image-cropper.test.tsx::ImageCropper geometry > covers the frame, keeps the image over it, and reads the crop in the image's pixels)\n * @claim \"An offset kept within the image's\" registry/ouro/components/ouro/image-cropper/image-cropper.test.tsx verify:testExists(registry/ouro/components/ouro/image-cropper/image-cropper.test.tsx::ImageCropper > moves the photo the way the arrow keys point, ten times further with Shift, and never past its edge)\n */\nfunction clampOffset(image: Size, frame: Size, scale: number, offset: Offset): Offset {\n  const spareX = Math.max(0, (image.width * scale - frame.width) / 2);\n  const spareY = Math.max(0, (image.height * scale - frame.height) / 2);\n  return { x: Math.min(spareX, Math.max(-spareX, offset.x)), y: Math.min(spareY, Math.max(-spareY, offset.y)) };\n}\n\n/** The part of the image the frame shows, in the image's own pixels. */\nfunction cropRect(image: Size, frame: Size, scale: number, offset: Offset): { x: number; y: number; width: number; height: number } {\n  const width = frame.width / scale;\n  const height = frame.height / scale;\n  return {\n    x: image.width / 2 - offset.x / scale - width / 2,\n    y: image.height / 2 - offset.y / scale - height / 2,\n    width,\n    height,\n  };\n}\n\nconst MIN_ZOOM = 1;\nconst MAX_ZOOM = 3;\n/**\n * Pixels an arrow key moves the image; ten times as far with Shift.\n *\n * @claim \"Pixels an arrow key moves the\" registry/ouro/components/ouro/image-cropper/image-cropper.test.tsx verify:testExists(registry/ouro/components/ouro/image-cropper/image-cropper.test.tsx::ImageCropper > moves the photo the way the arrow keys point, ten times further with Shift, and never past its edge)\n */\nconst STEP = 10;\n",
      "type": "registry:ui",
      "target": "@components/ouro/image-cropper/image-cropper-styles.ts"
    },
    {
      "path": "registry/ouro/components/ouro/image-cropper/image-cropper.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useId, useMemo, useRef, useState, type JSX, type KeyboardEvent, type PointerEvent } from \"react\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { useDevWarnings } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { Button } from \"@/registry/ouro/components/ouro/button/button\";\nimport { Dialog } from \"@/registry/ouro/components/ouro/dialog/dialog\";\nimport { Slider } from \"@/registry/ouro/components/ouro/slider/slider\";\nimport {\n  clampOffset,\n  coverScale,\n  cropRect,\n  MAX_ZOOM,\n  MIN_ZOOM,\n  STEP,\n  type Offset,\n  type Size,\n} from \"@/registry/ouro/components/ouro/image-cropper/image-cropper-styles\";\n\n/** The words the cropper shows and says, for apps in other languages. */\nexport interface ImageCropperLabels {\n  /** @default \"Save\" */\n  save?: string | undefined;\n  /** @default \"Cancel\" */\n  cancel?: string | undefined;\n  /** The zoom slider's label. @default \"Zoom\" */\n  zoom?: string | undefined;\n  /** The crop area's name for screen readers. @default \"Photo to crop\" */\n  area?: string | undefined;\n  /** How to move the photo, read with the crop area. @default \"Drag the photo, or move it with the arrow keys, to choose what shows. Plus and minus zoom.\" */\n  instructions?: string | undefined;\n  /**\n   * Shown and announced when the browser cannot open the image.\n   * @default \"The browser can't read this file as a photo. Choose a JPEG or PNG photo instead.\" for a `File` or `Blob`; for a URL, \"The browser didn't load the photo at this address: it is missing, blocked, or not a photo the browser can read. Choose another photo.\"\n   */\n  openError?: string | undefined;\n  /** Shown and announced when the browser cannot save the crop; Save can be tried again. @default \"The browser didn't turn the crop into a file. Press <save label> to try again, or choose another photo.\" */\n  saveError?: string | undefined;\n}\n\n/** What went wrong: `open`, the browser cannot show the image (a format it cannot decode, or an address it may not read); `save`, it cannot encode the crop. */\nexport type ImageCropperFailure = \"open\" | \"save\";\n\n/** Props for {@link ImageCropper}. */\nexport interface ImageCropperProps {\n  /** Whether the cropper's dialog is open. */\n  open: boolean;\n  /** Called when it opens or closes: after Save, Cancel, Escape or the close button. */\n  onOpenChange: (open: boolean) => void;\n  /** The image to crop: a `File` from a picker, a `Blob`, or a URL the page may read pixels from (same origin or CORS). */\n  image: File | Blob | string | null;\n  /** Called with the cropped image, as a `File`, when the person saves. The dialog then closes. */\n  onCrop: (file: File) => void;\n  /** The dialog's title. @default \"Crop photo\" */\n  title?: string | undefined;\n  /** The crop's width divided by its height: `1` square, `16 / 9` wide. @default 1 */\n  aspect?: number | undefined;\n  /** `circle` shows a round frame for a profile photo; the saved image is still the square around it. @default \"rect\" */\n  shape?: \"rect\" | \"circle\" | (string & { 'Use \"rect\" or \"circle\"': never }) | undefined;\n  /** The saved image's width in pixels; its height follows `aspect`. @default 1024 */\n  outputWidth?: number | undefined;\n  /** The saved image's format. @default \"image/jpeg\" */\n  type?: \"image/jpeg\" | \"image/png\" | \"image/webp\" | (string & { 'Use \"image/jpeg\", \"image/png\" or \"image/webp\"': never }) | undefined;\n  /** The words it shows and says. */\n  labels?: ImageCropperLabels | undefined;\n  /** Called when the image cannot be opened or the crop cannot be saved. The cropper shows and announces `labels.openError` or `labels.saveError` itself; close it or offer another image. */\n  onError?: ((reason: ImageCropperFailure) => void) | undefined;\n\n  /** Not a prop. The cropped image comes to `onCrop`: `<ImageCropper onCrop={(file) => …} />`. */\n  onChange?: { 'Use onCrop={(file) => ...}': never };\n  /** Not a prop. The image is `image`: `<ImageCropper image={file} />`. */\n  src?: { 'Use image={file}': never };\n  /** Not a prop. The shape is `aspect`, width over height: `aspect={16 / 9}`. */\n  aspectRatio?: { 'Use aspect={16 / 9}': never };\n  /** Not a prop. Ouro UI uses `shape`: `<ImageCropper shape=\"circle\" />`. */\n  round?: { 'Use shape=\"circle\"': never };\n}\n\nconst FRAME_WIDTH = 288;\nconst words = {\n  save: \"Save\",\n  cancel: \"Cancel\",\n  zoom: \"Zoom\",\n  area: \"Photo to crop\",\n  instructions: \"Drag the photo, or move it with the arrow keys, to choose what shows. Plus and minus zoom.\",\n};\n\n/** What an image that will not open says by default, by where it came from: a file, or an address. */\nconst openErrors = {\n  file: \"The browser can't read this file as a photo. Choose a JPEG or PNG photo instead.\",\n  url: \"The browser didn't load the photo at this address: it is missing, blocked, or not a photo the browser can read. Choose another photo.\",\n};\n\n/** Draws the chosen part of the image at the output size and returns it as a file. */\nasync function crop(image: HTMLImageElement, natural: Size, frame: Size, scale: number, offset: Offset, width: number, type: string, name: string): Promise<File> {\n  const rect = cropRect(natural, frame, scale, offset);\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = Math.round(width);\n  canvas.height = Math.round((width * frame.height) / frame.width);\n  const context = canvas.getContext(\"2d\")!;\n  context.imageSmoothingQuality = \"high\";\n  context.drawImage(image, rect.x, rect.y, rect.width, rect.height, 0, 0, canvas.width, canvas.height);\n  // Stryker disable next-line StringLiteral: the cropper catches this error and shows saveError; the message is only for a debugger.\n  const blob = await new Promise<Blob>((resolve, reject) => canvas.toBlob((result) => (result ? resolve(result) : reject(new Error(\"canvas.toBlob returned no image for the crop\"))), type, 0.92));\n  const extension = blob.type.split(\"/\")[1]!.replace(\"jpeg\", \"jpg\");\n  return new File([blob], `${name.replace(/\\.[^.]+$/, \"\")}.${extension}`, { type: blob.type });\n}\n\n/**\n * A dialog for cropping a photo to a shape before it is used: drag the photo (or move it the\n * way the arrow keys point) to choose what shows in the frame, zoom with the slider (or Plus and Minus),\n * and Save hands the cropped image to `onCrop` as a `File`, ready for a form or an upload.\n * The frame is a rectangle of `aspect`, or a circle for a profile photo. It always opens as a\n * centered dialog, so dragging the photo never drags the dialog away.\n *\n * Use `ImageField` with `crop` instead to pick a photo and crop it in one field, and `FileField`\n * for files that need no cropping.\n *\n * @group Forms\n * @see https://ui.ouroboros.bot/docs/image-cropper\n *\n * @example\n * <ImageCropper open={file !== null} onOpenChange={(open) => !open && setFile(null)} image={file} shape=\"circle\" onCrop={upload} />\n * @claim \"It always opens as a centered\" registry/ouro/components/ouro/image-cropper/image-cropper.tsx verify:fileLine(registry/ouro/components/ouro/image-cropper/image-cropper.tsx, /presentation=\"dialog\"/)\n */\nexport function ImageCropper(props: ImageCropperProps): JSX.Element {\n  const {\n    open,\n    onOpenChange,\n    image,\n    onCrop,\n    title = \"Crop photo\",\n    aspect: aspectProp = 1,\n    shape: shapeProp = \"rect\",\n    outputWidth = 1024,\n    type: typeProp = \"image/jpeg\",\n    labels,\n    onError,\n    // Guard props (hint types), never used.\n    onChange,\n    src: srcProp,\n    aspectRatio,\n    round,\n  } = props;\n  const aspect = aspectProp > 0 && Number.isFinite(aspectProp) ? aspectProp : 1;\n  const shape = shapeProp === \"circle\" ? \"circle\" : \"rect\";\n  const type = [\"image/jpeg\", \"image/png\", \"image/webp\"].includes(typeProp) ? typeProp : \"image/jpeg\";\n  useDevWarnings(\n    \"ImageCropper\",\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`, \"<ImageCropper aspect={16 / 9} />\"],\n          shape !== shapeProp && [`shape=\"${String(shapeProp)}\" is not a shape; use \"rect\" or \"circle\"`, '<ImageCropper shape=\"circle\" />'],\n          type !== typeProp && [`type=\"${String(typeProp)}\" is not an image format the browser saves`, '<ImageCropper type=\"image/jpeg\" />'],\n          onChange !== undefined && [\"onChange is not a prop\", \"<ImageCropper onCrop={(file) => {}} />\"],\n          srcProp !== undefined && [\"src is not a prop\", \"<ImageCropper image={file} />\"],\n          aspectRatio !== undefined && [\"aspectRatio is not a prop\", \"<ImageCropper aspect={16 / 9} />\"],\n          round !== undefined && [\"round is not a prop\", '<ImageCropper shape=\"circle\" />'],\n        ]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n  // Merged once per labels object, so an app that keeps its labels in a constant merges them once.\n  const word = useMemo(() => ({ ...words, ...Object.fromEntries(Object.entries(labels ?? {}).filter(([, value]) => value !== undefined)) }), [labels]);\n  const openError = labels?.openError ?? (typeof image === \"string\" ? openErrors.url : openErrors.file);\n  const saveError = labels?.saveError ?? `The browser didn't turn the crop into a file. Press ${word.save} to try again, or choose another photo.`;\n  const frame: Size = { width: FRAME_WIDTH, height: Math.round(FRAME_WIDTH / aspect) };\n\n  const [natural, setNatural] = useState<Size | null>(null);\n  const [zoom, setZoom] = useState(MIN_ZOOM);\n  const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });\n  const [saving, setSaving] = useState(false);\n  const [failure, setFailure] = useState<ImageCropperFailure | null>(null);\n  const statusId = useId();\n  const img = useRef<HTMLImageElement>(null);\n  const drag = useRef<{ x: number; y: number; from: Offset } | null>(null);\n  // A File or Blob is shown through an object URL that lives as long as its <img>.\n  const attach = useCallback(\n    (element: HTMLImageElement | null) => {\n      /* istanbul ignore if @preserve -- React 19 calls a ref that returns a cleanup with the element only */\n      if (!element) return;\n      img.current = element;\n      if (typeof image === \"string\") {\n        element.src = image;\n        return;\n      }\n      const url = URL.createObjectURL(image!);\n      element.src = url;\n      return () => URL.revokeObjectURL(url);\n    },\n    [image],\n  );\n  // A new image starts centred at the smallest zoom.\n  const [shown, setShown] = useState(image);\n  if (shown !== image) {\n    setShown(image);\n    setNatural(null);\n    setZoom(MIN_ZOOM);\n    setOffset({ x: 0, y: 0 });\n    setFailure(null);\n  }\n\n  const scale = natural ? coverScale(natural, frame) * zoom : 1;\n  const move = (next: Offset, nextZoom = zoom) => {\n    if (!natural) return;\n    setOffset(clampOffset(natural, frame, coverScale(natural, frame) * nextZoom, next));\n  };\n  const zoomTo = (next: number) => {\n    const clamped = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next));\n    setZoom(clamped);\n    move(offset, clamped);\n  };\n\n  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    drag.current = { x: event.clientX, y: event.clientY, from: offset };\n  };\n  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n    const start = drag.current;\n    if (!start) return;\n    move({ x: start.from.x + event.clientX - start.x, y: start.from.y + event.clientY - start.y });\n  };\n  const onPointerUp = () => {\n    drag.current = null;\n  };\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    const step = event.shiftKey ? STEP * 10 : STEP;\n    const moves: Record<string, Offset> = { ArrowLeft: { x: -step, y: 0 }, ArrowRight: { x: step, y: 0 }, ArrowUp: { x: 0, y: -step }, ArrowDown: { x: 0, y: step } };\n    const by = moves[event.key];\n    if (by) move({ x: offset.x + by.x, y: offset.y + by.y });\n    else if (event.key === \"+\" || event.key === \"=\") zoomTo(zoom + 0.1);\n    else if (event.key === \"-\" || event.key === \"_\") zoomTo(zoom - 0.1);\n    else return;\n    event.preventDefault();\n  };\n\n  const fail = (reason: ImageCropperFailure) => {\n    setFailure(reason);\n    onError?.(reason);\n  };\n  const save = async () => {\n    setSaving(true);\n    setFailure(null);\n    let file: File;\n    try {\n      file = await crop(img.current!, natural!, frame, scale, offset, outputWidth, type, image instanceof File ? image.name : \"photo\");\n    } catch {\n      // The browser turned the crop into no file; the dialog stays open, so Save can be tried again.\n      setSaving(false);\n      fail(\"save\");\n      return;\n    }\n    setSaving(false);\n    // Outside the try, so an error the app's onCrop throws reaches the app.\n    onCrop(file);\n    onOpenChange(false);\n  };\n\n  return (\n    <Dialog\n      open={open}\n      onOpenChange={onOpenChange}\n      title={title}\n      presentation=\"dialog\"\n      size=\"sm\"\n      footer={\n        <>\n          <Button data-ouro-control=\"image-cropper\" data-ouro-part=\"cancel\" variant=\"outline\" tone=\"secondary\" onClick={() => onOpenChange(false)}>\n            {word.cancel}\n          </Button>\n          <Button data-ouro-control=\"image-cropper\" data-ouro-part=\"save\" onClick={save} disabled={!natural} loading={saving}>\n            {word.save}\n          </Button>\n        </>\n      }\n    >\n      <div data-ouro=\"image-cropper\" data-shape={shape} className=\"grid justify-items-center gap-4\">\n        <div\n          data-ouro-control=\"image-cropper\"\n          data-ouro-part=\"area\"\n          role=\"application\"\n          aria-label={word.area}\n          aria-describedby={failure ? `ouro-image-cropper-instructions ${statusId}` : \"ouro-image-cropper-instructions\"}\n          aria-busy={natural || failure === \"open\" ? undefined : true}\n          tabIndex={0}\n          onPointerDown={onPointerDown}\n          onPointerMove={onPointerMove}\n          onPointerUp={onPointerUp}\n          onPointerCancel={onPointerUp}\n          onKeyDown={onKeyDown}\n          style={{ width: frame.width, height: frame.height }}\n          className={cn(\n            \"relative max-w-full cursor-grab touch-none overflow-hidden bg-muted select-none active:cursor-grabbing\",\n            \"outline-ring outline-offset-2 focus-visible:outline-2 focus-visible:outline-solid\",\n            shape === \"circle\" ? \"rounded-full\" : \"rounded-ouro-lg\",\n          )}\n        >\n          {/* `left`, not `start`: the offset and the crop are in screen pixels in either direction. */}\n          {image !== null ? (\n            <img\n              ref={attach}\n              alt=\"\"\n              draggable={false}\n              crossOrigin={typeof image === \"string\" ? \"anonymous\" : undefined}\n              onLoad={(event) => setNatural({ width: event.currentTarget.naturalWidth, height: event.currentTarget.naturalHeight })}\n              onError={() => fail(\"open\")}\n              className=\"pointer-events-none absolute top-1/2 left-1/2 max-w-none\"\n              style={{\n                width: natural ? natural.width * scale : undefined,\n                height: natural ? natural.height * scale : undefined,\n                translate: `calc(-50% + ${offset.x}px) calc(-50% + ${offset.y}px)`,\n                visibility: natural ? undefined : \"hidden\",\n              }}\n            />\n          ) : null}\n        </div>\n        <p id=\"ouro-image-cropper-instructions\" className=\"sr-only\">\n          {word.instructions}\n        </p>\n        {/* A polite status region from the first render, so a failure is announced once when it appears; hidden while empty. */}\n        <p id={statusId} role=\"status\" className={cn(\"m-0 text-center text-sm leading-5 text-destructive\", !failure && \"sr-only\")}>\n          {failure === \"open\" ? openError : failure === \"save\" ? saveError : null}\n        </p>\n        <Slider label={word.zoom} min={MIN_ZOOM} max={MAX_ZOOM} step={0.01} value={zoom} onValueChange={zoomTo} disabled={!natural} format={{ style: \"percent\" }} className=\"w-full max-w-72\" />\n      </div>\n    </Dialog>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/image-cropper/image-cropper.tsx"
    }
  ],
  "docs": "A dialog for cropping a photo to a shape before it is used: drag the photo (or move it the way the arrow keys point) to choose what shows in the frame, zoom with the slider (or Plus and Minus), and Save hands the cropped image to `onCrop` as a `File`, ready for a form or an upload. Import: import { ImageCropper } from \"@/components/ouro/image-cropper/image-cropper\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: button, dialog, field, 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-cropper.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}