{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"image-crop","type":"registry:component","title":"Image crop","description":"Frame a photo to any aspect and straighten it with a dial: the photo zooms itself just enough that no corner ever shows empty.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/image-crop.tsx","type":"registry:component","content":"// Hairline UI · image-crop · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\n/* ─────────────────────────────────────────────────────────\n * IMAGE CROP: frame it, straighten it, get exact pixels back\n *\n * A fixed window over the photo, the photo moving under it: drag\n * to place it, wheel or pinch to zoom, pick an aspect and the\n * window reshapes. Straighten with the dial and the photo turns\n * under the window while zooming itself just enough that no\n * corner ever shows empty. Every change reports the crop in the\n * image's own pixels; cropImage() turns that into a Blob.\n * ───────────────────────────────────────────────────────── */\n\nimport * as React from \"react\";\nimport { RotateCcw, RotateCw } from \"lucide-react\";\nimport { createSpring, projectInertia, rubberBand, type Spring } from \"./ui-interaction-motion\";\n\nexport interface CropArea {\n  /** Top-left of the crop in the image's own pixels (exact when rotation is 0). */\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n  /** Degrees clockwise the image is turned under the crop, quarter turns included. */\n  rotation: number;\n  /** The crop's centre in the image's own pixels, before rotation. */\n  centerX: number;\n  centerY: number;\n}\n\nexport interface CropAspect {\n  label: string;\n  /** Width over height, or null for the image's own shape. */\n  value: number | null;\n}\n\nexport interface ImageCropProps {\n  src: string;\n  alt: string;\n  aspects?: CropAspect[];\n  /** Index into aspects to start with. */\n  defaultAspect?: number;\n  /** Called with the crop each time a change settles (and once the image has loaded). */\n  onChange?: (area: CropArea) => void;\n  crossOrigin?: \"anonymous\" | \"use-credentials\";\n  maxZoom?: number;\n  labels?: { straighten?: string; rotateLeft?: string; rotateRight?: string; reset?: string; frame?: string };\n  className?: string;\n}\n\nconst ASPECTS: CropAspect[] = [\n  { label: \"Original\", value: null },\n  { label: \"1:1\", value: 1 },\n  { label: \"4:5\", value: 4 / 5 },\n  { label: \"16:9\", value: 16 / 9 },\n];\nconst SNAP = { stiffness: 380, damping: 38 };\nconst DEG = Math.PI / 180;\nconst TICK = 6; // px per degree on the dial\n\n/** The smallest scale at which the image, turned by theta, still covers a W × H window. */\nfunction coverScale(w: number, h: number, W: number, H: number, theta: number) {\n  const c = Math.abs(Math.cos(theta));\n  const s = Math.abs(Math.sin(theta));\n  return Math.max((W * c + H * s) / w, (W * s + H * c) / h);\n}\n\n/** How far the window's centre may sit from the image's centre, in the image's own turned frame. */\nfunction slack(w: number, h: number, W: number, H: number, theta: number, scale: number) {\n  const c = Math.abs(Math.cos(theta));\n  const s = Math.abs(Math.sin(theta));\n  return { u: Math.max(0, (w * scale - (W * c + H * s)) / 2), v: Math.max(0, (h * scale - (W * s + H * c)) / 2) };\n}\n\n/** Keeps a pan inside what the window allows, worked out in the image's frame and turned back. */\nfunction clampPan(px: number, py: number, w: number, h: number, W: number, H: number, theta: number, scale: number) {\n  const cos = Math.cos(theta);\n  const sin = Math.sin(theta);\n  // The window's offset from the image centre is -pan; into the image frame by -theta.\n  let u = -px * cos - py * sin;\n  let v = px * sin - py * cos;\n  const lim = slack(w, h, W, H, theta, scale);\n  u = Math.max(-lim.u, Math.min(lim.u, u));\n  v = Math.max(-lim.v, Math.min(lim.v, v));\n  return { x: -(u * cos - v * sin), y: -(u * sin + v * cos) };\n}\n\n/** Draws the cropped picture into a Blob, at the image's own resolution (or capped by maxSize on the longer side). */\nexport async function cropImage(source: string | HTMLImageElement, area: CropArea, options: { type?: string; quality?: number; maxSize?: number } = {}): Promise<Blob> {\n  const img =\n    typeof source === \"string\"\n      ? await new Promise<HTMLImageElement>((resolve, reject) => {\n          const i = new Image();\n          i.crossOrigin = \"anonymous\";\n          i.onload = () => resolve(i);\n          i.onerror = reject;\n          i.src = source;\n        })\n      : source;\n  const k = options.maxSize ? Math.min(1, options.maxSize / Math.max(area.width, area.height)) : 1;\n  const canvas = document.createElement(\"canvas\");\n  canvas.width = Math.max(1, Math.round(area.width * k));\n  canvas.height = Math.max(1, Math.round(area.height * k));\n  const ctx = canvas.getContext(\"2d\")!;\n  ctx.imageSmoothingQuality = \"high\";\n  ctx.translate(canvas.width / 2, canvas.height / 2);\n  ctx.scale(k, k);\n  ctx.rotate(area.rotation * DEG);\n  ctx.drawImage(img, -area.centerX, -area.centerY);\n  return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(\"The crop couldn’t be encoded.\"))), options.type ?? \"image/jpeg\", options.quality ?? 0.92));\n}\n\nexport function ImageCrop({ src, alt, aspects = ASPECTS, defaultAspect = 0, onChange, crossOrigin, maxZoom = 5, labels, className = \"\" }: ImageCropProps) {\n  const stage = React.useRef<HTMLDivElement>(null);\n  const photo = React.useRef<HTMLImageElement>(null);\n  const dial = React.useRef<HTMLDivElement>(null);\n  const dialText = React.useRef<HTMLSpanElement>(null);\n  const [aspect, setAspect] = React.useState(defaultAspect);\n  const [natural, setNatural] = React.useState<{ w: number; h: number; src: string } | null>(null);\n  const [size, setSize] = React.useState({ w: 0, h: 0 });\n  const [busy, setBusy] = React.useState(false);\n  const [quarter, setQuarter] = React.useState(0);\n  const st = React.useRef({ w: 1, h: 1, W: 1, H: 1, fine: 0, quarter: 0, settle: 0, src: \"\" });\n  const springs = React.useRef<{ x: Spring; y: Spring; z: Spring } | null>(null);\n  const changed = React.useRef(onChange);\n  React.useLayoutEffect(() => {\n    changed.current = onChange;\n  });\n\n  // The window: as large as fits the stage at the chosen aspect.\n  const ratio = aspects[aspect]?.value ?? (natural ? (quarter % 2 ? natural.h / natural.w : natural.w / natural.h) : 1);\n  const pad = 24;\n  const fitW = Math.max(1, Math.min(size.w - pad * 2, (size.h - pad * 2) * ratio));\n  const fitH = fitW / ratio;\n\n  const theta = () => (st.current.quarter * 90 + st.current.fine) * DEG;\n\n  const paint = React.useCallback(() => {\n    const sp = springs.current;\n    if (!sp || !photo.current) return;\n    const { w, h, fine, quarter: q } = st.current;\n    photo.current.style.width = `${w}px`;\n    photo.current.style.height = `${h}px`;\n    photo.current.style.transform = `translate(-50%, -50%) translate3d(${sp.x.get()}px, ${sp.y.get()}px, 0) rotate(${q * 90 + fine}deg) scale(${sp.z.get()})`;\n    if (dial.current) dial.current.style.transform = `translateX(${-fine * TICK}px)`;\n    if (dialText.current) dialText.current.textContent = `${fine > 0 ? \"+\" : fine < 0 ? \"−\" : \"\"}${Math.abs(fine).toFixed(1)}°`;\n  }, []);\n\n  const report = React.useCallback(() => {\n    const sp = springs.current;\n    if (!sp) return;\n    const { w, h, W, H } = st.current;\n    const t = theta();\n    const z = sp.z.getTarget();\n    const px = sp.x.getTarget();\n    const py = sp.y.getTarget();\n    const u = (-px * Math.cos(t) - py * Math.sin(t)) / z;\n    const v = (px * Math.sin(t) - py * Math.cos(t)) / z;\n    const width = W / z;\n    const height = H / z;\n    const centerX = w / 2 + u;\n    const centerY = h / 2 + v;\n    changed.current?.({ x: centerX - width / 2, y: centerY - height / 2, width, height, rotation: st.current.quarter * 90 + st.current.fine, centerX, centerY });\n  }, []);\n\n  /** Re-fits zoom and pan to the window after anything changed, animated unless told otherwise. */\n  const settle = React.useCallback(\n    (animate = true) => {\n      const sp = springs.current;\n      if (!sp) return;\n      const { w, h, W, H } = st.current;\n      const t = theta();\n      const min = coverScale(w, h, W, H, t);\n      const z = Math.max(min, Math.min(min * maxZoom, sp.z.getTarget()));\n      const p = clampPan(sp.x.getTarget(), sp.y.getTarget(), w, h, W, H, t, z);\n      if (animate) {\n        sp.z.set(z);\n        sp.x.set(p.x);\n        sp.y.set(p.y);\n      } else {\n        sp.z.jump(z);\n        sp.x.jump(p.x);\n        sp.y.jump(p.y);\n      }\n      report();\n    },\n    [maxZoom, report],\n  );\n\n  // Measure the stage.\n  React.useEffect(() => {\n    const el = stage.current;\n    if (!el) return;\n    const ro = new ResizeObserver(() => setSize((s) => (s.w === el.clientWidth && s.h === el.clientHeight ? s : { w: el.clientWidth, h: el.clientHeight })));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  // A new image starts covered, centred, unturned.\n  const loaded = React.useCallback((img: HTMLImageElement) => {\n    // Once per picture: the attach check and onLoad can both see a cached image.\n    if (st.current.src === img.src) return;\n    st.current.src = img.src;\n    st.current.w = img.naturalWidth;\n    st.current.h = img.naturalHeight;\n    st.current.fine = 0;\n    st.current.quarter = 0;\n    // A new picture starts from rest, not from the last one's zoom and place.\n    springs.current?.z.jump(1);\n    springs.current?.x.jump(0);\n    springs.current?.y.jump(0);\n    setQuarter(0);\n    setNatural((n) => (n && n.w === img.naturalWidth && n.h === img.naturalHeight && n.src === img.src ? n : { w: img.naturalWidth, h: img.naturalHeight, src: img.src }));\n  }, []);\n  const onLoad = (event: React.SyntheticEvent<HTMLImageElement>) => loaded(event.currentTarget);\n  // A server-rendered photo can finish loading before React attaches onLoad; catch that when the element arrives.\n  const photoRef = React.useCallback(\n    (img: HTMLImageElement | null) => {\n      photo.current = img;\n      if (img?.complete && img.naturalWidth) loaded(img);\n    },\n    [loaded],\n  );\n\n\n  // The window changed size (aspect, stage, quarter turn): keep the picture covering it.\n  React.useEffect(() => {\n    if (!natural || !size.w) return;\n    st.current.W = fitW;\n    st.current.H = fitH;\n    springs.current ??= { x: createSpring(0, SNAP, paint, 0.05), y: createSpring(0, SNAP, paint, 0.05), z: createSpring(1, SNAP, paint, 0.0005) };\n    const first = springs.current.z.getTarget() === 1 && springs.current.x.getTarget() === 0;\n    if (first) springs.current.z.jump(coverScale(natural.w, natural.h, fitW, fitH, theta()));\n    settle(!first);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [natural, fitW, fitH, settle]);\n\n  /* ── gestures ─────────────────────────────────────────── */\n\n  const g = React.useRef({ points: new Map<number, { x: number; y: number }>(), x0: 0, y0: 0, px: 0, py: 0, z: 1, dist: 0, samples: [] as { x: number; y: number; t: number }[] });\n\n  const zoomTo = (z: number, cx: number, cy: number, animate: boolean) => {\n    const sp = springs.current;\n    if (!sp) return;\n    const { w, h, W, H } = st.current;\n    const t = theta();\n    const min = coverScale(w, h, W, H, t);\n    const z0 = sp.z.getTarget();\n    const z1 = Math.max(min, Math.min(min * maxZoom, z));\n    // Keep the point under the pointer still: offsets are measured from the stage centre.\n    const nx = sp.x.getTarget() + (cx - sp.x.getTarget()) * (1 - z1 / z0);\n    const ny = sp.y.getTarget() + (cy - sp.y.getTarget()) * (1 - z1 / z0);\n    const p = clampPan(nx, ny, w, h, W, H, t, z1);\n    if (animate) {\n      sp.z.set(z1);\n      sp.x.set(p.x);\n      sp.y.set(p.y);\n    } else {\n      sp.z.jump(z1);\n      sp.x.jump(p.x);\n      sp.y.jump(p.y);\n    }\n  };\n\n  // Wheel zooms at the pointer; a quiet moment afterwards reports the crop.\n  React.useEffect(() => {\n    const el = stage.current;\n    if (!el) return;\n    const wheel = (event: WheelEvent) => {\n      event.preventDefault();\n      const r = el.getBoundingClientRect();\n      const z = springs.current?.z.getTarget() ?? 1;\n      zoomTo(z * Math.exp(-event.deltaY * (event.ctrlKey ? 0.01 : 0.002)), event.clientX - r.left - r.width / 2, event.clientY - r.top - r.height / 2, false);\n      window.clearTimeout(st.current.settle);\n      st.current.settle = window.setTimeout(report, 220);\n    };\n    el.addEventListener(\"wheel\", wheel, { passive: false });\n    return () => el.removeEventListener(\"wheel\", wheel);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [report]);\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    const sp = springs.current;\n    if (!sp) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const s = g.current;\n    s.points.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    s.px = sp.x.get();\n    s.py = sp.y.get();\n    s.z = sp.z.get();\n    sp.x.jump(s.px);\n    sp.y.jump(s.py);\n    if (s.points.size === 2) {\n      const [a, b] = [...s.points.values()];\n      s.dist = Math.hypot(a.x - b.x, a.y - b.y);\n      s.x0 = (a.x + b.x) / 2;\n      s.y0 = (a.y + b.y) / 2;\n    } else {\n      s.x0 = event.clientX;\n      s.y0 = event.clientY;\n    }\n    s.samples = [{ x: event.clientX, y: event.clientY, t: event.timeStamp }];\n    setBusy(true);\n  };\n\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const sp = springs.current;\n    const s = g.current;\n    if (!sp || !s.points.has(event.pointerId)) return;\n    s.points.set(event.pointerId, { x: event.clientX, y: event.clientY });\n    const { w, h, W, H } = st.current;\n    const t = theta();\n    if (s.points.size >= 2) {\n      const [a, b] = [...s.points.values()];\n      const r = stage.current!.getBoundingClientRect();\n      const mx = (a.x + b.x) / 2;\n      const my = (a.y + b.y) / 2;\n      const min = coverScale(w, h, W, H, t);\n      const z = Math.max(min * 0.9, Math.min(min * maxZoom * 1.1, (s.z * Math.hypot(a.x - b.x, a.y - b.y)) / Math.max(1, s.dist)));\n      const cx = s.x0 - r.left - r.width / 2;\n      const cy = s.y0 - r.top - r.height / 2;\n      sp.z.jump(z);\n      sp.x.jump(s.px + (cx - s.px) * (1 - z / s.z) + (mx - s.x0));\n      sp.y.jump(s.py + (cy - s.py) * (1 - z / s.z) + (my - s.y0));\n      return;\n    }\n    s.samples.push({ x: event.clientX, y: event.clientY, t: event.timeStamp });\n    while (s.samples.length > 2 && event.timeStamp - s.samples[0].t > 100) s.samples.shift();\n    const want = { x: s.px + event.clientX - s.x0, y: s.py + event.clientY - s.y0 };\n    const z = sp.z.get();\n    const inside = clampPan(want.x, want.y, w, h, W, H, t, z);\n    // Past the edge it gives, it doesn't stop.\n    sp.x.jump(inside.x + rubberBand(want.x - inside.x, W));\n    sp.y.jump(inside.y + rubberBand(want.y - inside.y, H));\n  };\n\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const sp = springs.current;\n    const s = g.current;\n    if (!sp || !s.points.has(event.pointerId)) return;\n    s.points.delete(event.pointerId);\n    if (s.points.size) {\n      const [p] = [...s.points.values()];\n      s.x0 = p.x;\n      s.y0 = p.y;\n      s.px = sp.x.get();\n      s.py = sp.y.get();\n      s.z = sp.z.get();\n      return;\n    }\n    const first = s.samples[0];\n    const end = s.samples[s.samples.length - 1];\n    const fresh = event.timeStamp - end.t < 100;\n    const span = Math.max(1, end.t - first.t);\n    sp.x.set(projectInertia(sp.x.get(), fresh ? (end.x - first.x) / span : 0, 0.2));\n    sp.y.set(projectInertia(sp.y.get(), fresh ? (end.y - first.y) / span : 0, 0.2));\n    settle();\n    setBusy(false);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const sp = springs.current;\n    if (!sp) return;\n    const step = event.shiftKey ? 40 : 10;\n    const move = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] }[event.key];\n    if (move) {\n      event.preventDefault();\n      sp.x.set(sp.x.getTarget() + move[0]);\n      sp.y.set(sp.y.getTarget() + move[1]);\n      settle();\n    } else if (event.key === \"+\" || event.key === \"=\" || event.key === \"-\") {\n      event.preventDefault();\n      zoomTo(sp.z.getTarget() * (event.key === \"-\" ? 1 / 1.25 : 1.25), 0, 0, true);\n      report();\n    }\n  };\n\n  /* ── straighten dial ──────────────────────────────────── */\n\n  const dialDrag = React.useRef({ on: false, x: 0, from: 0 });\n  const setFine = (deg: number) => {\n    // A soft detent at level.\n    const d = Math.abs(deg) < 0.6 ? 0 : Math.max(-45, Math.min(45, deg));\n    st.current.fine = Math.round(d * 10) / 10;\n    settle(false);\n    paint();\n  };\n  const onDialDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    dialDrag.current = { on: true, x: event.clientX, from: st.current.fine };\n    setBusy(true);\n  };\n  const onDialMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!dialDrag.current.on) return;\n    setFine(dialDrag.current.from - (event.clientX - dialDrag.current.x) / TICK);\n  };\n  const onDialUp = () => {\n    if (!dialDrag.current.on) return;\n    dialDrag.current.on = false;\n    setBusy(false);\n    report();\n  };\n  const onDialKey = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const step = event.shiftKey ? 5 : 0.5;\n    const next = { ArrowLeft: st.current.fine - step, ArrowRight: st.current.fine + step, ArrowDown: st.current.fine - step, ArrowUp: st.current.fine + step, Home: 0 }[event.key];\n    if (next === undefined) return;\n    event.preventDefault();\n    setFine(next);\n    report();\n  };\n\n  const turn = (dir: 1 | -1) => {\n    st.current.quarter = (st.current.quarter + dir + 4) % 4;\n    setQuarter(st.current.quarter);\n    settle();\n  };\n  const reset = () => {\n    st.current.fine = 0;\n    st.current.quarter = 0;\n    setQuarter(0);\n    if (springs.current) {\n      springs.current.z.set(0.0001);\n      springs.current.x.set(0);\n      springs.current.y.set(0);\n    }\n    settle();\n  };\n\n  const ticks = React.useMemo(() => Array.from({ length: 91 }, (_, i) => i - 45), []);\n  const action = \"grid size-8 cursor-pointer place-items-center rounded-full text-muted-foreground transition-[background-color,color,scale] duration-150 hover:bg-accent hover:text-foreground active:scale-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\n\n  return (\n    <div className={`flex [:where(&)]:w-full flex-col gap-3 ${className}`}>\n      <div\n        ref={stage}\n        role=\"group\"\n        tabIndex={0}\n        aria-label={`${alt}. ${labels?.frame ?? \"Drag to place, scroll or pinch to zoom; arrow keys move, plus and minus zoom.\"}`}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={onPointerUp}\n        onPointerCancel={onPointerUp}\n        onKeyDown={onKeyDown}\n        className=\"relative aspect-[4/3] w-full cursor-grab touch-none overflow-clip rounded-[18px] bg-muted outline-none select-none active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring/60\"\n      >\n        {/* eslint-disable-next-line @next/next/no-img-element */}\n        <img\n          ref={photoRef}\n          key={src}\n          src={src}\n          alt=\"\"\n          crossOrigin={crossOrigin}\n          onLoad={onLoad}\n          draggable={false}\n          className=\"pointer-events-none absolute top-1/2 left-1/2 max-w-none origin-center will-change-transform\"\n          style={{ opacity: natural ? 1 : 0, transition: \"opacity 300ms ease-out\" }}\n        />\n        {/* The window: everything outside it is dimmed; thirds show while you adjust. */}\n        <div\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-[4px] ring-1 ring-background/90\"\n          style={{\n            width: fitW,\n            height: fitH,\n            boxShadow: \"0 0 0 9999px color-mix(in oklab, var(--background) 62%, transparent)\",\n            transition: \"width 360ms cubic-bezier(0.16,1,0.3,1), height 360ms cubic-bezier(0.16,1,0.3,1)\",\n          }}\n        >\n          <div className=\"absolute inset-0 transition-opacity duration-300\" style={{ opacity: busy ? 1 : 0 }}>\n            {[1, 2].map((n) => (\n              <React.Fragment key={n}>\n                <span className=\"absolute inset-y-0 w-px bg-background/70\" style={{ left: `${(n * 100) / 3}%` }} />\n                <span className=\"absolute inset-x-0 h-px bg-background/70\" style={{ top: `${(n * 100) / 3}%` }} />\n              </React.Fragment>\n            ))}\n          </div>\n        </div>\n      </div>\n\n      <div className=\"flex flex-col gap-1\">\n        <div className=\"flex items-center justify-between px-0.5 text-[12px] text-muted-foreground\">\n          <span>{labels?.straighten ?? \"Straighten\"}</span>\n          <span ref={dialText} aria-hidden=\"true\" className=\"tabular-nums text-foreground\">\n            0.0°\n          </span>\n        </div>\n        <div\n          role=\"slider\"\n          tabIndex={0}\n          aria-label={labels?.straighten ?? \"Straighten\"}\n          aria-valuemin={-45}\n          aria-valuemax={45}\n          aria-valuenow={0}\n          aria-valuetext=\"Drag or use the arrow keys\"\n          onPointerDown={onDialDown}\n          onPointerMove={onDialMove}\n          onPointerUp={onDialUp}\n          onPointerCancel={onDialUp}\n          onKeyDown={onDialKey}\n          onKeyUp={(e) => e.currentTarget.setAttribute(\"aria-valuenow\", String(st.current.fine))}\n          className=\"relative h-9 cursor-ew-resize touch-none overflow-clip rounded-full outline-none select-none focus-visible:ring-2 focus-visible:ring-ring/50\"\n          style={{ maskImage: \"linear-gradient(90deg, transparent, #000 22%, #000 78%, transparent)\" }}\n        >\n          <div ref={dial} className=\"absolute inset-y-0 left-1/2 will-change-transform\">\n            {ticks.map((d) => (\n              <span\n                key={d}\n                className={`absolute bottom-2 w-px ${d === 0 ? \"h-4 bg-foreground/70\" : d % 5 === 0 ? \"h-3 bg-muted-foreground/70\" : \"h-2 bg-muted-foreground/40\"}`}\n                style={{ left: d * TICK }}\n              />\n            ))}\n          </div>\n          <span aria-hidden=\"true\" className=\"absolute bottom-1.5 left-1/2 h-5 w-[2px] -translate-x-1/2 rounded-full bg-primary\" />\n        </div>\n      </div>\n\n      <div className=\"flex items-center justify-between gap-2\">\n        <div role=\"radiogroup\" aria-label=\"Aspect ratio\" className=\"inline-flex h-8 items-center gap-0.5 rounded-full p-0.5 ring-1 ring-border\">\n          {aspects.map((a, i) => (\n            <button\n              key={a.label}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={aspect === i}\n              onClick={() => setAspect(i)}\n              className={`h-7 cursor-pointer rounded-full px-2.5 text-[12px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 ${aspect === i ? \"bg-accent text-foreground\" : \"text-muted-foreground hover:text-foreground\"}`}\n            >\n              {a.label}\n            </button>\n          ))}\n        </div>\n        <div className=\"flex items-center gap-0.5\">\n          <button type=\"button\" className={action} aria-label={labels?.rotateLeft ?? \"Turn left\"} onClick={() => turn(-1)}>\n            <RotateCcw className=\"size-3.5\" aria-hidden=\"true\" />\n          </button>\n          <button type=\"button\" className={action} aria-label={labels?.rotateRight ?? \"Turn right\"} onClick={() => turn(1)}>\n            <RotateCw className=\"size-3.5\" aria-hidden=\"true\" />\n          </button>\n          <button type=\"button\" className={`${action} w-auto px-2.5 text-[12px] font-medium`} onClick={reset}>\n            {labels?.reset ?? \"Reset\"}\n          </button>\n        </div>\n      </div>\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · image-crop · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/image-crop. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}