{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "maps-01",
  "title": "Agent activity globe",
  "description": "A dotted globe beside the live runs, tokens and spend of four regions: each hand-off turns the globe to show both regions and draws its arc between them while the counts roll in the list, and picking a region turns the globe back to it.",
  "dependencies": [],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/mesh-tile.json",
    "https://ui.ndekocode.dev/r/motion-globe.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/replay-button.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/use-session.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/maps/maps-01/index.tsx",
      "content": "'use client';\n\nimport { memo, useCallback, useState } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { ArrowRightIcon } from '@/registry/ndeko/lib/icons';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MeshTile } from '@/registry/ndeko/ui/mesh-tile';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { ACTIVITY_TITLE, AGENTS, regionOf, type RegionId } from './data';\nimport { GlobeStage } from './globe-stage';\nimport { RegionList } from './region-list';\nimport {\n  facingLineOf,\n  handoffLineOf,\n  INITIAL,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n  totalRunsOf,\n  type Handoff,\n} from './session';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nconst ARROW_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);\n\n/** The latest hand-off, under the globe, so the arc says what it is. It stays on one line. */\nconst HandoffLine = memo(function HandoffLine({\n  handoff,\n}: {\n  handoff: Handoff;\n}) {\n  const agent = AGENTS[handoff.agentId];\n  const color = seriesColorOf(agent.series);\n  const line = handoffLineOf(handoff);\n  const from = regionOf(handoff.from).name;\n  const to = regionOf(handoff.to).name;\n\n  return (\n    <p className='text-muted-foreground flex h-5 items-center justify-center text-xs whitespace-nowrap'>\n      <span className='sr-only'>{line}</span>\n      <Swap swapKey={line}>\n        <span aria-hidden='true' className='flex items-center'>\n          <MeshTile\n            seed={agent.name}\n            color={color}\n            size='sm'\n            className='me-1.5'\n          />\n          <span className='text-foreground me-1.5 font-medium'>\n            {agent.name}\n          </span>\n          {from}\n          <ArrowRightIcon className='mx-1 size-3' />\n          {to}\n        </span>\n      </Swap>\n    </p>\n  );\n});\n\nexport default function Maps01() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const isVisible = useDocumentVisible();\n  const [releasedId, setReleasedId] = useState<RegionId | null>(null);\n  const isOnScreen = isInView && isVisible;\n  const isHeld = releasedId !== state.selectedId;\n  const total = totalRunsOf(state);\n  const canReplay = isFinished && !isAutoplaying;\n  const message = spokenUnless(isAutoplaying, state.notice);\n  const facingLine = facingLineOf(state.facing);\n  const globeLabel = `Globe of agent activity, ${facingLine}`;\n\n  const pick = useCallback(\n    (id: RegionId) => {\n      setReleasedId(null);\n      act({ type: 'selected', id });\n    },\n    [act]\n  );\n\n  function letGo() {\n    setReleasedId(state.selectedId);\n  }\n\n  function letGoOnArrows(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (ARROW_KEYS.has(event.key)) {\n      letGo();\n    }\n  }\n\n  function replay() {\n    setReleasedId(null);\n    restart();\n  }\n\n  return (\n    <div\n      ref={ref}\n      className='bg-background text-foreground @container min-h-dvh w-full'\n    >\n      <div className='mx-auto flex max-w-5xl flex-col gap-5 p-4 @3xl:gap-6 @3xl:p-8'>\n        <header className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n          <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n            <h1 className='text-lg font-semibold text-balance'>\n              {ACTIVITY_TITLE}\n            </h1>\n            <p className='text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs'>\n              Live runs, tokens and spend by region\n              <Badge variant='secondary'>Illustrative</Badge>\n            </p>\n          </div>\n          <ReplayButton\n            isShown={canReplay}\n            onReplay={replay}\n            label='Replay the activity'\n          />\n        </header>\n\n        <div className='grid grid-cols-1 items-center gap-6 @3xl:grid-cols-2 @3xl:gap-8'>\n          <div className='flex min-w-0 flex-col items-center gap-3'>\n            <div\n              onPointerDown={letGo}\n              onKeyDown={letGoOnArrows}\n              className='relative aspect-square w-full max-w-[17rem] @md:max-w-[20rem] @3xl:max-w-[26rem]'\n            >\n              <div\n                aria-hidden='true'\n                className='bg-foreground/[0.04] absolute inset-[10%] rounded-full'\n              />\n              <GlobeStage\n                selectedId={state.selectedId}\n                handoff={state.lastHandoff}\n                drawingId={state.drawingId}\n                facing={state.facing}\n                isHeld={isHeld}\n                isActive={isOnScreen}\n                label={globeLabel}\n              />\n            </div>\n            <HandoffLine handoff={state.lastHandoff} />\n          </div>\n          <RegionList\n            loads={state.loads}\n            selectedId={state.selectedId}\n            total={total}\n            pressed={pressed}\n            onSelect={pick}\n          />\n        </div>\n      </div>\n      <LiveRegion message={message} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/maps-01/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/maps/maps-01/globe-stage.tsx",
      "content": "'use client';\n\nimport { memo, useEffect, useMemo, useState } from 'react';\n\nimport {\n  Globe,\n  type GlobeArc,\n  type GlobeLocation,\n  type GlobeMarker,\n} from '@/components/core/globe';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nimport { regionOf, type RegionId } from './data';\nimport { drawnShareOf, pointAlong } from './geo';\nimport {\n  facingKeyOf,\n  facingLocationOf,\n  handoffKeyOf,\n  regionsInViewOf,\n  type Facing,\n  type Handoff,\n} from './session';\n\n/** The globe has come most of the way to a new view this long after it starts to turn. */\nconst TURN_LEAD_MS = 600;\n\n/** An arc draws itself in a few steps, one render each, while the globe settles: never one render a frame. */\nconst DRAW_STEPS = 6;\n\nconst STEP_MS = 50;\n\nconst PICKED_MARKER = 0.075;\n\nconst REGION_MARKER = 0.05;\n\n/** Close to the latitude of the views, so the globe barely tilts when it first faces one. */\nconst STARTING_TILT = 30;\n\nconst NO_ARCS: GlobeArc[] = [];\n\ntype Settled = {\n  key: string;\n  location: GlobeLocation;\n};\n\n/**\n * The globe starts on the meridian ninety degrees west, tilted as asked, and still has to turn to\n * its first view: even the first arc waits for it.\n */\nconst STARTING_VIEW: Settled = { key: '', location: [STARTING_TILT, -90] };\n\ntype Drawing = {\n  id: number | null;\n  step: number;\n};\n\nfunction markerSizeOf(isPicked: boolean) {\n  if (isPicked) {\n    return PICKED_MARKER;\n  }\n  return REGION_MARKER;\n}\n\n/** Only the regions near the centre of the view the globe leaves and of the one it turns to. */\nfunction markersOf(\n  selectedId: RegionId,\n  target: GlobeLocation,\n  previous: GlobeLocation\n): GlobeMarker[] {\n  const regions = regionsInViewOf(target, previous);\n  return regions.map((region) => {\n    const isPicked = region.id === selectedId;\n    return {\n      location: region.location,\n      size: markerSizeOf(isPicked),\n      label: `${region.name}, ${region.place}`,\n    };\n  });\n}\n\nfunction arcOf(handoff: Handoff, drawing: Drawing): GlobeArc | null {\n  const from = regionOf(handoff.from).location;\n  const to = regionOf(handoff.to).location;\n  const isDrawing = handoff.id === drawing.id;\n  const isWhole = !isDrawing || drawing.step >= DRAW_STEPS;\n  if (isWhole) {\n    return { from, to };\n  }\n  if (drawing.step === 0) {\n    return null;\n  }\n  const progress = drawing.step / DRAW_STEPS;\n  const share = drawnShareOf(progress);\n  const end = pointAlong(from, to, share);\n  return { from, to: end };\n}\n\n/** The arc of the last hand-off, only while the globe faces its route: from elsewhere it would cross the rim. */\nfunction arcsOf(handoff: Handoff, drawing: Drawing, isFramed: boolean) {\n  if (!isFramed) {\n    return NO_ARCS;\n  }\n  const arc = arcOf(handoff, drawing);\n  if (!arc) {\n    return NO_ARCS;\n  }\n  return [arc];\n}\n\nfunction grown(drawing: Drawing): Drawing {\n  const next = drawing.step + 1;\n  const step = Math.min(next, DRAW_STEPS);\n  return { id: drawing.id, step };\n}\n\n/** Under reduced motion an arc is whole as soon as its hand-off happens. */\nfunction firstStepOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return DRAW_STEPS;\n  }\n  return 0;\n}\n\n/** A globe a person turned by hand stays where they left it until a region is picked again. */\nfunction focusOf(isHeld: boolean, target: GlobeLocation) {\n  if (isHeld) {\n    return target;\n  }\n  return null;\n}\n\nexport type GlobeStageProps = {\n  selectedId: RegionId;\n  handoff: Handoff;\n  drawingId: number | null;\n  facing: Facing;\n  /** False once a person turned the globe by hand. */\n  isHeld: boolean;\n  /** Nothing turns or draws while the block is off screen or the tab is hidden. */\n  isActive: boolean;\n  label: string;\n};\n\n/**\n * The globe draws frames only while it turns, and an arc draws itself in a few renders once the\n * globe has nearly arrived. Between two beats nothing here renders, and the globe stays still.\n */\nexport const GlobeStage = memo(function GlobeStage({\n  selectedId,\n  handoff,\n  drawingId,\n  facing,\n  isHeld,\n  isActive,\n  label,\n}: GlobeStageProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const facingKey = facingKeyOf(facing);\n  const target = useMemo(() => facingLocationOf(facing), [facing]);\n  const [settled, setSettled] = useState<Settled>(STARTING_VIEW);\n  const [drawing, setDrawing] = useState<Drawing>({\n    id: drawingId,\n    step: DRAW_STEPS,\n  });\n  const isNewDrawing = drawing.id !== drawingId;\n  if (isNewDrawing) {\n    setDrawing({ id: drawingId, step: firstStepOf(shouldReduceMotion) });\n  }\n  const isTurning = settled.key !== facingKey;\n  const arrivesAtOnce = isTurning && shouldReduceMotion;\n  if (arrivesAtOnce) {\n    setSettled({ key: facingKey, location: target });\n  }\n  const routeKey = handoffKeyOf(handoff);\n  const facesRoute = facingKey === routeKey;\n  const hasArrived = settled.key === routeKey;\n  const isFramed = isHeld && facesRoute && hasArrived;\n  const hasDrawing = drawing.id !== null;\n  const isUnfinished = hasDrawing && drawing.step < DRAW_STEPS;\n  const canDraw = isActive && isFramed;\n  const isGrowing = canDraw && isUnfinished;\n\n  useEffect(() => {\n    if (!isTurning || !isActive) {\n      return;\n    }\n    const arrival: Settled = { key: facingKey, location: target };\n    const timer = setTimeout(() => setSettled(arrival), TURN_LEAD_MS);\n    return () => clearTimeout(timer);\n  }, [isTurning, isActive, facingKey, target]);\n\n  useEffect(() => {\n    if (!isGrowing) {\n      return;\n    }\n    const timer = setTimeout(() => setDrawing(grown), STEP_MS);\n    return () => clearTimeout(timer);\n  }, [isGrowing, drawing.step]);\n\n  const markers = useMemo(\n    () => markersOf(selectedId, target, settled.location),\n    [selectedId, target, settled.location]\n  );\n  const arcs = useMemo(\n    () => arcsOf(handoff, drawing, isFramed),\n    [handoff, drawing, isFramed]\n  );\n  const focus = useMemo(() => focusOf(isHeld, target), [isHeld, target]);\n\n  return (\n    <Globe\n      markers={markers}\n      arcs={arcs}\n      focus={focus}\n      autoRotate={false}\n      tilt={STARTING_TILT}\n      label={label}\n    />\n  );\n});\n",
      "type": "registry:component",
      "target": "components/blocks/maps-01/globe-stage.tsx"
    },
    {
      "path": "registry/ndeko/blocks/maps/maps-01/region-list.tsx",
      "content": "'use client';\n\nimport { memo } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { REGIONS, type Region, type RegionId, type RegionLoad } from './data';\n\n/** A row is 48px tall with 2px below it: the highlight travels this far a row, on transform alone. */\nconst ROW_PITCH_PX = 50;\n\nconst ROW = [\n  'flex h-12 w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-start outline-none',\n  'transition-[background-color,scale] duration-150 ease-(--ease-out-strong) active:scale-[0.98]',\n  'hover:bg-foreground/[0.03] focus-visible:ring-ring/25 focus-visible:ring-[3px]',\n].join(' ');\n\nconst HIGHLIGHT =\n  'bg-foreground/[0.06] pointer-events-none absolute inset-x-0 top-0 h-12 rounded-lg transition-transform duration-200 ease-(--ease-out-strong)';\n\nconst FIGURE = 'shrink-0 justify-end text-[13px]';\n\nconst SPEND: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 2,\n  maximumFractionDigits: 2,\n};\n\nconst SPEND_TEXT = new Intl.NumberFormat('en-US', SPEND);\n\nfunction runsWordOf(count: number) {\n  if (count === 1) {\n    return '1 run';\n  }\n  return `${count} runs`;\n}\n\nfunction liveWordOf(count: number) {\n  if (count === 1) {\n    return 'run live';\n  }\n  return 'runs live';\n}\n\nfunction regionsWordOf(count: number) {\n  if (count === 1) {\n    return '1 region';\n  }\n  return `${count} regions`;\n}\n\nfunction totalLineOf(total: number) {\n  const live = liveWordOf(total);\n  const regions = regionsWordOf(REGIONS.length);\n  return `${live} in ${regions}`;\n}\n\nfunction dollarsOf(cents: number) {\n  return cents / 100;\n}\n\n/** Europe, Frankfurt: 11 runs, 140k tokens a minute, $7.10 an hour. */\nfunction spokenOf(region: Region, load: RegionLoad) {\n  const runs = runsWordOf(load.runs);\n  const dollars = dollarsOf(load.cents);\n  const spend = SPEND_TEXT.format(dollars);\n  const place = `${region.name}, ${region.place}`;\n  return `${place}: ${runs}, ${load.tokens}k tokens a minute, ${spend} an hour`;\n}\n\nfunction dotOf(isPicked: boolean) {\n  if (isPicked) {\n    return 'bg-primary';\n  }\n  return 'bg-foreground/25';\n}\n\nfunction highlightStyleOf(selectedId: RegionId) {\n  const index = REGIONS.findIndex((region) => region.id === selectedId);\n  const row = Math.max(index, 0);\n  const offset = row * ROW_PITCH_PX;\n  return { transform: `translateY(${offset}px)` };\n}\n\ntype RegionRowProps = {\n  region: Region;\n  load: RegionLoad;\n  isPicked: boolean;\n  isPressed: boolean;\n  onSelect: (id: RegionId) => void;\n};\n\n/** A row renders again only when its own figures, its pick or its press change. */\nconst RegionRow = memo(function RegionRow({\n  region,\n  load,\n  isPicked,\n  isPressed,\n  onSelect,\n}: RegionRowProps) {\n  const spend = dollarsOf(load.cents);\n\n  return (\n    <li>\n      <button\n        type='button'\n        aria-pressed={isPicked}\n        aria-label={spokenOf(region, load)}\n        onClick={() => onSelect(region.id)}\n        className={cn(ROW, pressedQuietOf(isPressed))}\n      >\n        <span\n          aria-hidden='true'\n          className={cn(\n            'size-2 shrink-0 rounded-full transition-colors duration-150',\n            dotOf(isPicked)\n          )}\n        />\n        <span className='flex min-w-0 flex-1 flex-col'>\n          <span className='truncate text-[13px] leading-5 font-medium'>\n            {region.name}\n          </span>\n          <span className='text-muted-foreground truncate text-xs leading-4'>\n            {region.place}\n          </span>\n        </span>\n        <MotionNumber value={load.runs} className={cn(FIGURE, 'w-9')} />\n        <MotionNumber\n          value={load.tokens}\n          suffix='k'\n          className={cn(FIGURE, 'w-12')}\n        />\n        <MotionNumber\n          value={spend}\n          format={SPEND}\n          className={cn(FIGURE, 'w-14')}\n        />\n      </button>\n    </li>\n  );\n});\n\nconst TotalLine = memo(function TotalLine({ total }: { total: number }) {\n  return (\n    <p className='flex flex-wrap items-baseline gap-x-2 px-2.5 pt-1.5 pb-3'>\n      <MotionNumber\n        value={total}\n        className='text-2xl leading-8 font-semibold'\n      />\n      <span className='text-muted-foreground text-xs'>\n        {totalLineOf(total)}\n      </span>\n    </p>\n  );\n});\n\nexport type RegionListProps = {\n  loads: Record<RegionId, RegionLoad>;\n  selectedId: RegionId;\n  total: number;\n  /** The region a demonstration picks, shown held down. */\n  pressed: string | null;\n  onSelect: (id: RegionId) => void;\n};\n\n/** One row per region: picking one turns the globe to it, and its figures roll as runs come and go. */\nexport function RegionList({\n  loads,\n  selectedId,\n  total,\n  pressed,\n  onSelect,\n}: RegionListProps) {\n  return (\n    <section\n      aria-label='Regions'\n      className='bg-card hairline-ring ring-border dark:bg-foreground/[0.04] flex min-w-0 flex-col rounded-xl p-2 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n    >\n      <TotalLine total={total} />\n      <div\n        aria-hidden='true'\n        className='text-muted-foreground flex items-center gap-2.5 px-2.5 pb-1 text-xs'\n      >\n        <span className='size-2 shrink-0' />\n        <span className='min-w-0 flex-1'>Region</span>\n        <span className='w-9 shrink-0 text-end'>Runs</span>\n        <span className='w-12 shrink-0 text-end'>Tokens</span>\n        <span className='w-14 shrink-0 text-end'>Spend</span>\n      </div>\n      <div className='relative'>\n        <span\n          aria-hidden='true'\n          style={highlightStyleOf(selectedId)}\n          className={HIGHLIGHT}\n        />\n        <ul className='relative flex flex-col gap-0.5'>\n          {REGIONS.map((region) => (\n            <RegionRow\n              key={region.id}\n              region={region}\n              load={loads[region.id]}\n              isPicked={region.id === selectedId}\n              isPressed={pressed === `region-${region.id}`}\n              onSelect={onSelect}\n            />\n          ))}\n        </ul>\n      </div>\n      <p className='text-muted-foreground px-2.5 pt-2 pb-1 text-xs'>\n        Tokens a minute and spend an hour, as they stand now\n      </p>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/maps-01/region-list.tsx"
    },
    {
      "path": "registry/ndeko/blocks/maps/maps-01/geo.ts",
      "content": "import type { GlobeLocation } from '@/components/core/globe';\n\ntype Vector = [x: number, y: number, z: number];\n\n/** Two places this close, or exactly opposite, have no single path between them to follow. */\nconst SAME_PLACE = 0.0001;\n\n/**\n * How far to the south of a route the globe looks from. Seen from a point on the route, an arc runs\n * through the centre as a straight line; seen from here it bows over the surface, and both ends of a\n * route of sixty degrees sit about thirty-five degrees from the centre, well inside the disk.\n */\nconst ROUTE_VIEW_ASIDE_DEG = 20;\n\n/** A picked region sits this far above the centre, so an arc that leaves it bows instead of running straight. */\nconst REGION_VIEW_SOUTH_DEG = 15;\n\n/**\n * The globe draws its markers a little above the sphere and hides only those behind the disk, so a\n * marker near the rim, or just past it, is drawn outside the disk. One shows only this close to the\n * centre of a view, which keeps the largest dot inside the disk up to about sixty-eight degrees.\n */\nconst MARKER_REACH_DEG = 60;\n\nfunction radiansOf(degrees: number) {\n  const halfTurns = degrees / 180;\n  return halfTurns * Math.PI;\n}\n\nfunction degreesOf(radians: number) {\n  const halfTurns = radians / Math.PI;\n  return halfTurns * 180;\n}\n\nfunction vectorOf([latitude, longitude]: GlobeLocation): Vector {\n  const latitudeAngle = radiansOf(latitude);\n  const longitudeAngle = radiansOf(longitude);\n  const ring = Math.cos(latitudeAngle);\n  const x = ring * Math.cos(longitudeAngle);\n  const y = ring * Math.sin(longitudeAngle);\n  const z = Math.sin(latitudeAngle);\n  return [x, y, z];\n}\n\n/** Rounding can push a sine or a cosine a hair past 1, where the inverse functions give no answer. */\nfunction withinUnit(value: number) {\n  const atMostOne = Math.min(1, value);\n  return Math.max(-1, atMostOne);\n}\n\nfunction locationOf([x, y, z]: Vector): GlobeLocation {\n  const height = withinUnit(z);\n  const latitudeAngle = Math.asin(height);\n  const longitudeAngle = Math.atan2(y, x);\n  const latitude = degreesOf(latitudeAngle);\n  const longitude = degreesOf(longitudeAngle);\n  return [latitude, longitude];\n}\n\nfunction alignmentOf(first: Vector, second: Vector) {\n  const alongX = first[0] * second[0];\n  const alongY = first[1] * second[1];\n  const alongZ = first[2] * second[2];\n  const flat = alongX + alongY;\n  return flat + alongZ;\n}\n\nfunction sumOf(first: Vector, second: Vector): Vector {\n  const x = first[0] + second[0];\n  const y = first[1] + second[1];\n  const z = first[2] + second[2];\n  return [x, y, z];\n}\n\nfunction scaledOf([x, y, z]: Vector, factor: number): Vector {\n  const scaledX = x * factor;\n  const scaledY = y * factor;\n  const scaledZ = z * factor;\n  return [scaledX, scaledY, scaledZ];\n}\n\n/** A route with no length has no direction: it stays at zero instead of dividing by it. */\nfunction unitOf(vector: Vector): Vector {\n  const length = Math.hypot(...vector);\n  if (length === 0) {\n    return vector;\n  }\n  return scaledOf(vector, 1 / length);\n}\n\nfunction crossOf(first: Vector, second: Vector): Vector {\n  const xUp = first[1] * second[2];\n  const xDown = first[2] * second[1];\n  const yUp = first[2] * second[0];\n  const yDown = first[0] * second[2];\n  const zUp = first[0] * second[1];\n  const zDown = first[1] * second[0];\n  const x = xUp - xDown;\n  const y = yUp - yDown;\n  const z = zUp - zDown;\n  return [x, y, z];\n}\n\nfunction blend(\n  start: number,\n  end: number,\n  startWeight: number,\n  endWeight: number\n) {\n  const fromStart = start * startWeight;\n  const fromEnd = end * endWeight;\n  return fromStart + fromEnd;\n}\n\n/** The point a share of the way from one place to another, along the shortest path over the globe. */\nexport function pointAlong(\n  from: GlobeLocation,\n  to: GlobeLocation,\n  share: number\n): GlobeLocation {\n  const start = vectorOf(from);\n  const end = vectorOf(to);\n  const alignment = alignmentOf(start, end);\n  const bounded = withinUnit(alignment);\n  const angle = Math.acos(bounded);\n  const spread = Math.sin(angle);\n  if (spread < SAME_PLACE) {\n    return to;\n  }\n  const rest = 1 - share;\n  const startAngle = rest * angle;\n  const endAngle = share * angle;\n  const startTurn = Math.sin(startAngle);\n  const endTurn = Math.sin(endAngle);\n  const startWeight = startTurn / spread;\n  const endWeight = endTurn / spread;\n  const x = blend(start[0], end[0], startWeight, endWeight);\n  const y = blend(start[1], end[1], startWeight, endWeight);\n  const z = blend(start[2], end[2], startWeight, endWeight);\n  return locationOf([x, y, z]);\n}\n\n/** Fast at the start and slow at the end, the way a line is drawn by hand. */\nexport function drawnShareOf(progress: number) {\n  const left = 1 - progress;\n  const leftCubed = left ** 3;\n  return 1 - leftCubed;\n}\n\n/** The pole of the circle a route runs along, taken on its southern side. */\nfunction southSideOf(start: Vector, end: Vector): Vector {\n  const across = crossOf(start, end);\n  const pole = unitOf(across);\n  const isNorthern = pole[2] > 0;\n  if (isNorthern) {\n    return scaledOf(pole, -1);\n  }\n  return pole;\n}\n\n/** Where the globe looks from to show a route: past its middle, a little to its south. */\nexport function routeViewOf(from: GlobeLocation, to: GlobeLocation) {\n  const start = vectorOf(from);\n  const end = vectorOf(to);\n  const sum = sumOf(start, end);\n  const middle = unitOf(sum);\n  const side = southSideOf(start, end);\n  const aside = radiansOf(ROUTE_VIEW_ASIDE_DEG);\n  const middleShare = Math.cos(aside);\n  const sideShare = Math.sin(aside);\n  const fromMiddle = scaledOf(middle, middleShare);\n  const fromSide = scaledOf(side, sideShare);\n  const view = sumOf(fromMiddle, fromSide);\n  return locationOf(view);\n}\n\nexport function regionViewOf([latitude, longitude]: GlobeLocation) {\n  const southern = latitude - REGION_VIEW_SOUTH_DEG;\n  const view: GlobeLocation = [southern, longitude];\n  return view;\n}\n\n/** The angle between two places, seen from the centre of the earth, in degrees. */\nexport function degreesApartOf(first: GlobeLocation, second: GlobeLocation) {\n  const start = vectorOf(first);\n  const end = vectorOf(second);\n  const alignment = alignmentOf(start, end);\n  const bounded = withinUnit(alignment);\n  const angle = Math.acos(bounded);\n  return degreesOf(angle);\n}\n\nexport function isNearCentreOf(location: GlobeLocation, view: GlobeLocation) {\n  const apart = degreesApartOf(location, view);\n  return apart <= MARKER_REACH_DEG;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/maps-01/geo.ts"
    },
    {
      "path": "registry/ndeko/blocks/maps/maps-01/session.ts",
      "content": "import type { GlobeLocation } from '@/components/core/globe';\nimport type { SessionStep } from '@/registry/ndeko/hooks/use-session';\n\nimport {\n  AGENTS,\n  LOADS,\n  regionOf,\n  REGIONS,\n  type AgentId,\n  type Region,\n  type RegionId,\n  type RegionLoad,\n} from './data';\nimport { isNearCentreOf, regionViewOf, routeViewOf } from './geo';\n\n/** What one run carries while it lives in a region: thousands of tokens a minute and cents an hour. */\nexport type RunRate = {\n  tokens: number;\n  cents: number;\n};\n\nexport type Handoff = {\n  id: number;\n  agentId: AgentId;\n  from: RegionId;\n  to: RegionId;\n};\n\n/** What the globe turns to: the region picked last, or the route of the hand-off that just happened. */\nexport type Facing =\n  | { kind: 'region'; id: RegionId }\n  | { kind: 'route'; from: RegionId; to: RegionId };\n\nexport type ActivityState = {\n  selectedId: RegionId;\n  loads: Record<RegionId, RegionLoad>;\n  lastHandoff: Handoff;\n  /** The hand-off whose arc still has to draw itself. Null while the arc on the globe is whole. */\n  drawingId: number | null;\n  facing: Facing;\n  nextId: number;\n  /** The last change, said to screen readers. */\n  notice: string;\n};\n\nexport type ActivityAction =\n  | { type: 'selected'; id: RegionId }\n  | { type: 'started'; region: RegionId; rate: RunRate }\n  | { type: 'finished'; region: RegionId; rate: RunRate }\n  | {\n      type: 'handedOff';\n      agentId: AgentId;\n      from: RegionId;\n      to: RegionId;\n      rate: RunRate;\n    };\n\ntype Step = SessionStep<ActivityState, ActivityAction>;\n\ntype Sign = 1 | -1;\n\n/** The hand-off a round ends on: a new round starts where the last one stopped, so the loop never shows. */\nconst LAST_HANDOFF: Handoff = {\n  id: 1,\n  agentId: 'coder',\n  from: 'us-east',\n  to: 'europe',\n};\n\nexport const INITIAL: ActivityState = {\n  selectedId: 'us-east',\n  loads: LOADS,\n  lastHandoff: LAST_HANDOFF,\n  drawingId: null,\n  facing: { kind: 'route', from: 'us-east', to: 'europe' },\n  nextId: LAST_HANDOFF.id + 1,\n  notice: '',\n};\n\n/** A route reads the same both ways, so a hand-off back along it needs no turn. */\nfunction routeKeyOf(from: RegionId, to: RegionId) {\n  const ends = [from, to];\n  ends.sort();\n  return `route:${ends.join(':')}`;\n}\n\nexport function facingKeyOf(facing: Facing) {\n  if (facing.kind === 'region') {\n    return `region:${facing.id}`;\n  }\n  return routeKeyOf(facing.from, facing.to);\n}\n\nexport function handoffKeyOf(handoff: Handoff) {\n  return routeKeyOf(handoff.from, handoff.to);\n}\n\nexport function facingLocationOf(facing: Facing): GlobeLocation {\n  if (facing.kind === 'region') {\n    const region = regionOf(facing.id);\n    return regionViewOf(region.location);\n  }\n  const from = regionOf(facing.from).location;\n  const to = regionOf(facing.to).location;\n  return routeViewOf(from, to);\n}\n\n/**\n * The regions whose marker the globe may draw while it turns from one view to the next: close to\n * the centre of both, so on the front of the sphere and inside the disk the whole way.\n */\nexport function regionsInViewOf(\n  target: GlobeLocation,\n  previous: GlobeLocation\n): Region[] {\n  return REGIONS.filter((region) => {\n    const isAhead = isNearCentreOf(region.location, target);\n    const wasInView = isNearCentreOf(region.location, previous);\n    return isAhead && wasInView;\n  });\n}\n\n/** US East in front, or: the route from Europe to India in front. */\nexport function facingLineOf(facing: Facing) {\n  if (facing.kind === 'region') {\n    const name = regionOf(facing.id).name;\n    return `${name} in front`;\n  }\n  const from = regionOf(facing.from).name;\n  const to = regionOf(facing.to).name;\n  return `the route from ${from} to ${to} in front`;\n}\n\nfunction shifted(value: number, amount: number, sign: Sign) {\n  const change = amount * sign;\n  const next = value + change;\n  return Math.max(0, next);\n}\n\nfunction loadAfter(load: RegionLoad, rate: RunRate, sign: Sign): RegionLoad {\n  return {\n    runs: shifted(load.runs, 1, sign),\n    tokens: shifted(load.tokens, rate.tokens, sign),\n    cents: shifted(load.cents, rate.cents, sign),\n  };\n}\n\nfunction withRun(\n  state: ActivityState,\n  region: RegionId,\n  rate: RunRate,\n  sign: Sign\n): ActivityState {\n  const load = loadAfter(state.loads[region], rate, sign);\n  return { ...state, loads: { ...state.loads, [region]: load } };\n}\n\nexport function handoffLineOf(handoff: Handoff) {\n  const agent = AGENTS[handoff.agentId].name;\n  const from = regionOf(handoff.from).name;\n  const to = regionOf(handoff.to).name;\n  return `${agent} handed a run from ${from} to ${to}`;\n}\n\nfunction facesRegion(facing: Facing, id: RegionId) {\n  if (facing.kind !== 'region') {\n    return false;\n  }\n  return facing.id === id;\n}\n\n/** Picking a region turns the globe to it, also when it is already picked and a hand-off turned the globe away. */\nfunction selected(state: ActivityState, id: RegionId): ActivityState {\n  const isPicked = state.selectedId === id;\n  const isInFront = facesRegion(state.facing, id);\n  if (isPicked && isInFront) {\n    return state;\n  }\n  const facing: Facing = { kind: 'region', id };\n  const notice = facingLineOf(facing);\n  return { ...state, selectedId: id, facing, notice };\n}\n\n/** A run leaves one region for another: the globe turns to show both, and the arc draws itself. */\nfunction handedOff(\n  state: ActivityState,\n  agentId: AgentId,\n  from: RegionId,\n  to: RegionId,\n  rate: RunRate\n): ActivityState {\n  const left = withRun(state, from, rate, -1);\n  const arrived = withRun(left, to, rate, 1);\n  const handoff: Handoff = { id: state.nextId, agentId, from, to };\n  const facing: Facing = { kind: 'route', from, to };\n  const nextId = state.nextId + 1;\n  const notice = handoffLineOf(handoff);\n  return {\n    ...arrived,\n    lastHandoff: handoff,\n    drawingId: handoff.id,\n    facing,\n    nextId,\n    notice,\n  };\n}\n\nexport function reducer(\n  state: ActivityState,\n  action: ActivityAction\n): ActivityState {\n  switch (action.type) {\n    case 'selected':\n      return selected(state, action.id);\n    case 'started':\n      return withRun(state, action.region, action.rate, 1);\n    case 'finished':\n      return withRun(state, action.region, action.rate, -1);\n    case 'handedOff':\n      return handedOff(\n        state,\n        action.agentId,\n        action.from,\n        action.to,\n        action.rate\n      );\n  }\n}\n\nexport function totalRunsOf(state: ActivityState) {\n  let total = 0;\n  for (const region of REGIONS) {\n    total += state.loads[region.id].runs;\n  }\n  return total;\n}\n\nconst SHORT_RUN: RunRate = { tokens: 12, cents: 62 };\n\nconst LONG_RUN: RunRate = { tokens: 14, cents: 71 };\n\nconst CODE_RUN: RunRate = { tokens: 9, cents: 48 };\n\n/**\n * Two hand-offs and one pick: the globe turns three times a round and rests in between. Every run\n * that starts also ends and every hand-off is answered, so each region is back to its first figures\n * when the round ends, facing the same route.\n */\nexport const SCRIPT: Step[] = [\n  {\n    after: 1800,\n    action: { type: 'started', region: 'us-east', rate: SHORT_RUN },\n  },\n  {\n    after: 1400,\n    action: {\n      type: 'handedOff',\n      agentId: 'researcher',\n      from: 'europe',\n      to: 'india',\n      rate: LONG_RUN,\n    },\n  },\n  {\n    after: 2600,\n    action: { type: 'started', region: 'asia-pacific', rate: SHORT_RUN },\n  },\n  {\n    after: 1400,\n    action: { type: 'finished', region: 'us-east', rate: SHORT_RUN },\n  },\n  {\n    after: 1500,\n    by: 'demo',\n    press: 'region-us-east',\n    action: { type: 'selected', id: 'us-east' },\n  },\n  {\n    after: 2800,\n    action: {\n      type: 'handedOff',\n      agentId: 'coder',\n      from: 'us-east',\n      to: 'europe',\n      rate: CODE_RUN,\n    },\n  },\n  {\n    after: 1600,\n    action: { type: 'finished', region: 'europe', rate: CODE_RUN },\n  },\n  {\n    after: 1300,\n    action: { type: 'started', region: 'us-east', rate: CODE_RUN },\n  },\n  {\n    after: 1300,\n    action: { type: 'finished', region: 'asia-pacific', rate: SHORT_RUN },\n  },\n  {\n    after: 1300,\n    action: { type: 'started', region: 'europe', rate: LONG_RUN },\n  },\n  {\n    after: 1300,\n    action: { type: 'finished', region: 'india', rate: LONG_RUN },\n  },\n];\n\n/** Under reduced motion the globe rests on the route from US East to Europe, its arc drawn, as a round begins and ends. */\nexport const RESTING = INITIAL;\n\nexport const LOOP_AFTER_MS = 2400;\n",
      "type": "registry:component",
      "target": "components/blocks/maps-01/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/maps/maps-01/data.ts",
      "content": "import type { GlobeLocation } from '@/components/core/globe';\nimport type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\n\nexport const ACTIVITY_TITLE = 'Agent activity';\n\nexport type RegionId = 'us-east' | 'europe' | 'india' | 'asia-pacific';\n\nexport type Region = {\n  id: RegionId;\n  name: string;\n  place: string;\n  location: GlobeLocation;\n};\n\n/** Neighbours on the globe sit less than sixty degrees apart, so every arc between them stays above the sphere. */\nexport const REGIONS: Region[] = [\n  {\n    id: 'us-east',\n    name: 'US East',\n    place: 'Virginia',\n    location: [38.9, -77.04],\n  },\n  {\n    id: 'europe',\n    name: 'Europe',\n    place: 'Frankfurt',\n    location: [50.11, 8.68],\n  },\n  {\n    id: 'india',\n    name: 'India',\n    place: 'Mumbai',\n    location: [19.08, 72.88],\n  },\n  {\n    id: 'asia-pacific',\n    name: 'Asia Pacific',\n    place: 'Singapore',\n    location: [1.35, 103.82],\n  },\n];\n\nexport function regionOf(id: RegionId) {\n  const region = REGIONS.find((candidate) => candidate.id === id);\n  return region ?? REGIONS[0];\n}\n\nexport type AgentId = 'researcher' | 'writer' | 'coder';\n\nexport type Agent = {\n  name: string;\n  series: SeriesSlot;\n};\n\nexport const AGENTS: Record<AgentId, Agent> = {\n  researcher: { name: 'Researcher', series: 2 },\n  writer: { name: 'Writer', series: 3 },\n  coder: { name: 'Coder', series: 5 },\n};\n\nexport type RegionLoad = {\n  runs: number;\n  /** Thousands of tokens a minute. */\n  tokens: number;\n  /** Cents an hour, so that sums stay exact. */\n  cents: number;\n};\n\n/** Invented figures. The block marks them as illustrative. */\nexport const LOADS: Record<RegionId, RegionLoad> = {\n  'us-east': { runs: 14, tokens: 182, cents: 940 },\n  europe: { runs: 11, tokens: 140, cents: 710 },\n  india: { runs: 6, tokens: 71, cents: 360 },\n  'asia-pacific': { runs: 8, tokens: 96, cents: 490 },\n};\n",
      "type": "registry:component",
      "target": "components/blocks/maps-01/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "maps"
  ],
  "type": "registry:block"
}