{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"animated-beam","type":"registry:block","title":"Animated beam","description":"A live routing diagram where beams of light travel from three sources through a gateway to three destinations, with hover and keyboard inspection.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/animated-beam/animated-beam.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport {\n  MotionConfig,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  Activity,\n  Bell,\n  Code2,\n  Database,\n  Inbox,\n  Network,\n  RotateCcw,\n  type LucideIcon,\n} from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\nconst HUB_KEY = \"__hub\";\n\n/* the travelling light on each connection */\nconst KEYFRAMES = `\n@keyframes prequel-beam-travel {\n  from { stroke-dashoffset: 0; }\n  to { stroke-dashoffset: -1; }\n}\n`;\n\n/* ------------------------------------------------------------------ */\n/* types                                                               */\n/* ------------------------------------------------------------------ */\n\nexport type BeamNode = {\n  id: string;\n  label: string;\n  /** One short sentence about what happens at this node. */\n  detail: string;\n  /** Optional Lucide icon; a plain node reads fine without one. */\n  icon?: LucideIcon;\n  /** Primary value shown in the inspector row. */\n  value: string;\n  /** Small context beneath the value. */\n  meta: string;\n};\n\nexport type AnimatedBeamProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  /** Nodes feeding the gateway, stacked on the left. */\n  sources?: BeamNode[];\n  /** Nodes the gateway fans out to, stacked on the right. */\n  destinations?: BeamNode[];\n  /** Label under the gateway lens. */\n  hubLabel?: string;\n  /** Seconds for one light to cross a connection. Defaults to 3.4. */\n  speed?: number;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data                                             */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_SOURCES: BeamNode[] = [\n  {\n    id: \"ingest\",\n    label: \"Ingest\",\n    detail: \"HTTP and webhook intake, verified at the edge.\",\n    icon: Inbox,\n    value: \"4,218/min\",\n    meta: \"1.4M today\",\n  },\n  {\n    id: \"sdk\",\n    label: \"SDK\",\n    detail: \"Browser and server SDKs sending batched events.\",\n    icon: Code2,\n    value: \"2,906/min\",\n    meta: \"18.2k active keys\",\n  },\n  {\n    id: \"replay\",\n    label: \"Replay\",\n    detail: \"Retries drained from the dead-letter lane.\",\n    icon: RotateCcw,\n    value: \"37/min\",\n    meta: \"0.9% of total\",\n  },\n];\n\nconst DEFAULT_DESTINATIONS: BeamNode[] = [\n  {\n    id: \"warehouse\",\n    label: \"Warehouse\",\n    detail: \"Append-only cold storage, partitioned by day.\",\n    icon: Database,\n    value: \"1.2 ms\",\n    meta: \"p95 · 4.8 TB written\",\n  },\n  {\n    id: \"alerts\",\n    label: \"Alerts\",\n    detail: \"Pager and chat delivery with signed payloads.\",\n    icon: Bell,\n    value: \"38 ms\",\n    meta: \"p95 · 99.98% delivered\",\n  },\n  {\n    id: \"analytics\",\n    label: \"Analytics\",\n    detail: \"Session and funnel rollups for the live boards.\",\n    icon: Activity,\n    value: \"21 ms\",\n    meta: \"p95 · 312 ms lag\",\n  },\n];\n\n/* ------------------------------------------------------------------ */\n/* geometry                                                            */\n/* ------------------------------------------------------------------ */\n\ntype Point = { x: number; y: number };\n\ntype BeamEdge = {\n  id: string;\n  nodeId: string;\n  d: string;\n};\n\nfunction curve(a: Point, b: Point) {\n  const mid = a.x + (b.x - a.x) * 0.5;\n  const x1 = a.x.toFixed(1);\n  const y1 = a.y.toFixed(1);\n  const x2 = b.x.toFixed(1);\n  const y2 = b.y.toFixed(1);\n  const xm = mid.toFixed(1);\n  return `M ${x1} ${y1} C ${xm} ${y1} ${xm} ${y2} ${x2} ${y2}`;\n}\n\n/* ------------------------------------------------------------------ */\n/* the block                                                           */\n/* ------------------------------------------------------------------ */\n\nexport function AnimatedBeam({\n  className,\n  title = \"Event routing\",\n  description = \"Every event, checked once and delivered everywhere.\",\n  sources = DEFAULT_SOURCES,\n  destinations = DEFAULT_DESTINATIONS,\n  hubLabel = \"Router\",\n  speed = 3.4,\n}: AnimatedBeamProps) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const diagramRef = useRef<HTMLDivElement>(null);\n  const nodeEls = useRef<Map<string, HTMLElement>>(new Map());\n  const inView = useInView(rootRef, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n  const headingId = useId();\n\n  const safeSources = sources.length > 0 ? sources : DEFAULT_SOURCES;\n  const safeDestinations =\n    destinations.length > 0 ? destinations : DEFAULT_DESTINATIONS;\n  const safeSpeed = Math.max(1, speed);\n\n  const [edges, setEdges] = useState<BeamEdge[]>([]);\n  const [selectedId, setSelectedId] = useState(\n    () => safeSources[0]?.id ?? safeDestinations[0]?.id ?? \"\",\n  );\n  const [hoverId, setHoverId] = useState<string | null>(null);\n\n  const allNodes = [...safeSources, ...safeDestinations];\n  const activeId = hoverId ?? selectedId;\n  const activeNode =\n    allNodes.find((node) => node.id === activeId) ?? allNodes[0];\n\n  const layoutKey = [\n    ...safeSources.map((node) => node.id),\n    HUB_KEY,\n    ...safeDestinations.map((node) => node.id),\n  ].join(\"|\");\n\n  /* Measure the real DOM nodes so the beams follow the responsive grid. */\n  useEffect(() => {\n    const container = diagramRef.current;\n    if (!container) return;\n\n    let frame = 0;\n\n    const measure = () => {\n      const box = container.getBoundingClientRect();\n      const points = new Map<string, Point>();\n\n      nodeEls.current.forEach((element, id) => {\n        const rect = element.getBoundingClientRect();\n        points.set(id, {\n          x: rect.left - box.left + rect.width / 2,\n          y: rect.top - box.top + rect.height / 2,\n        });\n      });\n\n      const hub = points.get(HUB_KEY);\n      if (!hub) return;\n\n      const next: BeamEdge[] = [];\n      for (const node of safeSources) {\n        const point = points.get(node.id);\n        if (point) {\n          next.push({\n            id: `in-${node.id}`,\n            nodeId: node.id,\n            d: curve(point, hub),\n          });\n        }\n      }\n      for (const node of safeDestinations) {\n        const point = points.get(node.id);\n        if (point) {\n          next.push({\n            id: `out-${node.id}`,\n            nodeId: node.id,\n            d: curve(hub, point),\n          });\n        }\n      }\n\n      setEdges(next);\n    };\n\n    const schedule = () => {\n      window.cancelAnimationFrame(frame);\n      frame = window.requestAnimationFrame(measure);\n    };\n\n    schedule();\n\n    const observer =\n      typeof ResizeObserver === \"undefined\"\n        ? null\n        : new ResizeObserver(schedule);\n    observer?.observe(container);\n    nodeEls.current.forEach((element) => observer?.observe(element));\n    window.addEventListener(\"resize\", schedule);\n\n    return () => {\n      window.cancelAnimationFrame(frame);\n      observer?.disconnect();\n      window.removeEventListener(\"resize\", schedule);\n    };\n  }, [layoutKey, safeSources, safeDestinations]);\n\n  const registerNode = (id: string) => (element: HTMLElement | null) => {\n    if (element) nodeEls.current.set(id, element);\n    else nodeEls.current.delete(id);\n  };\n\n  const rowCount = Math.max(safeSources.length, safeDestinations.length, 1);\n  const hubRow = Math.ceil(rowCount / 2);\n\n  const chip = (node: BeamNode, index: number, side: \"left\" | \"right\") => {\n    const Icon = node.icon;\n    const isActive = activeId === node.id;\n\n    return (\n      <motion.button\n        key={node.id}\n        ref={registerNode(node.id)}\n        type=\"button\"\n        aria-pressed={selectedId === node.id}\n        onClick={() => setSelectedId(node.id)}\n        onPointerEnter={() => setHoverId(node.id)}\n        onPointerLeave={() => setHoverId(null)}\n        onFocus={() => setHoverId(node.id)}\n        onBlur={() => setHoverId(null)}\n        initial={reduce ? false : { opacity: 0 }}\n        animate={reduce || show ? { opacity: 1 } : { opacity: 0 }}\n        transition={{\n          duration: reduce ? 0 : 0.45,\n          delay: reduce ? 0 : 0.12 + index * 0.06,\n          ease: EASE,\n        }}\n        style={{ gridColumn: side === \"left\" ? 1 : 3, gridRow: index + 1 }}\n        className={cn(\n          \"group flex min-w-0 items-center gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors duration-200\",\n          \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card\",\n          side === \"left\" ? \"justify-end text-right\" : \"justify-start\",\n          isActive\n            ? \"border-foreground/25 bg-muted text-foreground\"\n            : \"border-border bg-card text-muted-foreground hover:border-muted-foreground/35 hover:text-foreground\"\n        )}\n      >\n        {Icon ? (\n          <Icon\n            aria-hidden=\"true\"\n            className=\"h-3.5 w-3.5 shrink-0\"\n            strokeWidth={1.6}\n          />\n        ) : null}\n        <span className=\"truncate text-[11.5px] font-medium sm:text-[12px]\">\n          {node.label}\n        </span>\n      </motion.button>\n    );\n  };\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <style>{KEYFRAMES}</style>\n      <motion.div\n        ref={rootRef}\n        initial={reduce ? false : { opacity: 0, y: 14 }}\n        animate={\n          reduce || show ? { opacity: 1, y: 0 } : { opacity: 0, y: 14 }\n        }\n        transition={{ duration: reduce ? 0 : 0.6, ease: EASE }}\n        className={cn(\"w-full text-foreground\", className)}\n      >\n        <section\n          aria-labelledby={headingId}\n          className=\"overflow-hidden rounded-xl border border-border bg-card text-card-foreground\"\n        >\n          <header className=\"flex flex-col gap-2.5 border-b border-border px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5\">\n            <div className=\"min-w-0\">\n              <h2\n                id={headingId}\n                className=\"text-[15px] font-medium tracking-[-0.01em] text-foreground\"\n              >\n                {title}\n              </h2>\n              <p className=\"mt-0.5 text-[12px] leading-relaxed text-muted-foreground\">\n                {description}\n              </p>\n            </div>\n            <span className=\"inline-flex w-fit shrink-0 items-center gap-1.5 rounded-full border border-border bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground\">\n              <span\n                aria-hidden=\"true\"\n                className=\"h-1.5 w-1.5 rounded-full bg-success\"\n              />\n              Live\n            </span>\n          </header>\n\n          <div className=\"px-4 py-5 sm:px-6 sm:py-6\">\n            <div ref={diagramRef} className=\"relative\">\n              <svg\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute inset-0 h-full w-full overflow-visible\"\n                fill=\"none\"\n              >\n                {edges.map((edge, index) => {\n                  const isActive =\n                    activeId === edge.nodeId || hoverId === edge.nodeId;\n                  return (\n                    <g key={edge.id}>\n                      <path\n                        d={edge.d}\n                        stroke=\"currentColor\"\n                        strokeWidth={1.25}\n                        strokeLinecap=\"round\"\n                        className={cn(\n                          \"transition-colors duration-200\",\n                          isActive ? \"text-foreground/45\" : \"text-border\"\n                        )}\n                      />\n                      {reduce ? null : (\n                        <path\n                          d={edge.d}\n                          pathLength={1}\n                          stroke=\"currentColor\"\n                          strokeWidth={2.25}\n                          strokeLinecap=\"round\"\n                          strokeDasharray=\"0.14 0.86\"\n                          className={cn(\n                            \"transition-colors duration-200\",\n                            isActive\n                              ? \"text-foreground\"\n                              : \"text-muted-foreground/40\"\n                          )}\n                          style={{\n                            animation: `prequel-beam-travel ${safeSpeed}s linear infinite`,\n                            animationDelay: `${index * 0.42}s`,\n                          }}\n                        />\n                      )}\n                    </g>\n                  );\n                })}\n              </svg>\n\n              <div\n                className=\"relative grid items-center gap-x-2 gap-y-2.5 sm:gap-x-4\"\n                style={{\n                  gridTemplateColumns: \"minmax(0, 1fr) auto minmax(0, 1fr)\",\n                  gridTemplateRows: `repeat(${rowCount}, minmax(0, auto))`,\n                }}\n              >\n                {safeSources.map((node, index) =>\n                  chip(node, index, \"left\")\n                )}\n\n                <div\n                  className=\"flex flex-col items-center gap-2\"\n                  style={{ gridColumn: 2, gridRow: hubRow }}\n                >\n                  <div\n                    ref={registerNode(HUB_KEY)}\n                    className=\"relative grid h-14 w-14 place-items-center rounded-full border border-border bg-card text-foreground sm:h-16 sm:w-16\"\n                  >\n                    <Network\n                      aria-hidden=\"true\"\n                      className=\"h-5 w-5\"\n                      strokeWidth={1.5}\n                    />\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"absolute -right-1 -top-1 grid h-3 w-3 place-items-center rounded-full border border-border bg-card\"\n                    >\n                      <span className=\"h-1 w-1 translate-x-[0.5px] -translate-y-[0.5px] rounded-full bg-foreground\" />\n                    </span>\n                  </div>\n                  <span className=\"whitespace-nowrap text-[10.5px] font-medium uppercase tracking-[0.12em] text-muted-foreground\">\n                    {hubLabel}\n                  </span>\n                </div>\n\n                {safeDestinations.map((node, index) =>\n                  chip(node, index, \"right\")\n                )}\n              </div>\n            </div>\n\n            {activeNode ? (\n              <div className=\"mt-5 flex flex-col gap-3 border-t border-border pt-4 sm:flex-row sm:items-center sm:justify-between\">\n                <div className=\"flex min-w-0 items-center gap-2.5\">\n                  {activeNode.icon ? (\n                    <span className=\"grid h-8 w-8 shrink-0 place-items-center rounded-lg border border-border bg-muted text-muted-foreground\">\n                      <activeNode.icon\n                        aria-hidden=\"true\"\n                        className=\"h-3.5 w-3.5\"\n                        strokeWidth={1.6}\n                      />\n                    </span>\n                  ) : null}\n                  <div className=\"min-w-0\">\n                    <div className=\"text-[12.5px] font-medium text-foreground\">\n                      {activeNode.label}\n                    </div>\n                    <p className=\"text-[11.5px] leading-relaxed text-muted-foreground\">\n                      {activeNode.detail}\n                    </p>\n                  </div>\n                </div>\n\n                <dl className=\"flex shrink-0 items-center gap-5 sm:text-right\">\n                  <div>\n                    <dt className=\"text-[10.5px] text-muted-foreground\">\n                      Rate\n                    </dt>\n                    <dd className=\"mt-0.5 text-[13px] font-medium tabular-nums text-foreground\">\n                      {activeNode.value}\n                    </dd>\n                  </div>\n                  <div\n                    aria-hidden=\"true\"\n                    className=\"h-7 w-px bg-border\"\n                  />\n                  <div>\n                    <dt className=\"text-[10.5px] text-muted-foreground\">\n                      Context\n                    </dt>\n                    <dd className=\"mt-0.5 text-[13px] font-medium tabular-nums text-foreground\">\n                      {activeNode.meta}\n                    </dd>\n                  </div>\n                </dl>\n              </div>\n            ) : null}\n          </div>\n        </section>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default AnimatedBeam;\n"}]}