{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"animated-beam","type":"registry:component","title":"Animated Beam","description":"Workflow connectors: light pulses travel between any elements along stepped, curved or straight beams, and the beams re-route themselves as your layout responds.","dependencies":["framer-motion"],"files":[{"path":"registry/dot/animated-beam.tsx","type":"registry:component","target":"components/dot/animated-beam.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\";\nimport { motion, useInView, useReducedMotion } from \"framer-motion\";\n\n// ─── Layout registry ─────────────────────────────────────────────────────────\n\ninterface Box {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\ninterface BeamContextValue {\n  register: (id: string, node: HTMLElement | null) => void;\n  boxes: Record<string, Box>;\n  size: { width: number; height: number };\n  /** False when offscreen, so pulses stop costing frames */\n  inView: boolean;\n}\n\nconst BeamContext = createContext<BeamContextValue | null>(null);\n\nfunction useBeamContext(component: string) {\n  const ctx = useContext(BeamContext);\n  if (!ctx) throw new Error(`<${component}> must be placed inside <BeamCanvas>.`);\n  return ctx;\n}\n\nconst half = (n: number) => Math.round(n * 2) / 2;\n\nfunction sameBoxes(a: Record<string, Box>, b: Record<string, Box>) {\n  const keys = Object.keys(b);\n  if (keys.length !== Object.keys(a).length) return false;\n  return keys.every((k) => {\n    const p = a[k];\n    const q = b[k];\n    return p && p.x === q.x && p.y === q.y && p.width === q.width && p.height === q.height;\n  });\n}\n\nexport interface BeamCanvasProps {\n  children: ReactNode;\n  className?: string;\n  style?: CSSProperties;\n}\n\n/**\n * Positioned container for a beam diagram. Measures every <BeamNode> inside it and re-measures\n * whenever the container or a node resizes or the content changes, so beams follow any responsive\n * layout — a row on desktop can become a stack on mobile and the beams re-route themselves.\n */\nexport function BeamCanvas({ children, className, style }: BeamCanvasProps) {\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  const nodes = useRef(new Map<string, HTMLElement>());\n  const observer = useRef<ResizeObserver | null>(null);\n  const frame = useRef(0);\n  const [boxes, setBoxes] = useState<Record<string, Box>>({});\n  const [size, setSize] = useState({ width: 0, height: 0 });\n  const inView = useInView(containerRef, { margin: \"120px\" });\n\n  // Batched to one read per frame, however many observers fire\n  const measure = useCallback(() => {\n    cancelAnimationFrame(frame.current);\n    frame.current = requestAnimationFrame(() => {\n      const container = containerRef.current;\n      if (!container) return;\n      const origin = container.getBoundingClientRect();\n      // Undo any CSS scale on an ancestor (e.g. a shrunken thumbnail): SVG coordinates are unscaled\n      const scale = container.offsetWidth ? origin.width / container.offsetWidth : 1;\n      const next: Record<string, Box> = {};\n      nodes.current.forEach((el, id) => {\n        const r = el.getBoundingClientRect();\n        next[id] = {\n          x: half((r.left - origin.left) / scale),\n          y: half((r.top - origin.top) / scale),\n          width: half(r.width / scale),\n          height: half(r.height / scale),\n        };\n      });\n      setBoxes((prev) => (sameBoxes(prev, next) ? prev : next));\n      setSize((prev) =>\n        prev.width === container.offsetWidth && prev.height === container.offsetHeight\n          ? prev\n          : { width: container.offsetWidth, height: container.offsetHeight }\n      );\n    });\n  }, []);\n\n  const register = useCallback(\n    (id: string, node: HTMLElement | null) => {\n      const previous = nodes.current.get(id);\n      if (previous && previous !== node) observer.current?.unobserve(previous);\n      if (node) {\n        nodes.current.set(id, node);\n        observer.current?.observe(node);\n      } else if (previous) {\n        nodes.current.delete(id);\n      }\n      measure();\n    },\n    [measure]\n  );\n\n  useEffect(() => {\n    const container = containerRef.current;\n    if (!container) return;\n    const resize = new ResizeObserver(measure);\n    observer.current = resize;\n    resize.observe(container);\n    nodes.current.forEach((node) => resize.observe(node));\n    // Nodes can move without resizing when content around them changes\n    const mutations = new MutationObserver(measure);\n    mutations.observe(container, { childList: true, subtree: true });\n    window.addEventListener(\"resize\", measure);\n    document.fonts?.addEventListener(\"loadingdone\", measure);\n    measure();\n    return () => {\n      cancelAnimationFrame(frame.current);\n      resize.disconnect();\n      mutations.disconnect();\n      observer.current = null;\n      window.removeEventListener(\"resize\", measure);\n      document.fonts?.removeEventListener(\"loadingdone\", measure);\n    };\n  }, [measure]);\n\n  const value = useMemo(() => ({ register, boxes, size, inView }), [register, boxes, size, inView]);\n\n  return (\n    <div ref={containerRef} className={className} style={{ position: \"relative\", ...style }}>\n      <BeamContext.Provider value={value}>{children}</BeamContext.Provider>\n    </div>\n  );\n}\n\nexport interface BeamNodeProps {\n  /** Name beams use to connect to this node */\n  id: string;\n  children: ReactNode;\n  className?: string;\n  style?: CSSProperties;\n}\n\n/** Any element a beam can start or end at. Sits above the beams, so lines tuck in behind it. */\nexport function BeamNode({ id, children, className, style }: BeamNodeProps) {\n  const { register } = useBeamContext(\"BeamNode\");\n  const ref = useCallback((node: HTMLDivElement | null) => register(id, node), [register, id]);\n  return (\n    <div ref={ref} className={className} style={{ position: \"relative\", zIndex: 1, ...style }}>\n      {children}\n    </div>\n  );\n}\n\n// ─── Beam ────────────────────────────────────────────────────────────────────\n\nexport type BeamVariant = \"curve\" | \"step\" | \"straight\";\nexport type BeamOrientation = \"auto\" | \"horizontal\" | \"vertical\";\n\ninterface PathOptions {\n  variant: BeamVariant;\n  orientation: BeamOrientation;\n  bend: number;\n  cornerRadius: number;\n}\n\n/** Path between two node centres, plus its end points for the colour gradient */\nfunction beamPath(a: Box, b: Box, { variant, orientation, bend, cornerRadius }: PathOptions) {\n  const x1 = a.x + a.width / 2;\n  const y1 = a.y + a.height / 2;\n  const x2 = b.x + b.width / 2;\n  const y2 = b.y + b.height / 2;\n  const dx = x2 - x1;\n  const dy = y2 - y1;\n  // \"auto\" follows the layout: side-by-side nodes connect horizontally, stacked nodes vertically\n  const vertical = orientation === \"vertical\" || (orientation === \"auto\" && Math.abs(dy) > Math.abs(dx));\n  const ends = { x1, y1, x2, y2 };\n\n  if (variant === \"straight\" || (vertical ? dx === 0 : dy === 0)) {\n    return { d: `M${x1} ${y1} L${x2} ${y2}`, ...ends };\n  }\n\n  if (variant === \"curve\") {\n    // S-curve with tangents along the flow direction, like a node editor\n    const d = vertical\n      ? `M${x1} ${y1} C${x1} ${y1 + dy * bend} ${x2} ${y2 - dy * bend} ${x2} ${y2}`\n      : `M${x1} ${y1} C${x1 + dx * bend} ${y1} ${x2 - dx * bend} ${y2} ${x2} ${y2}`;\n    return { d, ...ends };\n  }\n\n  // Step: out along the flow axis, across at the elbow (placed by `bend`), then in; rounded corners\n  const sx = Math.sign(dx) || 1;\n  const sy = Math.sign(dy) || 1;\n  if (vertical) {\n    const mid = y1 + dy * bend;\n    const r = Math.min(cornerRadius, Math.abs(mid - y1), Math.abs(y2 - mid), Math.abs(dx) / 2);\n    const d = `M${x1} ${y1} L${x1} ${mid - sy * r} Q${x1} ${mid} ${x1 + sx * r} ${mid} L${x2 - sx * r} ${mid} Q${x2} ${mid} ${x2} ${mid + sy * r} L${x2} ${y2}`;\n    return { d, ...ends };\n  }\n  const mid = x1 + dx * bend;\n  const r = Math.min(cornerRadius, Math.abs(mid - x1), Math.abs(x2 - mid), Math.abs(dy) / 2);\n  const d = `M${x1} ${y1} L${mid - sx * r} ${y1} Q${mid} ${y1} ${mid} ${y1 + sy * r} L${mid} ${y2 - sy * r} Q${mid} ${y2} ${mid + sx * r} ${y2} L${x2} ${y2}`;\n  return { d, ...ends };\n}\n\nexport interface BeamProps {\n  /** id of the <BeamNode> the beam starts at */\n  from: string;\n  /** id of the <BeamNode> the beam ends at */\n  to: string;\n  variant?: BeamVariant;\n  /** Which way curves and steps flow; \"auto\" picks from where the nodes sit */\n  orientation?: BeamOrientation;\n  /** Curve tension, or where the step's elbow sits between the nodes (0–1) */\n  bend?: number;\n  /** Corner radius of step beams, in px */\n  cornerRadius?: number;\n  /** Seconds for one pulse to travel the beam */\n  duration?: number;\n  /** Seconds before the first pulse */\n  delay?: number;\n  /** Pulses travelling the beam at once, evenly spaced */\n  pulses?: number;\n  /** Pulse length as a fraction of the beam (0–1) */\n  pulseLength?: number;\n  /** Send pulses from `to` back to `from` */\n  reverse?: boolean;\n  /** Line width in px */\n  thickness?: number;\n  colorFrom?: string;\n  colorTo?: string;\n  /** Colour of the resting line; \"currentColor\" follows the surrounding text colour */\n  trackColor?: string;\n  trackOpacity?: number;\n  /** Soft light around the pulse */\n  glow?: boolean;\n  className?: string;\n}\n\n/**\n * Animated connector between two <BeamNode>s: a faint track with light pulses running along it.\n * With reduced motion the beam is drawn once, fully lit, without movement.\n */\nexport function Beam({\n  from,\n  to,\n  variant = \"step\",\n  orientation = \"auto\",\n  bend = 0.5,\n  cornerRadius = 12,\n  duration = 1.7,\n  delay = 0,\n  pulses = 1,\n  pulseLength = 0.25,\n  reverse = false,\n  thickness = 1,\n  colorFrom = \"#FF5A1F\",\n  colorTo = \"#FFC46B\",\n  trackColor = \"currentColor\",\n  trackOpacity = 0.1,\n  glow = false,\n  className,\n}: BeamProps) {\n  const { boxes, size, inView } = useBeamContext(\"Beam\");\n  const reduceMotion = useReducedMotion() ?? false;\n  const uid = useId().replace(/:/g, \"\");\n  const a = boxes[from];\n  const b = boxes[to];\n  if (!a || !b || !size.width) return null;\n\n  const { d, x1, y1, x2, y2 } = beamPath(a, b, {\n    variant,\n    orientation,\n    bend: Math.min(1, Math.max(0, bend)),\n    cornerRadius,\n  });\n  const gradientId = `beam-gradient-${uid}`;\n  const glowId = `beam-glow-${uid}`;\n  const length = Math.min(1, Math.max(0.02, pulseLength));\n  const count = Math.max(1, Math.round(pulses));\n  // Pulses enter just before the start and leave just past the end\n  const start = reverse ? 1 : -length;\n  const end = reverse ? -length : 1;\n\n  const pulse = (i: number, glowLayer: boolean) => (\n    <motion.path\n      key={`${glowLayer ? \"glow\" : \"core\"}-${i}`}\n      d={d}\n      fill=\"none\"\n      stroke={`url(#${gradientId})`}\n      strokeWidth={glowLayer ? thickness * 3 : thickness}\n      strokeLinecap=\"round\"\n      opacity={glowLayer ? 0.55 : 1}\n      filter={glowLayer ? `url(#${glowId})` : undefined}\n      initial={{ pathLength: length, pathOffset: start }}\n      animate={{ pathOffset: end }}\n      transition={{ duration, delay: delay + (i * duration) / count, ease: \"linear\", repeat: Infinity }}\n    />\n  );\n\n  return (\n    <svg\n      aria-hidden\n      className={className}\n      width={size.width}\n      height={size.height}\n      viewBox={`0 0 ${size.width} ${size.height}`}\n      style={{ position: \"absolute\", inset: 0, overflow: \"visible\", pointerEvents: \"none\", zIndex: 0 }}\n    >\n      <defs>\n        {/* Colour runs from the pulse's starting node to its destination */}\n        <linearGradient id={gradientId} gradientUnits=\"userSpaceOnUse\" x1={x1} y1={y1} x2={x2} y2={y2}>\n          <stop offset=\"0\" stopColor={reverse ? colorTo : colorFrom} />\n          <stop offset=\"1\" stopColor={reverse ? colorFrom : colorTo} />\n        </linearGradient>\n        {glow && (\n          <filter id={glowId} x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\">\n            <feGaussianBlur stdDeviation={thickness * 1.5} />\n          </filter>\n        )}\n      </defs>\n\n      <path d={d} fill=\"none\" stroke={trackColor} strokeOpacity={trackOpacity} strokeWidth={thickness} strokeLinecap=\"round\" />\n\n      {reduceMotion ? (\n        <path d={d} fill=\"none\" stroke={`url(#${gradientId})`} strokeWidth={thickness} strokeLinecap=\"round\" opacity={0.9} />\n      ) : (\n        inView && (\n          // Keyed on the timing so changed settings restart the pulses cleanly\n          <g key={`${duration}-${delay}-${count}-${length}-${reverse}`}>\n            {glow && Array.from({ length: count }, (_, i) => pulse(i, true))}\n            {Array.from({ length: count }, (_, i) => pulse(i, false))}\n          </g>\n        )\n      )}\n    </svg>\n  );\n}\n\n// ─── Ready-made workflow ─────────────────────────────────────────────────────\n\nconst iconProps = {\n  viewBox: \"0 0 24 24\",\n  fill: \"none\",\n  stroke: \"currentColor\",\n  strokeWidth: 1.75,\n  strokeLinecap: \"round\" as const,\n  strokeLinejoin: \"round\" as const,\n  width: \"100%\",\n  height: \"100%\",\n  \"aria-hidden\": true,\n};\n\n/** Built-in icons for the default workflow boxes, and the Dot mark for the hub */\nexport const BeamIcons = {\n  bolt: () => (\n    <svg {...iconProps}>\n      <path d=\"M13 2 4 14h7l-1 8 9-12h-7z\" />\n    </svg>\n  ),\n  form: () => (\n    <svg {...iconProps}>\n      <rect x=\"5\" y=\"3\" width=\"14\" height=\"18\" rx=\"2\" />\n      <path d=\"M9 8h6M9 12h6M9 16h4\" />\n    </svg>\n  ),\n  clock: () => (\n    <svg {...iconProps}>\n      <circle cx=\"12\" cy=\"12\" r=\"9\" />\n      <path d=\"M12 7v5l3 2\" />\n    </svg>\n  ),\n  message: () => (\n    <svg {...iconProps}>\n      <path d=\"M4 5h16v11h-9l-5 4v-4H4z\" />\n    </svg>\n  ),\n  mail: () => (\n    <svg {...iconProps}>\n      <rect x=\"3\" y=\"6\" width=\"18\" height=\"12\" rx=\"1.5\" />\n      <path d=\"m3 7 9 6 9-6\" />\n    </svg>\n  ),\n  database: () => (\n    <svg {...iconProps}>\n      <ellipse cx=\"12\" cy=\"6\" rx=\"7\" ry=\"3\" />\n      <path d=\"M5 6v12c0 1.7 3.1 3 7 3s7-1.3 7-3V6M5 12c0 1.7 3.1 3 7 3s7-1.3 7-3\" />\n    </svg>\n  ),\n  dot: () => (\n    <svg viewBox=\"0 0 88 104\" fill=\"currentColor\" width=\"100%\" height=\"100%\" aria-hidden>\n      <rect x=\"48\" width=\"16\" height=\"95\" />\n      <rect y=\"104\" width=\"16\" height=\"64\" transform=\"rotate(-90 0 104)\" />\n      <path d=\"M16 80H0V60C0 48.9543 8.95431 40 20 40H80V56H20C17.7909 56 16 57.7909 16 60V80Z\" />\n      <rect x=\"72\" y=\"88\" width=\"16\" height=\"16\" rx=\"8\" />\n    </svg>\n  ),\n};\n\nconst DEFAULT_INPUT_ICONS = [BeamIcons.bolt, BeamIcons.form, BeamIcons.clock];\nconst DEFAULT_OUTPUT_ICONS = [BeamIcons.message, BeamIcons.mail, BeamIcons.database];\n\n/** A logo: an image URL, or any element such as an inline SVG or icon component */\nexport type BeamLogo = string | ReactNode;\n\nexport interface BeamWorkflowProps extends Omit<BeamProps, \"from\" | \"to\" | \"delay\" | \"className\"> {\n  /** Logo in the centre box; defaults to the Dot mark */\n  hubLogo?: BeamLogo;\n  /** One logo per input box (left, or top when stacked). Empty entries and \"\" keep the built-in icon. */\n  inputLogos?: (BeamLogo | undefined)[];\n  /** One logo per output box (right, or bottom when stacked) */\n  outputLogos?: (BeamLogo | undefined)[];\n  /** Hub logo height in px */\n  hubSize?: number;\n  /** Other logos' height in px */\n  iconSize?: number;\n  /** Box background */\n  nodeColor?: string;\n  nodeBorderColor?: string;\n  /** Colour of the built-in icons */\n  iconColor?: string;\n  /** Colour of the default Dot mark */\n  hubColor?: string;\n  /** Stack inputs, hub and outputs vertically when narrower than this, in px */\n  stackBelow?: number;\n  /** Seconds before the first pulses */\n  delay?: number;\n  className?: string;\n  style?: CSSProperties;\n}\n\n/**\n * Inputs → hub → outputs, ready to drop in. Every incoming pulse leaves together and reaches the\n * hub at the same moment; the outgoing pulses then leave together and arrive together. Lays out in\n * a row, and stacks vertically in narrow containers, with the beams re-routing to match. Styled\n * inline, so it needs no CSS framework.\n */\nexport function BeamWorkflow({\n  hubLogo,\n  inputLogos,\n  outputLogos,\n  hubSize = 36,\n  iconSize = 20,\n  nodeColor = \"#111114\",\n  nodeBorderColor = \"rgba(255,255,255,0.1)\",\n  iconColor = \"#E4E4E7\",\n  hubColor = \"#FFF9F9\",\n  stackBelow = 576,\n  delay = 0,\n  duration = 1.7,\n  className,\n  style,\n  ...beam\n}: BeamWorkflowProps) {\n  const rootRef = useRef<HTMLDivElement | null>(null);\n  const [stacked, setStacked] = useState(false);\n\n  // Responds to the component's own width, not the window's, so it works in any column or frame\n  useEffect(() => {\n    const node = rootRef.current;\n    if (!node) return;\n    const observer = new ResizeObserver(([entry]) => setStacked(entry.contentRect.width < stackBelow));\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, [stackBelow]);\n\n  const inputs = inputLogos?.length ? inputLogos : DEFAULT_INPUT_ICONS.map(() => undefined);\n  const outputs = outputLogos?.length ? outputLogos : DEFAULT_OUTPUT_ICONS.map(() => undefined);\n  const scale = stacked ? 0.85 : 1;\n\n  const node = (id: string, rawLogo: BeamLogo | undefined, Fallback: () => ReactNode, size: number, ratio: number, color: string) => {\n    const logoSize = size * scale;\n    // An empty string (e.g. a cleared image control in Framer) keeps the built-in icon\n    const logo = typeof rawLogo === \"string\" && !rawLogo.trim() ? undefined : rawLogo;\n    return (\n      <BeamNode\n        key={id}\n        id={id}\n        style={{\n          width: logoSize * ratio,\n          height: logoSize * ratio,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          flexShrink: 0,\n          background: nodeColor,\n          border: `1px solid ${nodeBorderColor}`,\n          color,\n          boxShadow: \"0 10px 24px -12px rgba(0,0,0,0.6)\",\n        }}\n      >\n        {typeof logo === \"string\" ? (\n          // eslint-disable-next-line @next/next/no-img-element -- any image URL the user passes\n          <img src={logo} alt=\"\" style={{ height: logoSize, maxWidth: logoSize * 1.4, objectFit: \"contain\" }} />\n        ) : (\n          <span style={{ display: \"flex\", width: logoSize, height: logoSize }}>{logo ?? <Fallback />}</span>\n        )}\n      </BeamNode>\n    );\n  };\n\n  const column: CSSProperties = { display: \"flex\", flexDirection: stacked ? \"row\" : \"column\", gap: 24 };\n\n  return (\n    <div ref={rootRef} className={className} style={{ width: \"100%\", height: \"100%\", ...style }}>\n      <BeamCanvas style={{ width: \"100%\", height: \"100%\" }}>\n        <div\n          style={{\n            height: \"100%\",\n            display: \"flex\",\n            flexDirection: stacked ? \"column\" : \"row\",\n            alignItems: \"center\",\n            justifyContent: \"center\",\n            gap: stacked ? 48 : \"clamp(48px, 12%, 144px)\",\n            padding: \"40px 24px\",\n            boxSizing: \"border-box\",\n          }}\n        >\n          <div style={column}>\n            {inputs.map((logo, i) =>\n              node(`input-${i}`, logo, DEFAULT_INPUT_ICONS[i % DEFAULT_INPUT_ICONS.length], iconSize, 2.8, iconColor)\n            )}\n          </div>\n          {node(\"hub\", hubLogo, BeamIcons.dot, hubSize, 2.2, hubColor)}\n          <div style={column}>\n            {outputs.map((logo, i) =>\n              node(`output-${i}`, logo, DEFAULT_OUTPUT_ICONS[i % DEFAULT_OUTPUT_ICONS.length], iconSize, 2.8, iconColor)\n            )}\n          </div>\n        </div>\n        {inputs.map((_, i) => (\n          <Beam key={`in-${i}`} from={`input-${i}`} to=\"hub\" {...beam} duration={duration} delay={delay} />\n        ))}\n        {outputs.map((_, i) => (\n          <Beam key={`out-${i}`} from=\"hub\" to={`output-${i}`} {...beam} duration={duration} delay={delay + duration} />\n        ))}\n      </BeamCanvas>\n    </div>\n  );\n}\n"}],"docs":"Animated Beam is ready. Props and a live canvas: https://bydot.co/component/animated-beam","meta":{"tier":"free","category":"Interactive","version":"1.0.0"}}