{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"beam-connector","type":"registry:component","title":"Beam Connector","description":"A hairline beam between any two elements, routed with rounded right-angle elbows, that carries a pulse of light once per cycle and lands with a flash at the far end.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/beam-connector.tsx","content":"\"use client\";\n\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, RefObject } from \"react\";\n\n/**\n * BeamConnector — a beam of light between any two elements.\n *\n * Draws a hairline between two elements inside a relatively positioned\n * container, routed with rounded right-angle elbows, and sends a pulse of\n * light along it once per cycle that lands with a flash at the far end.\n * Ends are refs or CSS selectors resolved inside the container; stagger\n * several beams with delay to show a request travelling through a system.\n * It measures in layout pixels and re-routes on resize.\n *\n * Part of the Dark Precision kit: OLED black, 1px hairlines, one cool accent\n * used only as light (default #4fd1ff; also mint, amber, white or any\n * #rrggbb). Fonts come from CSS variables with Geist fallbacks. Respects\n * prefers-reduced-motion. No dependencies beyond React.\n */\n\nconst LINE_2 = \"rgba(255,255,255,0.14)\";\n\nconst HEX = /^#[0-9a-fA-F]{6}$/;\n\nexport const DP_ACCENTS = {\n  ice: \"#4fd1ff\",\n  mint: \"#5ef2c1\",\n  amber: \"#ffb45e\",\n  white: \"#f2f4f7\",\n} as const;\n\nfunction own<T extends object>(map: T, key: string): key is Extract<keyof T, string> {\n  return Object.prototype.hasOwnProperty.call(map, key);\n}\n\n/** A named accent or a #rrggbb hex; anything else falls back to ice. */\nfunction accentHex(value: string): string {\n  if (own(DP_ACCENTS, value)) return DP_ACCENTS[value];\n  return HEX.test(value) ? value : DP_ACCENTS.ice;\n}\n\nfunction subscribeMotion(cb: () => void) {\n  const m = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  m.addEventListener(\"change\", cb);\n  return () => m.removeEventListener(\"change\", cb);\n}\n\n/** True when the visitor asked for reduced motion. False on the server. */\nfunction useReducedMotion(): boolean {\n  return useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n// Each part carries only the CSS it needs, so any one of them works on its own.\n// Nothing is interpolated into these sheets; colours arrive as CSS variables.\nconst MOTION_CSS = \"@media (prefers-reduced-motion: reduce){.dp-motion{animation:none!important}}\";\n\nconst PULSE_CSS =\n  \"@keyframes dp-pulse{0%{stroke-dashoffset:var(--d)}30%,100%{stroke-dashoffset:calc(var(--d) - var(--len) - var(--dmax))}}\" +\n  \"@keyframes dp-arrive{0%,27%{opacity:0;transform:scale(.5)}31%{opacity:1;transform:scale(1)}62%,100%{opacity:0;transform:scale(1.9)}}\" +\n  \"@keyframes dp-lit{0%,27%{opacity:0}32%{opacity:1}70%,100%{opacity:0}}\";\n\ntype Pt = { x: number; y: number };\n\nexport type BeamSide = \"left\" | \"right\" | \"top\" | \"bottom\";\n\nfunction portOf(b: { x: number; y: number; w: number; h: number }, side: BeamSide): Pt {\n  if (side === \"left\") return { x: b.x, y: b.y + b.h / 2 };\n  if (side === \"right\") return { x: b.x + b.w, y: b.y + b.h / 2 };\n  if (side === \"top\") return { x: b.x + b.w / 2, y: b.y };\n  return { x: b.x + b.w / 2, y: b.y + b.h };\n}\n\n/** Orthogonal route between two ports with rounded elbows; returns the SVG path and its exact length. */\nfunction elbowPath(a: Pt, b: Pt, from: BeamSide, to: BeamSide, lane: number, radius: number) {\n  const hA = from === \"left\" || from === \"right\";\n  const hB = to === \"left\" || to === \"right\";\n  let pts: Pt[];\n  if (hA && hB) {\n    const mx = a.x + (b.x - a.x) * lane;\n    pts = [a, { x: mx, y: a.y }, { x: mx, y: b.y }, b];\n  } else if (!hA && !hB) {\n    const my = a.y + (b.y - a.y) * lane;\n    pts = [a, { x: a.x, y: my }, { x: b.x, y: my }, b];\n  } else if (hA) pts = [a, { x: b.x, y: a.y }, b];\n  else pts = [a, { x: a.x, y: b.y }, b];\n  const clean: Pt[] = [];\n  for (const p of pts) {\n    const q = clean[clean.length - 1];\n    if (!q || Math.abs(q.x - p.x) > 0.5 || Math.abs(q.y - p.y) > 0.5) clean.push(p);\n  }\n  let d = `M${clean[0].x.toFixed(1)} ${clean[0].y.toFixed(1)}`;\n  let len = 0;\n  let cur = clean[0];\n  for (let i = 1; i < clean.length; i++) {\n    const v = clean[i];\n    const n = clean[i + 1];\n    if (!n) {\n      len += Math.hypot(v.x - cur.x, v.y - cur.y);\n      d += ` L${v.x.toFixed(1)} ${v.y.toFixed(1)}`;\n      break;\n    }\n    const l1 = Math.hypot(v.x - cur.x, v.y - cur.y);\n    const l2 = Math.hypot(n.x - v.x, n.y - v.y);\n    const r = Math.min(radius, l1 / 2, l2 / 2);\n    const p1 = { x: v.x - ((v.x - cur.x) / (l1 || 1)) * r, y: v.y - ((v.y - cur.y) / (l1 || 1)) * r };\n    const p2 = { x: v.x + ((n.x - v.x) / (l2 || 1)) * r, y: v.y + ((n.y - v.y) / (l2 || 1)) * r };\n    const cross = (v.x - cur.x) * (n.y - v.y) - (v.y - cur.y) * (n.x - v.x);\n    len += Math.hypot(p1.x - cur.x, p1.y - cur.y) + (Math.PI / 2) * r;\n    d += ` L${p1.x.toFixed(1)} ${p1.y.toFixed(1)} A${r.toFixed(1)} ${r.toFixed(1)} 0 0 ${cross > 0 ? 1 : 0} ${p2.x.toFixed(1)} ${p2.y.toFixed(1)}`;\n    cur = p2;\n  }\n  return { d, len, end: clean[clean.length - 1] };\n}\n\nexport type BeamConnectorProps = {\n  containerRef: RefObject<HTMLElement | null>;\n  /** The start: a ref, or a CSS selector resolved inside the container. */\n  from: RefObject<HTMLElement | null> | string;\n  /** The end: a ref, or a CSS selector resolved inside the container. */\n  to: RefObject<HTMLElement | null> | string;\n  fromSide?: BeamSide;\n  toSide?: BeamSide;\n  accent?: string;\n  /** Seconds per cycle; the pulse travels during the first 30% of it. */\n  duration?: number;\n  delay?: number;\n  /** Where the elbow sits between the two ports, 0 to 1. */\n  lane?: number;\n  radius?: number;\n  /** Pulses run only while true (for example, once the section is in view). */\n  active?: boolean;\n};\n\n/**\n * A hairline beam between any two elements in a container, routed with\n * rounded right-angle elbows. A pulse of light travels it once per cycle and\n * lands with a flash at the far end. Put it inside a relatively positioned\n * container; it measures in layout pixels, so scaled previews stay aligned.\n */\nexport function BeamConnector({ containerRef, from, to, fromSide = \"right\", toSide = \"left\", accent = \"ice\", duration = 9, delay = 0, lane = 0.5, radius = 12, active = true }: BeamConnectorProps) {\n  const acc = accentHex(accent);\n  const reduced = useReducedMotion();\n  const [geo, setGeo] = useState<{ d: string; len: number; end: Pt; w: number; h: number } | null>(null);\n  useEffect(() => {\n    const c = containerRef.current;\n    if (!c) return;\n    const pick = (x: RefObject<HTMLElement | null> | string) => (typeof x === \"string\" ? c.querySelector<HTMLElement>(x) : x.current);\n    const a = pick(from);\n    const b = pick(to);\n    if (!a || !b) return;\n    const measure = () => {\n      const cr = c.getBoundingClientRect();\n      const k = c.offsetWidth / (cr.width || 1);\n      const box = (el: HTMLElement) => {\n        const r = el.getBoundingClientRect();\n        return { x: (r.left - cr.left) * k, y: (r.top - cr.top) * k, w: r.width * k, h: r.height * k };\n      };\n      const p = elbowPath(portOf(box(a), fromSide), portOf(box(b), toSide), fromSide, toSide, lane, radius);\n      setGeo({ ...p, w: c.offsetWidth, h: c.offsetHeight });\n    };\n    const ro = new ResizeObserver(measure);\n    ro.observe(c);\n    ro.observe(a);\n    ro.observe(b);\n    window.addEventListener(\"resize\", measure);\n    return () => {\n      ro.disconnect();\n      window.removeEventListener(\"resize\", measure);\n    };\n  }, [containerRef, from, to, fromSide, toSide, lane, radius]);\n  if (!geo) return null;\n  const run = active && !reduced;\n  const timing = { animationDuration: duration + \"s\", animationDelay: delay + \"s\", animationIterationCount: \"infinite\", animationTimingFunction: \"linear\" };\n  const dash = (d: number): CSSProperties =>\n    ({ \"--d\": d + \"px\", \"--len\": geo.len.toFixed(1) + \"px\", \"--dmax\": \"96px\", strokeDasharray: `${d} ${geo.len + 200}`, strokeDashoffset: d, animationName: \"dp-pulse\", ...timing }) as CSSProperties;\n  return (\n    <svg aria-hidden className=\"pointer-events-none absolute left-0 top-0 overflow-visible\" width={geo.w} height={geo.h}>\n      <style>{PULSE_CSS + MOTION_CSS}</style>\n      <path d={geo.d} fill=\"none\" stroke={LINE_2} strokeWidth={1} />\n      {run && (\n        <>\n          <path className=\"dp-motion\" d={geo.d} fill=\"none\" stroke={acc} strokeWidth={5} strokeLinecap=\"round\" style={{ ...dash(96), opacity: 0.28, filter: \"blur(3px)\" }} />\n          <path className=\"dp-motion\" d={geo.d} fill=\"none\" stroke={acc} strokeWidth={1.25} strokeLinecap=\"round\" style={dash(56)} />\n          <path className=\"dp-motion\" d={geo.d} fill=\"none\" stroke=\"#ffffff\" strokeWidth={1.5} strokeLinecap=\"round\" style={dash(10)} />\n          <circle\n            className=\"dp-motion\"\n            cx={geo.end.x}\n            cy={geo.end.y}\n            r={5}\n            fill={acc}\n            style={{ transformBox: \"fill-box\", transformOrigin: \"center\", opacity: 0, filter: `drop-shadow(0 0 6px ${acc})`, animationName: \"dp-arrive\", ...timing }}\n          />\n        </>\n      )}\n    </svg>\n  );\n}\n","type":"registry:component","target":"components/viberdy/beam-connector.tsx"}],"meta":{"tier":"free","tags":["animated beam","connector","svg","diagram","integrations","pulse","dark","flow"],"href":"https://viberdy.dev/library/beam-connector","aiPrompt":"Build a React primitive, `BeamConnector({ containerRef, from, to, fromSide, toSide, accent, duration, delay, lane, radius, active })`, that draws a beam between two elements inside a relatively positioned container.\n\nResolve from and to as refs or as CSS selectors via container.querySelector. Measure both boxes relative to the container in layout pixels (rect offset times container.offsetWidth / rect.width) with a ResizeObserver on all three and a window resize listener. Take each end's port (the midpoint of the chosen side) and route: both horizontal sides -> a vertical segment at lane between them; both vertical -> a horizontal segment at lane; mixed -> one corner. Round each corner with an arc of radius min(radius, half of either adjacent segment), choosing the sweep from the turn's cross product, and compute the exact length (straights plus pi/2 * r per corner).\n\nRender an aria-hidden SVG the size of the container: the path as a white 14% hairline, then (while active and motion is allowed) three copies with dash arrays of 96, 56 and 10px (blurred glow at 28%, accent core, white head) animated by one keyframe on stroke-dashoffset from var(--d) to var(--d) - var(--len) - var(--dmax) during the first 30% of `duration`, so the three heads stay aligned; plus a circle at the far end that flashes (scale and fade) at 30%. Put the keyframes in a <style> inside the SVG.\n\nDark Precision grammar: ground #050505, surfaces #0b0b0d and #121215, hairlines white 6% at rest and 14% lit (drawn as inset box-shadows or SVG strokes, never border colours), ink white 92/60/38%, one cool accent used only as light (default #4fd1ff; mint #5ef2c1, amber #ffb45e, white #f2f4f7 or any #rrggbb, validated against /^#[0-9a-fA-F]{6}$/), Geist never heavier than 600 with tight tracking, Geist Mono only for captions and data, fonts through CSS variables with fallbacks (var(--font-sans, \"Geist\", ...)). Morphs use cubic-bezier(0.16, 1, 0.3, 1); ambient loops are 30s or slower. Respect prefers-reduced-motion. No dependencies beyond React.","license":"https://viberdy.dev/license"}}