{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-cropper",
  "title": "Image Cropper",
  "description": "An image cropper with a draggable, resizable crop box, aspect presets or a circle mask for avatars, keyboard nudging, drag-and-drop upload and the cropped image returned as a data URL.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/image-cropper/image-cropper.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type ImageCropperSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface CropArea {\n  /** In the image's natural pixels. */\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\nexport interface CropResult {\n  area: CropArea;\n  /** The cropped image as a data URL, or null if the image can't be read (a cross-origin image without CORS). */\n  dataUrl: string | null;\n}\n\nexport interface AspectOption {\n  label: string;\n  /** width / height; null means free. */\n  value: number | null;\n}\n\nexport interface ImageCropperProps {\n  /** Image URL. Leave empty to start with a drop zone. */\n  src?: string;\n  /** Called when a crop settles (after a drag, a key press or an aspect change). */\n  onChange?: (result: CropResult) => void;\n  /** Called with a newly chosen file, in case you want to upload the original too. */\n  onFileChange?: (file: File) => void;\n  aspectOptions?: AspectOption[];\n  defaultAspect?: number | null;\n  /** \"circle\" masks the crop for avatars and exports a round PNG. Forces a 1:1 aspect. */\n  shape?: \"rect\" | \"circle\";\n  /** Longest side of the exported image, in pixels. */\n  maxOutputSize?: number;\n  outputType?: \"image/png\" | \"image/jpeg\" | \"image/webp\";\n  label?: string;\n  helperText?: string;\n  height?: number;\n  size?: ImageCropperSize;\n  theme?: \"dark\" | \"light\";\n  width?: number | string;\n  disabled?: boolean;\n  className?: string;\n}\n\nconst DEFAULT_ASPECTS: AspectOption[] = [\n  { label: \"Free\", value: null },\n  { label: \"1:1\", value: 1 },\n  { label: \"4:3\", value: 4 / 3 },\n  { label: \"16:9\", value: 16 / 9 },\n];\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.5)\", faint: \"rgba(245,244,241,0.3)\", bg: \"rgba(255,255,255,0.03)\", stage: \"#050505\", border: \"rgba(255,255,255,0.12)\", borderHover: \"rgba(255,255,255,0.24)\", focus: \"rgba(245,244,241,0.85)\", hover: \"rgba(255,255,255,0.07)\", sel: \"#F5F4F1\", selText: \"#0A0A0A\", track: \"rgba(255,255,255,0.06)\", shade: \"rgba(0,0,0,0.62)\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.5)\", faint: \"rgba(10,10,10,0.3)\", bg: \"#FFFFFF\", stage: \"#F2F2F0\", border: \"rgba(10,10,10,0.16)\", borderHover: \"rgba(10,10,10,0.3)\", focus: \"rgba(10,10,10,0.85)\", hover: \"rgba(10,10,10,0.05)\", sel: \"#0A0A0A\", selText: \"#FFFFFF\", track: \"rgba(10,10,10,0.05)\", shade: \"rgba(0,0,0,0.5)\" },\n};\n\nconst SIZES: Record<ImageCropperSize, { font: number; radius: number; btn: number }> = {\n  sm: { font: 13, radius: 11, btn: 30 },\n  md: { font: 14.5, radius: 13, btn: 34 },\n  lg: { font: 16, radius: 15, btn: 38 },\n};\n\n// Crop box in fractions of the image (0–1), so it survives resizes of the stage.\ninterface Box {\n  x: number;\n  y: number;\n  w: number;\n  h: number;\n}\ntype Handle = \"move\" | \"n\" | \"s\" | \"e\" | \"w\" | \"ne\" | \"nw\" | \"se\" | \"sw\";\n\nconst clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v));\n\n/** Largest centred box of the aspect (in natural pixels) covering `cover` of the image. */\nfunction initialBox(natW: number, natH: number, aspect: number | null, cover = 0.8): Box {\n  if (!aspect) return { x: (1 - cover) / 2, y: (1 - cover) / 2, w: cover, h: cover };\n  let wPx = natW * cover;\n  let hPx = wPx / aspect;\n  if (hPx > natH * cover) {\n    hPx = natH * cover;\n    wPx = hPx * aspect;\n  }\n  const w = wPx / natW;\n  const h = hPx / natH;\n  return { x: (1 - w) / 2, y: (1 - h) / 2, w, h };\n}\n\nconst HANDLES: Exclude<Handle, \"move\">[] = [\"nw\", \"n\", \"ne\", \"e\", \"se\", \"s\", \"sw\", \"w\"];\n\nexport function ImageCropper({\n  src,\n  onChange,\n  onFileChange,\n  aspectOptions = DEFAULT_ASPECTS,\n  defaultAspect = null,\n  shape = \"rect\",\n  maxOutputSize = 2048,\n  outputType = \"image/png\",\n  label,\n  helperText,\n  height = 340,\n  size = \"md\",\n  theme = \"dark\",\n  width = 560,\n  disabled = false,\n  className,\n}: ImageCropperProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const uid = React.useId();\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const imgRef = React.useRef<HTMLImageElement>(null);\n  const fileRef = React.useRef<HTMLInputElement>(null);\n  const drag = React.useRef<{ handle: Handle; startX: number; startY: number; box: Box } | null>(null);\n  const [uploaded, setUploaded] = React.useState<string | null>(null);\n  const imageSrc = uploaded ?? src ?? null;\n  const circle = shape === \"circle\";\n  const [aspect, setAspect] = React.useState<number | null>(circle ? 1 : defaultAspect);\n  const activeAspect = circle ? 1 : aspect;\n  const [nat, setNat] = React.useState<{ w: number; h: number } | null>(null);\n  const [stage, setStage] = React.useState({ w: 0, h: height });\n  const [box, setBox] = React.useState<Box>({ x: 0.1, y: 0.1, w: 0.8, h: 0.8 });\n  const [dragging, setDragging] = React.useState(false);\n  const [dropHover, setDropHover] = React.useState(false);\n\n  React.useEffect(() => {\n    const el = stageRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => setStage({ w: el.clientWidth, h: el.clientHeight }));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  // Where the image sits inside the stage (object-fit: contain).\n  const view = React.useMemo(() => {\n    if (!nat || !stage.w) return null;\n    const scale = Math.min(stage.w / nat.w, stage.h / nat.h);\n    const w = nat.w * scale;\n    const h = nat.h * scale;\n    return { x: (stage.w - w) / 2, y: (stage.h - h) / 2, w, h };\n  }, [nat, stage]);\n\n  const areaFor = (b: Box, size = nat): CropArea | null => (size ? { x: Math.round(b.x * size.w), y: Math.round(b.y * size.h), width: Math.round(b.w * size.w), height: Math.round(b.h * size.h) } : null);\n\n  // `size` lets the first export run in the same tick the image loads, before `nat` is in state.\n  const exportCrop = (b: Box, size = nat) => {\n    const img = imgRef.current;\n    const area = areaFor(b, size);\n    if (!img || !area || !onChange) return;\n    let dataUrl: string | null = null;\n    try {\n      const scale = Math.min(1, maxOutputSize / Math.max(area.width, area.height));\n      const canvas = document.createElement(\"canvas\");\n      canvas.width = Math.max(1, Math.round(area.width * scale));\n      canvas.height = Math.max(1, Math.round(area.height * scale));\n      const ctx = canvas.getContext(\"2d\");\n      if (ctx) {\n        if (circle) {\n          ctx.beginPath();\n          ctx.arc(canvas.width / 2, canvas.height / 2, Math.min(canvas.width, canvas.height) / 2, 0, Math.PI * 2);\n          ctx.clip();\n        }\n        ctx.drawImage(img, area.x, area.y, area.width, area.height, 0, 0, canvas.width, canvas.height);\n        dataUrl = canvas.toDataURL(circle ? \"image/png\" : outputType, 0.92);\n      }\n    } catch {\n      dataUrl = null; // tainted canvas: the image was served without CORS headers\n    }\n    onChange({ area, dataUrl });\n  };\n\n  const setAndExport = (b: Box) => {\n    setBox(b);\n    exportCrop(b);\n  };\n\n  const onImageLoad = () => {\n    const img = imgRef.current;\n    if (!img) return;\n    const size = { w: img.naturalWidth, h: img.naturalHeight };\n    setNat(size);\n    const b = initialBox(size.w, size.h, activeAspect);\n    setBox(b);\n    exportCrop(b, size);\n  };\n\n  // An image that finished loading before hydration never fires onLoad, so catch that case here.\n  React.useEffect(() => {\n    const img = imgRef.current;\n    if (img && img.complete && img.naturalWidth > 0) onImageLoad();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [imageSrc]);\n\n  const loadFile = (file: File | undefined) => {\n    if (!file || !file.type.startsWith(\"image/\")) return;\n    onFileChange?.(file);\n    const reader = new FileReader();\n    reader.onload = () => setUploaded(String(reader.result));\n    reader.readAsDataURL(file);\n  };\n\n  // Keep the box's aspect (in natural pixels) when resizing with a locked ratio.\n  const fracAspect = activeAspect && nat ? (activeAspect * nat.h) / nat.w : null;\n  const minFrac = view ? { w: 40 / view.w, h: 40 / view.h } : { w: 0.05, h: 0.05 };\n\n  const resize = (start: Box, handle: Handle, dx: number, dy: number): Box => {\n    if (handle === \"move\") {\n      return { ...start, x: clamp(start.x + dx, 0, 1 - start.w), y: clamp(start.y + dy, 0, 1 - start.h) };\n    }\n    let { x, y, w, h } = start;\n    const right = x + w;\n    const bottom = y + h;\n    if (handle.includes(\"e\")) w = clamp(w + dx, minFrac.w, 1 - x);\n    if (handle.includes(\"w\")) {\n      const nx = clamp(x + dx, 0, right - minFrac.w);\n      w = right - nx;\n      x = nx;\n    }\n    if (handle.includes(\"s\")) h = clamp(h + dy, minFrac.h, 1 - y);\n    if (handle.includes(\"n\")) {\n      const ny = clamp(y + dy, 0, bottom - minFrac.h);\n      h = bottom - ny;\n      y = ny;\n    }\n    if (fracAspect) {\n      // Follow the dragged dimension, then fit the other one; shrink both if that runs off the image.\n      const horizontal = handle === \"e\" || handle === \"w\" || (handle.length === 2 && Math.abs(dx) >= Math.abs(dy));\n      if (horizontal) h = w / fracAspect;\n      else w = h * fracAspect;\n      if (handle === \"n\" || handle === \"s\") x = start.x + (start.w - w) / 2;\n      if (handle === \"e\" || handle === \"w\") y = start.y + (start.h - h) / 2;\n      if (handle.includes(\"n\")) y = bottom - h;\n      if (handle.includes(\"w\")) x = right - w;\n      const fit = Math.min(1, x < 0 ? (w + x) / w : 1, y < 0 ? (h + y) / h : 1, x + w > 1 ? (1 - x) / w : 1, y + h > 1 ? (1 - y) / h : 1);\n      if (fit < 1) {\n        const nw = w * fit;\n        const nh = h * fit;\n        if (handle.includes(\"w\")) x = right - nw;\n        if (handle.includes(\"n\")) y = bottom - nh;\n        w = nw;\n        h = nh;\n      }\n      x = clamp(x, 0, 1 - w);\n      y = clamp(y, 0, 1 - h);\n    }\n    return { x, y, w, h };\n  };\n\n  // One handler for the box and every handle; which one was grabbed comes from data-handle.\n  const onPointerDown = (e: React.PointerEvent<HTMLElement>) => {\n    if (disabled || !view) return;\n    const handle = (e.currentTarget.dataset.handle ?? \"move\") as Handle;\n    e.preventDefault();\n    e.stopPropagation();\n    (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n    drag.current = { handle, startX: e.clientX, startY: e.clientY, box };\n    setDragging(true);\n  };\n\n  const onPointerMove = (e: React.PointerEvent) => {\n    const d = drag.current;\n    if (!d || !view) return;\n    setBox(resize(d.box, d.handle, (e.clientX - d.startX) / view.w, (e.clientY - d.startY) / view.h));\n  };\n\n  const onPointerUp = () => {\n    if (!drag.current) return;\n    drag.current = null;\n    setDragging(false);\n    exportCrop(box);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (!view) return;\n    const step = (e.shiftKey ? 10 : 1) / view.w;\n    const stepY = (e.shiftKey ? 10 : 1) / view.h;\n    const dirs: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -stepY], ArrowDown: [0, stepY] };\n    const d = dirs[e.key];\n    if (!d) return;\n    e.preventDefault();\n    // Alt resizes from the bottom-right corner; plain arrows move the box.\n    setAndExport(e.altKey ? resize(box, \"se\", d[0], d[1]) : resize(box, \"move\", d[0], d[1]));\n  };\n\n  const pickAspect = (value: number | null) => {\n    setAspect(value);\n    if (!nat) return;\n    setAndExport(initialBox(nat.w, nat.h, value));\n  };\n\n  const area = areaFor(box);\n  const rect = view ? { left: view.x + box.x * view.w, top: view.y + box.y * view.h, width: box.w * view.w, height: box.h * view.h } : null;\n\n  return (\n    <div className={cn(\"relative inline-flex flex-col gap-2\", className)} style={{ width, maxWidth: \"100%\", fontFamily: \"Inter, sans-serif\", opacity: disabled ? 0.5 : 1 }}>\n      {label && (\n        <span id={`${uid}-label`} className=\"font-semibold tracking-[-0.01em]\" style={{ color: p.text, fontSize: s.font }}>\n          {label}\n        </span>\n      )}\n\n      <div\n        ref={stageRef}\n        onPointerMove={onPointerMove}\n        onPointerUp={onPointerUp}\n        onPointerCancel={onPointerUp}\n        onDragOver={(e) => {\n          e.preventDefault();\n          setDropHover(true);\n        }}\n        onDragLeave={() => setDropHover(false)}\n        onDrop={(e) => {\n          e.preventDefault();\n          setDropHover(false);\n          loadFile(e.dataTransfer.files[0]);\n        }}\n        className=\"relative overflow-hidden select-none\"\n        style={{ height, borderRadius: s.radius, background: p.stage, border: `1px solid ${dropHover ? p.focus : p.border}`, transition: \"border-color 0.18s ease\" }}\n      >\n        {imageSrc ? (\n          <>\n            {/* eslint-disable-next-line @next/next/no-img-element */}\n            <img\n              ref={imgRef}\n              src={imageSrc}\n              alt=\"\"\n              crossOrigin={imageSrc.startsWith(\"data:\") ? undefined : \"anonymous\"}\n              draggable={false}\n              onLoad={onImageLoad}\n              className=\"pointer-events-none absolute\"\n              style={view ? { left: view.x, top: view.y, width: view.w, height: view.h } : { opacity: 0 }}\n            />\n            {rect && (\n              <>\n                {/* Shade outside the crop: one huge box-shadow around the crop hole. */}\n                <div\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute\"\n                  style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height, borderRadius: circle ? \"50%\" : 0, boxShadow: `0 0 0 9999px ${p.shade}`, transition: dragging ? \"none\" : \"left 0.18s ease, top 0.18s ease, width 0.18s ease, height 0.18s ease\" }}\n                />\n                <div\n                  role=\"group\"\n                  tabIndex={disabled ? -1 : 0}\n                  aria-label={`Crop area${area ? `, ${area.width} by ${area.height} pixels` : \"\"}. Arrow keys move it, Shift for bigger steps, Alt with arrows resizes.`}\n                  aria-labelledby={label ? `${uid}-label` : undefined}\n                  data-handle=\"move\"\n                  onPointerDown={onPointerDown}\n                  onKeyDown={onKeyDown}\n                  className=\"absolute outline-none focus-visible:ring-2\"\n                  style={{ left: rect.left, top: rect.top, width: rect.width, height: rect.height, cursor: disabled ? \"default\" : dragging ? \"grabbing\" : \"grab\", border: \"1px solid rgba(255,255,255,0.9)\", borderRadius: circle ? \"50%\" : 0, [\"--tw-ring-color\" as string]: \"rgba(255,255,255,0.9)\", transition: dragging ? \"none\" : \"left 0.18s ease, top 0.18s ease, width 0.18s ease, height 0.18s ease\" }}\n                >\n                  <AnimatePresence>\n                    {dragging && (\n                      <motion.div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0\" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.15 }}>\n                        {[1, 2].map((i) => (\n                          <React.Fragment key={i}>\n                            <span className=\"absolute top-0 bottom-0\" style={{ left: `${(i * 100) / 3}%`, width: 1, background: \"rgba(255,255,255,0.45)\" }} />\n                            <span className=\"absolute right-0 left-0\" style={{ top: `${(i * 100) / 3}%`, height: 1, background: \"rgba(255,255,255,0.45)\" }} />\n                          </React.Fragment>\n                        ))}\n                      </motion.div>\n                    )}\n                  </AnimatePresence>\n                  {!disabled &&\n                    HANDLES.filter((h) => !circle || h.length === 2).map((h) => {\n                      const corner = h.length === 2;\n                      const pos: React.CSSProperties = {\n                        top: h.includes(\"n\") ? -6 : h.includes(\"s\") ? undefined : \"50%\",\n                        bottom: h.includes(\"s\") ? -6 : undefined,\n                        left: h.includes(\"w\") ? -6 : h.includes(\"e\") ? undefined : \"50%\",\n                        right: h.includes(\"e\") ? -6 : undefined,\n                        marginTop: h === \"e\" || h === \"w\" ? -10 : undefined,\n                        marginLeft: h === \"n\" || h === \"s\" ? -10 : undefined,\n                      };\n                      const cursor = { n: \"ns\", s: \"ns\", e: \"ew\", w: \"ew\", ne: \"nesw\", sw: \"nesw\", nw: \"nwse\", se: \"nwse\" }[h];\n                      return (\n                        <span\n                          key={h}\n                          aria-hidden=\"true\"\n                          data-handle={h}\n                          onPointerDown={onPointerDown}\n                          className=\"absolute\"\n                          style={{ ...pos, width: corner ? 12 : h === \"n\" || h === \"s\" ? 20 : 6, height: corner ? 12 : h === \"e\" || h === \"w\" ? 20 : 6, borderRadius: corner ? 3 : 3, background: \"#FFFFFF\", boxShadow: \"0 1px 3px rgba(0,0,0,0.4)\", cursor: `${cursor}-resize`, touchAction: \"none\" }}\n                        />\n                      );\n                    })}\n                </div>\n              </>\n            )}\n          </>\n        ) : (\n          <button\n            type=\"button\"\n            disabled={disabled}\n            onClick={() => fileRef.current?.click()}\n            className=\"flex h-full w-full cursor-pointer flex-col items-center justify-center border-none bg-transparent outline-none focus-visible:ring-2\"\n            style={{ gap: 10, color: p.muted, fontSize: s.font, [\"--tw-ring-color\" as string]: p.focus }}\n          >\n            <svg width=\"28\" height=\"28\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n              <rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"3\" />\n              <circle cx=\"9\" cy=\"10\" r=\"1.8\" />\n              <path d=\"m21 16-5-5-8 9\" />\n            </svg>\n            <span>\n              <span style={{ color: p.text, fontWeight: 600 }}>Choose an image</span> or drop it here\n            </span>\n          </button>\n        )}\n      </div>\n\n      <input ref={fileRef} type=\"file\" accept=\"image/*\" className=\"hidden\" onChange={(e) => loadFile(e.target.files?.[0])} />\n\n      <div className=\"flex flex-wrap items-center justify-between\" style={{ gap: 10 }}>\n        {!circle && aspectOptions.length > 1 ? (\n          <div role=\"radiogroup\" aria-label=\"Aspect ratio\" className=\"relative flex\" style={{ padding: 3, borderRadius: 10, background: p.track }}>\n            {aspectOptions.map((o) => {\n              const on = o.value === aspect;\n              return (\n                <button\n                  key={o.label}\n                  type=\"button\"\n                  role=\"radio\"\n                  aria-checked={on}\n                  disabled={disabled || !imageSrc}\n                  onClick={() => pickAspect(o.value)}\n                  className=\"relative cursor-pointer border-none bg-transparent font-medium outline-none focus-visible:ring-2 disabled:cursor-default\"\n                  style={{ height: s.btn - 8, padding: \"0 11px\", borderRadius: 8, color: on ? p.selText : p.muted, fontSize: s.font - 2, fontVariantNumeric: \"tabular-nums\", [\"--tw-ring-color\" as string]: p.focus }}\n                >\n                  {on && <motion.span layoutId={`${uid}-aspect`} className=\"absolute inset-0\" style={{ borderRadius: 8, background: p.sel }} transition={{ type: \"spring\", stiffness: 500, damping: 36 }} />}\n                  <span className=\"relative\">{o.label}</span>\n                </button>\n              );\n            })}\n          </div>\n        ) : (\n          <span />\n        )}\n        <div className=\"flex items-center\" style={{ gap: 4 }}>\n          {area && (\n            <span style={{ color: p.faint, fontSize: s.font - 2.5, fontVariantNumeric: \"tabular-nums\", marginRight: 6 }} aria-live=\"polite\">\n              {area.width} × {area.height} px\n            </span>\n          )}\n          {imageSrc && (\n            <button\n              type=\"button\"\n              disabled={disabled || !nat}\n              onClick={() => nat && setAndExport(initialBox(nat.w, nat.h, activeAspect))}\n              className=\"cursor-pointer border-none bg-transparent font-medium outline-none focus-visible:ring-2\"\n              style={{ height: s.btn - 4, padding: \"0 10px\", borderRadius: 8, color: p.muted, fontSize: s.font - 2, [\"--tw-ring-color\" as string]: p.focus }}\n              onMouseEnter={(e) => (e.currentTarget.style.background = p.hover)}\n              onMouseLeave={(e) => (e.currentTarget.style.background = \"transparent\")}\n            >\n              Reset\n            </button>\n          )}\n          <button\n            type=\"button\"\n            disabled={disabled}\n            onClick={() => fileRef.current?.click()}\n            className=\"cursor-pointer border-none font-medium outline-none focus-visible:ring-2\"\n            style={{ height: s.btn - 4, padding: \"0 12px\", borderRadius: 8, background: p.track, color: p.text, fontSize: s.font - 2, [\"--tw-ring-color\" as string]: p.focus }}\n          >\n            {imageSrc ? \"Replace\" : \"Choose image\"}\n          </button>\n        </div>\n      </div>\n\n      {helperText && <span style={{ color: p.muted, fontSize: s.font - 1.5, lineHeight: 1.4 }}>{helperText}</span>}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}