{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "interactive-skill-cloud",
  "type": "registry:ui",
  "title": "Interactive Skill Cloud",
  "description": "A draggable physics pill cloud powered by matter.js, pills rain down, pile at the bottom, and collide; grab one and fling it.",
  "author": "Aditya Ojha <https://akoder.xyz>",
  "categories": [
    "skills",
    "tags",
    "physics",
    "interactive"
  ],
  "dependencies": [
    "matter-js"
  ],
  "meta": {
    "docs": "https://akoder.xyz/components/interactive-skill-cloud",
    "source": "https://github.com/AdityaKodez/adityaojha/blob/main/components/ui/interactive-skill-cloud.tsx"
  },
  "files": [
    {
      "path": "components/ui/interactive-skill-cloud.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport Matter from \"matter-js\";\nimport {\n  type RefObject,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useSyncExternalStore,\n} from \"react\";\n\nexport interface SkillCloudItem {\n  id: string;\n  name: string;\n  /** Optional icon rendered inside the pill. Any React node works. */\n  icon?: ReactNode;\n}\n\nexport interface InteractiveSkillCloudProps {\n  items: SkillCloudItem[];\n  /** Height of the physics arena in px. */\n  height?: number;\n  /**\n   * Whether pills fall or float. `1` (default) drops them into a pile at\n   * the bottom of the arena. Set it to `0` for a float-and-throw playground\n   * where pills keep their momentum after a fling.\n   */\n  gravity?: number;\n  className?: string;\n  /** Optional overlay or background content rendered inside the arena. */\n  children?: ReactNode;\n}\n\nconst FONT_STACK = \"Geist Mono, ui-monospace, SFMono-Regular, monospace\";\nconst REDUCED_MOTION_QUERY = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeMotionPreference(callback: () => void) {\n  const mediaQuery = window.matchMedia(REDUCED_MOTION_QUERY);\n  mediaQuery.addEventListener(\"change\", callback);\n  return () => mediaQuery.removeEventListener(\"change\", callback);\n}\n\nfunction getAnimationSnapshot() {\n  return !window.matchMedia(REDUCED_MOTION_QUERY).matches;\n}\n\nfunction getAnimationServerSnapshot() {\n  return false;\n}\n\nlet sharedCtx: CanvasRenderingContext2D | null = null;\nconst measureCache = new Map<string, { width: number; height: number }>();\n\n/** Width a pill needs for its icon + label, in px. */\nfunction measureName(name: string): { width: number; height: number } {\n  const cached = measureCache.get(name);\n  if (cached) return cached;\n\n  if (typeof document === \"undefined\") {\n    return { width: 140, height: 34 };\n  }\n\n  if (!sharedCtx) {\n    const canvas = document.createElement(\"canvas\");\n    sharedCtx = canvas.getContext(\"2d\");\n  }\n\n  if (!sharedCtx) {\n    return { width: 140, height: 34 };\n  }\n\n  sharedCtx.font = `600 12px ${FONT_STACK}`;\n  const textWidth = Math.ceil(sharedCtx.measureText(name).width);\n  const result = {\n    // 16px icon + 12px gap + label + 2 * 12px padding\n    width: Math.max(56, 16 + 12 + textWidth + 24),\n    height: 34,\n  };\n  measureCache.set(name, result);\n  return result;\n}\n\nfunction spawnPosition(width: number, height: number, falling: boolean) {\n  return {\n    x: 60 + Math.random() * Math.max(width - 120, 120),\n    y: falling\n      ? 30 + Math.random() * Math.max(height * 0.4, 60)\n      : 40 + Math.random() * Math.max(height - 80, 80),\n  };\n}\n\nexport function InteractiveSkillCloud({\n  items,\n  height = 360,\n  gravity = 1,\n  className,\n  children,\n}: InteractiveSkillCloudProps) {\n  const containerRef = useRef<HTMLDivElement>(null);\n\n  // Enable physics only on the client, and only when the user hasn't asked\n  // for reduced motion. The static cloud is the SSR and a11y fallback.\n  const animated = useSyncExternalStore(\n    subscribeMotionPreference,\n    getAnimationSnapshot,\n    getAnimationServerSnapshot,\n  );\n\n  return (\n    <div\n      ref={containerRef}\n      className={cn(\"relative w-full overflow-hidden\", className)}\n      style={{ height }}\n    >\n      {children}\n      {!animated ? (\n        <div className=\"absolute inset-0 flex flex-wrap content-start gap-2.5 p-4\">\n          {items.map((item) => (\n            <span\n              key={item.id}\n              className=\"inline-flex items-center gap-2 rounded-full border bg-card px-3 py-1.5 font-mono text-xs font-medium text-foreground\"\n            >\n              {item.icon}\n              {item.name}\n            </span>\n          ))}\n        </div>\n      ) : null}\n\n      {animated ? (\n        <PhysicsLayer\n          containerRef={containerRef}\n          items={items}\n          height={height}\n          gravity={gravity}\n        />\n      ) : null}\n    </div>\n  );\n}\n\ninterface PhysicsLayerProps {\n  containerRef: RefObject<HTMLDivElement | null>;\n  items: SkillCloudItem[];\n  height: number;\n  gravity: number;\n}\nfunction PhysicsLayer({\n  containerRef,\n  items,\n  height,\n  gravity,\n}: PhysicsLayerProps) {\n  const pointerRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    const container = containerRef.current;\n    const pointer = pointerRef.current;\n    if (!container || !pointer) {\n      return;\n    }\n\n    const width = container.clientWidth || 640;\n\n    const engine = Matter.Engine.create();\n    engine.gravity.y = gravity;\n    // Chamfered (capsule) bodies compile to compound bodies in matter-js and\n    // oscillate when stacked, so physics runs on plain rectangles. Sleeping\n    // plus extra solver iterations let the pile settle fully still.\n    engine.enableSleeping = true;\n    engine.positionIterations = 10;\n    engine.velocityIterations = 8;\n    const falling = gravity > 0;\n\n    // One rigid body per pill. We store the DOM-measured size so the transform\n    // math stays exact even when a body rotates (bounds inflate under tilt).\n    const pills = items.map((item) => {\n      const dims = measureName(item.name);\n      const pos = spawnPosition(width, height, falling);\n      const body = Matter.Bodies.rectangle(\n        pos.x,\n        pos.y,\n        dims.width,\n        dims.height,\n        {\n          restitution: falling ? 0.05 : 0.9,\n          frictionAir: falling ? 0.015 : 0.04,\n          friction: falling ? 0.6 : 0.02,\n          angle: (Math.random() - 0.5) * 0.2,\n          label: item.id,\n        },\n      );\n      // A little shove so the cloud drifts and bumps on its own.\n      Matter.Body.setVelocity(body, {\n        x: (Math.random() - 0.5) * 1.5,\n        y: (Math.random() - 0.5) * 1.5,\n      });\n      return { body, dims };\n    });\n\n    // Invisible walls keep pills inside the arena with a subtle inner padding.\n    const wall = 64;\n    const padding = 6;\n    const walls = [\n      Matter.Bodies.rectangle(width / 2, -wall / 2 + padding, width + wall * 2, wall, { isStatic: true }),\n      Matter.Bodies.rectangle(width / 2, height + wall / 2 - padding, width + wall * 2, wall, { isStatic: true }),\n      Matter.Bodies.rectangle(-wall / 2 + padding, height / 2, wall, height + wall * 2, { isStatic: true }),\n      Matter.Bodies.rectangle(width + wall / 2 - padding, height / 2, wall, height + wall * 2, { isStatic: true }),\n    ];\n\n    Matter.Composite.add(engine.world, [\n      ...pills.map((p) => p.body),\n      ...walls,\n    ]);\n\n    // Mouse drag + fling. Matter's Mouse binds its own mousemove updates.\n    const mouseConstraint = Matter.MouseConstraint.create(engine, {\n      mouse: Matter.Mouse.create(pointer),\n      constraint: {\n        stiffness: 0.1,\n        damping: 0.15,\n        render: { visible: false },\n      },\n    });\n    Matter.Composite.add(engine.world, mouseConstraint);\n\n    // Keep pills upright and prevent upside-down text flipping.\n    const uprightPills = () => {\n      for (const { body } of pills) {\n        let angle = body.angle % (2 * Math.PI);\n        if (angle > Math.PI) angle -= 2 * Math.PI;\n        if (angle < -Math.PI) angle += 2 * Math.PI;\n\n        // Apply gentle restoring torque towards upright\n        body.torque = -angle * 0.05;\n\n        // Limit tilt angle to max ~45deg so pill labels are always readable\n        const maxAngle = Math.PI / 4;\n        if (Math.abs(angle) > maxAngle) {\n          Matter.Body.setAngle(body, Math.sign(angle) * maxAngle);\n          Matter.Body.setAngularVelocity(body, body.angularVelocity * 0.5);\n        }\n      }\n    };\n\n    // Cache DOM pill elements for fast 60fps transform updates\n    const pillElementMap = new Map<string, HTMLElement>();\n    for (const { body } of pills) {\n      const el = container.querySelector<HTMLElement>(\n        `[data-pill=\"${body.label}\"]`,\n      );\n      if (el) pillElementMap.set(body.label, el);\n    }\n\n    // Move the DOM pills to match their bodies every engine tick.\n    const syncPills = () => {\n      uprightPills();\n      for (const { body, dims } of pills) {\n        const el =\n          pillElementMap.get(body.label) ??\n          container.querySelector<HTMLElement>(`[data-pill=\"${body.label}\"]`);\n        if (!el) continue;\n        if (!pillElementMap.has(body.label)) {\n          pillElementMap.set(body.label, el);\n        }\n        // Translate center of DOM pill to body.position and apply rotation\n        el.style.transform = `translate3d(${body.position.x - dims.width / 2}px, ${body.position.y - dims.height / 2}px, 0) rotate(${body.angle}rad)`;\n      }\n    };\n\n    // Initial position sync on mount\n    syncPills();\n\n    const handleResize = () => {\n      const newWidth = container.clientWidth || 640;\n      Matter.Body.setPosition(walls[0], { x: newWidth / 2, y: -wall / 2 + padding });\n      Matter.Body.setPosition(walls[1], { x: newWidth / 2, y: height + wall / 2 - padding });\n      Matter.Body.setPosition(walls[2], { x: -wall / 2 + padding, y: height / 2 });\n      Matter.Body.setPosition(walls[3], { x: newWidth + wall / 2 - padding, y: height / 2 });\n    };\n\n    const ro = new ResizeObserver(handleResize);\n    ro.observe(container);\n\n    const runner = Matter.Runner.create();\n    let isRunning = false;\n\n    const startRunner = () => {\n      if (!isRunning) {\n        Matter.Runner.run(runner, engine);\n        isRunning = true;\n      }\n    };\n\n    const stopRunner = () => {\n      if (isRunning) {\n        Matter.Runner.stop(runner);\n        isRunning = false;\n      }\n    };\n\n    const io = new IntersectionObserver(\n      (entries) => {\n        const [entry] = entries;\n        if (entry?.isIntersecting) {\n          startRunner();\n        } else {\n          stopRunner();\n        }\n      },\n      { rootMargin: \"100px\" },\n    );\n    io.observe(container);\n\n    Matter.Events.on(engine, \"afterUpdate\", syncPills);\n\n    return () => {\n      io.disconnect();\n      ro.disconnect();\n      Matter.Events.off(engine, \"afterUpdate\", syncPills);\n      stopRunner();\n      Matter.Composite.clear(engine.world, false);\n      Matter.Engine.clear(engine);\n    };\n  }, [containerRef, items, height, gravity]);\n\n  return (\n    <div className=\"absolute inset-0\">\n      <div\n        ref={pointerRef}\n        className=\"absolute inset-0 z-10 h-full w-full cursor-grab active:cursor-grabbing\"\n      />\n      {/* DOM pills — rendered here, moved by physics, inert to events.\n          The overlay above them owns pointer input. */}\n      <div className=\"pointer-events-none absolute inset-0 z-0\">\n        {items.map((item) => {\n          const dims = measureName(item.name);\n          return (\n            <div\n              key={item.id}\n              data-pill={item.id}\n              className=\"absolute left-0 top-0 flex items-center gap-2 rounded-full border bg-card px-3 py-1.5 font-mono text-xs font-medium text-foreground will-change-transform\"\n              style={{\n                width: dims.width,\n                height: dims.height,\n                transformOrigin: \"center\",\n                transform: \"translate3d(-9999px, -9999px, 0)\",\n              }}\n            >\n              {item.icon}\n              <span className=\"truncate\">{item.name}</span>\n            </div>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "docs": "## Installation\n\n```bash\nnpx shadcn@latest add @akoder/interactive-skill-cloud\n```\n\n## Usage\n\n```tsx\nimport { InteractiveSkillCloud } from \"@/components/ui/interactive-skill-cloud\";\nimport { Code2, Zap } from \"lucide-react\";\n\nconst items = [\n  { id: \"react\", name: \"React\", icon: <Code2 className=\"size-4\" /> },\n  { id: \"zap\", name: \"tRPC\", icon: <Zap className=\"size-4\" /> },\n];\n\nexport function TechStack() {\n  return <InteractiveSkillCloud items={items} height={360} />;\n}\n```"
}