{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "motion-globe",
  "title": "Globe",
  "description": "A WebGL globe in the theme colours that turns on its own, follows a drag with momentum and glides to a chosen city.",
  "dependencies": [
    "cobe"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "components/core/globe.tsx",
      "content": "'use client';\n\nimport createGlobe, { type COBEOptions } from 'cobe';\nimport { useEffect, useId, useRef } from 'react';\n\nimport { cn } from '@/lib/utils';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nexport type GlobeLocation = [latitude: number, longitude: number];\n\nexport type GlobeMarker = {\n  location: GlobeLocation;\n  size?: number;\n  label?: string;\n};\n\nexport type GlobeArc = {\n  from: GlobeLocation;\n  to: GlobeLocation;\n};\n\ntype Rgb = [number, number, number];\n\ntype ThemeColors = Pick<\n  COBEOptions,\n  'baseColor' | 'markerColor' | 'glowColor' | 'dark' | 'mapBrightness'\n> & { arcColor: Rgb };\n\ntype ControllerSettings = {\n  markers: GlobeMarker[];\n  arcs: GlobeArc[];\n  markerSize: number;\n  autoRotate: boolean;\n  turnDuration: number;\n  reducedMotion: boolean;\n};\n\ntype FocusTarget = {\n  phi: number;\n  theta: number;\n  holds: boolean;\n  hasArrived: boolean;\n};\n\ntype Controller = {\n  configure: (settings: ControllerSettings) => void;\n  focus: (location: GlobeLocation | null) => void;\n  nudge: (deltaPhi: number, deltaTheta: number) => void;\n  grab: (event: PointerEvent) => void;\n  drag: (event: PointerEvent) => void;\n  release: (event: PointerEvent) => void;\n  hold: (isHeld: boolean) => void;\n  destroy: () => void;\n};\n\nconst MAX_TILT = 0.9;\n\nconst GLOW_SHARE = 0.06;\n\nconst MAX_PIXEL_RATIO = 2;\n\nconst WARM_UP_FRAMES = 8;\n\nconst MOMENTUM_DECAY_MS = 420;\n\nconst FOCUS_EASE_MS = 240;\n\nconst RELEASE_STILL_MS = 80;\n\nconst MAX_SPIN = 0.012;\n\nconst MIN_SPIN = 0.00002;\n\nconst ARRIVED = 0.0005;\n\nconst FRAME_CAP_MS = 64;\n\nconst NUDGE_TURN = 0.35;\n\nconst NUDGE_TILT = 0.15;\n\nconst DEFAULT_MARKER_SIZE = 0.05;\n\nconst DEFAULT_TURN_DURATION = 40;\n\nconst FULL_TURN = Math.PI * 2;\n\nconst THREE_QUARTER_TURN = (Math.PI * 3) / 2;\n\nconst DEFAULT_SETTINGS: ControllerSettings = {\n  markers: [],\n  arcs: [],\n  markerSize: DEFAULT_MARKER_SIZE,\n  autoRotate: true,\n  turnDuration: DEFAULT_TURN_DURATION,\n  reducedMotion: false,\n};\n\nconst MAP_BRIGHTNESS = 0.65;\n\nconst REVEAL_TRANSITION = 'opacity 600ms cubic-bezier(0.23, 1, 0.32, 1)';\n\nfunction clamp(value: number, min: number, max: number) {\n  const atLeastMin = Math.max(value, min);\n  return Math.min(atLeastMin, max);\n}\n\nfunction radiansOf(degrees: number) {\n  return (degrees * Math.PI) / 180;\n}\n\n/** The phi and theta that put a location at the centre of the globe, worked out from cobe's projection. */\nfunction anglesOf([latitude, longitude]: GlobeLocation) {\n  const longitudeAngle = radiansOf(longitude);\n  const latitudeAngle = radiansOf(latitude);\n  const phi = THREE_QUARTER_TURN - longitudeAngle;\n  const theta = clamp(latitudeAngle, -MAX_TILT, MAX_TILT);\n  return { phi, theta };\n}\n\nfunction nearestTurnOf(target: number, current: number) {\n  const difference = target - current;\n  const turns = Math.round(difference / FULL_TURN);\n  const wrapped = difference - FULL_TURN * turns;\n  return current + wrapped;\n}\n\nfunction followFactorOf(elapsed: number, timeConstant: number) {\n  const remaining = Math.exp(-elapsed / timeConstant);\n  return 1 - remaining;\n}\n\nfunction rgbOfColor(color: string, probe: CanvasRenderingContext2D): Rgb {\n  probe.clearRect(0, 0, 1, 1);\n  probe.fillStyle = '#000';\n  probe.fillStyle = color;\n  probe.fillRect(0, 0, 1, 1);\n  const [red, green, blue] = probe.getImageData(0, 0, 1, 1).data;\n  return [red / 255, green / 255, blue / 255];\n}\n\nfunction mixRgb(from: Rgb, to: Rgb, share: number): Rgb {\n  const red = from[0] + (to[0] - from[0]) * share;\n  const green = from[1] + (to[1] - from[1]) * share;\n  const blue = from[2] + (to[2] - from[2]) * share;\n  return [red, green, blue];\n}\n\nfunction luminanceOf([red, green, blue]: Rgb) {\n  return 0.2126 * red + 0.7152 * green + 0.0722 * blue;\n}\n\nfunction tokenRgbOf(\n  styles: CSSStyleDeclaration,\n  token: string,\n  probe: CanvasRenderingContext2D\n) {\n  const value = styles.getPropertyValue(token);\n  const color = value.trim();\n  return rgbOfColor(color, probe);\n}\n\nfunction createColorProbe() {\n  const canvas = document.createElement('canvas');\n  canvas.width = 1;\n  canvas.height = 1;\n  return canvas.getContext('2d', { willReadFrequently: true });\n}\n\n/** Cobe takes colours as RGB triplets from 0 to 1, so the theme tokens are read and converted on every theme change. */\nfunction themeColorsOf(host: HTMLElement): ThemeColors | null {\n  const probe = createColorProbe();\n  if (!probe) {\n    return null;\n  }\n  const styles = getComputedStyle(host);\n  const background = tokenRgbOf(styles, '--background', probe);\n  const foreground = tokenRgbOf(styles, '--foreground', probe);\n  const card = tokenRgbOf(styles, '--card', probe);\n  const primary = tokenRgbOf(styles, '--primary', probe);\n  const glowColor = mixRgb(background, foreground, GLOW_SHARE);\n  const backgroundLuminance = luminanceOf(background);\n  const isDarkTheme = backgroundLuminance < 0.5;\n  if (isDarkTheme) {\n    return {\n      dark: 1,\n      baseColor: foreground,\n      mapBrightness: MAP_BRIGHTNESS,\n      markerColor: primary,\n      arcColor: primary,\n      glowColor,\n    };\n  }\n  return {\n    dark: 0,\n    baseColor: card,\n    mapBrightness: MAP_BRIGHTNESS,\n    markerColor: primary,\n    arcColor: primary,\n    glowColor,\n  };\n}\n\nfunction cobeMarkersOf(markers: GlobeMarker[], markerSize: number) {\n  return markers.map((marker) => ({\n    location: marker.location,\n    size: marker.size ?? markerSize,\n  }));\n}\n\nfunction sideOf(host: HTMLElement) {\n  const width = host.clientWidth;\n  return Math.max(width, 1);\n}\n\nfunction createController(host: HTMLElement, tilt: number): Controller {\n  let settings = DEFAULT_SETTINGS;\n  let phi = 0;\n  let theta = tilt;\n  let spin = 0;\n  let focusTarget: FocusTarget | null = null;\n  let frameId = 0;\n  let lastFrameTime = 0;\n  let warmUpLeft = WARM_UP_FRAMES;\n  let isRevealed = false;\n  let isVisible = true;\n  let isHeld = false;\n  let activePointer: number | null = null;\n  let lastPointerX = 0;\n  let lastPointerY = 0;\n  let lastMoveTime = 0;\n\n  const canvas = document.createElement('canvas');\n  canvas.style.width = '100%';\n  canvas.style.height = '100%';\n  canvas.style.opacity = '0';\n  canvas.style.transition = REVEAL_TRANSITION;\n  host.append(canvas);\n\n  const side = sideOf(host);\n  const screenRatio = window.devicePixelRatio || 1;\n  const pixelRatio = Math.min(screenRatio, MAX_PIXEL_RATIO);\n  const colors = themeColorsOf(host);\n  const globe = createGlobe(canvas, {\n    devicePixelRatio: pixelRatio,\n    width: side,\n    height: side,\n    phi,\n    theta,\n    mapSamples: 16000,\n    mapBrightness: MAP_BRIGHTNESS,\n    diffuse: 1.2,\n    dark: 0,\n    baseColor: [1, 1, 1],\n    markerColor: [0.4, 0.4, 0.95],\n    glowColor: [1, 1, 1],\n    arcWidth: 0.6,\n    arcHeight: 0.25,\n    // cobe hides a marker only when it is behind the sphere and inside its outline: any\n    // elevation lets a city just past the edge float outside the disk.\n    markerElevation: 0,\n    ...colors,\n  });\n\n  function isAutoRotating() {\n    const isAllowed = settings.autoRotate && !settings.reducedMotion;\n    const isUntouched = activePointer === null && !isHeld;\n    const isFree = isUntouched && focusTarget === null;\n    return isAllowed && isFree;\n  }\n\n  function isFocusing() {\n    if (!focusTarget) {\n      return false;\n    }\n    return !focusTarget.hasArrived;\n  }\n\n  function isSettling() {\n    const isSpinning = Math.abs(spin) > MIN_SPIN;\n    const isWarmingUp = warmUpLeft > 0;\n    return isSpinning || isFocusing() || isWarmingUp;\n  }\n\n  function shouldKeepRendering() {\n    if (!isVisible) {\n      return false;\n    }\n    return isAutoRotating() || isSettling();\n  }\n\n  function arrive(target: FocusTarget) {\n    phi = target.phi;\n    theta = target.theta;\n    target.hasArrived = true;\n    if (!target.holds) {\n      focusTarget = null;\n    }\n  }\n\n  function stepFocus(target: FocusTarget, elapsed: number) {\n    if (target.hasArrived) {\n      return;\n    }\n    const follow = followFactorOf(elapsed, FOCUS_EASE_MS);\n    const phiGap = target.phi - phi;\n    const thetaGap = target.theta - theta;\n    phi += phiGap * follow;\n    theta += thetaGap * follow;\n    const phiDistance = Math.abs(phiGap);\n    const thetaDistance = Math.abs(thetaGap);\n    const hasArrived = phiDistance + thetaDistance < ARRIVED;\n    if (hasArrived) {\n      arrive(target);\n    }\n  }\n\n  function aim(target: FocusTarget) {\n    focusTarget = target;\n    spin = 0;\n    if (settings.reducedMotion) {\n      arrive(target);\n    }\n    schedule();\n  }\n\n  function step(elapsed: number) {\n    if (activePointer !== null) {\n      return;\n    }\n    if (focusTarget) {\n      stepFocus(focusTarget, elapsed);\n      return;\n    }\n    const decay = Math.exp(-elapsed / MOMENTUM_DECAY_MS);\n    phi += spin * elapsed;\n    spin *= decay;\n    if (isAutoRotating()) {\n      const turnMs = settings.turnDuration * 1000;\n      const autoSpeed = FULL_TURN / turnMs;\n      phi += autoSpeed * elapsed;\n    }\n  }\n\n  function reveal() {\n    if (isRevealed) {\n      return;\n    }\n    isRevealed = true;\n    canvas.style.opacity = '1';\n  }\n\n  function render(time: number) {\n    frameId = 0;\n    const sinceLastFrame = time - lastFrameTime;\n    const positiveGap = Math.max(sinceLastFrame, 0);\n    const elapsed = Math.min(positiveGap, FRAME_CAP_MS);\n    lastFrameTime = time;\n    step(elapsed);\n    globe.update({ phi, theta });\n    if (warmUpLeft > 0) {\n      warmUpLeft -= 1;\n    }\n    if (warmUpLeft === 0) {\n      reveal();\n    }\n    if (shouldKeepRendering()) {\n      frameId = requestAnimationFrame(render);\n    }\n  }\n\n  function schedule() {\n    if (frameId) {\n      return;\n    }\n    if (!isVisible) {\n      return;\n    }\n    lastFrameTime = performance.now();\n    frameId = requestAnimationFrame(render);\n  }\n\n  function applyTheme() {\n    const themeColors = themeColorsOf(host);\n    if (!themeColors) {\n      return;\n    }\n    globe.update(themeColors);\n    schedule();\n  }\n\n  function resize() {\n    const nextSide = sideOf(host);\n    globe.update({ width: nextSide, height: nextSide });\n    schedule();\n  }\n\n  const visibilityObserver = new IntersectionObserver(([entry]) => {\n    isVisible = entry.isIntersecting;\n    if (isVisible) {\n      schedule();\n      return;\n    }\n    cancelAnimationFrame(frameId);\n    frameId = 0;\n  });\n  visibilityObserver.observe(host);\n\n  const sizeObserver = new ResizeObserver(resize);\n  sizeObserver.observe(host);\n\n  const themeObserver = new MutationObserver(applyTheme);\n  themeObserver.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['class', 'style', 'data-theme'],\n  });\n\n  schedule();\n\n  return {\n    configure(next) {\n      settings = next;\n      globe.update({\n        markers: cobeMarkersOf(next.markers, next.markerSize),\n        arcs: next.arcs,\n      });\n      if (next.reducedMotion) {\n        spin = 0;\n      }\n      schedule();\n    },\n    focus(location) {\n      if (!location) {\n        focusTarget = null;\n        schedule();\n        return;\n      }\n      const angles = anglesOf(location);\n      const targetPhi = nearestTurnOf(angles.phi, phi);\n      aim({\n        phi: targetPhi,\n        theta: angles.theta,\n        holds: true,\n        hasArrived: false,\n      });\n    },\n    nudge(deltaPhi, deltaTheta) {\n      const startPhi = focusTarget?.phi ?? phi;\n      const startTheta = focusTarget?.theta ?? theta;\n      const tiltedTheta = startTheta + deltaTheta;\n      aim({\n        phi: startPhi + deltaPhi,\n        theta: clamp(tiltedTheta, -MAX_TILT, MAX_TILT),\n        holds: false,\n        hasArrived: false,\n      });\n    },\n    grab(event) {\n      if (activePointer !== null) {\n        return;\n      }\n      activePointer = event.pointerId;\n      lastPointerX = event.clientX;\n      lastPointerY = event.clientY;\n      lastMoveTime = event.timeStamp;\n      focusTarget = null;\n      spin = 0;\n      host.setPointerCapture(event.pointerId);\n    },\n    drag(event) {\n      if (event.pointerId !== activePointer) {\n        return;\n      }\n      const width = sideOf(host);\n      const deltaX = event.clientX - lastPointerX;\n      const deltaY = event.clientY - lastPointerY;\n      const sinceLastMove = event.timeStamp - lastMoveTime;\n      const elapsed = Math.max(sinceLastMove, 1);\n      const deltaPhi = (deltaX / width) * Math.PI;\n      const deltaTheta = (deltaY / width) * Math.PI;\n      const tiltedTheta = theta + deltaTheta;\n      phi += deltaPhi;\n      theta = clamp(tiltedTheta, -MAX_TILT, MAX_TILT);\n      const rawVelocity = deltaPhi / elapsed;\n      const velocity = clamp(rawVelocity, -MAX_SPIN, MAX_SPIN);\n      spin = spin * 0.5 + velocity * 0.5;\n      lastPointerX = event.clientX;\n      lastPointerY = event.clientY;\n      lastMoveTime = event.timeStamp;\n      globe.update({ phi, theta });\n    },\n    release(event) {\n      if (event.pointerId !== activePointer) {\n        return;\n      }\n      activePointer = null;\n      const stillFor = event.timeStamp - lastMoveTime;\n      const wasHeldStill = stillFor > RELEASE_STILL_MS;\n      if (wasHeldStill || settings.reducedMotion) {\n        spin = 0;\n      }\n      schedule();\n    },\n    hold(nextHeld) {\n      isHeld = nextHeld;\n      schedule();\n    },\n    destroy() {\n      cancelAnimationFrame(frameId);\n      visibilityObserver.disconnect();\n      sizeObserver.disconnect();\n      themeObserver.disconnect();\n      globe.destroy();\n      host.replaceChildren();\n    },\n  };\n}\n\nconst KEY_NUDGES: Record<string, [number, number]> = {\n  ArrowLeft: [-NUDGE_TURN, 0],\n  ArrowRight: [NUDGE_TURN, 0],\n  ArrowUp: [0, -NUDGE_TILT],\n  ArrowDown: [0, NUDGE_TILT],\n};\n\nconst NO_MARKERS: GlobeMarker[] = [];\n\nconst NO_ARCS: GlobeArc[] = [];\n\nfunction labelsOf(markers: GlobeMarker[]) {\n  const labels = markers.map((marker) => marker.label);\n  return labels.filter((label): label is string => Boolean(label));\n}\n\nexport type GlobeProps = {\n  markers?: GlobeMarker[];\n  arcs?: GlobeArc[];\n  focus?: GlobeLocation | null;\n  autoRotate?: boolean;\n  turnDuration?: number;\n  tilt?: number;\n  markerSize?: number;\n  label?: string;\n  className?: string;\n};\n\nexport function Globe({\n  markers = NO_MARKERS,\n  arcs = NO_ARCS,\n  focus = null,\n  autoRotate = true,\n  turnDuration = DEFAULT_TURN_DURATION,\n  tilt = 15,\n  markerSize = DEFAULT_MARKER_SIZE,\n  label = 'Globe',\n  className,\n}: GlobeProps) {\n  const hostRef = useRef<HTMLDivElement>(null);\n  const controllerRef = useRef<Controller | null>(null);\n  const startingTiltRef = useRef(tilt);\n  const prefersReducedMotion = usePrefersReducedMotion();\n  const reducedMotion = prefersReducedMotion === true;\n  const hintId = useId();\n  const markerLabels = labelsOf(markers);\n  const focusLatitude = focus?.[0];\n  const focusLongitude = focus?.[1];\n\n  useEffect(() => {\n    const host = hostRef.current;\n    if (!host) {\n      return;\n    }\n    const startingTilt = radiansOf(startingTiltRef.current);\n    const controller = createController(host, startingTilt);\n    controllerRef.current = controller;\n    return () => {\n      controller.destroy();\n      controllerRef.current = null;\n    };\n  }, []);\n\n  useEffect(() => {\n    controllerRef.current?.configure({\n      markers,\n      arcs,\n      markerSize,\n      autoRotate,\n      turnDuration,\n      reducedMotion,\n    });\n  }, [markers, arcs, markerSize, autoRotate, turnDuration, reducedMotion]);\n\n  useEffect(() => {\n    const isUnset = focusLatitude === undefined || focusLongitude === undefined;\n    if (isUnset) {\n      controllerRef.current?.focus(null);\n      return;\n    }\n    controllerRef.current?.focus([focusLatitude, focusLongitude]);\n  }, [focusLatitude, focusLongitude]);\n\n  function grab(event: React.PointerEvent<HTMLDivElement>) {\n    const isMainButton = event.button === 0;\n    if (!isMainButton) {\n      return;\n    }\n    controllerRef.current?.grab(event.nativeEvent);\n  }\n\n  function drag(event: React.PointerEvent<HTMLDivElement>) {\n    controllerRef.current?.drag(event.nativeEvent);\n  }\n\n  function release(event: React.PointerEvent<HTMLDivElement>) {\n    controllerRef.current?.release(event.nativeEvent);\n  }\n\n  function holdForKeyboard(event: React.FocusEvent<HTMLDivElement>) {\n    const isKeyboardFocus = event.currentTarget.matches(':focus-visible');\n    controllerRef.current?.hold(isKeyboardFocus);\n  }\n\n  function letGo() {\n    controllerRef.current?.hold(false);\n  }\n\n  function turnWithKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const nudge = KEY_NUDGES[event.key];\n    if (!nudge) {\n      return;\n    }\n    event.preventDefault();\n    controllerRef.current?.nudge(nudge[0], nudge[1]);\n  }\n\n  return (\n    <div\n      className={cn('relative aspect-square w-full max-w-[600px]', className)}\n    >\n      <div\n        ref={hostRef}\n        role='group'\n        aria-roledescription='globe'\n        aria-label={label}\n        aria-describedby={hintId}\n        tabIndex={0}\n        onPointerDown={grab}\n        onPointerMove={drag}\n        onPointerUp={release}\n        onPointerCancel={release}\n        onKeyDown={turnWithKeys}\n        onFocus={holdForKeyboard}\n        onBlur={letGo}\n        className='focus-visible:outline-ring size-full cursor-grab touch-pan-y rounded-full [contain:layout_paint_size] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 active:cursor-grabbing'\n      />\n      <div id={hintId} className='sr-only'>\n        <p>Drag the globe or use the arrow keys to turn it.</p>\n        {markerLabels.length > 0 && (\n          <ul>\n            {markerLabels.map((markerLabel) => (\n              <li key={markerLabel}>{markerLabel}</li>\n            ))}\n          </ul>\n        )}\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/core/globe.tsx"
    }
  ],
  "categories": [
    "motion"
  ],
  "type": "registry:component"
}