{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"particle-text","type":"registry:component","title":"Particle text","description":"A word made of dots that part around your cursor and burst when clicked.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":[],"registryDependencies":["utils"],"files":[{"path":"components/particle-text.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef } from \"react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Sampling pitch in CSS px. Sized for about 1,500 particles in \"LAB\" at this\n// canvas size: dense enough to read as letters, light enough for any phone.\nconst PITCH = 3.6;\nconst DOT = 1.15;\n// Hard cap, so a long word can't balloon the loop.\nconst MAX_PARTICLES = 2400;\n// The cursor pushes particles within this radius, hardest at the centre.\nconst FIELD = 64;\nconst PUSH = 6000;\n// Home springs. A damping ratio of 0.7 lets letters overshoot a touch as they\n// land, which reads as elastic instead of snapping into a grid.\nconst STIFFNESS = 120;\nconst DAMPING_RATIO = 0.7;\n// Each particle's spring is varied by up to this share, so a reassembling\n// word arrives as a swarm instead of one rigid scaling shape.\nconst JITTER = 0.35;\n// Explosion speed range in px/s; a spread keeps the burst from being a ring.\nconst BURST_MIN = 500;\nconst BURST_MAX = 1600;\nconst REST = 0.05;\n// Reduced motion: particles near the pointer fade to this instead of moving.\nconst DIM = 0.3;\nconst BANDS = 4;\n\nfunction bandOf(alpha: number) {\n  return Math.min(BANDS - 1, Math.floor(((alpha - DIM) / (1 - DIM)) * BANDS));\n}\n\nexport function ParticleText({\n  text = \"LAB\",\n  className,\n}: {\n  text?: string;\n  className?: string;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  const wrapRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n\n  useEffect(() => {\n    const wrap = wrapRef.current;\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!wrap || !canvas || !ctx) return;\n\n    // Flat typed arrays keep the per-frame loop allocation free.\n    let count = 0;\n    let homeX = new Float32Array(0);\n    let homeY = new Float32Array(0);\n    let px = new Float32Array(0);\n    let py = new Float32Array(0);\n    let vx = new Float32Array(0);\n    let vy = new Float32Array(0);\n    let stiff = new Float32Array(0);\n    let alpha = new Float32Array(0);\n\n    let width = 0;\n    let height = 0;\n    let color = \"\";\n    let pointer: { x: number; y: number } | null = null;\n    let frameId = 0;\n    let pending = 0;\n    let then = 0;\n    let inView = true;\n    let visible = true;\n    let alive = true;\n\n    const readColor = () => {\n      // Computed colors resolve light-dark(), which a raw custom property doesn't.\n      color = getComputedStyle(canvas).color;\n    };\n\n    // Renders the word on an offscreen canvas at the device's pixel density\n    // and keeps one particle per filled grid cell.\n    const sample = () => {\n      const dpr = window.devicePixelRatio || 1;\n      const off = document.createElement(\"canvas\");\n      off.width = Math.round(width * dpr);\n      off.height = Math.round(height * dpr);\n      const o = off.getContext(\"2d\", { willReadFrequently: true });\n      if (!o || !off.width || !off.height) return;\n      const family = getComputedStyle(wrap).fontFamily;\n      o.scale(dpr, dpr);\n      o.font = `700 100px ${family}`;\n      // Fit the word to 86% of the width and 80% of the height.\n      const measured = o.measureText(text).width || 1;\n      const size = Math.min((width * 0.86 * 100) / measured, height * 0.8);\n      o.font = `700 ${size}px ${family}`;\n      o.textAlign = \"center\";\n      o.textBaseline = \"middle\";\n      o.letterSpacing = `${-size * 0.02}px`;\n      o.fillText(text, width / 2, height / 2 + size * 0.04);\n      const data = o.getImageData(0, 0, off.width, off.height).data;\n\n      const xs: number[] = [];\n      const ys: number[] = [];\n      let pitch = PITCH;\n      // Wider pitch until it fits the cap; one pass for short words.\n      for (;;) {\n        xs.length = 0;\n        ys.length = 0;\n        for (let y = pitch / 2; y < height; y += pitch) {\n          for (let x = pitch / 2; x < width; x += pitch) {\n            const i = (Math.round(y * dpr) * off.width + Math.round(x * dpr)) * 4;\n            if (data[i + 3] > 128) {\n              xs.push(x);\n              ys.push(y);\n            }\n          }\n        }\n        if (xs.length <= MAX_PARTICLES) break;\n        pitch *= 1.15;\n      }\n\n      const next = xs.length;\n      const keep = Math.min(count, next);\n      const nx = new Float32Array(next);\n      const ny = new Float32Array(next);\n      const nvx = new Float32Array(next);\n      const nvy = new Float32Array(next);\n      // Existing particles keep their position and fly to their new home;\n      // new ones start at home so a first paint is already the word.\n      for (let i = 0; i < next; i++) {\n        nx[i] = i < keep ? px[i] : xs[i];\n        ny[i] = i < keep ? py[i] : ys[i];\n        nvx[i] = i < keep ? vx[i] : 0;\n        nvy[i] = i < keep ? vy[i] : 0;\n      }\n      homeX = Float32Array.from(xs);\n      homeY = Float32Array.from(ys);\n      px = nx;\n      py = ny;\n      vx = nvx;\n      vy = nvy;\n      stiff = new Float32Array(next);\n      alpha = new Float32Array(next).fill(1);\n      for (let i = 0; i < next; i++) {\n        stiff[i] = STIFFNESS * (1 - JITTER + Math.random() * JITTER * 2);\n      }\n      count = next;\n    };\n\n    const layout = () => {\n      const dpr = window.devicePixelRatio || 1;\n      width = wrap.clientWidth;\n      height = wrap.clientHeight;\n      canvas.width = Math.round(width * dpr);\n      canvas.height = Math.round(height * dpr);\n      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n      sample();\n    };\n\n    const draw = () => {\n      ctx.clearRect(0, 0, width, height);\n      ctx.fillStyle = color;\n      if (reduce) {\n        // Grouped into four alpha bands, so it's still four fills, not 1,500.\n        for (let band = 0; band < BANDS; band++) {\n          ctx.globalAlpha = DIM + ((1 - DIM) * (band + 1)) / BANDS;\n          ctx.beginPath();\n          for (let i = 0; i < count; i++) {\n            if (bandOf(alpha[i]) !== band) continue;\n            ctx.moveTo(px[i] + DOT, py[i]);\n            ctx.arc(px[i], py[i], DOT, 0, Math.PI * 2);\n          }\n          ctx.fill();\n        }\n        ctx.globalAlpha = 1;\n        return;\n      }\n      // One batched path for the whole word.\n      ctx.beginPath();\n      for (let i = 0; i < count; i++) {\n        ctx.moveTo(px[i] + DOT, py[i]);\n        ctx.arc(px[i], py[i], DOT, 0, Math.PI * 2);\n      }\n      ctx.fill();\n    };\n\n    const step = (now: number) => {\n      // Clamped so a dropped frame can't kick the springs into orbit.\n      const dt = Math.min((now - then) / 1000, 1 / 30);\n      then = now;\n      let moving = false;\n      const p = pointer;\n      for (let i = 0; i < count; i++) {\n        const k = stiff[i];\n        const c = 2 * DAMPING_RATIO * Math.sqrt(k);\n        let ax = k * (homeX[i] - px[i]) - c * vx[i];\n        let ay = k * (homeY[i] - py[i]) - c * vy[i];\n        if (p) {\n          const dx = px[i] - p.x;\n          const dy = py[i] - p.y;\n          const d2 = dx * dx + dy * dy;\n          if (d2 < FIELD * FIELD && d2 > 0.01) {\n            const d = Math.sqrt(d2);\n            // Squared falloff: a soft edge, a firm centre.\n            const f = PUSH * (1 - d / FIELD) ** 2;\n            ax += (dx / d) * f;\n            ay += (dy / d) * f;\n          }\n        }\n        vx[i] += ax * dt;\n        vy[i] += ay * dt;\n        px[i] += vx[i] * dt;\n        py[i] += vy[i] * dt;\n        // With a cursor resting inside, pushed particles settle into balance\n        // away from home, so only speed counts; without one, they must be home.\n        if (\n          !moving &&\n          (Math.abs(vx[i]) > REST ||\n            Math.abs(vy[i]) > REST ||\n            (!p &&\n              (Math.abs(homeX[i] - px[i]) > REST ||\n                Math.abs(homeY[i] - py[i]) > REST)))\n        ) {\n          moving = true;\n        }\n      }\n      draw();\n      // Sleeps once everything is still, and wakes on the next pointer event.\n      frameId = moving && visible ? requestAnimationFrame(step) : 0;\n    };\n\n    const wake = () => {\n      if (frameId || !visible || reduce || !alive) return;\n      then = performance.now();\n      frameId = requestAnimationFrame(step);\n    };\n\n    // Reduced motion: nothing moves; particles near the pointer fade a little.\n    const fade = () => {\n      for (let i = 0; i < count; i++) {\n        let a = 1;\n        if (pointer) {\n          const d = Math.hypot(px[i] - pointer.x, py[i] - pointer.y);\n          a = d < FIELD ? DIM + (1 - DIM) * (d / FIELD) : 1;\n        }\n        alpha[i] = a;\n      }\n      draw();\n    };\n    const fadeSoon = () => {\n      if (pending) return;\n      // One draw per frame at most; pointermove can fire far faster.\n      pending = requestAnimationFrame(() => {\n        pending = 0;\n        fade();\n      });\n    };\n\n    const aim = (e: PointerEvent) => {\n      const box = canvas.getBoundingClientRect();\n      pointer = { x: e.clientX - box.left, y: e.clientY - box.top };\n      if (reduce) fadeSoon();\n      else wake();\n    };\n    const release = () => {\n      pointer = null;\n      if (reduce) fadeSoon();\n      else wake();\n    };\n\n    const burst = (e: MouseEvent) => {\n      if (reduce) return;\n      const box = canvas.getBoundingClientRect();\n      const cx = e.clientX - box.left;\n      const cy = e.clientY - box.top;\n      for (let i = 0; i < count; i++) {\n        const dx = px[i] - cx;\n        const dy = py[i] - cy;\n        const d = Math.hypot(dx, dy) || 1;\n        // Added to the current velocity, so a second click mid-burst adds\n        // energy instead of resetting it.\n        const speed = BURST_MIN + Math.random() * (BURST_MAX - BURST_MIN);\n        // A little sideways scatter keeps it from looking like a clean ring.\n        const spread = (Math.random() - 0.5) * 0.6;\n        vx[i] += ((dx / d) * Math.cos(spread) - (dy / d) * Math.sin(spread)) * speed;\n        vy[i] += ((dx / d) * Math.sin(spread) + (dy / d) * Math.cos(spread)) * speed;\n      }\n      wake();\n    };\n\n    const onMove = (e: PointerEvent) => {\n      // A finger only steers while pressed, which onDown captures.\n      if (e.pointerType === \"touch\" && !canvas.hasPointerCapture(e.pointerId)) {\n        return;\n      }\n      aim(e);\n    };\n    const onDown = (e: PointerEvent) => {\n      if (e.pointerType === \"touch\") {\n        canvas.setPointerCapture(e.pointerId);\n        aim(e);\n      }\n    };\n    const onUp = (e: PointerEvent) => {\n      if (e.pointerType === \"touch\") release();\n    };\n    const onLeave = (e: PointerEvent) => {\n      if (e.pointerType !== \"touch\") release();\n    };\n\n    readColor();\n    layout();\n    draw();\n    // The word is sampled from the page font; resample once it has loaded,\n    // or the first paint would be the fallback face.\n    document.fonts.ready.then(() => {\n      if (!alive) return;\n      layout();\n      if (reduce) fade();\n      else wake();\n      if (!frameId) draw();\n    });\n\n    const resize = new ResizeObserver(() => {\n      layout();\n      if (reduce) fade();\n      else wake();\n      if (!frameId) draw();\n    });\n    resize.observe(wrap);\n\n    // Zooming changes the pixel ratio without resizing the box.\n    let dprQuery: MediaQueryList | null = null;\n    const onDpr = () => {\n      layout();\n      draw();\n      watchDpr();\n    };\n    const watchDpr = () => {\n      dprQuery?.removeEventListener(\"change\", onDpr);\n      dprQuery = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);\n      dprQuery.addEventListener(\"change\", onDpr);\n    };\n    watchDpr();\n\n    const repaint = () =>\n      requestAnimationFrame(() => {\n        readColor();\n        if (!frameId) draw();\n      });\n    const theme = new MutationObserver(repaint);\n    theme.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: [\"data-theme\"],\n    });\n    const scheme = window.matchMedia(\"(prefers-color-scheme: dark)\");\n    scheme.addEventListener(\"change\", repaint);\n\n    // Offscreen or in a hidden tab, the loop stops entirely.\n    const sync = () => {\n      const was = visible;\n      visible = inView && !document.hidden;\n      if (visible && !was) wake();\n      else if (!visible && frameId) {\n        cancelAnimationFrame(frameId);\n        frameId = 0;\n      }\n    };\n    const seen = new IntersectionObserver(([entry]) => {\n      inView = entry.isIntersecting;\n      sync();\n    });\n    seen.observe(wrap);\n    document.addEventListener(\"visibilitychange\", sync);\n\n    canvas.addEventListener(\"pointermove\", onMove);\n    canvas.addEventListener(\"pointerdown\", onDown);\n    canvas.addEventListener(\"pointerup\", onUp);\n    canvas.addEventListener(\"pointercancel\", onUp);\n    canvas.addEventListener(\"pointerleave\", onLeave);\n    canvas.addEventListener(\"click\", burst);\n\n    return () => {\n      alive = false;\n      cancelAnimationFrame(frameId);\n      cancelAnimationFrame(pending);\n      resize.disconnect();\n      theme.disconnect();\n      seen.disconnect();\n      dprQuery?.removeEventListener(\"change\", onDpr);\n      document.removeEventListener(\"visibilitychange\", sync);\n      scheme.removeEventListener(\"change\", repaint);\n      canvas.removeEventListener(\"pointermove\", onMove);\n      canvas.removeEventListener(\"pointerdown\", onDown);\n      canvas.removeEventListener(\"pointerup\", onUp);\n      canvas.removeEventListener(\"pointercancel\", onUp);\n      canvas.removeEventListener(\"pointerleave\", onLeave);\n      canvas.removeEventListener(\"click\", burst);\n    };\n  }, [reduce, text]);\n\n  return (\n    <div\n      ref={wrapRef}\n      className={cn(\n        \"relative h-[240px] w-[min(520px,100%)] overflow-hidden rounded-2xl bg-muted font-sans shadow-raised\",\n        className,\n      )}\n    >\n      {/* touch-none: while a finger is down it scatters the word, so the page\n          shouldn't scroll out from under it. */}\n      <canvas\n        ref={canvasRef}\n        aria-hidden\n        className=\"absolute inset-0 size-full cursor-pointer touch-none text-foreground\"\n      />\n      <span className=\"sr-only\">{text}</span>\n    </div>\n  );\n}\n\nexport default function ParticleTextDemo() {\n  return <ParticleText />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/particle-text"}