{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "beams",
  "title": "Beams",
  "description": "Lines between the nodes of a picture, placed by its layout rather than measured, so they hold at every width: each draws in the first time the picture is seen, and a pulse travels it when asked.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/resize.json",
    "https://kinoui.com/r/scene.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/beams.tsx",
      "content": "'use client'\n\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport { FOLLOWS_TRANSITION, transitionTiming } from '@/registry/lib/resize'\nimport { onScreen, type SceneSeen, useSeen } from '@/registry/lib/scene'\nimport { mergeProps, type PartProps, renderElement } from '@ui-sdk/react/primitive'\nimport {\n  type ComponentProps,\n  createContext,\n  type CSSProperties,\n  use,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * Lines between nodes, with a pulse that travels them, such as tools that\n * send their data into a product. The layout says where every node sits, in\n * the field's own units, and a beam is worked out from its two ends, so\n * nothing is measured: the beams are right in the page's HTML, at every\n * width and after any reflow. The field keeps its layout's shape and scales\n * as one drawing, the nodes with it.\n *\n * The beams draw in, one after another, the first time the field is seen;\n * on screen as the page loads, they are there already. A pulse runs along a\n * beam each time its count in `pulses` goes up, the way its data travels.\n * Under reduced motion the beams stand still and no pulse runs.\n *\n *   <BeamField layout={{ width: 300, height: 80, at: { form: { x: 30, y: 40 }, kino: { x: 150, y: 40 } } }} links={[{ id: 'in', from: 'form', to: 'kino', flow: 'forward' }]} pulses={{ in: sent }}>\n *     <BeamSpot node='form'>…</BeamSpot>\n *     <BeamSpot node='kino'>…</BeamSpot>\n *   </BeamField>\n */\n\n/** A point in the field's own units, `x` from its start edge. */\ninterface BeamPoint {\n  x: number\n  y: number\n}\n\n/** The field's size in its own units, and where each node sits in it. */\ninterface BeamLayout {\n  width: number\n  height: number\n  at: Record<string, BeamPoint>\n}\n\n/**\n * A beam's shape: `level` leaves and arrives level, bending halfway, as a\n * diagram's lines do; `arc` bows up, more the further apart its ends are, as\n * a route drawn on a map does.\n */\ntype BeamCurve = 'level' | 'arc'\n\n/** Which way data travels a beam: from `from` to `to`, back, or both ways. */\ntype BeamFlow = 'forward' | 'back' | 'both'\n\n/** A beam between two nodes of the layout. */\ninterface BeamLink {\n  id: string\n  from: string\n  to: string\n  flow: BeamFlow\n}\n\n/**\n * Where the beams are: drawn, as the page's HTML has them; waiting off\n * screen, undrawn, until the field is seen; or drawing in.\n */\ntype BeamsPhase = 'drawn' | 'waiting' | 'drawing'\n\nconst BeamLayoutContext = createContext<BeamLayout | null>(null)\n\n/** How long a pulse's dash is, as a share of its beam. */\nconst PULSE_LENGTH = 0.2\n\n/** How long a pulse's bright head is, as a share of its beam. */\nconst PULSE_HEAD = 0.05\n\nfunction BeamField({\n  layout,\n  links,\n  curve = 'level',\n  lit = [],\n  pulses = {},\n  className,\n  style,\n  children,\n  ...props\n}: ComponentProps<'div'> & {\n  layout: BeamLayout\n  links: BeamLink[]\n  curve?: BeamCurve\n  /** The beams brought forward, by `id`, such as the one whose node is hovered. */\n  lit?: string[]\n  /** A count for each beam, by `id`: each time one goes up, a pulse runs along that beam. */\n  pulses?: Record<string, number>\n}) {\n  const { ref, seen } = useSeen<HTMLDivElement>(0.5)\n  const beams = useRef<SVGSVGElement>(null)\n  // Drawn until it is known to be off screen, so the page's HTML holds the beams.\n  const [offScreen, setOffScreen] = useState(false)\n\n  // Before the first paint: on screen as the page shows it, it stays as it is (motion rule 6);\n  // further down, the beams go, which nobody sees, and draw in once the field is seen.\n  useLayoutEffect(() => {\n    const element = ref.current\n    if (element && !reducesMotion(element) && !onScreen(element)) setOffScreen(true)\n  }, [ref])\n\n  const phase = beamsPhase(offScreen, seen)\n  const drawn = drawScale(layout.width)\n\n  const sent = useRef(pulses)\n  useEffect(() => {\n    const last = sent.current\n    sent.current = pulses\n    const svg = beams.current\n    if (!svg || phase === 'waiting') return\n    for (const [id, count] of Object.entries(pulses)) {\n      if (count > (last[id] ?? 0)) sendPulse(svg, id)\n    }\n  }, [pulses, phase])\n\n  return (\n    <div\n      ref={ref}\n      data-slot='beam-field'\n      data-phase={phase}\n      style={{ aspectRatio: `${layout.width} / ${layout.height}`, ...style }}\n      className={cn('group/beams @container/beams relative w-full min-w-0', className)}\n      {...props}\n    >\n      <svg\n        ref={beams}\n        aria-hidden\n        viewBox={`0 0 ${layout.width * drawn} ${layout.height * drawn}`}\n        preserveAspectRatio='none'\n        // The layout's `x` runs from the start edge, so right to left draws the picture mirrored: by the\n        // element's own direction, as `BeamSpot`'s `inset-inline-start` reads it, so a map held left to\n        // right inside a right-to-left page stays the right way round.\n        className='pointer-events-none absolute inset-0 size-full overflow-visible [&:dir(rtl)]:-scale-x-100'\n      >\n        {links.map((link, index) => {\n          const shape = curve === 'arc' ? arcPath : beamPath\n          const d = shape(\n            scaledBy(spotOf(layout, link.from), drawn),\n            scaledBy(spotOf(layout, link.to), drawn),\n          )\n          const on = lit.includes(link.id)\n          return (\n            <g key={link.id} data-beam={link.id}>\n              <path\n                d={d}\n                pathLength={1}\n                data-lit={on ? '' : undefined}\n                style={\n                  {\n                    '--beam-delay': `calc(var(--motion-draw-duration) * ${drawDelay(index, links.length)})`,\n                  } as CSSProperties\n                }\n                className={beamClassName}\n              />\n              {link.flow !== 'back' ? <Pulse d={d} way='forward' /> : null}\n              {link.flow !== 'forward' ? <Pulse d={d} way='back' /> : null}\n            </g>\n          )\n        })}\n      </svg>\n      <BeamLayoutContext value={layout}>{children}</BeamLayoutContext>\n    </div>\n  )\n}\n\n/**\n * A beam: a hairline in `--beam-line`, the line colour unless the picture\n * sets its own, such as a map whose land is darker than a line, and in\n * `--beam-line-lit`, darker, while it is lit.\n * It is dashed as long as itself, so moving the dash draws it: undrawn while\n * the field waits to be seen, and drawn in on `draw`, each beam a share of\n * the role later than the one before, once it is.\n */\nconst beamClassName = cn(\n  'fill-none stroke-(--beam-line,var(--border)) [stroke-width:1.5] [vector-effect:non-scaling-stroke] [stroke-dasharray:1] [stroke-dashoffset:0] data-lit:stroke-(--beam-line-lit,color-mix(in_oklab,var(--muted-foreground)_60%,transparent)) forced-colors:stroke-[CanvasText] forced-colors:data-lit:stroke-[Highlight]',\n  '[transition:stroke_var(--motion-enter-duration)_var(--motion-enter-fade-easing)]',\n  'group-data-[phase=waiting]/beams:[stroke-dashoffset:1]',\n  'group-data-[phase=drawing]/beams:[transition:stroke_var(--motion-enter-duration)_var(--motion-enter-fade-easing),stroke-dashoffset_var(--motion-draw-duration)_var(--motion-draw-easing)_var(--beam-delay)] motion-reduce:group-data-[phase=drawing]/beams:[transition:stroke_var(--motion-enter-duration)_var(--motion-enter-fade-easing)]',\n)\n\n/**\n * A pulse: a short faint dash with a bright head at its front, waiting\n * before its beam's start, hidden, until it runs to its end as a Web\n * Animation timed by the transition named on it, on `draw`, so the feel\n * and reduced motion hold.\n */\nfunction Pulse({ d, way }: { d: string; way: 'forward' | 'back' }) {\n  return (\n    <g data-pulse={way}>\n      <path\n        d={d}\n        pathLength={1}\n        data-part='tail'\n        className={cn(pulseClassName, 'stroke-foreground/40')}\n      />\n      <path\n        d={d}\n        pathLength={1}\n        data-part='head'\n        className={cn(pulseClassName, 'stroke-foreground')}\n      />\n    </g>\n  )\n}\n\nconst pulseClassName =\n  'fill-none opacity-0 [stroke-width:2] [stroke-linecap:round] [vector-effect:non-scaling-stroke] transition-[stroke-dashoffset] duration-(--motion-draw-duration) ease-(--motion-draw-easing) motion-reduce:transition-none forced-colors:stroke-[Highlight]'\n\n/** Runs one pulse along beam `id`, its own way; under reduced motion, none. */\nfunction sendPulse(svg: SVGSVGElement, id: string) {\n  const group = [...svg.querySelectorAll<SVGGElement>('[data-beam]')].find(\n    (node) => node.dataset.beam === id,\n  )\n  if (!group) return\n  // A pulse still on its way finishes, rather than jumping back to its start.\n  const running = group\n    .getAnimations({ subtree: true })\n    .some((run) => run.id === FOLLOWS_TRANSITION && run.playState === 'running')\n  if (running) return\n  for (const pulse of group.querySelectorAll<SVGGElement>('[data-pulse]')) {\n    const way = pulse.dataset.pulse === 'back' ? 'back' : 'forward'\n    for (const path of pulse.querySelectorAll<SVGPathElement>('[data-part]')) {\n      const timing = transitionTiming(getComputedStyle(path), 'stroke-dashoffset')\n      if (!timing) continue\n      const { dash, from, to } = pulseDash(\n        way,\n        path.dataset.part === 'head' ? 'head' : 'tail',\n      )\n      path.animate(\n        [\n          { strokeDasharray: dash, strokeDashoffset: from, opacity: 1 },\n          { strokeDasharray: dash, strokeDashoffset: to, opacity: 1 },\n        ],\n        // Draw's duration, at an even pace, as a marquee's: on draw's spring the dash would race\n        // across in a few frames and then drain out of sight behind the node.\n        { duration: timing.duration, easing: 'linear', id: FOLLOWS_TRANSITION },\n      )\n    }\n  }\n}\n\n/**\n * Places its child's centre on a node of the field's layout. The child is\n * yours: a tile, a link, a mark.\n */\nfunction BeamSpot({\n  node,\n  className,\n  style,\n  render,\n  ...props\n}: Omit<PartProps<'div'>, 'className' | 'style'> & {\n  node: string\n  className?: string\n  style?: CSSProperties\n}) {\n  const layout = use(BeamLayoutContext)\n  if (!layout) throw new Error('A BeamSpot goes inside a BeamField.')\n  return renderElement(\n    'div',\n    mergeProps(\n      {\n        'data-slot': 'beam-spot',\n        style: { ...spotPlace(layout, node), ...style },\n        className: cn(\n          'absolute -translate-x-1/2 -translate-y-1/2 [&:dir(rtl)]:translate-x-1/2',\n          className,\n        ),\n      },\n      props,\n    ),\n    render,\n  )\n}\n\n/**\n * How wide the beams' drawing is, at the least, in its own units. A beam\n * keeps a hairline's width as the field scales, and Chromium then measures\n * its dashes in the drawing's units, not the screen's: shown wider than its\n * units, a beam would draw only part of its length, and a pulse would stop\n * short. Drawn this wide, no page shows it wider.\n */\nconst DRAWN_WIDTH = 2400\n\n/** What the beams' drawing scales the layout by, so it is at least `DRAWN_WIDTH` units wide. */\nfunction drawScale(width: number): number {\n  return Math.max(1, Math.ceil(DRAWN_WIDTH / width))\n}\n\nfunction scaledBy(point: BeamPoint, scale: number): BeamPoint {\n  return { x: point.x * scale, y: point.y * scale }\n}\n\n/** Node `node`'s point, or a thrown error naming it, since a beam to nowhere is a mistake in the layout. */\nfunction spotOf(layout: BeamLayout, node: string): BeamPoint {\n  const point = layout.at[node]\n  if (!point) throw new Error(`The beams' layout has no node \"${node}\".`)\n  return point\n}\n\n/** Where a node sits, as shares of the field: from its start edge and from its top. */\nfunction spotPlace(layout: BeamLayout, node: string) {\n  const { x, y } = spotOf(layout, node)\n  return {\n    insetInlineStart: `${round((x / layout.width) * 100)}%`,\n    top: `${round((y / layout.height) * 100)}%`,\n  }\n}\n\n/**\n * A beam from `from` to `to`: a curve that leaves and arrives level along\n * whichever way the two are further apart, bending halfway, so beams that\n * meet at one node arrive side by side rather than crossing.\n */\nfunction beamPath(from: BeamPoint, to: BeamPoint): string {\n  const across = Math.abs(to.x - from.x) >= Math.abs(to.y - from.y)\n  const c1 = across\n    ? { x: (from.x + to.x) / 2, y: from.y }\n    : { x: from.x, y: (from.y + to.y) / 2 }\n  const c2 = across\n    ? { x: (from.x + to.x) / 2, y: to.y }\n    : { x: to.x, y: (from.y + to.y) / 2 }\n  const at = (point: BeamPoint) => `${round(point.x)} ${round(point.y)}`\n  return `M${at(from)} C${at(c1)} ${at(c2)} ${at(to)}`\n}\n\n/** How far an arc bows, as a share of the distance between its ends. */\nconst ARC_BOW = 0.22\n\n/** How long the beams take to start drawing in, from the first to the last, in `draw` durations. */\nconst DRAW_SPAN = 1.75\n\n/**\n * When beam `index` of `count` starts drawing in, in `draw` durations: a\n * quarter of one after the one before, or less when there are so many that\n * they would take longer than `DRAW_SPAN` to start, so a map of fifty lines\n * draws in as quickly as a hub of eight.\n */\nfunction drawDelay(index: number, count: number): number {\n  return round(index * Math.min(0.25, DRAW_SPAN / Math.max(1, count - 1)))\n}\n\n/**\n * A beam from `from` to `to` that bows up, away from the line between them,\n * by `ARC_BOW` of their distance, as a route drawn on a map does.\n */\nfunction arcPath(from: BeamPoint, to: BeamPoint): string {\n  const dx = to.x - from.x\n  const dy = to.y - from.y\n  const distance = Math.hypot(dx, dy)\n  // The normal to the line that points up the field; a line straight up and down bows towards its start edge.\n  const sign = dx > 0 ? -1 : 1\n  const control = {\n    x: (from.x + to.x) / 2 + ((sign * -dy) / distance || 0) * distance * ARC_BOW,\n    y: (from.y + to.y) / 2 + ((sign * dx) / distance || 0) * distance * ARC_BOW,\n  }\n  const at = (point: BeamPoint) => `${round(point.x)} ${round(point.y)}`\n  return `M${at(from)} Q${at(control)} ${at(to)}`\n}\n\n/**\n * A pulse's dash and where it runs, as dash offsets along a beam whose\n * length is 1: the tail from just before the start to just past the end\n * (or back), and the head the short piece at the tail's front.\n */\nfunction pulseDash(\n  way: 'forward' | 'back',\n  part: 'tail' | 'head',\n): { dash: string; from: number; to: number } {\n  const length = part === 'tail' ? PULSE_LENGTH : PULSE_HEAD\n  // Going forward, the front is the tail's far end, so the head sits that much further on.\n  const ahead = way === 'forward' && part === 'head' ? PULSE_LENGTH - PULSE_HEAD : 0\n  const [from, to] = way === 'forward' ? [PULSE_LENGTH, -1] : [-1, PULSE_LENGTH]\n  return {\n    dash: `${length} 2`,\n    from: round(from - ahead),\n    to: round(to - ahead),\n  }\n}\n\n/** Where the beams are, from whether the field was off screen as the page showed it and whether it has been seen since. */\nfunction beamsPhase(offScreen: boolean, seen: SceneSeen): BeamsPhase {\n  if (!offScreen || seen === 'reduced') return 'drawn'\n  return seen === 'seen' ? 'drawing' : 'waiting'\n}\n\n/** To three places, so the server's markup and the browser's agree. */\nfunction round(value: number): number {\n  return Math.round(value * 1000) / 1000\n}\n\nexport {\n  type BeamCurve,\n  type BeamFlow,\n  BeamField,\n  type BeamLayout,\n  type BeamLink,\n  type BeamPoint,\n  BeamSpot,\n}\nexport { arcPath, beamPath, beamsPhase, drawDelay, drawScale, pulseDash, spotPlace }\n",
      "type": "registry:lib",
      "target": "@lib/beams.tsx"
    }
  ],
  "type": "registry:lib"
}