{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "card-12",
  "title": "Globe with routes",
  "description": "A globe that turns to the city picked in the list or under a drag, where an arc draws from that city to each one it is linked to.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/card.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-globe.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/card/card-12.tsx",
      "content": "'use client';\n\nimport { useInView } from 'motion/react';\nimport { useEffect, useId, useMemo, useRef, useState } from 'react';\nimport { flushSync } from 'react-dom';\n\nimport {\n  Globe,\n  type GlobeArc,\n  type GlobeLocation,\n  type GlobeMarker,\n} from '@/components/core/globe';\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport type { AutoplayStep } from '@/registry/ndeko/hooks/use-autoplay';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Card } from '@/registry/ndeko/ui/card';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { SampleNote } from './_parts/sample-note';\nimport { useCardDemo } from './_parts/use-card-demo';\n\nexport type RouteCity = {\n  id: string;\n  name: string;\n  country: string;\n  location: GlobeLocation;\n};\n\n/** A route joins two cities and is drawn from whichever of them is picked. */\nexport type Route = {\n  id: string;\n  fromId: string;\n  toId: string;\n};\n\ntype Vector = [x: number, y: number, z: number];\n\ntype Drawing = { hubId: string; progress: number };\n\nconst DRAW_MS = 900;\n\n/** The globe turns first: a route starts to draw once its city has come most of the way to the front. */\nconst TURN_LEAD_MS = 520;\n\n/** Under this share an arc is a needle standing on its city: it is drawn from here on. */\nconst FIRST_STROKE = 0.04;\n\n/** Two cities this close, or exactly opposite, have no single path between them to follow. */\nconst SAME_PLACE = 0.0001;\n\nconst HUB_MARKER = 0.075;\n\nconst CITY_MARKER = 0.045;\n\nconst NO_ARCS: GlobeArc[] = [];\n\nconst ARROW_KEYS = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'];\n\n/** Under 18rem a row puts the country under the city, across the width the route count leaves free. */\nconst ROW = [\n  'flex h-10 w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-start text-[13px] outline-none',\n  '@max-2xs:grid @max-2xs:grid-cols-[auto_minmax(0,1fr)_auto] @max-2xs:content-center @max-2xs:gap-y-0',\n  'transition-[background-color,scale] duration-150 ease-(--ease-out-strong) active:scale-[0.98]',\n  'hover:bg-foreground/[0.04] focus-visible:ring-ring/25 focus-visible:ring-[3px]',\n].join(' ');\n\nconst PICKED_ROW = 'bg-foreground/[0.06] hover:bg-foreground/[0.06]';\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 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 city to another, along the shortest path over the globe. */\nfunction 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. */\nfunction easedOf(progress: number) {\n  const left = 1 - progress;\n  const leftCubed = left ** 3;\n  return 1 - leftCubed;\n}\n\nfunction otherEndOf(route: Route, cityId: string) {\n  if (route.fromId === cityId) {\n    return route.toId;\n  }\n  if (route.toId === cityId) {\n    return route.fromId;\n  }\n  return null;\n}\n\nfunction destinationsOf(cityId: string, cities: RouteCity[], routes: Route[]) {\n  const destinations: RouteCity[] = [];\n  for (const route of routes) {\n    const otherId = otherEndOf(route, cityId);\n    const other = cities.find((city) => city.id === otherId);\n    if (other) {\n      destinations.push(other);\n    }\n  }\n  return destinations;\n}\n\nfunction arcsOf(hub: RouteCity, destinations: RouteCity[], progress: number) {\n  if (progress < FIRST_STROKE) {\n    return NO_ARCS;\n  }\n  const share = easedOf(progress);\n  return destinations.map((destination) => ({\n    from: hub.location,\n    to: pointAlong(hub.location, destination.location, share),\n  }));\n}\n\nfunction markerSizeOf(isHub: boolean) {\n  if (isHub) {\n    return HUB_MARKER;\n  }\n  return CITY_MARKER;\n}\n\nfunction markersOf(cities: RouteCity[], hubId: string): GlobeMarker[] {\n  return cities.map((city) => {\n    const isHub = city.id === hubId;\n    return {\n      location: city.location,\n      size: markerSizeOf(isHub),\n      label: city.name,\n    };\n  });\n}\n\nfunction startOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return 1;\n  }\n  return 0;\n}\n\nfunction leadOf(isFresh: boolean) {\n  if (isFresh) {\n    return TURN_LEAD_MS;\n  }\n  return 0;\n}\n\nfunction grown(drawing: Drawing, elapsed: number): Drawing {\n  const step = elapsed / DRAW_MS;\n  const further = drawing.progress + step;\n  const progress = Math.min(1, further);\n  return { hubId: drawing.hubId, progress };\n}\n\nfunction routeCountOf(count: number) {\n  if (count === 0) {\n    return 'No route';\n  }\n  if (count === 1) {\n    return '1 route';\n  }\n  return `${count} routes`;\n}\n\nfunction focusOf(isHeld: boolean, hub: RouteCity) {\n  if (isHeld) {\n    return hub.location;\n  }\n  return null;\n}\n\nfunction dotOf(isPicked: boolean) {\n  if (isPicked) {\n    return 'bg-primary';\n  }\n  return 'bg-foreground/20';\n}\n\ntype RouteLayerProps = {\n  hub: RouteCity;\n  cities: RouteCity[];\n  destinations: RouteCity[];\n  /** False once a person turns the globe by hand: it stays where they left it until a city is picked. */\n  isHeld: boolean;\n  /** Nothing is drawn while the card is off screen or the tab is hidden. */\n  isActive: boolean;\n  label: string;\n};\n\n/**\n * The globe takes its arcs as a prop, so the growing end of a route is state. This layer holds it\n * alone: while a route draws, nothing but the globe renders, and once it is drawn nothing runs.\n */\nfunction RouteLayer({\n  hub,\n  cities,\n  destinations,\n  isHeld,\n  isActive,\n  label,\n}: RouteLayerProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const [drawing, setDrawing] = useState<Drawing>({\n    hubId: hub.id,\n    progress: 1,\n  });\n  const isNewHub = drawing.hubId !== hub.id;\n  if (isNewHub) {\n    setDrawing({ hubId: hub.id, progress: startOf(shouldReduceMotion) });\n  }\n  const isDrawn = drawing.progress >= 1;\n  const isFresh = drawing.progress === 0;\n  const isDrawing = isActive && !isDrawn && !isNewHub;\n\n  useEffect(() => {\n    if (!isDrawing) {\n      return;\n    }\n    let frame = 0;\n    let lastTime = 0;\n\n    function draw(time: number) {\n      const sinceLastFrame = time - lastTime;\n      const elapsed = Math.max(sinceLastFrame, 0);\n      lastTime = time;\n      setDrawing((current) => grown(current, elapsed));\n      frame = requestAnimationFrame(draw);\n    }\n\n    function begin() {\n      lastTime = performance.now();\n      frame = requestAnimationFrame(draw);\n    }\n\n    const lead = setTimeout(begin, leadOf(isFresh));\n    return () => {\n      clearTimeout(lead);\n      cancelAnimationFrame(frame);\n    };\n  }, [isDrawing, isFresh, drawing.hubId]);\n\n  const markers = useMemo(() => markersOf(cities, hub.id), [cities, hub.id]);\n  const arcs = useMemo(\n    () => arcsOf(hub, destinations, drawing.progress),\n    [hub, destinations, drawing.progress]\n  );\n\n  return (\n    <Globe\n      markers={markers}\n      arcs={arcs}\n      focus={focusOf(isHeld, hub)}\n      autoRotate={false}\n      label={label}\n    />\n  );\n}\n\nexport type RouteGlobeProps = {\n  title: string;\n  cities: RouteCity[];\n  routes: Route[];\n  selectedId: string;\n  onSelect: (cityId: string) => void;\n  /** Says the routes are made up. Leave it out for real ones. */\n  note?: string;\n  /** The city a demonstration picks, shown held down. */\n  pressedId?: string | null;\n  className?: string;\n};\n\nexport function RouteGlobe({\n  title,\n  cities,\n  routes,\n  selectedId,\n  onSelect,\n  note,\n  pressedId = null,\n  className,\n}: RouteGlobeProps) {\n  const cardRef = useRef<HTMLDivElement>(null);\n  const titleId = useId();\n  const isInView = useInView(cardRef, { amount: 0.3 });\n  const isVisible = useDocumentVisible();\n  const [hasAppeared, setHasAppeared] = useState(false);\n  const [releasedId, setReleasedId] = useState<string | null>(null);\n  const isFirstSight = isInView && !hasAppeared;\n  if (isFirstSight) {\n    setHasAppeared(true);\n  }\n  const isOnScreen = isInView && isVisible;\n  const isHeld = releasedId !== selectedId;\n  const hub = cities.find((city) => city.id === selectedId);\n  const destinations = useMemo(\n    () => destinationsOf(selectedId, cities, routes),\n    [selectedId, cities, routes]\n  );\n\n  function pick(cityId: string) {\n    setReleasedId(null);\n    onSelect(cityId);\n  }\n\n  /** A person who turns the globe by hand keeps it where they leave it, until a city is picked again. */\n  function letGo() {\n    setReleasedId(selectedId);\n  }\n\n  /**\n   * The globe turns on this same key press. Letting go clears its focus, which would stop that turn\n   * if it landed after it, so the release is committed before the globe sees the key.\n   */\n  function letGoBeforeArrowTurn(event: React.KeyboardEvent<HTMLDivElement>) {\n    const isArrow = ARROW_KEYS.includes(event.key);\n    const isFirstTurn = isArrow && isHeld;\n    if (isFirstTurn) {\n      flushSync(letGo);\n    }\n  }\n\n  if (!hub) {\n    return null;\n  }\n\n  const globeLabel = `Globe of ${title}, ${hub.name} in front`;\n\n  return (\n    <Card\n      ref={cardRef}\n      role='group'\n      aria-labelledby={titleId}\n      className={cn('@container w-full gap-4 p-5', className)}\n    >\n      <div className='flex items-baseline justify-between gap-3'>\n        <h3 id={titleId} className='text-sm font-medium'>\n          {title}\n        </h3>\n        {note && <SampleNote>{note}</SampleNote>}\n      </div>\n      <div className='flex flex-col gap-4 @sm:flex-row @sm:items-center'>\n        <div\n          onPointerDown={letGo}\n          onKeyDownCapture={letGoBeforeArrowTurn}\n          className='relative mx-auto aspect-square w-full max-w-[15rem] shrink-0 @sm:mx-0 @sm:w-44 @lg:w-56'\n        >\n          <div\n            aria-hidden='true'\n            className='bg-foreground/[0.04] absolute inset-[10%] rounded-full'\n          />\n          {hasAppeared && (\n            <RouteLayer\n              hub={hub}\n              cities={cities}\n              destinations={destinations}\n              isHeld={isHeld}\n              isActive={isOnScreen}\n              label={globeLabel}\n            />\n          )}\n        </div>\n        <ul className='flex min-w-0 flex-1 flex-col gap-0.5'>\n          {cities.map((city) => {\n            const isPicked = city.id === hub.id;\n            const isPressed = city.id === pressedId;\n            const cityRoutes = destinationsOf(city.id, cities, routes);\n            return (\n              <li key={city.id}>\n                <button\n                  type='button'\n                  aria-pressed={isPicked}\n                  onClick={() => pick(city.id)}\n                  className={cn(\n                    ROW,\n                    isPicked && PICKED_ROW,\n                    pressedQuietOf(isPressed)\n                  )}\n                >\n                  <span\n                    aria-hidden='true'\n                    className={cn(\n                      'size-2 shrink-0 rounded-full',\n                      dotOf(isPicked)\n                    )}\n                  />\n                  <span className='min-w-0 flex-1 truncate @max-2xs:contents'>\n                    <span className='font-medium @max-2xs:col-start-2 @max-2xs:row-start-1 @max-2xs:truncate'>\n                      {city.name}\n                    </span>\n                    <span className='text-muted-foreground @max-2xs:col-[2/4] @max-2xs:row-start-2 @max-2xs:truncate @max-2xs:text-xs'>\n                      <span className='@max-2xs:hidden'>, </span>\n                      {city.country}\n                    </span>\n                  </span>\n                  <span className='text-muted-foreground text-xs tabular-nums @max-2xs:col-start-3 @max-2xs:row-start-1'>\n                    {routeCountOf(cityRoutes.length)}\n                  </span>\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      </div>\n    </Card>\n  );\n}\n\nconst CITIES: RouteCity[] = [\n  {\n    id: 'kinshasa',\n    name: 'Kinshasa',\n    country: 'DR Congo',\n    location: [-4.44, 15.27],\n  },\n  {\n    id: 'lisbon',\n    name: 'Lisbon',\n    country: 'Portugal',\n    location: [38.72, -9.14],\n  },\n  { id: 'lagos', name: 'Lagos', country: 'Nigeria', location: [6.52, 3.38] },\n  {\n    id: 'new-york',\n    name: 'New York',\n    country: 'United States',\n    location: [40.71, -74.01],\n  },\n  {\n    id: 'sao-paulo',\n    name: 'São Paulo',\n    country: 'Brazil',\n    location: [-23.55, -46.63],\n  },\n  {\n    id: 'dubai',\n    name: 'Dubai',\n    country: 'United Arab Emirates',\n    location: [25.2, 55.27],\n  },\n];\n\nconst ROUTES: Route[] = [\n  { id: 'kinshasa-lagos', fromId: 'kinshasa', toId: 'lagos' },\n  { id: 'kinshasa-lisbon', fromId: 'kinshasa', toId: 'lisbon' },\n  { id: 'kinshasa-dubai', fromId: 'kinshasa', toId: 'dubai' },\n  { id: 'kinshasa-sao-paulo', fromId: 'kinshasa', toId: 'sao-paulo' },\n  { id: 'lisbon-new-york', fromId: 'lisbon', toId: 'new-york' },\n  { id: 'lisbon-lagos', fromId: 'lisbon', toId: 'lagos' },\n  { id: 'lisbon-dubai', fromId: 'lisbon', toId: 'dubai' },\n  { id: 'lagos-sao-paulo', fromId: 'lagos', toId: 'sao-paulo' },\n  { id: 'lagos-dubai', fromId: 'lagos', toId: 'dubai' },\n  { id: 'new-york-sao-paulo', fromId: 'new-york', toId: 'sao-paulo' },\n];\n\nconst FIRST_CITY_ID = 'kinshasa';\n\nfunction announcementOf(cityId: string) {\n  const city = CITIES.find((candidate) => candidate.id === cityId);\n  if (!city) {\n    return '';\n  }\n  const destinations = destinationsOf(cityId, CITIES, ROUTES);\n  const names = destinations.map((destination) => destination.name);\n  const count = routeCountOf(destinations.length);\n  const list = names.join(', ');\n  return `${city.name} in front, ${count}: ${list}`;\n}\n\nexport default function Card12() {\n  const [selectedId, setSelectedId] = useState(FIRST_CITY_ID);\n  const { pressed, press } = usePress<string>();\n\n  const steps: AutoplayStep[] = [\n    { after: 2600, run: () => press('lagos') },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId('lagos') },\n    { after: 3400, run: () => press('dubai') },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId('dubai') },\n    { after: 3400, run: () => press('new-york') },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId('new-york') },\n    { after: 3400, run: () => press(FIRST_CITY_ID) },\n    { after: PRESS_LEAD_MS, run: () => setSelectedId(FIRST_CITY_ID) },\n  ];\n  const { ref, isAutoplaying } = useCardDemo(steps, {\n    loopAfter: 800,\n  });\n\n  return (\n    <div ref={ref} className='min-h-[18.75rem] w-full max-w-[36rem]'>\n      <RouteGlobe\n        title='Freight routes'\n        cities={CITIES}\n        routes={ROUTES}\n        selectedId={selectedId}\n        onSelect={setSelectedId}\n        note='Illustrative'\n        pressedId={pressed}\n      />\n      <LiveRegion\n        message={spokenUnless(isAutoplaying, announcementOf(selectedId))}\n      />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/card-12.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/sample-note.tsx",
      "content": "import { cn } from '@/registry/ndeko/lib/utils';\n\ntype SampleNoteProps = {\n  /** What the sample is: \"Illustrative\", \"Sample quote\". */\n  children?: React.ReactNode;\n  className?: string;\n};\n\n/** The word that says the figures or the words of a demo are made up. */\nexport function SampleNote({\n  children = 'Illustrative',\n  className,\n}: SampleNoteProps) {\n  return (\n    <span className={cn('text-muted-foreground text-xs', className)}>\n      {children}\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/sample-note.tsx"
    },
    {
      "path": "registry/ndeko/components/card/_parts/use-card-demo.ts",
      "content": "'use client';\n\nimport {\n  useAutoplay,\n  type AutoplayOptions,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\n\n/**\n * What every card demo shares: the demonstration, and the box that keeps its tallest height so a\n * round never moves the page.\n */\nexport function useCardDemo(\n  steps: readonly AutoplayStep[],\n  options?: AutoplayOptions\n) {\n  const demo = useAutoplay(steps, options);\n  const { ref } = demo;\n\n  useKeptHeight(ref);\n\n  return demo;\n}\n",
      "type": "registry:component",
      "target": "components/card/_parts/use-card-demo.ts"
    }
  ],
  "categories": [
    "components",
    "card"
  ],
  "type": "registry:component"
}