{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"infinite-canvas","type":"registry:ui","title":"Infinite Canvas","description":"A bounded moodboard-style canvas on a dotted grid: drag to pan with inertia, scroll or pinch to zoom around the pointer, keyboard friendly.","dependencies":["lucide-react"],"registryDependencies":[],"files":[{"path":"registry/ui/infinite-canvas.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useRef, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\nimport { Minus, Plus, Scan } from \"lucide-react\";\n\nexport interface CanvasItem {\n  id: string;\n  /** Center of the item in world px (0,0 is the middle of the canvas). */\n  x: number;\n  y: number;\n  content: ReactNode;\n}\n\nexport interface InfiniteCanvasProps {\n  items: CanvasItem[];\n  /** World width in px; panning stops at its edges. */\n  worldWidth?: number;\n  /** World height in px. */\n  worldHeight?: number;\n  /** Zoom at first render and on reset. */\n  defaultZoom?: number;\n  minZoom?: number;\n  maxZoom?: number;\n  /** Px between grid dots at 100% zoom. */\n  gridGap?: number;\n  /** Dot radius in px. */\n  dotSize?: number;\n  /** Glide after a flick. */\n  inertia?: boolean;\n  /** Show the zoom buttons. */\n  showControls?: boolean;\n  /** Accessible name for the canvas. */\n  label?: string;\n  className?: string;\n}\n\nconst clamp = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));\n\n/**\n * A bounded, pannable and zoomable board. Drag to pan (with inertia), scroll or pinch to zoom\n * around the pointer, or use arrows / + / - / 0 when focused. The camera lives in refs and is\n * written straight to the DOM, so panning never re-renders React.\n */\nexport function InfiniteCanvas({\n  items,\n  worldWidth = 2400,\n  worldHeight = 1600,\n  defaultZoom = 0.8,\n  minZoom = 0.3,\n  maxZoom = 2.5,\n  gridGap = 24,\n  dotSize = 1.1,\n  inertia = true,\n  showControls = true,\n  label = \"Canvas\",\n  className,\n}: InfiniteCanvasProps) {\n  const root = useRef<HTMLDivElement>(null);\n  const layer = useRef<HTMLDivElement>(null);\n  const zoomText = useRef<HTMLSpanElement>(null);\n  // Camera: pan offset from the viewport center (px) and zoom.\n  const cam = useRef({ x: 0, y: 0, z: defaultZoom });\n  const size = useRef({ w: 0, h: 0 });\n  const raf = useRef(0);\n  const pointers = useRef(new Map<number, { x: number; y: number }>());\n  const drag = useRef({ vx: 0, vy: 0, t: 0, pinch: 0 });\n  const opts = useRef({ worldWidth, worldHeight, minZoom, maxZoom, gridGap, dotSize });\n  useEffect(() => {\n    opts.current = { worldWidth, worldHeight, minZoom, maxZoom, gridGap, dotSize };\n  });\n\n  const apply = () => {\n    const el = root.current;\n    const l = layer.current;\n    if (!el || !l) return;\n    const o = opts.current;\n    const c = cam.current;\n    c.z = clamp(c.z, o.minZoom, o.maxZoom);\n    // Keep the viewport center inside the world.\n    c.x = clamp(c.x, (-o.worldWidth / 2) * c.z, (o.worldWidth / 2) * c.z);\n    c.y = clamp(c.y, (-o.worldHeight / 2) * c.z, (o.worldHeight / 2) * c.z);\n    const ox = size.current.w / 2 + c.x;\n    const oy = size.current.h / 2 + c.y;\n    l.style.transform = `translate3d(${ox}px, ${oy}px, 0) scale(${c.z})`;\n    const g = o.gridGap * c.z;\n    el.style.backgroundSize = `${g}px ${g}px`;\n    el.style.backgroundPosition = `${ox}px ${oy}px`;\n    el.style.setProperty(\"--ic-dot\", `${Math.max(0.6, o.dotSize * Math.sqrt(c.z))}px`);\n    if (zoomText.current) zoomText.current.textContent = `${Math.round(c.z * 100)}%`;\n  };\n\n  /** Zoom to `z`, keeping the screen point (px, py) (relative to the viewport center) fixed. */\n  const zoomAt = (px: number, py: number, z: number) => {\n    const c = cam.current;\n    const nz = clamp(z, opts.current.minZoom, opts.current.maxZoom);\n    c.x = px - ((px - c.x) / c.z) * nz;\n    c.y = py - ((py - c.y) / c.z) * nz;\n    c.z = nz;\n    apply();\n  };\n\n  const stop = () => cancelAnimationFrame(raf.current);\n\n  /** Ease the camera to a target (buttons, keys). */\n  const tween = (to: { x?: number; y?: number; z?: number }, ms = 320) => {\n    stop();\n    const from = { ...cam.current };\n    const target = { x: to.x ?? from.x, y: to.y ?? from.y, z: to.z ?? from.z };\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) ms = 0;\n    const t0 = performance.now();\n    const tick = (now: number) => {\n      const k = ms ? Math.min(1, (now - t0) / ms) : 1;\n      const e = 1 - Math.pow(1 - k, 3);\n      // Interpolate zoom around the viewport center, pan linearly.\n      const z = from.z + (target.z - from.z) * e;\n      cam.current = { x: from.x + (target.x - from.x) * e, y: from.y + (target.y - from.y) * e, z };\n      apply();\n      if (k < 1) raf.current = requestAnimationFrame(tick);\n    };\n    raf.current = requestAnimationFrame(tick);\n  };\n\n  const zoomBy = (f: number) => {\n    const c = cam.current;\n    const z = clamp(c.z * f, opts.current.minZoom, opts.current.maxZoom);\n    tween({ z, x: (c.x / c.z) * z, y: (c.y / c.z) * z });\n  };\n\n  useEffect(() => {\n    const el = root.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([e]) => {\n      size.current = { w: e.contentRect.width, h: e.contentRect.height };\n      apply();\n    });\n    ro.observe(el);\n    // Non-passive so the page does not scroll while zooming the canvas.\n    const onWheel = (e: WheelEvent) => {\n      e.preventDefault();\n      stop();\n      const r = el.getBoundingClientRect();\n      // Pinch on trackpads arrives as ctrl+wheel with small deltas.\n      const k = e.ctrlKey ? 0.01 : 0.0015;\n      const d = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;\n      zoomAt(e.clientX - r.left - r.width / 2, e.clientY - r.top - r.height / 2, cam.current.z * Math.exp(-d * k));\n    };\n    el.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => {\n      ro.disconnect();\n      el.removeEventListener(\"wheel\", onWheel);\n      cancelAnimationFrame(raf.current);\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const onDown = (e: PointerEvent<HTMLDivElement>) => {\n    if ((e.target as Element).closest(\"[data-canvas-ui]\")) return;\n    stop();\n    e.currentTarget.setPointerCapture(e.pointerId);\n    pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n    drag.current = { vx: 0, vy: 0, t: performance.now(), pinch: 0 };\n    e.currentTarget.dataset.grabbing = \"\";\n  };\n\n  const onMove = (e: PointerEvent<HTMLDivElement>) => {\n    const ps = pointers.current;\n    const prev = ps.get(e.pointerId);\n    if (!prev) return;\n    const c = cam.current;\n    if (ps.size === 2) {\n      const other = [...ps.entries()].find(([id]) => id !== e.pointerId)![1];\n      const dist = Math.hypot(e.clientX - other.x, e.clientY - other.y);\n      const r = e.currentTarget.getBoundingClientRect();\n      const mx = (e.clientX + other.x) / 2 - r.left - r.width / 2;\n      const my = (e.clientY + other.y) / 2 - r.top - r.height / 2;\n      if (drag.current.pinch) zoomAt(mx, my, c.z * (dist / drag.current.pinch));\n      drag.current.pinch = dist;\n    } else {\n      const dx = e.clientX - prev.x;\n      const dy = e.clientY - prev.y;\n      const now = performance.now();\n      const dt = Math.max(1, now - drag.current.t);\n      // Smoothed velocity in px/ms for the release glide.\n      drag.current.vx = drag.current.vx * 0.6 + (dx / dt) * 0.4;\n      drag.current.vy = drag.current.vy * 0.6 + (dy / dt) * 0.4;\n      drag.current.t = now;\n      c.x += dx;\n      c.y += dy;\n      apply();\n    }\n    ps.set(e.pointerId, { x: e.clientX, y: e.clientY });\n  };\n\n  const onUp = (e: PointerEvent<HTMLDivElement>) => {\n    const ps = pointers.current;\n    if (!ps.delete(e.pointerId)) return;\n    drag.current.pinch = 0;\n    if (ps.size) return;\n    delete e.currentTarget.dataset.grabbing;\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    if (!inertia || reduce || performance.now() - drag.current.t > 80) return;\n    let { vx, vy } = drag.current;\n    let last = performance.now();\n    const glide = (now: number) => {\n      const dt = now - last;\n      last = now;\n      cam.current.x += vx * dt;\n      cam.current.y += vy * dt;\n      const decay = Math.pow(0.994, dt);\n      vx *= decay;\n      vy *= decay;\n      apply();\n      if (Math.hypot(vx, vy) > 0.02) raf.current = requestAnimationFrame(glide);\n    };\n    raf.current = requestAnimationFrame(glide);\n  };\n\n  const onKey = (e: KeyboardEvent<HTMLDivElement>) => {\n    const c = cam.current;\n    const step = 80;\n    const pan: Record<string, [number, number]> = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] };\n    if (e.key in pan) tween({ x: c.x + pan[e.key][0], y: c.y + pan[e.key][1] }, 200);\n    else if (e.key === \"+\" || e.key === \"=\") zoomBy(1.25);\n    else if (e.key === \"-\" || e.key === \"_\") zoomBy(0.8);\n    else if (e.key === \"0\") tween({ x: 0, y: 0, z: defaultZoom });\n    else return;\n    e.preventDefault();\n  };\n\n  const btn =\n    \"grid size-8 place-items-center rounded-lg text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring [&>svg]:size-4\";\n\n  return (\n    <div\n      ref={root}\n      role=\"region\"\n      aria-roledescription=\"canvas\"\n      aria-label={`${label}. Drag or use arrow keys to pan, scroll or plus and minus to zoom, 0 to reset.`}\n      tabIndex={0}\n      onPointerDown={onDown}\n      onPointerMove={onMove}\n      onPointerUp={onUp}\n      onPointerCancel={onUp}\n      onKeyDown={onKey}\n      className={`relative size-full cursor-grab touch-none select-none overflow-hidden bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring data-[grabbing]:cursor-grabbing ${className ?? \"\"}`}\n      style={{\n        backgroundImage: \"radial-gradient(circle, color-mix(in srgb, var(--foreground) 22%, transparent) var(--ic-dot, 1px), transparent calc(var(--ic-dot, 1px) + .5px))\",\n      }}\n    >\n      <div ref={layer} className=\"absolute left-0 top-0 origin-top-left\">\n        {items.map((it) => (\n          <div key={it.id} className=\"absolute -translate-x-1/2 -translate-y-1/2\" style={{ left: it.x, top: it.y }}>\n            {it.content}\n          </div>\n        ))}\n      </div>\n\n      {showControls && (\n        <div\n          data-canvas-ui\n          className=\"absolute bottom-4 right-4 flex items-center gap-0.5 rounded-xl border border-border bg-card/85 p-1 shadow-lg backdrop-blur\"\n        >\n          <button type=\"button\" aria-label=\"Zoom out\" className={btn} onClick={() => zoomBy(0.8)}>\n            <Minus />\n          </button>\n          <span ref={zoomText} className=\"w-12 text-center font-mono text-xs tabular-nums text-foreground\">\n            {Math.round(defaultZoom * 100)}%\n          </span>\n          <button type=\"button\" aria-label=\"Zoom in\" className={btn} onClick={() => zoomBy(1.25)}>\n            <Plus />\n          </button>\n          <button type=\"button\" aria-label=\"Reset view\" className={btn} onClick={() => tween({ x: 0, y: 0, z: defaultZoom })}>\n            <Scan />\n          </button>\n        </div>\n      )}\n    </div>\n  );\n}\n"}]}