{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "illustration-03",
  "title": "Run pulse",
  "description": "A lead, its agents and their tools, where a streak in the colour of the caller crosses the edge of each call and the node it reaches gives a little.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/brand-logos.json",
    "https://ui.ndekocode.dev/r/brand-tile.json",
    "https://ui.ndekocode.dev/r/mesh-tile.json",
    "https://ui.ndekocode.dev/r/speech-envelope.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/illustration/illustration-03.tsx",
      "content": "'use client';\n\nimport { useMemo } from 'react';\n\nimport { seriesColorOf, type SeriesSlot } from '@/registry/ndeko/lib/agent-run';\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\nimport { noiseAt } from '@/registry/ndeko/lib/speech-envelope';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { MeshTile } from '@/registry/ndeko/ui/mesh-tile';\n\nimport { placeOf, spanBetween, type ScenePoint } from './_parts/geometry';\nimport { useSceneAnimations } from './_parts/use-scene-animations';\nimport { useScenePlay } from './_parts/use-scene-play';\n\nexport type PulseLead = {\n  name: string;\n  series: SeriesSlot;\n};\n\nexport type PulseTool = {\n  id: string;\n  name: string;\n  brand: BrandSlug;\n};\n\nexport type PulseAgent = {\n  id: string;\n  name: string;\n  series: SeriesSlot;\n  toolIds: string[];\n};\n\ntype PulseNode = {\n  key: string;\n  point: ScenePoint;\n};\n\ntype PulseEdge = {\n  key: string;\n  fromKey: string;\n  toKey: string;\n  from: ScenePoint;\n  to: ScenePoint;\n  color: string;\n  startMs: number;\n};\n\ntype Score = {\n  nodes: PulseNode[];\n  edges: PulseEdge[];\n  cycleMs: number;\n};\n\nconst STAGE_ASPECT = 8 / 5;\n\nconst LEAD_COLUMN = 0.09;\n\nconst AGENT_COLUMN = 0.46;\n\nconst TOOL_COLUMN = 0.91;\n\nconst LEAD_KEY = 'lead';\n\nconst FIRST_CALL_MS = 1400;\n\nconst TRAVEL_MS = 900;\n\n/** An agent calls its first tool once the hand-off from the lead has landed. */\nconst AFTER_HAND_OFF_MS = TRAVEL_MS + 160;\n\nconst CALL_GAP_MS = 760;\n\nconst REST_MS = 1300;\n\nconst TRAVEL_EASE = 'cubic-bezier(0.65, 0, 0.35, 1)';\n\nconst BUMP_RISE_MS = 140;\n\nconst BUMP_FALL_MS = 420;\n\n/** Under reduced motion one streak in three is drawn where it would be in mid flight. */\nconst FROZEN_EVERY = 3;\n\nfunction rowOf(index: number, count: number) {\n  return (index + 0.5) / count;\n}\n\nfunction agentPointOf(index: number, count: number): ScenePoint {\n  return { x: AGENT_COLUMN, y: rowOf(index, count) };\n}\n\nfunction toolPointOf(index: number, count: number): ScenePoint {\n  return { x: TOOL_COLUMN, y: rowOf(index, count) };\n}\n\nfunction agentKeyOf(agent: PulseAgent) {\n  return `agent:${agent.id}`;\n}\n\nfunction toolKeyOf(toolId: string) {\n  return `tool:${toolId}`;\n}\n\n/** The wait between two calls changes from call to call, the same way on every round. */\nfunction gapOf(order: number) {\n  const noise = noiseAt(order, 7);\n  const stretch = 0.75 + noise * 0.9;\n  return CALL_GAP_MS * stretch;\n}\n\n/**\n * Where every node sits and when every call leaves: the lead hands work to each agent in turn, and\n * each agent then calls its tools one after the other.\n */\nfunction scoreOf(\n  lead: PulseLead,\n  agents: PulseAgent[],\n  tools: PulseTool[]\n): Score {\n  const leadPoint: ScenePoint = { x: LEAD_COLUMN, y: 0.5 };\n  const nodes: PulseNode[] = [{ key: LEAD_KEY, point: leadPoint }];\n  const points = new Map<string, ScenePoint>();\n  agents.forEach((agent, index) => {\n    const key = agentKeyOf(agent);\n    const point = agentPointOf(index, agents.length);\n    points.set(key, point);\n    nodes.push({ key, point });\n  });\n  tools.forEach((tool, index) => {\n    const key = toolKeyOf(tool.id);\n    const point = toolPointOf(index, tools.length);\n    points.set(key, point);\n    nodes.push({ key, point });\n  });\n\n  const edges: PulseEdge[] = [];\n  let clock = FIRST_CALL_MS;\n  let order = 0;\n  for (const agent of agents) {\n    const agentKey = agentKeyOf(agent);\n    const agentPoint = points.get(agentKey);\n    if (!agentPoint) {\n      continue;\n    }\n    edges.push({\n      key: `${LEAD_KEY}>${agentKey}`,\n      fromKey: LEAD_KEY,\n      toKey: agentKey,\n      from: leadPoint,\n      to: agentPoint,\n      color: seriesColorOf(lead.series),\n      startMs: clock,\n    });\n    clock += AFTER_HAND_OFF_MS;\n    for (const toolId of agent.toolIds) {\n      const toolKey = toolKeyOf(toolId);\n      const toolPoint = points.get(toolKey);\n      if (!toolPoint) {\n        continue;\n      }\n      edges.push({\n        key: `${agentKey}>${toolKey}`,\n        fromKey: agentKey,\n        toKey: toolKey,\n        from: agentPoint,\n        to: toolPoint,\n        color: seriesColorOf(agent.series),\n        startMs: clock,\n      });\n      clock += gapOf(order);\n      order += 1;\n    }\n  }\n  return { nodes, edges, cycleMs: clock + TRAVEL_MS + REST_MS };\n}\n\n/** A streak waits hidden at the start of its edge, crosses it once in the round, then waits at the end. */\nfunction streakKeyframesOf(edge: PulseEdge, cycleMs: number): Keyframe[] {\n  const leavesAt = edge.startMs / cycleMs;\n  const travel = TRAVEL_MS / cycleMs;\n  const showsAt = leavesAt + travel * 0.2;\n  const arrivesAt = leavesAt + travel;\n  const goneAt = arrivesAt + travel * 0.15;\n  const atStart = 'translateX(0%)';\n  const atEnd = 'translateX(100%)';\n  return [\n    { offset: 0, transform: atStart, opacity: 0 },\n    { offset: leavesAt, transform: atStart, opacity: 0, easing: TRAVEL_EASE },\n    { offset: showsAt, opacity: 1 },\n    { offset: arrivesAt, transform: atEnd, opacity: 1 },\n    { offset: goneAt, transform: atEnd, opacity: 0 },\n    { offset: 1, transform: atEnd, opacity: 0 },\n  ];\n}\n\n/** A node gives a little each time a call lands on it. */\nfunction bumpKeyframesOf(landings: PulseEdge[], cycleMs: number): Keyframe[] {\n  const rest = 'scale(1)';\n  const frames: Keyframe[] = [{ offset: 0, transform: rest }];\n  for (const edge of landings) {\n    const landsMs = edge.startMs + TRAVEL_MS;\n    const landsAt = landsMs / cycleMs;\n    const peakAt = (landsMs + BUMP_RISE_MS) / cycleMs;\n    const settledAt = (landsMs + BUMP_FALL_MS) / cycleMs;\n    frames.push({ offset: landsAt, transform: rest });\n    frames.push({ offset: peakAt, transform: 'scale(1.1)' });\n    frames.push({ offset: settledAt, transform: rest });\n  }\n  frames.push({ offset: 1, transform: rest });\n  return frames;\n}\n\nfunction animateScore(stage: HTMLElement, score: Score) {\n  const timing = { duration: score.cycleMs, iterations: Infinity };\n  const runners = stage.querySelectorAll<HTMLElement>('[data-pulse-streak]');\n  const tiles = stage.querySelectorAll<HTMLElement>('[data-pulse-node]');\n  const animations: Animation[] = [];\n  runners.forEach((runner, index) => {\n    const edge = score.edges[index];\n    if (edge) {\n      const keyframes = streakKeyframesOf(edge, score.cycleMs);\n      animations.push(runner.animate(keyframes, timing));\n    }\n  });\n  tiles.forEach((tile) => {\n    const nodeKey = tile.dataset.pulseNode;\n    const landings = score.edges.filter((edge) => edge.toKey === nodeKey);\n    if (landings.length > 0) {\n      const keyframes = bumpKeyframesOf(landings, score.cycleMs);\n      animations.push(tile.animate(keyframes, timing));\n    }\n  });\n  return animations;\n}\n\nfunction edgeStyleOf(edge: PulseEdge) {\n  const span = spanBetween(edge.from, edge.to, STAGE_ASPECT);\n  return {\n    ...placeOf(edge.from),\n    width: `${span.lengthPercent}%`,\n    transform: `rotate(${span.angleDeg}deg)`,\n  };\n}\n\nfunction streakStyleOf(edge: PulseEdge) {\n  return {\n    backgroundImage: `linear-gradient(to right, transparent, ${edge.color})`,\n  };\n}\n\nfunction isFrozenStreak(isStill: boolean, index: number) {\n  const isChosen = index % FROZEN_EVERY === 0;\n  return isStill && isChosen;\n}\n\nfunction structureKeyOf(score: Score) {\n  const edgeKeys = score.edges.map((edge) => edge.key);\n  return edgeKeys.join('|');\n}\n\nfunction labelOf(lead: PulseLead, agents: PulseAgent[], tools: PulseTool[]) {\n  const agentNames = agents.map((agent) => agent.name);\n  const toolNames = tools.map((tool) => tool.name);\n  const crew = agentNames.join(', ');\n  const kit = toolNames.join(', ');\n  return `${lead.name} hands work to ${crew}, who call ${kit}`;\n}\n\nconst NODE_CLASS = 'absolute -translate-x-1/2 -translate-y-1/2';\n\nconst NAME_CLASS =\n  'text-muted-foreground pointer-events-none absolute top-full left-1/2 mt-1 -translate-x-1/2 text-[11px] leading-4 whitespace-nowrap';\n\nexport type RunPulseProps = {\n  lead: PulseLead;\n  agents: PulseAgent[];\n  tools: PulseTool[];\n  className?: string;\n};\n\nexport function RunPulse({ lead, agents, tools, className }: RunPulseProps) {\n  const { ref, isPlaying, isStill } = useScenePlay();\n  const score = useMemo(\n    () => scoreOf(lead, agents, tools),\n    [lead, agents, tools]\n  );\n\n  useSceneAnimations(\n    ref,\n    isPlaying,\n    (stage) => animateScore(stage, score),\n    structureKeyOf(score)\n  );\n\n  return (\n    <div\n      ref={ref}\n      role='img'\n      aria-label={labelOf(lead, agents, tools)}\n      className={cn('relative aspect-[8/5] w-full max-w-[26rem]', className)}\n    >\n      {score.edges.map((edge, index) => (\n        <span\n          key={edge.key}\n          style={edgeStyleOf(edge)}\n          className='absolute h-0.5 origin-left -translate-y-1/2 overflow-hidden'\n        >\n          <span className='bg-foreground/10 absolute inset-x-0 top-1/2 h-px -translate-y-1/2' />\n          <span\n            data-pulse-streak=''\n            data-frozen={isFrozenStreak(isStill, index)}\n            className='absolute inset-0 opacity-0 data-[frozen=true]:translate-x-[45%] data-[frozen=true]:opacity-100'\n          >\n            <span\n              style={streakStyleOf(edge)}\n              className='absolute inset-y-0 left-0 w-7 rounded-full'\n            />\n          </span>\n        </span>\n      ))}\n      <span style={placeOf(score.nodes[0].point)} className={NODE_CLASS}>\n        <span data-pulse-node={LEAD_KEY} className='block'>\n          <MeshTile\n            seed={lead.name}\n            color={seriesColorOf(lead.series)}\n            className='block size-10 rounded-[10px]'\n          />\n        </span>\n        <span className={NAME_CLASS}>{lead.name}</span>\n      </span>\n      {agents.map((agent, index) => {\n        const point = agentPointOf(index, agents.length);\n\n        return (\n          <span key={agent.id} style={placeOf(point)} className={NODE_CLASS}>\n            <span data-pulse-node={agentKeyOf(agent)} className='block'>\n              <MeshTile\n                seed={agent.name}\n                color={seriesColorOf(agent.series)}\n                className='block size-8 rounded-lg'\n              />\n            </span>\n            <span className={NAME_CLASS}>{agent.name}</span>\n          </span>\n        );\n      })}\n      {tools.map((tool, index) => {\n        const point = toolPointOf(index, tools.length);\n\n        return (\n          <span key={tool.id} style={placeOf(point)} className={NODE_CLASS}>\n            <span data-pulse-node={toolKeyOf(tool.id)} className='block'>\n              <BrandTile brand={tool.brand} size='lg' className='flex' />\n            </span>\n          </span>\n        );\n      })}\n    </div>\n  );\n}\n\nconst LEAD: PulseLead = { name: 'Planner', series: 1 };\n\nconst TOOLS: PulseTool[] = [\n  { id: 'notion', name: 'Notion', brand: 'notion' },\n  { id: 'drive', name: 'Google Drive', brand: 'googledrive' },\n  { id: 'github', name: 'GitHub', brand: 'github' },\n  { id: 'sentry', name: 'Sentry', brand: 'sentry' },\n  { id: 'linear', name: 'Linear', brand: 'linear' },\n];\n\nconst AGENTS: PulseAgent[] = [\n  {\n    id: 'researcher',\n    name: 'Researcher',\n    series: 2,\n    toolIds: ['notion', 'drive'],\n  },\n  { id: 'coder', name: 'Coder', series: 5, toolIds: ['github', 'sentry'] },\n  {\n    id: 'reviewer',\n    name: 'Reviewer',\n    series: 4,\n    toolIds: ['sentry', 'linear'],\n  },\n];\n\nexport default function Illustration03() {\n  return <RunPulse lead={LEAD} agents={AGENTS} tools={TOOLS} />;\n}\n",
      "type": "registry:component",
      "target": "components/illustration/illustration-03.tsx"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/geometry.ts",
      "content": "export type ScenePoint = {\n  /** Share of the stage width, from 0 to 1. */\n  x: number;\n  /** Share of the stage height, from 0 to 1. */\n  y: number;\n};\n\nexport type SceneSpan = {\n  /** Length of the line as a percentage of the stage width. */\n  lengthPercent: number;\n  /** Angle of the line in degrees, clockwise from the right, as CSS turns it. */\n  angleDeg: number;\n};\n\nconst HALF_TURN_DEG = 180;\n\nconst FULL_TURN_DEG = 360;\n\n/**\n * Two engines can disagree on the last digit of a sine. A value written into a style is rounded, so\n * the server and the browser print the same text.\n */\nexport function rounded(value: number) {\n  const hundredths = Math.round(value * 100);\n  return hundredths / 100;\n}\n\nexport function percentOf(share: number) {\n  const percent = rounded(share * 100);\n  return `${percent}%`;\n}\n\nexport function degreesOf(radians: number) {\n  return (radians * HALF_TURN_DEG) / Math.PI;\n}\n\nexport function radiansOf(degrees: number) {\n  return (degrees * Math.PI) / HALF_TURN_DEG;\n}\n\n/** The angle equal to `target` that is closest to `current`, so a turn towards it goes the short way round. */\nexport function nearestAngleOf(target: number, current: number) {\n  const difference = target - current;\n  const turns = Math.round(difference / FULL_TURN_DEG);\n  const wrapped = difference - FULL_TURN_DEG * turns;\n  return current + wrapped;\n}\n\n/** The line between two points of a stage that is `aspect` times wider than it is tall. */\nexport function spanBetween(\n  from: ScenePoint,\n  to: ScenePoint,\n  aspect: number\n): SceneSpan {\n  const acrossShare = to.x - from.x;\n  const downShare = to.y - from.y;\n  const downInWidths = downShare / aspect;\n  const lengthInWidths = Math.hypot(acrossShare, downInWidths);\n  const angle = Math.atan2(downInWidths, acrossShare);\n  const degrees = degreesOf(angle);\n  return {\n    lengthPercent: rounded(lengthInWidths * 100),\n    angleDeg: rounded(degrees),\n  };\n}\n\n/** Where a tile centred on a point of the stage goes: its `left` and `top`. */\nexport function placeOf(point: ScenePoint) {\n  return { left: percentOf(point.x), top: percentOf(point.y) };\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/geometry.ts"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/use-scene-animations.ts",
      "content": "'use client';\n\nimport { useEffect, useEffectEvent, useRef, type RefObject } from 'react';\n\nfunction playAll(animations: Animation[]) {\n  for (const animation of animations) {\n    animation.play();\n  }\n}\n\nfunction pauseAll(animations: Animation[]) {\n  for (const animation of animations) {\n    animation.pause();\n  }\n}\n\nfunction cancelAll(animations: Animation[]) {\n  for (const animation of animations) {\n    animation.cancel();\n  }\n}\n\n/**\n * The looping animations of a scene, made on its stage the first time it plays. They pause while the\n * scene does not play and resume where they stopped, so nothing runs off screen or in a hidden tab.\n * A new `resetKey` drops them and makes them again, for a scene whose content changed.\n */\nexport function useSceneAnimations<Stage extends HTMLElement>(\n  stageRef: RefObject<Stage | null>,\n  isPlaying: boolean,\n  create: (stage: Stage) => Animation[],\n  resetKey = ''\n) {\n  const made = useRef<Animation[] | null>(null);\n\n  const animationsOf = useEffectEvent((stage: Stage) => {\n    made.current ??= create(stage);\n    return made.current;\n  });\n\n  const dropAnimations = useEffectEvent(() => {\n    const animations = made.current ?? [];\n    cancelAll(animations);\n    made.current = null;\n  });\n\n  useEffect(() => {\n    const stage = stageRef.current;\n    if (!stage || !isPlaying) {\n      return;\n    }\n    const animations = animationsOf(stage);\n    playAll(animations);\n    return () => pauseAll(animations);\n  }, [stageRef, isPlaying, resetKey]);\n\n  useEffect(() => {\n    return () => dropAnimations();\n  }, [resetKey]);\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/use-scene-animations.ts"
    },
    {
      "path": "registry/ndeko/components/illustration/_parts/use-scene-play.ts",
      "content": "'use client';\n\nimport { useInView } from 'motion/react';\nimport { useRef } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nconst IN_VIEW_SHARE = 0.3;\n\nexport type ScenePlay = {\n  /** True while a visitor can see the scene move: on screen, in a visible tab, without reduced motion. */\n  isPlaying: boolean;\n  /** True under reduced motion: the scene rests on its still frame. */\n  isStill: boolean;\n};\n\n/**\n * An illustration moves only while someone can see it. Everything that loops in a scene hangs on\n * `isPlaying`, so nothing runs off screen, in a hidden tab or under reduced motion.\n */\nexport function useScenePlay<Element extends HTMLElement = HTMLDivElement>() {\n  const ref = useRef<Element>(null);\n  const isInView = useInView(ref, { amount: IN_VIEW_SHARE });\n  const isTabVisible = useDocumentVisible();\n  const isStill = usePrefersReducedMotion();\n  const isOnScreen = isInView && isTabVisible;\n  const isPlaying = isOnScreen && !isStill;\n\n  return { ref, isPlaying, isStill };\n}\n",
      "type": "registry:component",
      "target": "components/illustration/_parts/use-scene-play.ts"
    }
  ],
  "categories": [
    "components",
    "illustration"
  ],
  "type": "registry:component"
}