{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "repelling-grid",
  "title": "Repelling Grid",
  "description": "An interactive dot-grid background whose dots move away from the cursor.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "packages/repelling-grid/repelling-grid.tsx",
      "content": "\"use client\";\r\n\r\nimport { MotionConfigContext } from \"motion/react\";\r\nimport React, { useEffect, useRef, useCallback, useSyncExternalStore, useContext } from \"react\";\r\nimport { cn } from \"@/lib/utils\";\r\n\r\n/**\r\n * \"user\" (the default) follows a surrounding <MotionConfig reducedMotion>,\r\n * then the visitor's \"reduce motion\" device setting. \"always\" and \"never\"\r\n * force the calm or the full version.\r\n */\r\nexport type ReducedMotion = \"user\" | \"always\" | \"never\";\r\n\r\nconst REDUCED_MOTION_QUERY = \"(prefers-reduced-motion: reduce)\";\r\n\r\nfunction subscribeToReducedMotion(onChange: () => void) {\r\n  const query = window.matchMedia(REDUCED_MOTION_QUERY);\r\n  query.addEventListener(\"change\", onChange);\r\n  return () => query.removeEventListener(\"change\", onChange);\r\n}\r\n\r\n// The prop wins, then MotionConfig, then the device setting. The device is\r\n// read as \"no\" while server rendering, so hydration always matches.\r\nfunction useShouldReduceMotion(mode: ReducedMotion = \"user\") {\r\n  const device = useSyncExternalStore(\r\n    subscribeToReducedMotion,\r\n    () => window.matchMedia(REDUCED_MOTION_QUERY).matches,\r\n    () => false,\r\n  );\r\n  const config = useContext(MotionConfigContext).reducedMotion;\r\n  if (mode !== \"user\") return mode === \"always\";\r\n  if (config === \"always\" || config === \"never\") return config === \"always\";\r\n  return device;\r\n}\r\n\r\n\r\n/**\r\n * Calls onChange(true) while `element` is on screen (or within 200px of it)\r\n * and the tab is showing, and onChange(false) otherwise, so an animation\r\n * loop can sleep while nobody can see it. Returns a function that stops\r\n * watching.\r\n */\r\nfunction watchVisibility(element: Element, onChange: (visible: boolean) => void) {\r\n  let onScreen = true;\r\n  let last: boolean | null = null;\r\n  const update = () => {\r\n    const visible = onScreen && document.visibilityState === \"visible\";\r\n    if (visible !== last) onChange((last = visible));\r\n  };\r\n  const observer =\r\n    typeof IntersectionObserver !== \"undefined\"\r\n      ? new IntersectionObserver(\r\n          ([entry]) => {\r\n            onScreen = entry.isIntersecting;\r\n            update();\r\n          },\r\n          { rootMargin: \"200px\" },\r\n        )\r\n      : null;\r\n  observer?.observe(element);\r\n  document.addEventListener(\"visibilitychange\", update);\r\n  update();\r\n  return () => {\r\n    observer?.disconnect();\r\n    document.removeEventListener(\"visibilitychange\", update);\r\n  };\r\n}\r\n\r\ninterface Dot {\r\n  homeX: number;\r\n  homeY: number;\r\n  x: number;\r\n  y: number;\r\n  baseOpacity: number;\r\n}\r\n\r\ninterface Ripple {\r\n  x: number;\r\n  y: number;\r\n  radius: number;\r\n  maxRadius: number;\r\n  /** Pixels per second, so the ring moves at the same pace at any frame rate. */\r\n  speed: number;\r\n  width: number;\r\n  active: boolean;\r\n}\r\n\r\n// Sizes are tuned for a full-screen background. Smaller containers scale them\r\n// down so a card shows the same field of dots, not a few oversized ones.\r\nconst GRID_SPACING = 45;\r\nconst DOT_RADIUS = 1.5;\r\nconst PUSH_RADIUS = 130;\r\nconst MAX_PUSH_DISTANCE = 45;\r\nconst SPIKE_LINE_OPACITY = 0.85;\r\nconst SPIKE_LINE_WIDTH = 2.5;\r\nconst RIPPLE_SPEED = 900; // px per second\r\nconst RIPPLE_WIDTH = 120;\r\nconst RIPPLE_PUSH = 40;\r\n\r\n/** Containers at least this tall (or wide) get the full-size grid. */\r\nconst REFERENCE_SIZE = 720;\r\nconst MIN_SCALE = 0.45;\r\n\r\ninterface Metrics {\r\n  scale: number;\r\n  spacing: number;\r\n  push: number;\r\n  maxPush: number;\r\n  rippleSpeed: number;\r\n  rippleWidth: number;\r\n  ripplePush: number;\r\n  /** Dots, glows and lines shrink more gently than distances. */\r\n  stroke: number;\r\n}\r\n\r\nfunction getMetrics(w: number, h: number): Metrics {\r\n  const scale = Math.min(1, Math.max(MIN_SCALE, Math.min(w, h) / REFERENCE_SIZE));\r\n  return {\r\n    scale,\r\n    spacing: Math.max(18, GRID_SPACING * scale),\r\n    push: PUSH_RADIUS * scale,\r\n    maxPush: MAX_PUSH_DISTANCE * scale,\r\n    rippleSpeed: RIPPLE_SPEED * scale,\r\n    rippleWidth: RIPPLE_WIDTH * scale,\r\n    ripplePush: RIPPLE_PUSH * scale,\r\n    stroke: 0.6 + 0.4 * scale,\r\n  };\r\n}\r\n\r\ninterface RepellingGridProps extends Omit<React.ComponentProps<\"div\">, \"color\"> {\r\n  /**\r\n   * Content shown over the grid. It fills the grid, so lay it out yourself, for example\r\n   * with flex centring.\r\n   */\r\n  children?: React.ReactNode;\r\n  /**\r\n   * Classes for the wrapper. The grid fills it, so give it a height. Its background shows\r\n   * through the grid.\r\n   */\r\n  className?: string;\r\n  /**\r\n   * Colour of the dots and lines, as any CSS colour, including a theme variable. Pick the\r\n   * colour you would use for text on this background.\r\n   * @default \"currentColor\"\r\n   */\r\n  color?: string;\r\n  /** Multiplies the opacity of dots, lines and glow. Values from 0.5 to 2 work well. @default 1 */\r\n  brightness?: number;\r\n  /**\r\n   * \"user\" follows a surrounding MotionConfig, then the visitor's reduce-motion setting.\r\n   * \"always\" and \"never\" force the calm or the full version.\r\n   */\r\n  reducedMotion?: ReducedMotion;\r\n}\r\n\r\n/**\r\n * The grid invites rapid clicking (each click is a ripple), which the browser\r\n * reads as a double or triple click and answers by selecting text. Cancel\r\n * that, but leave drag-selection and form fields alone.\r\n */\r\nfunction preventMultiClickSelect(e: React.MouseEvent) {\r\n  if (e.detail < 2) return;\r\n  const target = e.target as HTMLElement;\r\n  if (target.closest(\"input, textarea, select, [contenteditable='true']\")) return;\r\n  e.preventDefault();\r\n}\r\n\r\nlet colorProbe: CanvasRenderingContext2D | null | undefined;\r\n\r\n/** Any CSS colour the browser understands, as 0-255 channels, by painting one pixel. */\r\nfunction toRgb(css: string) {\r\n  if (colorProbe === undefined) {\r\n    colorProbe = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\r\n  }\r\n  if (!colorProbe || !css) return { r: 255, g: 255, b: 255 };\r\n  colorProbe.clearRect(0, 0, 1, 1);\r\n  colorProbe.fillStyle = \"#ffffff\";\r\n  colorProbe.fillStyle = css;\r\n  colorProbe.fillRect(0, 0, 1, 1);\r\n  const [r, g, b] = colorProbe.getImageData(0, 0, 1, 1).data;\r\n  return { r, g, b };\r\n}\r\n\r\nconst RepellingGrid = ({\r\n  children,\r\n  className,\r\n  color = \"currentColor\",\r\n  brightness = 1.0,\r\n  reducedMotion = \"user\",\r\n  ref,\r\n  onMouseMove,\r\n  onMouseLeave,\r\n  onMouseDown,\r\n  onClick,\r\n  ...props\r\n}: RepellingGridProps) => {\r\n  const canvasRef = useRef<HTMLCanvasElement>(null);\r\n  const colorRef = useRef<HTMLSpanElement>(null);\r\n  const dotsRef = useRef<Dot[]>([]);\r\n  const ripplesRef = useRef<Ripple[]>([]);\r\n  const animFrameRef = useRef<number>(0);\r\n  const mouseRef = useRef({ x: -9999, y: -9999, active: false });\r\n  const containerRef = useRef<HTMLDivElement>(null);\r\n  /** Size in CSS pixels, and the metrics derived from it. */\r\n  const sizeRef = useRef<{ w: number; h: number; m: Metrics }>({\r\n    w: 0,\r\n    h: 0,\r\n    m: getMetrics(REFERENCE_SIZE, REFERENCE_SIZE),\r\n  });\r\n  // Reduced motion: dots still part around the pointer, but they move there\r\n  // directly instead of drifting, and clicks send out no ripples.\r\n  const reduce = useShouldReduceMotion(reducedMotion);\r\n\r\n  // Brightness multiplier for dot opacity\r\n  const BASE_DOT_OPACITY_MIN = 0.08 * brightness;\r\n  const BASE_DOT_OPACITY_MAX = 0.13 * brightness;\r\n  const PUSH_OPACITY_MULTIPLIER = 0.8 * brightness;\r\n  const RIPPLE_OPACITY_MULTIPLIER = 0.6 * brightness;\r\n  const GLOW_OPACITY_MULTIPLIER = 0.4 * brightness;\r\n\r\n  const initDots = useCallback(\r\n    (width: number, height: number, spacing: number) => {\r\n      const dots: Dot[] = [];\r\n      const cols = Math.ceil(width / spacing) + 2;\r\n      const rows = Math.ceil(height / spacing) + 2;\r\n      const offsetX = (width % spacing) / 2;\r\n      const offsetY = (height % spacing) / 2;\r\n\r\n      for (let r = 0; r < rows; r++) {\r\n        for (let c = 0; c < cols; c++) {\r\n          const x = offsetX + c * spacing;\r\n          const y = offsetY + r * spacing;\r\n          dots.push({\r\n            homeX: x,\r\n            homeY: y,\r\n            x,\r\n            y,\r\n            baseOpacity:\r\n              BASE_DOT_OPACITY_MIN +\r\n              Math.random() * (BASE_DOT_OPACITY_MAX - BASE_DOT_OPACITY_MIN),\r\n          });\r\n        }\r\n      }\r\n      dotsRef.current = dots;\r\n    },\r\n    [BASE_DOT_OPACITY_MIN, BASE_DOT_OPACITY_MAX],\r\n  );\r\n\r\n  const updateMousePosition = useCallback(\r\n    (clientX: number, clientY: number) => {\r\n      const container = containerRef.current;\r\n      if (!container) return;\r\n\r\n      const rect = container.getBoundingClientRect();\r\n      mouseRef.current = {\r\n        x: clientX - rect.left,\r\n        y: clientY - rect.top,\r\n        active: true,\r\n      };\r\n    },\r\n    [],\r\n  );\r\n\r\n  const handleContainerMouseMove = useCallback(\r\n    (e: React.MouseEvent) => {\r\n      updateMousePosition(e.clientX, e.clientY);\r\n    },\r\n    [updateMousePosition],\r\n  );\r\n\r\n  const handleContainerMouseLeave = useCallback(() => {\r\n    mouseRef.current.active = false;\r\n    mouseRef.current.x = -9999;\r\n    mouseRef.current.y = -9999;\r\n  }, []);\r\n\r\n  const handleContainerClick = useCallback((e: React.MouseEvent) => {\r\n    const container = containerRef.current;\r\n    if (!container || reduce) return;\r\n\r\n    const rect = container.getBoundingClientRect();\r\n    const { w, h, m } = sizeRef.current;\r\n    ripplesRef.current.push({\r\n      x: e.clientX - rect.left,\r\n      y: e.clientY - rect.top,\r\n      radius: 0,\r\n      maxRadius: Math.max(w, h) * 1.5,\r\n      speed: m.rippleSpeed,\r\n      width: m.rippleWidth,\r\n      active: true,\r\n    });\r\n  }, [reduce]);\r\n\r\n  useEffect(() => {\r\n    const canvas = canvasRef.current;\r\n    if (!canvas) return;\r\n    const ctx = canvas.getContext(\"2d\");\r\n    if (!ctx) return;\r\n\r\n    let dpr = 1;\r\n\r\n    // Size the canvas to its container so the grid can be used as a contained\r\n    // section background, not only full screen. The backing store follows the\r\n    // screen's pixel density; drawing happens in CSS pixels.\r\n    const resize = () => {\r\n      const rect = canvas.parentElement?.getBoundingClientRect();\r\n      const w = Math.max(1, Math.round(rect?.width ?? window.innerWidth));\r\n      const h = Math.max(1, Math.round(rect?.height ?? window.innerHeight));\r\n      dpr = Math.min(2, window.devicePixelRatio || 1);\r\n      canvas.width = Math.round(w * dpr);\r\n      canvas.height = Math.round(h * dpr);\r\n      canvas.style.width = `${w}px`;\r\n      canvas.style.height = `${h}px`;\r\n      const m = getMetrics(w, h);\r\n      sizeRef.current = { w, h, m };\r\n      initDots(w, h, m.spacing);\r\n    };\r\n\r\n    resize();\r\n    window.addEventListener(\"resize\", resize);\r\n    const observer =\r\n      typeof ResizeObserver !== \"undefined\" && canvas.parentElement\r\n        ? new ResizeObserver(resize)\r\n        : null;\r\n    if (canvas.parentElement) observer?.observe(canvas.parentElement);\r\n\r\n    let last = performance.now();\r\n    let cssColor = \"\";\r\n    let rgb = { r: 255, g: 255, b: 255 };\r\n\r\n    const draw = (now: number) => {\r\n      // Clamp the step so a backgrounded tab doesn't fire a ripple across the\r\n      // whole grid in one frame when it comes back.\r\n      const dt = Math.min(0.05, (now - last) / 1000);\r\n      last = now;\r\n\r\n      // color may be a CSS variable or currentColor, so it is read back from a\r\n      // hidden span every frame, and only re-parsed when the theme changed it.\r\n      const css = colorRef.current ? getComputedStyle(colorRef.current).color : \"\";\r\n      if (css !== cssColor) {\r\n        cssColor = css;\r\n        rgb = toRgb(css);\r\n      }\r\n\r\n      const { w: W, h: H, m } = sizeRef.current;\r\n      const mouse = mouseRef.current;\r\n      const mx = mouse.x;\r\n      const my = mouse.y;\r\n\r\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\r\n      // Transparent: the wrapper's background shows through.\r\n      ctx.clearRect(0, 0, W, H);\r\n\r\n      // --- Update ripples ---\r\n      ripplesRef.current.forEach((ripple) => {\r\n        ripple.radius += ripple.speed * dt;\r\n        if (ripple.radius > ripple.maxRadius) {\r\n          ripple.active = false;\r\n        }\r\n      });\r\n      ripplesRef.current = ripplesRef.current.filter((r) => r.active);\r\n\r\n      const dots = dotsRef.current;\r\n\r\n      type DotInfo = {\r\n        dot: Dot;\r\n        dist: number;\r\n        drawX: number;\r\n        drawY: number;\r\n        push: number;\r\n        rippleGlow: number;\r\n      };\r\n\r\n      const infos: DotInfo[] = dots.map((dot) => {\r\n        const dx = dot.homeX - mx;\r\n        const dy = dot.homeY - my;\r\n        const dist = Math.sqrt(dx * dx + dy * dy);\r\n\r\n        let targetX = dot.homeX;\r\n        let targetY = dot.homeY;\r\n        let push = 0;\r\n\r\n        if (dist < m.push && dist > 0) {\r\n          push = Math.pow(1 - dist / m.push, 1.5);\r\n          const pushAmount = push * m.maxPush;\r\n          const nx = dx / dist;\r\n          const ny = dy / dist;\r\n          targetX = dot.homeX + nx * pushAmount;\r\n          targetY = dot.homeY + ny * pushAmount;\r\n        }\r\n\r\n        let rippleGlow = 0;\r\n        ripplesRef.current.forEach((ripple) => {\r\n          const rdx = dot.homeX - ripple.x;\r\n          const rdy = dot.homeY - ripple.y;\r\n          const rDist = Math.sqrt(rdx * rdx + rdy * rdy);\r\n\r\n          const ringDist = Math.abs(rDist - ripple.radius);\r\n          if (ringDist < ripple.width && rDist > 0) {\r\n            const pushForce = Math.pow(1 - ringDist / ripple.width, 2);\r\n            const pushAmount = pushForce * m.ripplePush;\r\n            const nx = rdx / rDist;\r\n            const ny = rdy / rDist;\r\n            targetX += nx * pushAmount;\r\n            targetY += ny * pushAmount;\r\n            rippleGlow = Math.max(\r\n              rippleGlow,\r\n              pushForce * RIPPLE_OPACITY_MULTIPLIER,\r\n            );\r\n          }\r\n        });\r\n\r\n        const ease = reduce ? 1 : 0.15;\r\n        dot.x += (targetX - dot.x) * ease;\r\n        dot.y += (targetY - dot.y) * ease;\r\n\r\n        return { dot, dist, drawX: dot.x, drawY: dot.y, push, rippleGlow };\r\n      });\r\n\r\n      // --- Draw spike lines ---\r\n      if (mouse.active) {\r\n        ctx.lineCap = \"round\";\r\n        ctx.lineWidth = SPIKE_LINE_WIDTH * m.stroke;\r\n\r\n        infos.forEach(({ drawX, drawY, dist }) => {\r\n          if (dist < m.push) {\r\n            const alpha =\r\n              Math.pow(1 - dist / m.push, 1.5) *\r\n              SPIKE_LINE_OPACITY *\r\n              brightness;\r\n            ctx.strokeStyle = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;\r\n            ctx.beginPath();\r\n            ctx.moveTo(drawX, drawY);\r\n            ctx.lineTo(mx, my);\r\n            ctx.stroke();\r\n          }\r\n        });\r\n      }\r\n\r\n      // --- Draw all dots ---\r\n      infos.forEach(({ dot, drawX, drawY, push, rippleGlow }) => {\r\n        // Combine all opacity factors with brightness multiplier\r\n        const opacity = Math.min(\r\n          1,\r\n          dot.baseOpacity + push * PUSH_OPACITY_MULTIPLIER + rippleGlow,\r\n        );\r\n        const r = (DOT_RADIUS + push * 1.5 + rippleGlow * 1.5) * m.stroke;\r\n\r\n        // Soft glow halo with brightness adjustment\r\n        const glowAmount = Math.max(push, rippleGlow);\r\n        if (glowAmount > 0.01) {\r\n          const glowR = r + glowAmount * 12 * m.stroke;\r\n          const glow = ctx.createRadialGradient(\r\n            drawX,\r\n            drawY,\r\n            0,\r\n            drawX,\r\n            drawY,\r\n            glowR,\r\n          );\r\n          glow.addColorStop(\r\n            0,\r\n            `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${glowAmount * GLOW_OPACITY_MULTIPLIER})`,\r\n          );\r\n          glow.addColorStop(1, `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0)`);\r\n          ctx.beginPath();\r\n          ctx.arc(drawX, drawY, glowR, 0, Math.PI * 2);\r\n          ctx.fillStyle = glow;\r\n          ctx.fill();\r\n        }\r\n\r\n        ctx.beginPath();\r\n        ctx.arc(drawX, drawY, r, 0, Math.PI * 2);\r\n        ctx.fillStyle = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${opacity})`;\r\n        ctx.fill();\r\n      });\r\n\r\n      // --- Cursor center glow with brightness adjustment ---\r\n      if (mouse.active) {\r\n        const bloomR = 30 * m.stroke;\r\n        const bloom = ctx.createRadialGradient(mx, my, 0, mx, my, bloomR);\r\n        bloom.addColorStop(\r\n          0,\r\n          `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${0.15 * brightness})`,\r\n        );\r\n        bloom.addColorStop(1, `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0)`);\r\n        ctx.beginPath();\r\n        ctx.arc(mx, my, bloomR, 0, Math.PI * 2);\r\n        ctx.fillStyle = bloom;\r\n        ctx.fill();\r\n\r\n        ctx.beginPath();\r\n        ctx.arc(mx, my, 2 * m.stroke, 0, Math.PI * 2);\r\n        ctx.fillStyle = `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${Math.min(1, brightness)})`;\r\n        ctx.fill();\r\n      }\r\n\r\n      animFrameRef.current = requestAnimationFrame(draw);\r\n    };\r\n\r\n    // The loop runs only while the grid can be seen: scrolled away or in a\r\n    // hidden tab it stops drawing, and picks up again where it was.\r\n    const stopWatching = watchVisibility(containerRef.current ?? canvas, (visible) => {\r\n      if (visible && !animFrameRef.current) {\r\n        animFrameRef.current = requestAnimationFrame(draw);\r\n      } else if (!visible && animFrameRef.current) {\r\n        cancelAnimationFrame(animFrameRef.current);\r\n        animFrameRef.current = 0;\r\n      }\r\n    });\r\n\r\n    return () => {\r\n      stopWatching();\r\n      cancelAnimationFrame(animFrameRef.current);\r\n      animFrameRef.current = 0;\r\n      window.removeEventListener(\"resize\", resize);\r\n      observer?.disconnect();\r\n    };\r\n  }, [\r\n    initDots,\r\n    brightness,\r\n    reduce,\r\n    PUSH_OPACITY_MULTIPLIER,\r\n    RIPPLE_OPACITY_MULTIPLIER,\r\n    GLOW_OPACITY_MULTIPLIER,\r\n  ]);\r\n\r\n  return (\r\n    <div\r\n      ref={(node) => {\r\n        containerRef.current = node;\r\n        if (typeof ref === \"function\") return ref(node);\r\n        if (ref) ref.current = node;\r\n      }}\r\n      className={cn(\"relative w-full overflow-hidden\", className)}\r\n      onMouseMove={(e) => {\r\n        handleContainerMouseMove(e);\r\n        onMouseMove?.(e);\r\n      }}\r\n      onMouseLeave={(e) => {\r\n        handleContainerMouseLeave();\r\n        onMouseLeave?.(e);\r\n      }}\r\n      onMouseDown={(e) => {\r\n        preventMultiClickSelect(e);\r\n        onMouseDown?.(e);\r\n      }}\r\n      onClick={(e) => {\r\n        handleContainerClick(e);\r\n        onClick?.(e);\r\n      }}\r\n      {...props}\r\n    >\r\n      {/* Resolves color, which may be a variable or currentColor, for the canvas. */}\r\n      <span ref={colorRef} hidden style={{ color }} />\r\n      <canvas\r\n        aria-hidden=\"true\"\r\n        ref={canvasRef}\r\n        className=\"absolute inset-0 pointer-events-none\"\r\n        style={{ display: \"block\" }}\r\n      />\r\n      {children && (\r\n        <div className=\"relative z-10 w-full h-full overflow-y-auto pointer-events-auto\">\r\n          {children}\r\n        </div>\r\n      )}\r\n    </div>\r\n  );\r\n};\r\n\r\nexport default RepellingGrid;\r\n",
      "type": "registry:component",
      "target": "components/satori-ui/repelling-grid.tsx"
    }
  ],
  "meta": {
    "usage": "<RepellingGrid className=\"h-[480px] bg-black text-white\">\n  <div className=\"flex h-full items-center justify-center\">Your content</div>\n</RepellingGrid>"
  },
  "type": "registry:component"
}