{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "illustration-07",
  "title": "Tool beam",
  "description": "Your product between the tools it connects, with a light that runs along each curved beam the way the data goes; pointing at a tool dims the others and a click holds the flow.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/brand-logos.json",
    "https://ui.ndekocode.dev/r/brand-tile.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.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-07.tsx",
      "content": "'use client';\n\nimport { useMemo, useState } from 'react';\n\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\nimport { PauseIcon, PlayIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport {\n  degreesOf,\n  nearestAngleOf,\n  placeOf,\n  rounded,\n  spanBetween,\n  type ScenePoint,\n} from './_parts/geometry';\nimport { useSceneAnimations } from './_parts/use-scene-animations';\nimport { useScenePlay } from './_parts/use-scene-play';\n\nexport type BeamFlow = 'in' | 'out';\n\nexport type BeamTool = {\n  id: string;\n  name: string;\n  brand: BrandSlug;\n  /** `in` sends data to the product, `out` receives data from it. */\n  flow: BeamFlow;\n};\n\ntype LightShape = 'along' | 'clockwise' | 'counterclockwise';\n\ntype Light = {\n  /** Where the transform of the light starts from: the centre of its arc, or the start of its line. */\n  origin: ScenePoint;\n  from: string;\n  to: string;\n  rest: string;\n  shape: LightShape;\n};\n\ntype Beam = {\n  tool: BeamTool;\n  point: ScenePoint;\n  /** The beam as a path of the stage drawing, 300 by 200. */\n  path: string;\n  light: Light;\n};\n\nconst STAGE_ASPECT = 3 / 2;\n\nconst VIEW_WIDTH = 300;\n\nconst VIEW_HEIGHT = 200;\n\nconst VIEW_BOX = `0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`;\n\nconst HUB: ScenePoint = { x: 0.5, y: 0.5 };\n\nconst SOURCE_COLUMN = 0.1;\n\nconst TARGET_COLUMN = 0.9;\n\n/** A tool nearly level with the product gets a straight beam: the arc through both would be almost flat. */\nconst LEVEL_WITHIN = 0.02;\n\nconst FLOW_MS = 2600;\n\nconst FLOW_STAGGER_MS = 430;\n\nconst LIGHT_CLASS: Record<LightShape, string> = {\n  along: 'h-0.5 w-5 bg-linear-to-r',\n  clockwise: 'h-5 w-0.5 bg-linear-to-b',\n  counterclockwise: 'h-5 w-0.5 bg-linear-to-t',\n};\n\nfunction rowOf(index: number, count: number) {\n  return (index + 0.5) / count;\n}\n\nfunction viewPointOf(point: ScenePoint) {\n  const x = rounded(point.x * VIEW_WIDTH);\n  const y = rounded(point.y * VIEW_HEIGHT);\n  return `${x} ${y}`;\n}\n\nfunction endsOf(tool: BeamTool, point: ScenePoint) {\n  if (tool.flow === 'in') {\n    return { source: point, target: HUB };\n  }\n  return { source: HUB, target: point };\n}\n\n/** A straight beam: the light slides from the source to the target. Lengths are in hundredths of the stage width. */\nfunction lineLightOf(source: ScenePoint, target: ScenePoint): Light {\n  const span = spanBetween(source, target, STAGE_ASPECT);\n  const half = rounded(span.lengthPercent / 2);\n  const turned = `rotate(${span.angleDeg}deg)`;\n  return {\n    origin: source,\n    from: `${turned} translateX(0cqw)`,\n    to: `${turned} translateX(${span.lengthPercent}cqw)`,\n    rest: `${turned} translateX(${half}cqw)`,\n    shape: 'along',\n  };\n}\n\nfunction shapeOfTurn(fromDeg: number, toDeg: number): LightShape {\n  if (toDeg > fromDeg) {\n    return 'clockwise';\n  }\n  return 'counterclockwise';\n}\n\nfunction sweepOf(fromDeg: number, toDeg: number) {\n  if (toDeg > fromDeg) {\n    return 1;\n  }\n  return 0;\n}\n\n/**\n * A curved beam is an arc of the circle that passes through the tool and touches the level line of\n * the product, so every beam runs into the product from its side. The light is turned around the\n * centre of that circle, which moves it along the arc with a transform alone.\n */\nfunction arcBeamOf(tool: BeamTool, point: ScenePoint): Beam {\n  const across = point.x - HUB.x;\n  const down = (point.y - HUB.y) / STAGE_ASPECT;\n  const side = Math.sign(down);\n  const reach = across * across + down * down;\n  const radius = reach / (2 * Math.abs(down));\n  const hubDown = HUB.y / STAGE_ASPECT;\n  const centreDown = hubDown + radius * side;\n  const centre: ScenePoint = { x: HUB.x, y: centreDown * STAGE_ASPECT };\n  const hubDeg = -90 * side;\n  const toolAngle = Math.atan2(down - radius * side, across);\n  const rawToolDeg = degreesOf(toolAngle);\n  const toolDeg = nearestAngleOf(rawToolDeg, hubDeg);\n  const radiusInHundredths = rounded(radius * 100);\n  const out = `translateX(${radiusInHundredths}cqw)`;\n  const viewRadius = rounded(radius * VIEW_WIDTH);\n  const sweep = sweepOf(toolDeg, hubDeg);\n  const start = viewPointOf(point);\n  const end = viewPointOf(HUB);\n  const path = `M ${start} A ${viewRadius} ${viewRadius} 0 0 ${sweep} ${end}`;\n  let fromDeg = rounded(toolDeg);\n  let toDeg = rounded(hubDeg);\n  if (tool.flow === 'out') {\n    fromDeg = rounded(hubDeg);\n    toDeg = rounded(toolDeg);\n  }\n  const restDeg = rounded((fromDeg + toDeg) / 2);\n  return {\n    tool,\n    point,\n    path,\n    light: {\n      origin: centre,\n      from: `rotate(${fromDeg}deg) ${out}`,\n      to: `rotate(${toDeg}deg) ${out}`,\n      rest: `rotate(${restDeg}deg) ${out}`,\n      shape: shapeOfTurn(fromDeg, toDeg),\n    },\n  };\n}\n\nfunction lineBeamOf(tool: BeamTool, point: ScenePoint): Beam {\n  const ends = endsOf(tool, point);\n  const start = viewPointOf(point);\n  const end = viewPointOf(HUB);\n  const path = `M ${start} L ${end}`;\n  return { tool, point, path, light: lineLightOf(ends.source, ends.target) };\n}\n\nfunction beamOf(tool: BeamTool, point: ScenePoint) {\n  const down = (point.y - HUB.y) / STAGE_ASPECT;\n  const isLevel = Math.abs(down) < LEVEL_WITHIN;\n  if (isLevel) {\n    return lineBeamOf(tool, point);\n  }\n  return arcBeamOf(tool, point);\n}\n\n/** Tools that send stand in a column on the left, tools that receive on the right. */\nfunction beamsOf(tools: BeamTool[]) {\n  const sources = tools.filter((tool) => tool.flow === 'in');\n  const targets = tools.filter((tool) => tool.flow === 'out');\n  const sourceBeams = sources.map((tool, index) => {\n    const point = { x: SOURCE_COLUMN, y: rowOf(index, sources.length) };\n    return beamOf(tool, point);\n  });\n  const targetBeams = targets.map((tool, index) => {\n    const point = { x: TARGET_COLUMN, y: rowOf(index, targets.length) };\n    return beamOf(tool, point);\n  });\n  return [...sourceBeams, ...targetBeams];\n}\n\n/** A light leaves from under its source and fades as it reaches its target. Each one starts part of the way, so they never leave together. */\nfunction animateLights(stage: HTMLElement, beams: Beam[]) {\n  const lights = stage.querySelectorAll<HTMLElement>('[data-beam-light]');\n  const animations: Animation[] = [];\n  lights.forEach((element, index) => {\n    const beam = beams[index];\n    if (!beam) {\n      return;\n    }\n    const keyframes: Keyframe[] = [\n      { offset: 0, transform: beam.light.from, opacity: 0 },\n      { offset: 0.15, opacity: 1 },\n      { offset: 0.8, opacity: 1 },\n      { offset: 1, transform: beam.light.to, opacity: 0 },\n    ];\n    const stagger = index * FLOW_STAGGER_MS;\n    const lead = stagger % FLOW_MS;\n    const timing = { duration: FLOW_MS, iterations: Infinity, delay: -lead };\n    animations.push(element.animate(keyframes, timing));\n  });\n  return animations;\n}\n\nfunction structureKeyOf(beams: Beam[]) {\n  const ids = beams.map((beam) => `${beam.tool.id}:${beam.tool.flow}`);\n  return ids.join('|');\n}\n\nfunction toolLabelOf(tool: BeamTool, productName: string) {\n  const flowWord = flowWordOf(tool.flow, productName);\n  return `${tool.name}, ${flowWord}`;\n}\n\nfunction isDimmed(focusedId: string | null, toolId: string) {\n  if (focusedId === null) {\n    return false;\n  }\n  return focusedId !== toolId;\n}\n\nfunction toggledPin(pinnedId: string | null, toolId: string) {\n  if (pinnedId === toolId) {\n    return null;\n  }\n  return toolId;\n}\n\nfunction flowWordOf(flow: BeamFlow, productName: string) {\n  if (flow === 'in') {\n    return `sends data to ${productName}`;\n  }\n  return `receives data from ${productName}`;\n}\n\nfunction pauseWordOf(isPaused: boolean) {\n  if (isPaused) {\n    return 'The flow is paused';\n  }\n  return 'The flow runs again';\n}\n\nfunction pauseLabelOf(isPaused: boolean) {\n  if (isPaused) {\n    return 'Resume flow';\n  }\n  return 'Pause flow';\n}\n\nfunction pauseKeyOf(isPaused: boolean) {\n  if (isPaused) {\n    return 'resume';\n  }\n  return 'pause';\n}\n\nfunction isMouse(event: React.PointerEvent) {\n  return event.pointerType === 'mouse';\n}\n\nfunction isKeyboardFocus(event: React.FocusEvent) {\n  const target = event.target;\n  if (!(target instanceof Element)) {\n    return false;\n  }\n  return target.matches(':focus-visible');\n}\n\nexport type ToolBeamProps = {\n  /** Your product, in the middle. Its mark is drawn from this name. */\n  productName: string;\n  tools: BeamTool[];\n  className?: string;\n};\n\nexport function ToolBeam({ productName, tools, className }: ToolBeamProps) {\n  const { ref, isPlaying, isStill } = useScenePlay();\n  const [isPaused, setIsPaused] = useState(false);\n  const [pointedId, setPointedId] = useState<string | null>(null);\n  const [pinnedId, setPinnedId] = useState<string | null>(null);\n  const [announcement, setAnnouncement] = useState('');\n  const beams = useMemo(() => beamsOf(tools), [tools]);\n  const focusedId = pointedId ?? pinnedId;\n  const isFlowing = isPlaying && !isPaused;\n\n  useSceneAnimations(\n    ref,\n    isFlowing,\n    (stage) => animateLights(stage, beams),\n    structureKeyOf(beams)\n  );\n\n  function togglePause() {\n    if (isStill) {\n      return;\n    }\n    const next = !isPaused;\n    setIsPaused(next);\n    setAnnouncement(pauseWordOf(next));\n  }\n\n  // A tap also gives the focus on some phones: only a focus from the keyboard counts as pointing at a tool.\n  function pointWithKeyboard(event: React.FocusEvent, toolId: string) {\n    if (isKeyboardFocus(event)) {\n      setPointedId(toolId);\n    }\n  }\n\n  function pointWithMouse(event: React.PointerEvent, toolId: string | null) {\n    if (isMouse(event)) {\n      setPointedId(toolId);\n    }\n  }\n\n  function togglePin(event: React.MouseEvent, toolId: string) {\n    event.stopPropagation();\n    setPinnedId((current) => toggledPin(current, toolId));\n  }\n\n  return (\n    <div\n      ref={ref}\n      className={cn(\n        'flex w-full max-w-[28rem] flex-col items-center gap-3',\n        className\n      )}\n    >\n      <div\n        role='group'\n        aria-label={`${productName} between the tools it connects`}\n        onClick={togglePause}\n        className='@container relative aspect-[3/2] w-full overflow-hidden'\n      >\n        <svg\n          aria-hidden='true'\n          viewBox={VIEW_BOX}\n          fill='none'\n          className='absolute inset-0 size-full'\n        >\n          {beams.map((beam) => (\n            <path\n              key={beam.tool.id}\n              d={beam.path}\n              data-dimmed={isDimmed(focusedId, beam.tool.id)}\n              vectorEffect='non-scaling-stroke'\n              strokeWidth={1.5}\n              strokeLinecap='round'\n              className='stroke-foreground/12 transition-opacity duration-200 ease-(--ease-out-strong) data-[dimmed=true]:opacity-30'\n            />\n          ))}\n        </svg>\n        {beams.map((beam) => (\n          <span\n            key={beam.tool.id}\n            aria-hidden='true'\n            data-dimmed={isDimmed(focusedId, beam.tool.id)}\n            className='pointer-events-none absolute inset-0 transition-opacity duration-200 ease-(--ease-out-strong) data-[dimmed=true]:opacity-15'\n          >\n            <span\n              data-beam-light=''\n              style={{\n                ...placeOf(beam.light.origin),\n                transform: beam.light.rest,\n              }}\n              className={cn(\n                'from-primary/0 to-primary absolute -translate-x-1/2 -translate-y-1/2 rounded-full',\n                LIGHT_CLASS[beam.light.shape]\n              )}\n            />\n          </span>\n        ))}\n        <span className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'>\n          <CompanyMark\n            seed={productName}\n            title={productName}\n            className='size-12 rounded-[14px]'\n          />\n        </span>\n        <ul aria-label='Tools'>\n          {beams.map((beam) => (\n            <li key={beam.tool.id}>\n              <button\n                type='button'\n                aria-pressed={pinnedId === beam.tool.id}\n                aria-label={toolLabelOf(beam.tool, productName)}\n                data-dimmed={isDimmed(focusedId, beam.tool.id)}\n                style={placeOf(beam.point)}\n                onClick={(event) => togglePin(event, beam.tool.id)}\n                onPointerEnter={(event) => pointWithMouse(event, beam.tool.id)}\n                onPointerLeave={(event) => pointWithMouse(event, null)}\n                onFocus={(event) => pointWithKeyboard(event, beam.tool.id)}\n                onBlur={() => setPointedId(null)}\n                className='focus-visible:ring-ring focus-visible:ring-offset-background absolute flex -translate-x-1/2 -translate-y-1/2 cursor-pointer rounded-lg transition-[opacity,scale] duration-150 ease-(--ease-out-strong) outline-none focus-visible:ring-2 focus-visible:ring-offset-2 active:scale-[0.97] data-[dimmed=true]:opacity-50'\n              >\n                <BrandTile brand={beam.tool.brand} size='xl' />\n              </button>\n            </li>\n          ))}\n        </ul>\n      </div>\n      <div className='flex h-7 items-center'>\n        {!isStill && (\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            onClick={togglePause}\n          >\n            <AnimatedSize\n              as='span'\n              axis='width'\n              contentClassName='flex items-center'\n            >\n              <Swap swapKey={pauseKeyOf(isPaused)}>\n                <span className='flex items-center gap-1.5'>\n                  {isPaused && <PlayIcon />}\n                  {!isPaused && <PauseIcon />}\n                  {pauseLabelOf(isPaused)}\n                </span>\n              </Swap>\n            </AnimatedSize>\n          </Button>\n        )}\n      </div>\n      <LiveRegion message={announcement} />\n    </div>\n  );\n}\n\nconst TOOLS: BeamTool[] = [\n  { id: 'stripe', name: 'Stripe', brand: 'stripe', flow: 'in' },\n  { id: 'shopify', name: 'Shopify', brand: 'shopify', flow: 'in' },\n  { id: 'hubspot', name: 'HubSpot', brand: 'hubspot', flow: 'in' },\n  { id: 'notion', name: 'Notion', brand: 'notion', flow: 'out' },\n  { id: 'linear', name: 'Linear', brand: 'linear', flow: 'out' },\n  { id: 'gmail', name: 'Gmail', brand: 'gmail', flow: 'out' },\n];\n\nexport default function Illustration07() {\n  return <ToolBeam productName='Meridian' tools={TOOLS} />;\n}\n",
      "type": "registry:component",
      "target": "components/illustration/illustration-07.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"
}