{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-cropper",
  "type": "registry:ui",
  "title": "Image Cropper",
  "description": "A picture with a frame over it that chooses the part to keep: dragged or resized by its corners, or moved with the arrow keys and resized with plus and minus, optionally held to a shape (square, 16:9); the choice comes out as fractions and as pixels of the original.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/image-cropper.tsx",
      "type": "registry:ui",
      "target": "components/ui/image-cropper.tsx",
      "content": "\"use client\";\n/**\n * @name image-cropper\n * @category ui\n * @description A picture with a frame over it that chooses the part to keep: dragged or resized by its corners, or moved with the arrow keys and resized with plus and minus, optionally held to a shape (square, 16:9); the choice comes out as fractions and as pixels of the original.\n * @when Cropping an avatar, a cover picture, a product photo before upload. The cutting itself is the project's (a canvas, the server); this gives the rectangle. For marking areas on a picture use image-annotator; for comparing two pictures use compare-slider.\n * @example\n * <ImageCropper src=\"/photo.jpg\" alt=\"The harbour at dawn\" aspect={1} onCropChange={(crop) => setCrop(crop.pixels)} />\n */\nimport { useId, useRef, useState, type ComponentProps, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\n/** A rectangle as fractions of the picture's width and height, from its top left. */\nexport type CropRect = { x: number; y: number; width: number; height: number };\nexport type Crop = { fractions: CropRect; pixels: CropRect };\n\nexport type ImageCropperLabels = { area: string; help: string; size: (width: number, height: number) => string };\nconst LABELS: ImageCropperLabels = {\n  area: \"Crop area\",\n  help: \"Arrow keys move the area, with Shift further. Plus and minus make it larger or smaller.\",\n  size: (width, height) => `${width} by ${height} pixels`,\n};\n\nexport type ImageCropperProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  src: string;\n  alt: string;\n  /** Width / height the area keeps. Left out, any shape. */\n  aspect?: number;\n  value?: CropRect;\n  defaultValue?: CropRect;\n  /** Called with the area as fractions and as pixels of the original picture. */\n  onCropChange?: (crop: Crop) => void;\n  /** Draws the picture: the framework's image component. It must pass `onLoad` through. */\n  renderImage?: (props: { src: string; alt: string; className: string; onLoad: (event: { currentTarget: HTMLImageElement }) => void; draggable: false }) => ReactNode;\n  labels?: Partial<ImageCropperLabels>;\n};\n\nconst MIN = 0.05;\n\nexport function ImageCropper({ src, alt, aspect, value, defaultValue, onCropChange, renderImage, labels: given, className, ...props }: ImageCropperProps) {\n  const labels = { ...LABELS, ...given };\n  const [natural, setNatural] = useState({ width: 0, height: 0 });\n  const start: CropRect = defaultValue ?? { x: 0.1, y: 0.1, width: 0.8, height: 0.8 };\n  const pixelsOf = (r: CropRect): CropRect => ({\n    x: Math.round(r.x * natural.width),\n    y: Math.round(r.y * natural.height),\n    width: Math.round(r.width * natural.width),\n    height: Math.round(r.height * natural.height),\n  });\n  const [crop, setCrop] = useControllableState<CropRect>({ value, defaultValue: start, onChange: (next) => onCropChange?.({ fractions: next, pixels: pixelsOf(next) }) });\n  const frame = useRef<HTMLDivElement>(null);\n  const drag = useRef<{ mode: \"move\" | \"nw\" | \"ne\" | \"sw\" | \"se\"; x: number; y: number; from: CropRect } | null>(null);\n  const helpId = useId();\n  // The shape in fractions: the picture's own shape changes what a square is.\n  const ratio = aspect && natural.width > 0 ? (aspect * natural.height) / natural.width : undefined;\n\n  const fit = (r: CropRect): CropRect => {\n    let { width, height } = r;\n    width = Math.max(MIN, Math.min(1, width));\n    height = Math.max(MIN, Math.min(1, height));\n    if (ratio) {\n      height = width / ratio;\n      if (height > 1) {\n        height = 1;\n        width = ratio;\n      }\n    }\n    return { x: Math.max(0, Math.min(1 - width, r.x)), y: Math.max(0, Math.min(1 - height, r.y)), width, height };\n  };\n  const set = (next: CropRect): void => setCrop(fit(next));\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    const step = event.shiftKey ? 0.1 : 0.01;\n    const moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] };\n    const move = moves[event.key];\n    // Plus and minus resize about the centre. (Alt with an arrow is the browser's Back and Forward.)\n    const grow = event.key === \"+\" || event.key === \"=\" ? 0.02 : event.key === \"-\" || event.key === \"_\" ? -0.02 : 0;\n    if (!move && grow === 0) return;\n    event.preventDefault();\n    // The picture is not mirrored in a right-to-left page, so Right is always right.\n    const next = move ? fit({ ...crop, x: crop.x + move[0], y: crop.y + move[1] }) : fit({ x: crop.x - grow / 2, y: crop.y - grow / 2, width: crop.width + grow, height: crop.height + grow });\n    setCrop(next);\n    if (grow !== 0) {\n      const px = pixelsOf(next);\n      announce(labels.size(px.width, px.height));\n    }\n  };\n  const onPointerDown = (mode: \"move\" | \"nw\" | \"ne\" | \"sw\" | \"se\", event: PointerEvent<HTMLElement>): void => {\n    event.stopPropagation();\n    event.currentTarget.setPointerCapture(event.pointerId);\n    drag.current = { mode, x: event.clientX, y: event.clientY, from: crop };\n  };\n  const onPointerMove = (event: PointerEvent<HTMLElement>): void => {\n    const box = frame.current?.getBoundingClientRect();\n    const d = drag.current;\n    if (!box || !d) return;\n    const dx = (event.clientX - d.x) / box.width;\n    const dy = (event.clientY - d.y) / box.height;\n    const f = d.from;\n    if (d.mode === \"move\") set({ ...f, x: f.x + dx, y: f.y + dy });\n    else {\n      const west = d.mode === \"nw\" || d.mode === \"sw\";\n      const north = d.mode === \"nw\" || d.mode === \"ne\";\n      const width = f.width + (west ? -dx : dx);\n      const height = ratio ? width / ratio : f.height + (north ? -dy : dy);\n      set({ x: west ? f.x + f.width - width : f.x, y: north ? f.y + f.height - height : f.y, width, height });\n    }\n  };\n  const px = pixelsOf(crop);\n  const pct = (n: number): string => `${n * 100}%`;\n  const image = {\n    src,\n    alt,\n    className: \"block h-auto w-full select-none\",\n    draggable: false as const,\n    onLoad: (event: { currentTarget: HTMLImageElement }) => setNatural({ width: event.currentTarget.naturalWidth, height: event.currentTarget.naturalHeight }),\n  };\n\n  return (\n    <div data-slot=\"image-cropper\" className={cn(\"relative w-full min-w-0 touch-none overflow-hidden rounded-surface border\", className)} dir=\"ltr\" {...props}>\n      <div ref={frame} className=\"relative\" onPointerMove={onPointerMove} onPointerUp={() => {\n          drag.current = null;\n        }}>\n        {renderImage ? (\n          renderImage(image)\n        ) : (\n          // eslint-disable-next-line @next/next/no-img-element -- The library is not tied to one framework: the default is the plain element, and `renderImage` takes the framework's image component.\n          <img {...image} />\n        )}\n        <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\">\n          <div className=\"absolute inset-x-0 top-0 bg-overlay\" style={{ height: pct(crop.y) }} />\n          <div className=\"absolute inset-x-0 bottom-0 bg-overlay\" style={{ height: pct(1 - crop.y - crop.height) }} />\n          <div className=\"absolute bg-overlay\" style={{ top: pct(crop.y), height: pct(crop.height), left: 0, width: pct(crop.x) }} />\n          <div className=\"absolute bg-overlay\" style={{ top: pct(crop.y), height: pct(crop.height), right: 0, width: pct(1 - crop.x - crop.width) }} />\n        </div>\n        <div\n          data-slot=\"image-cropper-area\"\n          role=\"group\"\n          aria-roledescription={labels.area}\n          aria-label={`${labels.area}: ${labels.size(px.width, px.height)}`}\n          aria-describedby={helpId}\n          tabIndex={0}\n          onKeyDown={onKeyDown}\n          onPointerDown={(event) => onPointerDown(\"move\", event)}\n          className=\"absolute cursor-move border-2 border-background outline-1 outline-foreground focus-visible:outline-2 focus-visible:outline-ring\"\n          style={{ left: pct(crop.x), top: pct(crop.y), width: pct(crop.width), height: pct(crop.height) }}\n        >\n          <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 grid grid-cols-3 grid-rows-3\">\n            {Array.from({ length: 9 }, (_, i) => (\n              <span key={i} className=\"border-background/50 [&:not(:nth-child(3n))]:border-e [&:nth-child(-n+6)]:border-b\" />\n            ))}\n          </span>\n          {([\"nw\", \"ne\", \"sw\", \"se\"] as const).map((corner) => (\n            <span\n              key={corner}\n              aria-hidden=\"true\"\n              onPointerDown={(event) => onPointerDown(corner, event)}\n              className={cn(\n                \"absolute size-5 rounded-full border-2 border-foreground bg-background pointer-coarse:size-7\",\n                corner[0] === \"n\" ? \"-top-2.5\" : \"-bottom-2.5\",\n                corner[1] === \"w\" ? \"-left-2.5\" : \"-right-2.5\",\n                corner === \"nw\" || corner === \"se\" ? \"cursor-nwse-resize\" : \"cursor-nesw-resize\",\n              )}\n            />\n          ))}\n        </div>\n      </div>\n      <span id={helpId} className=\"sr-only\">\n        {labels.help}\n      </span>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Cropping an avatar, a cover picture, a product photo before upload. The cutting itself is the project's (a canvas, the server); this gives the rectangle. For marking areas on a picture use image-annotator; for comparing two pictures use compare-slider.",
    "example": "<ImageCropper src=\"/photo.jpg\" alt=\"The harbour at dawn\" aspect={1} onCropChange={(crop) => setCrop(crop.pixels)} />",
    "client": true
  }
}
