Skip to content

armgit / mapcn

Public Imported from GitHub
0

Beautiful map components. 100% Free, Zero config, one command setup.

TypeScript

feat(map): make MapRoute composable with progress and active routes

Anmol752906803fbb
diff --git a/public/r/delivery-tracker.json b/public/r/delivery-tracker.json
index 9c939b8..320cd23 100644
--- a/public/r/delivery-tracker.json
+++ b/public/r/delivery-tracker.json
@@ -15,7 +15,7 @@
"files": [
{
"path": "src/registry/blocks/delivery-tracker/page.tsx",
- "content": "\"use client\";\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport { Clock3, House, Store, Utensils, Truck, UserRound } from \"lucide-react\";\n\nimport { Map, MapMarker, MapRoute, MarkerContent } from \"@/components/ui/map\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport {\n buildRouteUrl,\n deliveryMeals,\n dropoff,\n mapView,\n pickup,\n progressFraction,\n routeStyle,\n type OsrmRouteData,\n} from \"./data\";\n\nfunction formatDistance(meters?: number) {\n if (!meters) return \"--\";\n if (meters < 1000) return `${Math.round(meters)} m`;\n return `${(meters / 1000).toFixed(1)} km`;\n}\n\nfunction formatDuration(seconds?: number) {\n if (!seconds) return \"--\";\n const minutes = Math.round(seconds / 60);\n if (minutes < 60) return `${minutes} min`;\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n return `${hours}h ${remainingMinutes}m`;\n}\n\nexport default function Page() {\n const [routeData, setRouteData] = useState<OsrmRouteData | null>(null);\n const [loading, setLoading] = useState(true);\n const { resolvedTheme } = useTheme();\n const remainingRouteColor =\n resolvedTheme === \"dark\"\n ? routeStyle.remaining.color.dark\n : routeStyle.remaining.color.light;\n\n useEffect(() => {\n async function fetchRoute() {\n setLoading(true);\n try {\n const response = await fetch(buildRouteUrl(pickup, dropoff));\n const data = await response.json();\n const route = data?.routes?.[0];\n if (!route?.geometry?.coordinates) return;\n\n setRouteData({\n coordinates: route.geometry.coordinates as [number, number][],\n duration: route.duration as number,\n distance: route.distance as number,\n });\n } catch (error) {\n console.error(\"Failed to fetch route:\", error);\n } finally {\n setLoading(false);\n }\n }\n\n fetchRoute();\n }, []);\n\n const progressCoordinates = useMemo(() => {\n const total = routeData?.coordinates?.length ?? 0;\n const progressCount = Math.max(2, Math.floor(total * progressFraction));\n return routeData?.coordinates?.slice(0, progressCount) ?? [];\n }, [routeData]);\n\n const courierPosition = progressCoordinates[progressCoordinates.length - 1];\n\n return (\n <div className=\"flex min-h-screen items-center justify-center p-8\">\n <div className=\"bg-sidebar mx-auto grid w-[1200px] rounded-xl border md:grid-cols-[1.05fr_1fr]\">\n <div className=\"flex flex-col p-5 md:p-6\">\n <div className=\"space-y-1\">\n <h3 className=\"text-2xl font-semibold tracking-tight\">\n Track Delivery\n </h3>\n <p className=\"text-muted-foreground text-sm\">Mon Feb 10 - 2-3 PM</p>\n </div>\n\n <Card className=\"mt-5\">\n <CardHeader>\n <CardTitle className=\"font-medium\">\n Order items ({deliveryMeals.length})\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-5\">\n {deliveryMeals.map((meal) => (\n <div key={meal.name} className=\"flex items-center gap-3\">\n <div className=\"bg-muted grid size-8 place-items-center rounded-full text-xs\">\n <Utensils className=\"text-muted-foreground size-4\" />\n </div>\n <div className=\"min-w-4 flex-1\">\n <p className=\"truncate pb-1 text-sm font-medium\">\n {meal.name}\n </p>\n <p className=\"text-muted-foreground text-xs\">\n {meal.price}\n </p>\n </div>\n <Badge\n variant=\"secondary\"\n className=\"h-6 rounded-full px-2.5\"\n >\n x{meal.quantity}\n </Badge>\n </div>\n ))}\n <div className=\"border-border/60 flex items-center justify-between border-t pt-3 text-sm\">\n <span className=\"text-muted-foreground\">Bundle total</span>\n <span className=\"font-medium\">$189.00</span>\n </div>\n </CardContent>\n </Card>\n\n <div className=\"mt-4 grid gap-3 sm:grid-cols-2\">\n <Card>\n <CardContent className=\"space-y-2\">\n <p className=\"text-muted-foreground text-sm\">\n Pickup confirmed\n </p>\n <p className=\"text-sm font-medium\">Mon, Feb 10 at 1:48 PM</p>\n </CardContent>\n </Card>\n <Card>\n <CardContent className=\"space-y-2\">\n <p className=\"text-muted-foreground text-sm\">\n Remaining travel\n </p>\n <p className=\"text-sm font-medium\">\n {formatDuration(routeData?.duration)}\n <span className=\"text-muted-foreground font-normal\">\n {\" · \"}\n {formatDistance(routeData?.distance)}\n </span>\n </p>\n </CardContent>\n </Card>\n </div>\n\n <div className=\"mt-6 flex flex-wrap items-center gap-2\">\n <Button size=\"sm\">\n <Clock3 />\n View timeline\n </Button>\n <Button variant=\"outline\" size=\"sm\">\n <UserRound />\n Contact courier\n </Button>\n </div>\n </div>\n\n <div className=\"relative h-[450px] overflow-hidden rounded-xl shadow-sm md:h-full\">\n <Map\n loading={loading}\n center={mapView.center}\n zoom={mapView.zoom}\n minZoom={mapView.minZoom}\n maxZoom={mapView.maxZoom}\n >\n <MapRoute\n id=\"delivery-full-route\"\n coordinates={routeData?.coordinates ?? []}\n color={remainingRouteColor}\n width={routeStyle.remaining.width}\n opacity={routeStyle.remaining.opacity}\n interactive={false}\n />\n <MapRoute\n id=\"delivery-progress-route\"\n coordinates={progressCoordinates}\n color={routeStyle.progress.color}\n width={routeStyle.progress.width}\n opacity={routeStyle.progress.opacity}\n interactive={false}\n />\n\n {courierPosition && (\n <MapMarker\n longitude={courierPosition[0]}\n latitude={courierPosition[1]}\n offset={[0, 10]}\n >\n <MarkerContent>\n <div\n className=\"relative grid size-9 place-items-center rounded-full shadow-md\"\n style={{ backgroundColor: routeStyle.progress.color }}\n >\n <Truck className=\"size-4 text-white\" />\n <div className=\"bg-popover text-popover-foreground absolute bottom-full left-1/2 mb-2.5 -translate-x-1/2 rounded-md border px-2 py-1 text-xs font-medium whitespace-nowrap shadow-md\">\n {formatDuration(routeData?.duration)} away\n <span className=\"bg-popover absolute top-full left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rotate-45 border-r border-b\" />\n </div>\n </div>\n </MarkerContent>\n </MapMarker>\n )}\n\n <MapMarker longitude={pickup.lng} latitude={pickup.lat}>\n <MarkerContent>\n <div className=\"grid size-7 place-items-center rounded-full bg-emerald-500 shadow-md\">\n <Store className=\"size-3.5 text-white\" />\n </div>\n </MarkerContent>\n </MapMarker>\n\n <MapMarker longitude={dropoff.lng} latitude={dropoff.lat}>\n <MarkerContent>\n <div className=\"grid size-7 place-items-center rounded-full bg-rose-500 shadow-md\">\n <House className=\"size-3.5 text-white\" />\n </div>\n </MarkerContent>\n </MapMarker>\n </Map>\n </div>\n </div>\n </div>\n );\n}\n",
+ "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport { Clock3, House, Store, Utensils, Truck, UserRound } from \"lucide-react\";\n\nimport {\n Map,\n MapMarker,\n MapRoute,\n MarkerContent,\n RouteMarker,\n RouteProgress,\n} from \"@/components/ui/map\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport {\n buildRouteUrl,\n deliveryMeals,\n dropoff,\n mapView,\n pickup,\n progressFraction,\n routeStyle,\n type OsrmRouteData,\n} from \"./data\";\n\nfunction formatDistance(meters?: number) {\n if (!meters) return \"--\";\n if (meters < 1000) return `${Math.round(meters)} m`;\n return `${(meters / 1000).toFixed(1)} km`;\n}\n\nfunction formatDuration(seconds?: number) {\n if (!seconds) return \"--\";\n const minutes = Math.round(seconds / 60);\n if (minutes < 60) return `${minutes} min`;\n const hours = Math.floor(minutes / 60);\n const remainingMinutes = minutes % 60;\n return `${hours}h ${remainingMinutes}m`;\n}\n\nexport default function Page() {\n const [routeData, setRouteData] = useState<OsrmRouteData | null>(null);\n const [loading, setLoading] = useState(true);\n const { resolvedTheme } = useTheme();\n const remainingRouteColor =\n resolvedTheme === \"dark\"\n ? routeStyle.remaining.color.dark\n : routeStyle.remaining.color.light;\n\n useEffect(() => {\n async function fetchRoute() {\n setLoading(true);\n try {\n const response = await fetch(buildRouteUrl(pickup, dropoff));\n const data = await response.json();\n const route = data?.routes?.[0];\n if (!route?.geometry?.coordinates) return;\n\n setRouteData({\n coordinates: route.geometry.coordinates as [number, number][],\n duration: route.duration as number,\n distance: route.distance as number,\n });\n } catch (error) {\n console.error(\"Failed to fetch route:\", error);\n } finally {\n setLoading(false);\n }\n }\n\n fetchRoute();\n }, []);\n\n return (\n <div className=\"flex min-h-screen items-center justify-center p-8\">\n <div className=\"bg-sidebar mx-auto grid w-[1200px] rounded-xl border md:grid-cols-[1.05fr_1fr]\">\n <div className=\"flex flex-col p-5 md:p-6\">\n <div className=\"space-y-1\">\n <h3 className=\"text-2xl font-semibold tracking-tight\">\n Track Delivery\n </h3>\n <p className=\"text-muted-foreground text-sm\">Mon Feb 10 - 2-3 PM</p>\n </div>\n\n <Card className=\"mt-5\">\n <CardHeader>\n <CardTitle className=\"font-medium\">\n Order items ({deliveryMeals.length})\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-5\">\n {deliveryMeals.map((meal) => (\n <div key={meal.name} className=\"flex items-center gap-3\">\n <div className=\"bg-muted grid size-8 place-items-center rounded-full text-xs\">\n <Utensils className=\"text-muted-foreground size-4\" />\n </div>\n <div className=\"min-w-4 flex-1\">\n <p className=\"truncate pb-1 text-sm font-medium\">\n {meal.name}\n </p>\n <p className=\"text-muted-foreground text-xs\">\n {meal.price}\n </p>\n </div>\n <Badge\n variant=\"secondary\"\n className=\"h-6 rounded-full px-2.5\"\n >\n x{meal.quantity}\n </Badge>\n </div>\n ))}\n <div className=\"border-border/60 flex items-center justify-between border-t pt-3 text-sm\">\n <span className=\"text-muted-foreground\">Bundle total</span>\n <span className=\"font-medium\">$189.00</span>\n </div>\n </CardContent>\n </Card>\n\n <div className=\"mt-4 grid gap-3 sm:grid-cols-2\">\n <Card>\n <CardContent className=\"space-y-2\">\n <p className=\"text-muted-foreground text-sm\">\n Pickup confirmed\n </p>\n <p className=\"text-sm font-medium\">Mon, Feb 10 at 1:48 PM</p>\n </CardContent>\n </Card>\n <Card>\n <CardContent className=\"space-y-2\">\n <p className=\"text-muted-foreground text-sm\">\n Remaining travel\n </p>\n <p className=\"text-sm font-medium\">\n {formatDuration(routeData?.duration)}\n <span className=\"text-muted-foreground font-normal\">\n {\" · \"}\n {formatDistance(routeData?.distance)}\n </span>\n </p>\n </CardContent>\n </Card>\n </div>\n\n <div className=\"mt-6 flex flex-wrap items-center gap-2\">\n <Button size=\"sm\">\n <Clock3 />\n View timeline\n </Button>\n <Button variant=\"outline\" size=\"sm\">\n <UserRound />\n Contact courier\n </Button>\n </div>\n </div>\n\n <div className=\"relative h-[450px] overflow-hidden rounded-xl shadow-sm md:h-full\">\n <Map\n loading={loading}\n center={mapView.center}\n zoom={mapView.zoom}\n minZoom={mapView.minZoom}\n maxZoom={mapView.maxZoom}\n >\n <MapRoute\n id=\"delivery-route\"\n coordinates={routeData?.coordinates ?? []}\n progress={progressFraction}\n color={remainingRouteColor}\n width={routeStyle.remaining.width}\n opacity={routeStyle.remaining.opacity}\n interactive={false}\n >\n <RouteProgress\n color={routeStyle.progress.color}\n width={routeStyle.progress.width}\n opacity={routeStyle.progress.opacity}\n />\n\n <RouteMarker at=\"progress\" offset={[0, 10]}>\n <MarkerContent>\n <div\n className=\"relative grid size-9 place-items-center rounded-full shadow-md\"\n style={{ backgroundColor: routeStyle.progress.color }}\n >\n <Truck className=\"size-4 text-white\" />\n <div className=\"bg-popover text-popover-foreground absolute bottom-full left-1/2 mb-2.5 -translate-x-1/2 rounded-md border px-2 py-1 text-xs font-medium whitespace-nowrap shadow-md\">\n {formatDuration(routeData?.duration)} away\n <span className=\"bg-popover absolute top-full left-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rotate-45 border-r border-b\" />\n </div>\n </div>\n </MarkerContent>\n </RouteMarker>\n\n </MapRoute>\n\n {/* Fixed addresses, so they stay put if the route request fails. */}\n <MapMarker longitude={pickup.lng} latitude={pickup.lat}>\n <MarkerContent>\n <div className=\"grid size-7 place-items-center rounded-full bg-emerald-500 shadow-md\">\n <Store className=\"size-3.5 text-white\" />\n </div>\n </MarkerContent>\n </MapMarker>\n\n <MapMarker longitude={dropoff.lng} latitude={dropoff.lat}>\n <MarkerContent>\n <div className=\"grid size-7 place-items-center rounded-full bg-rose-500 shadow-md\">\n <House className=\"size-3.5 text-white\" />\n </div>\n </MarkerContent>\n </MapMarker>\n </Map>\n </div>\n </div>\n </div>\n );\n}\n",
"type": "registry:page",
"target": "app/delivery/page.tsx"
},
diff --git a/public/r/map.json b/public/r/map.json
index 37b2e34..a2dacdd 100644
--- a/public/r/map.json
+++ b/public/r/map.json
@@ -14,7 +14,7 @@
"files": [
{
"path": "src/registry/map.tsx",
- "content": "\"use client\";\n\nimport * as MapLibreGL from \"maplibre-gl\";\nimport type { PopupOptions, MarkerOptions } from \"maplibre-gl\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\nimport type * as GeoJSON from \"geojson\";\nimport {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { X, Minus, Plus, Locate, Maximize, Loader2 } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nif (typeof window !== \"undefined\" && !MapLibreGL.getWorkerUrl()) {\n MapLibreGL.setWorkerUrl(\n `https://unpkg.com/maplibre-gl@${MapLibreGL.getVersion()}/dist/maplibre-gl-worker.mjs`,\n );\n}\n\nconst defaultStyles = {\n dark: \"https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json\",\n light: \"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json\",\n};\n\n// A tile-less, dependency-free style with a transparent background. Use it for\n// data visualizations (choropleths, world arcs, dot maps) where you draw your\n// own layers and don't need a street basemap. The easiest way to opt in is the\n// `blank` prop:\n// <Map blank>...</Map>\n// The transparent background lets the themed container show through.\nconst blankMapStyle: MapLibreGL.StyleSpecification = {\n version: 8,\n sources: {},\n layers: [\n {\n id: \"background\",\n type: \"background\",\n paint: { \"background-color\": \"rgba(0, 0, 0, 0)\" },\n },\n ],\n};\n\n// Prevent equivalent inline style objects from triggering a full map style reload.\nfunction useStableValue<T>(value: T): T {\n const key = useMemo(() => JSON.stringify(value) ?? \"\", [value]);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => value, [key]);\n}\n\nfunction mergeHoverPaint<T extends Record<string, unknown>>(\n paint: T,\n hoverPaint: T | undefined,\n): T {\n if (!hoverPaint) return paint;\n const merged: Record<string, unknown> = { ...paint };\n for (const [key, hoverValue] of Object.entries(hoverPaint)) {\n if (hoverValue === undefined) continue;\n const baseValue = merged[key];\n merged[key] =\n baseValue === undefined\n ? hoverValue\n : [\n \"case\",\n [\"boolean\", [\"feature-state\", \"hover\"], false],\n hoverValue,\n baseValue,\n ];\n }\n return merged as T;\n}\n\ntype Theme = \"light\" | \"dark\";\n\n// Check the document for an explicit theme (works with next-themes, etc.).\n// Covers both `attribute=\"class\"` (the default) and `attribute=\"data-theme\"`.\nfunction getDocumentTheme(): Theme | null {\n if (typeof document === \"undefined\") return null;\n const root = document.documentElement;\n if (root.classList.contains(\"dark\")) return \"dark\";\n if (root.classList.contains(\"light\")) return \"light\";\n const dataTheme = root.dataset.theme;\n if (dataTheme === \"dark\" || dataTheme === \"light\") return dataTheme;\n return null;\n}\n\n// Get system preference\nfunction getSystemTheme(): Theme {\n if (typeof window === \"undefined\") return \"light\";\n return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n ? \"dark\"\n : \"light\";\n}\n\nfunction useResolvedTheme(themeProp?: \"light\" | \"dark\"): Theme {\n const [detectedTheme, setDetectedTheme] = useState<Theme>(\n () => getDocumentTheme() ?? getSystemTheme(),\n );\n\n useEffect(() => {\n if (themeProp) return; // Skip detection if theme is provided via prop\n\n // Watch for document theme changes (e.g., next-themes toggling the class\n // or the data-theme attribute).\n const observer = new MutationObserver(() => {\n const docTheme = getDocumentTheme();\n if (docTheme) {\n setDetectedTheme(docTheme);\n }\n });\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"class\", \"data-theme\"],\n });\n\n // Also watch for system preference changes\n const mediaQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n const handleSystemChange = (e: MediaQueryListEvent) => {\n // Only use system preference if no document class is set\n if (!getDocumentTheme()) {\n setDetectedTheme(e.matches ? \"dark\" : \"light\");\n }\n };\n mediaQuery.addEventListener(\"change\", handleSystemChange);\n\n return () => {\n observer.disconnect();\n mediaQuery.removeEventListener(\"change\", handleSystemChange);\n };\n }, [themeProp]);\n\n return themeProp ?? detectedTheme;\n}\n\ntype MapContextValue = {\n map: MapLibreGL.Map | null;\n isLoaded: boolean;\n resolvedTheme: Theme;\n};\n\nconst MapContext = createContext<MapContextValue | null>(null);\n\nfunction useMap() {\n const context = useContext(MapContext);\n if (!context) {\n throw new Error(\"useMap must be used within a Map component\");\n }\n return context;\n}\n\n/** Map viewport state */\ntype MapViewport = {\n /** Center coordinates [longitude, latitude] */\n center: [number, number];\n /** Zoom level */\n zoom: number;\n /** Bearing (rotation) in degrees */\n bearing: number;\n /** Pitch (tilt) in degrees */\n pitch: number;\n};\n\ntype MapStyleOption = string | MapLibreGL.StyleSpecification;\n\ntype MapRef = MapLibreGL.Map;\n\ntype MapProps = {\n children?: ReactNode;\n /** Additional CSS classes for the map container */\n className?: string;\n /**\n * Theme for the map. If not provided, automatically detects system preference.\n * Pass your theme value here.\n */\n theme?: Theme;\n /** Custom map styles for light and dark themes. Overrides the default Carto styles. */\n styles?: {\n light?: MapStyleOption;\n dark?: MapStyleOption;\n };\n /**\n * Use a transparent, tile-less basemap instead of the default Carto street\n * basemap — a blank canvas. Used alone it renders nothing; add your own\n * layers on top (`<MapGeoJSON>`, `<MapArc>`, markers, etc.). Ideal for data\n * visualizations (choropleths, arcs, dot maps).\n * Ignored when an explicit `styles` prop is provided.\n */\n blank?: boolean;\n /** Map projection type. Use `{ type: \"globe\" }` for 3D globe view. */\n projection?: MapLibreGL.ProjectionSpecification;\n /**\n * Controlled viewport. When provided with onViewportChange,\n * the map becomes controlled and viewport is driven by this prop.\n */\n viewport?: Partial<MapViewport>;\n /**\n * Callback fired continuously as the viewport changes (pan, zoom, rotate, pitch).\n * Can be used standalone to observe changes, or with `viewport` prop\n * to enable controlled mode where the map viewport is driven by your state.\n */\n onViewportChange?: (viewport: MapViewport) => void;\n /** Show a loading indicator on the map */\n loading?: boolean;\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\n\nfunction DefaultLoader() {\n return (\n <div className=\"bg-background/50 absolute inset-0 z-10 flex items-center justify-center backdrop-blur-xs\">\n <div className=\"flex gap-1\">\n <span className=\"bg-muted-foreground/60 size-1.5 animate-pulse rounded-full\" />\n <span className=\"bg-muted-foreground/60 size-1.5 animate-pulse rounded-full [animation-delay:150ms]\" />\n <span className=\"bg-muted-foreground/60 size-1.5 animate-pulse rounded-full [animation-delay:300ms]\" />\n </div>\n </div>\n );\n}\n\nfunction getViewport(map: MapLibreGL.Map): MapViewport {\n const center = map.getCenter();\n return {\n center: [center.lng, center.lat],\n zoom: map.getZoom(),\n bearing: map.getBearing(),\n pitch: map.getPitch(),\n };\n}\n\nconst Map = forwardRef<MapRef, MapProps>(function Map(\n {\n children,\n className,\n theme: themeProp,\n styles,\n blank = false,\n projection,\n viewport,\n onViewportChange,\n loading = false,\n ...props\n },\n ref,\n) {\n const containerRef = useRef<HTMLDivElement>(null);\n const [mapInstance, setMapInstance] = useState<MapLibreGL.Map | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [isStyleLoaded, setIsStyleLoaded] = useState(false);\n const [pendingStyle, setPendingStyle] = useState<MapStyleOption | null>(null);\n const currentStyleRef = useRef<MapStyleOption | null>(null);\n const styleSwapInFlightRef = useRef(false);\n const internalUpdateRef = useRef(false);\n const resolvedTheme = useResolvedTheme(themeProp);\n\n const isControlled = viewport !== undefined && onViewportChange !== undefined;\n\n const onViewportChangeRef = useRef(onViewportChange);\n onViewportChangeRef.current = onViewportChange;\n\n const stableStyles = useStableValue(styles);\n\n const mapStyles = useMemo(() => {\n // Explicit styles win. Otherwise `blank` opts into the transparent\n // tile-less basemap; with neither, fall back to the Carto defaults.\n if (stableStyles) {\n return {\n dark: stableStyles.dark ?? defaultStyles.dark,\n light: stableStyles.light ?? defaultStyles.light,\n };\n }\n if (blank) {\n return { dark: blankMapStyle, light: blankMapStyle };\n }\n return defaultStyles;\n }, [stableStyles, blank]);\n\n // Expose the map instance to the parent component\n useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);\n\n // Initialize the map\n useEffect(() => {\n if (!containerRef.current) return;\n\n const initialStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n currentStyleRef.current = initialStyle;\n\n const map = new MapLibreGL.Map({\n container: containerRef.current,\n style: initialStyle,\n renderWorldCopies: false,\n attributionControl: {\n compact: true,\n },\n ...props,\n ...viewport,\n });\n\n const styleLoadHandler = () => {\n styleSwapInFlightRef.current = false;\n setIsStyleLoaded(true);\n };\n const loadHandler = () => setIsLoaded(true);\n\n // Viewport change handler - skip if triggered by internal update\n const handleMove = () => {\n if (internalUpdateRef.current) return;\n onViewportChangeRef.current?.(getViewport(map));\n };\n\n map.on(\"load\", loadHandler);\n map.on(\"style.load\", styleLoadHandler);\n map.on(\"move\", handleMove);\n setMapInstance(map);\n\n return () => {\n map.off(\"load\", loadHandler);\n map.off(\"style.load\", styleLoadHandler);\n map.off(\"move\", handleMove);\n map.remove();\n setIsLoaded(false);\n setIsStyleLoaded(false);\n setMapInstance(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Sync controlled viewport to map\n useEffect(() => {\n if (!mapInstance || !isControlled || !viewport) return;\n if (mapInstance.isMoving()) return;\n\n const current = getViewport(mapInstance);\n const next = {\n center: viewport.center ?? current.center,\n zoom: viewport.zoom ?? current.zoom,\n bearing: viewport.bearing ?? current.bearing,\n pitch: viewport.pitch ?? current.pitch,\n };\n\n if (\n next.center[0] === current.center[0] &&\n next.center[1] === current.center[1] &&\n next.zoom === current.zoom &&\n next.bearing === current.bearing &&\n next.pitch === current.pitch\n ) {\n return;\n }\n\n internalUpdateRef.current = true;\n mapInstance.jumpTo(next);\n internalUpdateRef.current = false;\n }, [mapInstance, isControlled, viewport]);\n\n // Handle style change: close the gate (so layer children tear down and\n // re-add on the incoming style) - the swap itself is staged to the effect below.\n useEffect(() => {\n if (!mapInstance || !resolvedTheme) return;\n\n const newStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n if (currentStyleRef.current === newStyle) return;\n\n currentStyleRef.current = newStyle;\n setIsStyleLoaded(false);\n setPendingStyle(newStyle);\n }, [mapInstance, resolvedTheme, mapStyles]);\n\n useEffect(() => {\n if (!mapInstance || !pendingStyle) return;\n\n setPendingStyle(null);\n styleSwapInFlightRef.current = true;\n // Full reload (no diff) so `style.load` fires deterministically. A\n // successful diff would never fire it, leaving isStyleLoaded stuck false.\n mapInstance.setStyle(pendingStyle, { diff: false });\n }, [mapInstance, pendingStyle]);\n\n // Sync projection when the prop changes after mount.\n useEffect(() => {\n if (!mapInstance || !isStyleLoaded || !projection) return;\n if (styleSwapInFlightRef.current) return;\n mapInstance.setProjection(projection);\n }, [mapInstance, isStyleLoaded, projection]);\n\n const contextValue = useMemo(\n () => ({\n map: mapInstance,\n isLoaded: isLoaded && isStyleLoaded,\n resolvedTheme,\n }),\n [mapInstance, isLoaded, isStyleLoaded, resolvedTheme],\n );\n\n return (\n <MapContext.Provider value={contextValue}>\n <div\n ref={containerRef}\n className={cn(\"relative h-full w-full\", className)}\n >\n {(!isLoaded || loading) && <DefaultLoader />}\n {/* SSR-safe: children render only when map is loaded on client */}\n {mapInstance && children}\n </div>\n </MapContext.Provider>\n );\n});\n\ntype MarkerContextValue = {\n marker: MapLibreGL.Marker;\n map: MapLibreGL.Map | null;\n};\n\nconst MarkerContext = createContext<MarkerContextValue | null>(null);\n\nfunction useMarkerContext() {\n const context = useContext(MarkerContext);\n if (!context) {\n throw new Error(\"Marker components must be used within MapMarker\");\n }\n return context;\n}\n\ntype MapMarkerProps = {\n /** Longitude coordinate for marker position */\n longitude: number;\n /** Latitude coordinate for marker position */\n latitude: number;\n /** Marker subcomponents (MarkerContent, MarkerPopup, MarkerTooltip, MarkerLabel) */\n children: ReactNode;\n /** Callback when marker is clicked */\n onClick?: (e: MouseEvent) => void;\n /** Callback when mouse enters marker */\n onMouseEnter?: (e: MouseEvent) => void;\n /** Callback when mouse leaves marker */\n onMouseLeave?: (e: MouseEvent) => void;\n /** Callback when marker drag starts (requires draggable: true) */\n onDragStart?: (lngLat: { lng: number; lat: number }) => void;\n /** Callback during marker drag (requires draggable: true) */\n onDrag?: (lngLat: { lng: number; lat: number }) => void;\n /** Callback when marker drag ends (requires draggable: true) */\n onDragEnd?: (lngLat: { lng: number; lat: number }) => void;\n} & Omit<MarkerOptions, \"element\">;\n\nfunction MapMarker({\n longitude,\n latitude,\n children,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n draggable = false,\n ...markerOptions\n}: MapMarkerProps) {\n const { map } = useMap();\n\n const callbacksRef = useRef({\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n });\n callbacksRef.current = {\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n };\n\n const marker = useMemo(() => {\n const markerInstance = new MapLibreGL.Marker({\n ...markerOptions,\n element: document.createElement(\"div\"),\n draggable,\n }).setLngLat([longitude, latitude]);\n\n const handleClick = (e: MouseEvent) => callbacksRef.current.onClick?.(e);\n const handleMouseEnter = (e: MouseEvent) =>\n callbacksRef.current.onMouseEnter?.(e);\n const handleMouseLeave = (e: MouseEvent) =>\n callbacksRef.current.onMouseLeave?.(e);\n\n markerInstance.getElement()?.addEventListener(\"click\", handleClick);\n markerInstance\n .getElement()\n ?.addEventListener(\"mouseenter\", handleMouseEnter);\n markerInstance\n .getElement()\n ?.addEventListener(\"mouseleave\", handleMouseLeave);\n\n const handleDragStart = () => {\n const lngLat = markerInstance.getLngLat();\n callbacksRef.current.onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDrag = () => {\n const lngLat = markerInstance.getLngLat();\n callbacksRef.current.onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDragEnd = () => {\n const lngLat = markerInstance.getLngLat();\n callbacksRef.current.onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n\n markerInstance.on(\"dragstart\", handleDragStart);\n markerInstance.on(\"drag\", handleDrag);\n markerInstance.on(\"dragend\", handleDragEnd);\n\n return markerInstance;\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n marker.addTo(map);\n\n return () => {\n marker.remove();\n };\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n const { offset, rotation, rotationAlignment, pitchAlignment } = markerOptions;\n\n useEffect(() => {\n const current = marker.getLngLat();\n if (current.lng !== longitude || current.lat !== latitude) {\n marker.setLngLat([longitude, latitude]);\n }\n\n if (marker.isDraggable() !== draggable) {\n marker.setDraggable(draggable);\n }\n\n const currentOffset = marker.getOffset();\n const newOffset = offset ?? [0, 0];\n const [newOffsetX, newOffsetY] = Array.isArray(newOffset)\n ? newOffset\n : [newOffset.x, newOffset.y];\n if (currentOffset.x !== newOffsetX || currentOffset.y !== newOffsetY) {\n marker.setOffset(newOffset);\n }\n\n if (marker.getRotation() !== (rotation ?? 0)) {\n marker.setRotation(rotation ?? 0);\n }\n if (marker.getRotationAlignment() !== (rotationAlignment ?? \"auto\")) {\n marker.setRotationAlignment(rotationAlignment ?? \"auto\");\n }\n if (marker.getPitchAlignment() !== (pitchAlignment ?? \"auto\")) {\n marker.setPitchAlignment(pitchAlignment ?? \"auto\");\n }\n }, [\n marker,\n longitude,\n latitude,\n draggable,\n offset,\n rotation,\n rotationAlignment,\n pitchAlignment,\n ]);\n\n return (\n <MarkerContext.Provider value={{ marker, map }}>\n {children}\n </MarkerContext.Provider>\n );\n}\n\ntype MarkerContentProps = {\n /** Custom marker content. Defaults to a blue dot if not provided */\n children?: ReactNode;\n /** Additional CSS classes for the marker container */\n className?: string;\n};\n\nfunction MarkerContent({ children, className }: MarkerContentProps) {\n const { marker } = useMarkerContext();\n\n return createPortal(\n <div className={cn(\"relative cursor-pointer\", className)}>\n {children || <DefaultMarkerIcon />}\n </div>,\n marker.getElement(),\n );\n}\n\nfunction DefaultMarkerIcon() {\n return (\n <div className=\"relative h-4 w-4 rounded-full border-2 border-white bg-blue-500 shadow-lg\" />\n );\n}\n\nfunction PopupCloseButton({ onClick }: { onClick: () => void }) {\n return (\n <button\n type=\"button\"\n onClick={onClick}\n aria-label=\"Close popup\"\n className=\"focus-visible:ring-ring hover:bg-muted text-foreground absolute top-1 right-1 z-10 inline-flex size-5 cursor-pointer items-center justify-center rounded-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset\"\n >\n <X className=\"size-3.5\" />\n </button>\n );\n}\n\ntype MarkerPopupProps = {\n /** Popup content */\n children: ReactNode;\n /** Additional CSS classes for the popup container */\n className?: string;\n /** Show a close button in the popup (default: false) */\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\" | \"closeButton\">;\n\nfunction MarkerPopup({\n children,\n className,\n closeButton = false,\n ...popupOptions\n}: MarkerPopupProps) {\n const { marker, map } = useMarkerContext();\n const container = useMemo(() => document.createElement(\"div\"), []);\n const { offset, maxWidth } = popupOptions;\n\n const popup = useMemo(() => {\n const popupInstance = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n return popupInstance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n popup.setDOMContent(container);\n marker.setPopup(popup);\n\n return () => {\n marker.setPopup(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n // Sync popup options when they change.\n useEffect(() => {\n popup.setOffset(offset ?? 16);\n if (maxWidth) {\n popup.setMaxWidth(maxWidth);\n }\n }, [popup, offset, maxWidth]);\n\n const handleClose = () => popup.remove();\n\n return createPortal(\n <div\n className={cn(\n \"bg-popover text-popover-foreground relative max-w-62 rounded-md border p-3 shadow-md\",\n \"animate-in fade-in-0 zoom-in-95 duration-200 ease-out\",\n className,\n )}\n >\n {closeButton && <PopupCloseButton onClick={handleClose} />}\n {children}\n </div>,\n container,\n );\n}\n\ntype MarkerTooltipProps = {\n /** Tooltip content */\n children: ReactNode;\n /** Additional CSS classes for the tooltip container */\n className?: string;\n} & Omit<PopupOptions, \"className\" | \"closeButton\" | \"closeOnClick\">;\n\nfunction MarkerTooltip({\n children,\n className,\n ...popupOptions\n}: MarkerTooltipProps) {\n const { marker, map } = useMarkerContext();\n const container = useMemo(() => document.createElement(\"div\"), []);\n const { offset, maxWidth } = popupOptions;\n\n const tooltip = useMemo(() => {\n const tooltipInstance = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeOnClick: true,\n closeButton: false,\n }).setMaxWidth(\"none\");\n\n return tooltipInstance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n tooltip.setDOMContent(container);\n\n const handleMouseEnter = () => {\n tooltip.setLngLat(marker.getLngLat()).addTo(map);\n };\n const handleMouseLeave = () => tooltip.remove();\n\n marker.getElement()?.addEventListener(\"mouseenter\", handleMouseEnter);\n marker.getElement()?.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n marker.getElement()?.removeEventListener(\"mouseenter\", handleMouseEnter);\n marker.getElement()?.removeEventListener(\"mouseleave\", handleMouseLeave);\n tooltip.remove();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n // Sync tooltip options when they change.\n useEffect(() => {\n tooltip.setOffset(offset ?? 16);\n if (maxWidth) {\n tooltip.setMaxWidth(maxWidth);\n }\n }, [tooltip, offset, maxWidth]);\n\n return createPortal(\n <div\n className={cn(\n \"bg-foreground text-background pointer-events-none rounded-md px-2 py-1 text-xs text-balance shadow-md\",\n \"animate-in fade-in-0 zoom-in-95 duration-200 ease-out\",\n className,\n )}\n >\n {children}\n </div>,\n container,\n );\n}\n\ntype MarkerLabelProps = {\n /** Label text content */\n children: ReactNode;\n /** Additional CSS classes for the label */\n className?: string;\n /** Position of the label relative to the marker (default: \"top\") */\n position?: \"top\" | \"bottom\";\n};\n\nfunction MarkerLabel({\n children,\n className,\n position = \"top\",\n}: MarkerLabelProps) {\n const positionClasses = {\n top: \"bottom-full mb-1\",\n bottom: \"top-full mt-1\",\n };\n\n return (\n <div\n className={cn(\n \"absolute left-1/2 -translate-x-1/2 whitespace-nowrap\",\n \"text-foreground text-[10px] font-medium\",\n positionClasses[position],\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\ntype MapControlsProps = {\n /** Position of the controls on the map (default: \"bottom-right\") */\n position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\";\n /** Show zoom in/out buttons (default: true) */\n showZoom?: boolean;\n /** Show compass button to reset bearing (default: false) */\n showCompass?: boolean;\n /** Show locate button to find user's location (default: false) */\n showLocate?: boolean;\n /** Show fullscreen toggle button (default: false) */\n showFullscreen?: boolean;\n /** Additional CSS classes for the controls container */\n className?: string;\n /** Callback with user coordinates when located */\n onLocate?: (coords: { longitude: number; latitude: number }) => void;\n};\n\nconst positionClasses = {\n \"top-left\": \"top-2 left-2\",\n \"top-right\": \"top-2 right-2\",\n \"bottom-left\": \"bottom-2 left-2\",\n \"bottom-right\": \"bottom-10 right-2\",\n};\n\nfunction ControlGroup({ children }: { children: React.ReactNode }) {\n return (\n <div className=\"border-border bg-background [&>button:not(:last-child)]:border-border flex flex-col overflow-hidden rounded-md border shadow-sm [&>button:not(:last-child)]:border-b\">\n {children}\n </div>\n );\n}\n\nfunction ControlButton({\n onClick,\n label,\n children,\n disabled = false,\n}: {\n onClick: () => void;\n label: string;\n children: React.ReactNode;\n disabled?: boolean;\n}) {\n return (\n <button\n onClick={onClick}\n aria-label={label}\n type=\"button\"\n className={cn(\n \"flex size-8 items-center justify-center transition-colors\",\n \"first:rounded-t-md last:rounded-b-md\",\n \"hover:bg-accent dark:hover:bg-accent/40\",\n \"focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset\",\n \"disabled:pointer-events-none disabled:opacity-50\",\n )}\n disabled={disabled}\n >\n {children}\n </button>\n );\n}\n\nfunction MapControls({\n position = \"bottom-right\",\n showZoom = true,\n showCompass = false,\n showLocate = false,\n showFullscreen = false,\n className,\n onLocate,\n}: MapControlsProps) {\n const { map } = useMap();\n const [waitingForLocation, setWaitingForLocation] = useState(false);\n\n const handleZoomIn = useCallback(() => {\n map?.zoomTo(map.getZoom() + 1, { duration: 300 });\n }, [map]);\n\n const handleZoomOut = useCallback(() => {\n map?.zoomTo(map.getZoom() - 1, { duration: 300 });\n }, [map]);\n\n const handleResetBearing = useCallback(() => {\n map?.resetNorthPitch({ duration: 300 });\n }, [map]);\n\n const handleLocate = useCallback(() => {\n if (!(\"geolocation\" in navigator)) return;\n setWaitingForLocation(true);\n navigator.geolocation.getCurrentPosition(\n (pos) => {\n const coords = {\n longitude: pos.coords.longitude,\n latitude: pos.coords.latitude,\n };\n map?.flyTo({\n center: [coords.longitude, coords.latitude],\n zoom: 14,\n duration: 1500,\n });\n onLocate?.(coords);\n setWaitingForLocation(false);\n },\n (error) => {\n console.error(\"Error getting location:\", error);\n setWaitingForLocation(false);\n },\n // Without a timeout the spec default is Infinity: a dismissed permission\n // prompt would leave the button disabled forever.\n { timeout: 10000 },\n );\n }, [map, onLocate]);\n\n const handleFullscreen = useCallback(() => {\n const container = map?.getContainer();\n if (!container) return;\n if (document.fullscreenElement) {\n document.exitFullscreen();\n } else {\n container.requestFullscreen();\n }\n }, [map]);\n\n return (\n <div\n className={cn(\n \"absolute z-10 flex flex-col gap-1.5\",\n positionClasses[position],\n className,\n )}\n >\n {showZoom && (\n <ControlGroup>\n <ControlButton onClick={handleZoomIn} label=\"Zoom in\">\n <Plus className=\"size-4\" />\n </ControlButton>\n <ControlButton onClick={handleZoomOut} label=\"Zoom out\">\n <Minus className=\"size-4\" />\n </ControlButton>\n </ControlGroup>\n )}\n {showCompass && (\n <ControlGroup>\n <CompassButton onClick={handleResetBearing} />\n </ControlGroup>\n )}\n {showLocate && (\n <ControlGroup>\n <ControlButton\n onClick={handleLocate}\n label=\"Find my location\"\n disabled={waitingForLocation}\n >\n {waitingForLocation ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n <Locate className=\"size-4\" />\n )}\n </ControlButton>\n </ControlGroup>\n )}\n {showFullscreen && (\n <ControlGroup>\n <ControlButton onClick={handleFullscreen} label=\"Toggle fullscreen\">\n <Maximize className=\"size-4\" />\n </ControlButton>\n </ControlGroup>\n )}\n </div>\n );\n}\n\nfunction CompassButton({ onClick }: { onClick: () => void }) {\n const { map } = useMap();\n const compassRef = useRef<SVGSVGElement>(null);\n\n useEffect(() => {\n if (!map || !compassRef.current) return;\n\n const compass = compassRef.current;\n\n const updateRotation = () => {\n const bearing = map.getBearing();\n const pitch = map.getPitch();\n compass.style.transform = `rotateX(${pitch}deg) rotateZ(${-bearing}deg)`;\n };\n\n map.on(\"rotate\", updateRotation);\n map.on(\"pitch\", updateRotation);\n updateRotation();\n\n return () => {\n map.off(\"rotate\", updateRotation);\n map.off(\"pitch\", updateRotation);\n };\n }, [map]);\n\n return (\n <ControlButton onClick={onClick} label=\"Reset bearing to north\">\n <svg\n ref={compassRef}\n viewBox=\"0 0 24 24\"\n className=\"size-5\"\n style={{ transformStyle: \"preserve-3d\" }}\n >\n <path d=\"M12 2L16 12H12V2Z\" className=\"fill-red-500\" />\n <path d=\"M12 2L8 12H12V2Z\" className=\"fill-red-300\" />\n <path d=\"M12 22L16 12H12V22Z\" className=\"fill-muted-foreground/60\" />\n <path d=\"M12 22L8 12H12V22Z\" className=\"fill-muted-foreground/30\" />\n </svg>\n </ControlButton>\n );\n}\n\ntype MapPopupProps = {\n /** Longitude coordinate for popup position */\n longitude: number;\n /** Latitude coordinate for popup position */\n latitude: number;\n /** Callback when popup is closed */\n onClose?: () => void;\n /** Popup content */\n children: ReactNode;\n /** Additional CSS classes for the popup container */\n className?: string;\n /** Show a close button in the popup (default: false) */\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\" | \"closeButton\">;\n\nfunction MapPopup({\n longitude,\n latitude,\n onClose,\n children,\n className,\n closeButton = false,\n ...popupOptions\n}: MapPopupProps) {\n const { map } = useMap();\n const onCloseRef = useRef(onClose);\n onCloseRef.current = onClose;\n const container = useMemo(() => document.createElement(\"div\"), []);\n const { offset, maxWidth } = popupOptions;\n\n const popup = useMemo(() => {\n const popupInstance = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setLngLat([longitude, latitude]);\n\n return popupInstance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n const onCloseProp = () => onCloseRef.current?.();\n\n popup.on(\"close\", onCloseProp);\n\n popup.setDOMContent(container);\n popup.addTo(map);\n\n return () => {\n popup.off(\"close\", onCloseProp);\n if (popup.isOpen()) {\n popup.remove();\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n // Sync popup position and options when they change.\n useEffect(() => {\n const current = popup.getLngLat();\n if (!current || current.lng !== longitude || current.lat !== latitude) {\n popup.setLngLat([longitude, latitude]);\n }\n popup.setOffset(offset ?? 16);\n if (maxWidth) {\n popup.setMaxWidth(maxWidth);\n }\n }, [popup, longitude, latitude, offset, maxWidth]);\n\n const handleClose = () => {\n popup.remove();\n };\n\n return createPortal(\n <div\n className={cn(\n \"bg-popover text-popover-foreground relative max-w-62 rounded-md border p-3 shadow-md\",\n \"animate-in fade-in-0 zoom-in-95 duration-200 ease-out\",\n className,\n )}\n >\n {closeButton && <PopupCloseButton onClick={handleClose} />}\n {children}\n </div>,\n container,\n );\n}\n\ntype MapRouteProps = {\n /** Optional unique identifier for the route layer */\n id?: string;\n /** Array of [longitude, latitude] coordinate pairs defining the route */\n coordinates: [number, number][];\n /** Line color as CSS color value (default: \"#4285F4\") */\n color?: string;\n /** Line width in pixels (default: 3) */\n width?: number;\n /** Line opacity from 0 to 1 (default: 0.8) */\n opacity?: number;\n /** Dash pattern [dash length, gap length] for dashed lines */\n dashArray?: [number, number];\n /** Callback when the route line is clicked */\n onClick?: () => void;\n /** Callback when mouse enters the route line */\n onMouseEnter?: () => void;\n /** Callback when mouse leaves the route line */\n onMouseLeave?: () => void;\n /** Whether the route is interactive - shows pointer cursor on hover (default: true) */\n interactive?: boolean;\n};\n\nfunction MapRoute({\n id: propId,\n coordinates,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive = true,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `route-source-${id}`;\n const layerId = `route-layer-${id}`;\n\n // Add source and layer on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: {\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates: [] },\n },\n });\n\n map.addLayer({\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: { \"line-join\": \"round\", \"line-cap\": \"round\" },\n paint: {\n \"line-color\": color,\n \"line-width\": width,\n \"line-opacity\": opacity,\n ...(dashArray && { \"line-dasharray\": dashArray }),\n },\n });\n\n return () => {\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // When coordinates change, update the source data\n useEffect(() => {\n if (!isLoaded || !map || coordinates.length < 2) return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData({\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates },\n });\n }\n }, [isLoaded, map, coordinates, sourceId]);\n\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n\n map.setPaintProperty(layerId, \"line-color\", color);\n map.setPaintProperty(layerId, \"line-width\", width);\n map.setPaintProperty(layerId, \"line-opacity\", opacity);\n map.setPaintProperty(layerId, \"line-dasharray\", dashArray);\n }, [isLoaded, map, layerId, color, width, opacity, dashArray]);\n\n // Handle click and hover events\n useEffect(() => {\n if (!isLoaded || !map || !interactive) return;\n\n const handleClick = () => {\n onClick?.();\n };\n const handleMouseEnter = () => {\n map.getCanvas().style.cursor = \"pointer\";\n onMouseEnter?.();\n };\n const handleMouseLeave = () => {\n map.getCanvas().style.cursor = \"\";\n onMouseLeave?.();\n };\n\n map.on(\"click\", layerId, handleClick);\n map.on(\"mouseenter\", layerId, handleMouseEnter);\n map.on(\"mouseleave\", layerId, handleMouseLeave);\n\n return () => {\n map.off(\"click\", layerId, handleClick);\n map.off(\"mouseenter\", layerId, handleMouseEnter);\n map.off(\"mouseleave\", layerId, handleMouseLeave);\n };\n }, [\n isLoaded,\n map,\n layerId,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive,\n ]);\n\n return null;\n}\n\ntype MapGeoJSONData<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> =\n | GeoJSON.FeatureCollection<GeoJSON.Geometry, P>\n | GeoJSON.Feature<GeoJSON.Geometry, P>\n | GeoJSON.Geometry\n | string;\n\ntype MapFillPaint = NonNullable<MapLibreGL.FillLayerSpecification[\"paint\"]>;\ntype MapLinePaint = NonNullable<MapLibreGL.LineLayerSpecification[\"paint\"]>;\n\n/** A rendered feature with strongly-typed `properties`. */\ntype MapGeoJSONFeature<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = Omit<MapLibreGL.MapGeoJSONFeature, \"properties\"> & { properties: P };\n\n/** Event payload passed to MapGeoJSON interaction callbacks. */\ntype MapGeoJSONEvent<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = {\n /** The feature under the cursor, with its typed GeoJSON properties. */\n feature: MapGeoJSONFeature<P>;\n /** Longitude of the cursor at the time of the event. */\n longitude: number;\n /** Latitude of the cursor at the time of the event. */\n latitude: number;\n /** The underlying MapLibre mouse event for advanced use cases. */\n originalEvent: MapLibreGL.MapLayerMouseEvent;\n};\n\ntype MapGeoJSONProps<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = {\n /** GeoJSON data (FeatureCollection, Feature, Geometry) or a URL to fetch it from. */\n data: MapGeoJSONData<P>;\n /** Optional unique identifier prefix for the source/layers. Auto-generated if not provided. */\n id?: string;\n /**\n * Feature property to promote to the feature `id`. Required for hover\n * feature-state (`fillHoverPaint`) and stable `onHover`/`onClick` payloads.\n */\n promoteId?: string;\n /**\n * Paint for the polygon fill layer. Merged on top of a theme-aware monochrome\n * surface tone (`fill-color`). Pass `false` to omit the fill layer entirely\n * (e.g. outlines only).\n */\n fillPaint?: MapFillPaint | false;\n /**\n * Paint for the outline layer. Merged on top of a hairline default\n * (`line-color` = a near-surface neutral, `line-width` = 0.5) for thin\n * separators. Override `line-color` if your container differs, or pass\n * `false` to omit the layer.\n */\n linePaint?: MapLinePaint | false;\n /**\n * Paint merged onto the fill layer for the feature under the cursor, applied\n * as a `case` expression keyed on hover feature-state. Requires `promoteId`.\n */\n fillHoverPaint?: MapFillPaint;\n /** Callback when a feature is clicked. */\n onClick?: (e: MapGeoJSONEvent<P>) => void;\n /** Callback fired when the hovered feature changes; `null` when the cursor leaves. */\n onHover?: (e: MapGeoJSONEvent<P> | null) => void;\n /** Whether features respond to mouse events (default: false). */\n interactive?: boolean;\n /** Optional MapLibre layer id to insert the layers before (z-order control). */\n beforeId?: string;\n};\n\n// Monochrome defaults: a neutral-gray fill (hex of the grayscale chart tokens)\n// with a fixed near-surface line for thin separators. Colors are hardcoded (not\n// theme tokens), tuned for a typical light/dark surface. Override via\n// `fillPaint` / `linePaint`.\nconst GEOJSON_DEFAULT_COLORS = {\n light: { fill: \"#d4d4d4\", line: \"#ffffff\" },\n dark: { fill: \"#404040\", line: \"#171717\" },\n} satisfies Record<Theme, { fill: string; line: string }>;\n\n/**\n * Renders arbitrary GeoJSON as fill + outline layers on the map. Composes like\n * `MapRoute` / `MapArc` — drop it inside `<Map>` (typically with `blank`) for\n * choropleths and region/data maps. For full control over expressions and\n * multiple layers, manage layers directly via `useMap()` instead.\n */\nfunction MapGeoJSON<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n>({\n data,\n id: propId,\n promoteId,\n fillPaint,\n linePaint,\n fillHoverPaint,\n onClick,\n onHover,\n interactive = false,\n beforeId,\n}: MapGeoJSONProps<P>) {\n const { map, isLoaded, resolvedTheme } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `geojson-source-${id}`;\n const fillLayerId = `geojson-fill-${id}`;\n const lineLayerId = `geojson-line-${id}`;\n\n const defaults = GEOJSON_DEFAULT_COLORS[resolvedTheme];\n\n const showFill = fillPaint !== false;\n const showLine = linePaint !== false;\n\n const mergedFillPaint = useMemo(\n () =>\n mergeHoverPaint(\n { \"fill-color\": defaults.fill, ...(fillPaint || {}) },\n fillHoverPaint,\n ),\n [defaults.fill, fillPaint, fillHoverPaint],\n );\n const mergedLinePaint = useMemo(\n () => ({\n \"line-color\": defaults.line,\n \"line-width\": 0.5,\n ...(linePaint || {}),\n }),\n [defaults.line, linePaint],\n );\n const latestRef = useRef({ onClick, onHover });\n latestRef.current = { onClick, onHover };\n\n // Add source on mount.\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data,\n ...(promoteId ? { promoteId } : {}),\n });\n\n return () => {\n try {\n if (map.getLayer(lineLayerId)) map.removeLayer(lineLayerId);\n if (map.getLayer(fillLayerId)) map.removeLayer(fillLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // style may be mid-reload\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // Sync data when it changes.\n useEffect(() => {\n if (!isLoaded || !map) return;\n const source = map.getSource(sourceId) as\n | MapLibreGL.GeoJSONSource\n | undefined;\n source?.setData(data as never);\n }, [isLoaded, map, data, sourceId]);\n\n // Sync layers and paint when visibility or styling changes.\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const source = map.getSource(sourceId);\n if (!source) return;\n\n if (showFill && !map.getLayer(fillLayerId)) {\n map.addLayer(\n {\n id: fillLayerId,\n type: \"fill\",\n source: sourceId,\n paint: mergedFillPaint,\n },\n beforeId,\n );\n } else if (!showFill && map.getLayer(fillLayerId)) {\n map.removeLayer(fillLayerId);\n }\n\n if (showLine && !map.getLayer(lineLayerId)) {\n map.addLayer(\n {\n id: lineLayerId,\n type: \"line\",\n source: sourceId,\n paint: mergedLinePaint,\n },\n beforeId,\n );\n } else if (!showLine && map.getLayer(lineLayerId)) {\n map.removeLayer(lineLayerId);\n }\n\n if (showFill && map.getLayer(fillLayerId)) {\n for (const [key, value] of Object.entries(mergedFillPaint)) {\n map.setPaintProperty(\n fillLayerId,\n key as keyof MapFillPaint,\n value as never,\n );\n }\n }\n if (showLine && map.getLayer(lineLayerId)) {\n for (const [key, value] of Object.entries(mergedLinePaint)) {\n map.setPaintProperty(\n lineLayerId,\n key as keyof MapLinePaint,\n value as never,\n );\n }\n }\n }, [\n isLoaded,\n map,\n sourceId,\n fillLayerId,\n lineLayerId,\n showFill,\n showLine,\n mergedFillPaint,\n mergedLinePaint,\n beforeId,\n ]);\n\n // Interaction handlers (bound to the fill layer).\n useEffect(() => {\n if (!isLoaded || !map || !interactive || !showFill) return;\n\n let hoveredId: string | number | null = null;\n\n const setHover = (next: string | number | null) => {\n if (next === hoveredId) return;\n const sourceExists = !!map.getSource(sourceId);\n if (hoveredId != null && sourceExists) {\n map.setFeatureState(\n { source: sourceId, id: hoveredId },\n { hover: false },\n );\n }\n hoveredId = next;\n if (next != null && sourceExists) {\n map.setFeatureState({ source: sourceId, id: next }, { hover: true });\n }\n };\n\n const handleMouseMove = (e: MapLibreGL.MapLayerMouseEvent) => {\n const feature = e.features?.[0];\n if (!feature) return;\n map.getCanvas().style.cursor = \"pointer\";\n\n const featureId = feature.id;\n if (featureId === hoveredId) return;\n setHover(featureId ?? null);\n latestRef.current.onHover?.({\n feature: feature as unknown as MapGeoJSONFeature<P>,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n };\n\n const handleMouseLeave = () => {\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n latestRef.current.onHover?.(null);\n };\n\n const handleClick = (e: MapLibreGL.MapLayerMouseEvent) => {\n const feature = e.features?.[0];\n if (!feature) return;\n latestRef.current.onClick?.({\n feature: feature as unknown as MapGeoJSONFeature<P>,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n };\n\n map.on(\"mousemove\", fillLayerId, handleMouseMove);\n map.on(\"mouseleave\", fillLayerId, handleMouseLeave);\n map.on(\"click\", fillLayerId, handleClick);\n\n return () => {\n map.off(\"mousemove\", fillLayerId, handleMouseMove);\n map.off(\"mouseleave\", fillLayerId, handleMouseLeave);\n map.off(\"click\", fillLayerId, handleClick);\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n };\n }, [isLoaded, map, fillLayerId, sourceId, interactive, showFill]);\n\n return null;\n}\n\n/** A single arc to render inside <MapArc data={...}>. */\ntype MapArcDatum = {\n /** Unique identifier for this arc. Required for hover state tracking and event payloads. */\n id: string | number;\n /** Start coordinate as [longitude, latitude]. */\n from: [number, number];\n /** End coordinate as [longitude, latitude]. */\n to: [number, number];\n};\n\n/** Event payload passed to MapArc interaction callbacks. */\ntype MapArcEvent<T extends MapArcDatum = MapArcDatum> = {\n /** The arc datum that was hovered or clicked. */\n arc: T;\n /** Longitude of the cursor at the time of the event. */\n longitude: number;\n /** Latitude of the cursor at the time of the event. */\n latitude: number;\n /** The underlying MapLibre mouse event for advanced use cases. */\n originalEvent: MapLibreGL.MapMouseEvent;\n};\n\ntype MapArcLinePaint = NonNullable<MapLibreGL.LineLayerSpecification[\"paint\"]>;\ntype MapArcLineLayout = NonNullable<\n MapLibreGL.LineLayerSpecification[\"layout\"]\n>;\n\ntype MapArcProps<T extends MapArcDatum = MapArcDatum> = {\n /** Array of arcs to render. Each arc must have a unique `id`. */\n data: T[];\n /** Optional unique identifier prefix for the arc source/layers. Auto-generated if not provided. */\n id?: string;\n /**\n * How far each arc bows away from a straight line. `0` renders straight\n * lines; higher values bend further. Negative values bend to the opposite\n * side. Arcs are computed as a quadratic Bézier in lng/lat space; the\n * destination longitude is unwrapped relative to the origin so that arcs\n * cross the antimeridian via the shorter great-circle direction. (default: 0.2)\n */\n curvature?: number;\n /** Number of samples used to render each curve. Higher = smoother. (default: 64) */\n samples?: number;\n /**\n * MapLibre paint properties for the arc layer. Merged on top of sensible\n * defaults (`line-color: #4285F4`, `line-width: 2`, `line-opacity: 0.85`).\n * Any value can be a MapLibre expression for per-feature styling, every\n * field on each arc datum (besides `from`/`to`) is exposed via `[\"get\", ...]`.\n */\n paint?: MapArcLinePaint;\n /** MapLibre layout properties for the arc layer. Defaults to rounded joins/caps. */\n layout?: MapArcLineLayout;\n /**\n * Paint properties applied to the arc currently under the cursor. Each key\n * is merged into `paint` as a `case` expression keyed on per-feature hover\n * state, so only the hovered arc changes appearance.\n */\n hoverPaint?: MapArcLinePaint;\n /** Callback when an arc is clicked. */\n onClick?: (e: MapArcEvent<T>) => void;\n /**\n * Callback fired when the hovered arc changes. Receives the cursor's\n * lng/lat at the moment of entry, and `null` when the cursor leaves the\n * last hovered arc.\n */\n onHover?: (e: MapArcEvent<T> | null) => void;\n /** Whether arcs respond to mouse events (default: true). */\n interactive?: boolean;\n /** Optional MapLibre layer id to insert the arc layers before (z-order control). */\n beforeId?: string;\n};\n\nconst DEFAULT_ARC_CURVATURE = 0.2;\nconst DEFAULT_ARC_SAMPLES = 64;\nconst ARC_HIT_MIN_WIDTH = 12;\nconst ARC_HIT_PADDING = 6;\n\nconst DEFAULT_ARC_PAINT: MapArcLinePaint = {\n \"line-color\": \"#4285F4\",\n \"line-width\": 2,\n \"line-opacity\": 0.85,\n};\n\nconst DEFAULT_ARC_LAYOUT: MapArcLineLayout = {\n \"line-join\": \"round\",\n \"line-cap\": \"round\",\n};\n\nfunction buildArcCoordinates(\n from: [number, number],\n to: [number, number],\n curvature: number,\n samples: number,\n): [number, number][] {\n const [x0, y0] = from;\n const [xTo, y2] = to;\n // Unwrap the destination longitude so |dx| <= 180. This makes arcs that\n // straddle the antimeridian (e.g. Tokyo -> San Francisco) bow the short way\n // across the Pacific instead of the long way around the globe. Resulting\n // longitudes may fall outside [-180, 180]; MapLibre renders them correctly\n // on the globe projection, and on mercator when world copies are enabled.\n const rawDx = xTo - x0;\n const x2 = rawDx > 180 ? xTo - 360 : rawDx < -180 ? xTo + 360 : xTo;\n const dx = x2 - x0;\n const dy = y2 - y0;\n const distance = Math.hypot(dx, dy);\n\n if (distance === 0 || curvature === 0) return [from, [x2, y2]];\n\n const mx = (x0 + x2) / 2;\n const my = (y0 + y2) / 2;\n const nx = -dy / distance;\n const ny = dx / distance;\n const offset = distance * curvature;\n const cx = mx + nx * offset;\n const cy = my + ny * offset;\n\n const points: [number, number][] = [];\n const segments = Math.max(2, Math.floor(samples));\n for (let i = 0; i <= segments; i += 1) {\n const t = i / segments;\n const inv = 1 - t;\n const x = inv * inv * x0 + 2 * inv * t * cx + t * t * x2;\n const y = inv * inv * y0 + 2 * inv * t * cy + t * t * y2;\n points.push([x, y]);\n }\n return points;\n}\n\nfunction MapArc<T extends MapArcDatum = MapArcDatum>({\n data,\n id: propId,\n curvature = DEFAULT_ARC_CURVATURE,\n samples = DEFAULT_ARC_SAMPLES,\n paint,\n layout,\n hoverPaint,\n onClick,\n onHover,\n interactive = true,\n beforeId,\n}: MapArcProps<T>) {\n const { map, isLoaded } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `arc-source-${id}`;\n const layerId = `arc-layer-${id}`;\n const hitLayerId = `arc-hit-layer-${id}`;\n\n const mergedPaint = useMemo(\n () => mergeHoverPaint({ ...DEFAULT_ARC_PAINT, ...paint }, hoverPaint),\n [paint, hoverPaint],\n );\n const mergedLayout = useMemo(\n () => ({ ...DEFAULT_ARC_LAYOUT, ...layout }),\n [layout],\n );\n\n const hitWidth = useMemo(() => {\n const w = paint?.[\"line-width\"] ?? DEFAULT_ARC_PAINT[\"line-width\"];\n const base = typeof w === \"number\" ? w : ARC_HIT_MIN_WIDTH;\n return Math.max(base + ARC_HIT_PADDING, ARC_HIT_MIN_WIDTH);\n }, [paint]);\n\n const geoJSON = useMemo<GeoJSON.FeatureCollection<GeoJSON.LineString>>(\n () => ({\n type: \"FeatureCollection\",\n features: data.map((arc) => {\n const { from, to, ...properties } = arc;\n return {\n type: \"Feature\",\n properties,\n geometry: {\n type: \"LineString\",\n coordinates: buildArcCoordinates(from, to, curvature, samples),\n },\n };\n }),\n }),\n [data, curvature, samples],\n );\n\n const latestRef = useRef({ data, onClick, onHover });\n latestRef.current = { data, onClick, onHover };\n\n // Add source and layers on mount.\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: geoJSON,\n promoteId: \"id\",\n });\n\n map.addLayer(\n {\n id: hitLayerId,\n type: \"line\",\n source: sourceId,\n layout: DEFAULT_ARC_LAYOUT,\n paint: {\n \"line-color\": \"rgba(0, 0, 0, 0)\",\n \"line-width\": hitWidth,\n \"line-opacity\": 1,\n },\n },\n beforeId,\n );\n\n map.addLayer(\n {\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: mergedLayout,\n paint: mergedPaint,\n },\n beforeId,\n );\n\n return () => {\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getLayer(hitLayerId)) map.removeLayer(hitLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // Sync features when data / curvature / samples change.\n useEffect(() => {\n if (!isLoaded || !map) return;\n const source = map.getSource(sourceId) as\n | MapLibreGL.GeoJSONSource\n | undefined;\n source?.setData(geoJSON);\n }, [isLoaded, map, geoJSON, sourceId]);\n\n // Sync paint/layout when they change.\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n for (const [key, value] of Object.entries(mergedPaint)) {\n map.setPaintProperty(\n layerId,\n key as keyof MapArcLinePaint,\n value as never,\n );\n }\n for (const [key, value] of Object.entries(mergedLayout)) {\n map.setLayoutProperty(\n layerId,\n key as keyof MapArcLineLayout,\n value as never,\n );\n }\n if (map.getLayer(hitLayerId)) {\n map.setPaintProperty(hitLayerId, \"line-width\", hitWidth);\n }\n }, [isLoaded, map, layerId, hitLayerId, mergedPaint, mergedLayout, hitWidth]);\n\n // Interaction handlers\n useEffect(() => {\n if (!isLoaded || !map || !interactive) return;\n\n let hoveredId: string | number | null = null;\n\n const setHover = (next: string | number | null) => {\n if (next === hoveredId) return;\n const sourceExists = !!map.getSource(sourceId);\n if (hoveredId != null && sourceExists) {\n map.setFeatureState(\n { source: sourceId, id: hoveredId },\n { hover: false },\n );\n }\n hoveredId = next;\n if (next != null && sourceExists) {\n map.setFeatureState({ source: sourceId, id: next }, { hover: true });\n }\n };\n\n const findArc = (featureId: string | number | undefined) =>\n featureId == null\n ? undefined\n : latestRef.current.data.find(\n (arc) => String(arc.id) === String(featureId),\n );\n\n const handleMouseMove = (e: MapLibreGL.MapLayerMouseEvent) => {\n const featureId = e.features?.[0]?.id as string | number | undefined;\n if (featureId == null || featureId === hoveredId) return;\n\n setHover(featureId);\n map.getCanvas().style.cursor = \"pointer\";\n\n const arc = findArc(featureId);\n if (arc) {\n latestRef.current.onHover?.({\n arc: arc as T,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n }\n };\n\n const handleMouseLeave = () => {\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n latestRef.current.onHover?.(null);\n };\n\n const handleClick = (e: MapLibreGL.MapLayerMouseEvent) => {\n const arc = findArc(e.features?.[0]?.id as string | number | undefined);\n if (!arc) return;\n latestRef.current.onClick?.({\n arc: arc as T,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n };\n\n map.on(\"mousemove\", hitLayerId, handleMouseMove);\n map.on(\"mouseleave\", hitLayerId, handleMouseLeave);\n map.on(\"click\", hitLayerId, handleClick);\n\n return () => {\n map.off(\"mousemove\", hitLayerId, handleMouseMove);\n map.off(\"mouseleave\", hitLayerId, handleMouseLeave);\n map.off(\"click\", hitLayerId, handleClick);\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n };\n }, [isLoaded, map, hitLayerId, sourceId, interactive]);\n\n return null;\n}\n\ntype MapClusterLayerProps<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = {\n /** GeoJSON FeatureCollection data or URL to fetch GeoJSON from */\n data: string | GeoJSON.FeatureCollection<GeoJSON.Point, P>;\n /** Maximum zoom level to cluster points on (default: 14) */\n clusterMaxZoom?: number;\n /** Radius of each cluster when clustering points in pixels (default: 50) */\n clusterRadius?: number;\n /** Colors for cluster circles: [small, medium, large] based on point count (default: [\"#3b82f6\", \"#1d4ed8\", \"#1e3a8a\"]) */\n clusterColors?: [string, string, string];\n /** Point count thresholds for color/size steps: [medium, large] (default: [100, 750]) */\n clusterThresholds?: [number, number];\n /** Color for unclustered individual points (default: \"#3b82f6\") */\n pointColor?: string;\n /** Callback when an unclustered point is clicked */\n onPointClick?: (\n feature: GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates: [number, number],\n ) => void;\n /** Callback when a cluster is clicked. If not provided, zooms into the cluster */\n onClusterClick?: (\n clusterId: number,\n coordinates: [number, number],\n pointCount: number,\n ) => void;\n};\n\nconst DEFAULT_CLUSTER_COLORS: [string, string, string] = [\n \"#3b82f6\",\n \"#1d4ed8\",\n \"#1e3a8a\",\n];\nconst DEFAULT_CLUSTER_THRESHOLDS: [number, number] = [100, 750];\n\nfunction MapClusterLayer<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n>({\n data,\n clusterMaxZoom = 14,\n clusterRadius = 50,\n clusterColors = DEFAULT_CLUSTER_COLORS,\n clusterThresholds = DEFAULT_CLUSTER_THRESHOLDS,\n pointColor = \"#3b82f6\",\n onPointClick,\n onClusterClick,\n}: MapClusterLayerProps<P>) {\n const { map, isLoaded } = useMap();\n const id = useId();\n const sourceId = `cluster-source-${id}`;\n const clusterLayerId = `clusters-${id}`;\n const clusterCountLayerId = `cluster-count-${id}`;\n const unclusteredLayerId = `unclustered-point-${id}`;\n\n const stylePropsRef = useRef({\n clusterColors,\n clusterThresholds,\n pointColor,\n });\n\n // Add source and layers on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Add clustered GeoJSON source\n map.addSource(sourceId, {\n type: \"geojson\",\n data,\n cluster: true,\n clusterMaxZoom,\n clusterRadius,\n });\n\n // Add cluster circles layer\n map.addLayer({\n id: clusterLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n paint: {\n \"circle-color\": [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ],\n \"circle-radius\": [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ],\n \"circle-stroke-width\": 0.75,\n \"circle-stroke-color\": \"#fff\",\n \"circle-opacity\": 0.85,\n },\n });\n\n // Add cluster count text layer\n map.addLayer({\n id: clusterCountLayerId,\n type: \"symbol\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n layout: {\n \"text-field\": \"{point_count_abbreviated}\",\n \"text-font\": [\"Open Sans Semibold\"],\n \"text-size\": 12,\n },\n paint: {\n \"text-color\": \"#fff\",\n },\n });\n\n // Add unclustered point layer\n map.addLayer({\n id: unclusteredLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"!\", [\"has\", \"point_count\"]],\n paint: {\n \"circle-color\": pointColor,\n \"circle-radius\": 5,\n \"circle-stroke-width\": 2,\n \"circle-stroke-color\": \"#fff\",\n },\n });\n\n return () => {\n try {\n if (map.getLayer(clusterCountLayerId))\n map.removeLayer(clusterCountLayerId);\n if (map.getLayer(unclusteredLayerId))\n map.removeLayer(unclusteredLayerId);\n if (map.getLayer(clusterLayerId)) map.removeLayer(clusterLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map, sourceId]);\n\n // Update source data when data prop changes (only for non-URL data)\n useEffect(() => {\n if (!isLoaded || !map || typeof data === \"string\") return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData(data);\n }\n }, [isLoaded, map, data, sourceId]);\n\n // Update layer styles when props change\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const prev = stylePropsRef.current;\n const colorsChanged =\n prev.clusterColors !== clusterColors ||\n prev.clusterThresholds !== clusterThresholds;\n\n // Update cluster layer colors and sizes\n if (map.getLayer(clusterLayerId) && colorsChanged) {\n map.setPaintProperty(clusterLayerId, \"circle-color\", [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ]);\n map.setPaintProperty(clusterLayerId, \"circle-radius\", [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ]);\n }\n\n // Update unclustered point layer color\n if (map.getLayer(unclusteredLayerId) && prev.pointColor !== pointColor) {\n map.setPaintProperty(unclusteredLayerId, \"circle-color\", pointColor);\n }\n\n stylePropsRef.current = { clusterColors, clusterThresholds, pointColor };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n clusterColors,\n clusterThresholds,\n pointColor,\n ]);\n\n // Handle click events\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Cluster click handler - zoom into cluster\n const handleClusterClick = async (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n },\n ) => {\n const features = map.queryRenderedFeatures(e.point, {\n layers: [clusterLayerId],\n });\n if (!features.length) return;\n\n const feature = features[0];\n const clusterId = feature.properties?.cluster_id as number;\n const pointCount = feature.properties?.point_count as number;\n const coordinates = (feature.geometry as GeoJSON.Point).coordinates as [\n number,\n number,\n ];\n\n if (onClusterClick) {\n onClusterClick(clusterId, coordinates, pointCount);\n } else {\n // Default behavior: zoom to cluster expansion zoom\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n const zoom = await source.getClusterExpansionZoom(clusterId);\n map.easeTo({\n center: coordinates,\n zoom,\n });\n }\n };\n\n // Unclustered point click handler\n const handlePointClick = (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n },\n ) => {\n if (!onPointClick || !e.features?.length) return;\n\n const feature = e.features[0];\n const coordinates = (\n feature.geometry as GeoJSON.Point\n ).coordinates.slice() as [number, number];\n\n // Handle world copies\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n onPointClick(\n feature as unknown as GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates,\n );\n };\n\n // Cursor style handlers\n const handleMouseEnterCluster = () => {\n map.getCanvas().style.cursor = \"pointer\";\n };\n const handleMouseLeaveCluster = () => {\n map.getCanvas().style.cursor = \"\";\n };\n const handleMouseEnterPoint = () => {\n if (onPointClick) {\n map.getCanvas().style.cursor = \"pointer\";\n }\n };\n const handleMouseLeavePoint = () => {\n map.getCanvas().style.cursor = \"\";\n };\n\n map.on(\"click\", clusterLayerId, handleClusterClick);\n map.on(\"click\", unclusteredLayerId, handlePointClick);\n map.on(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.on(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.on(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.on(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n\n return () => {\n map.off(\"click\", clusterLayerId, handleClusterClick);\n map.off(\"click\", unclusteredLayerId, handlePointClick);\n map.off(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.off(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.off(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.off(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n sourceId,\n onClusterClick,\n onPointClick,\n ]);\n\n return null;\n}\n\nexport {\n Map,\n useMap,\n MapMarker,\n MarkerContent,\n MarkerPopup,\n MarkerTooltip,\n MarkerLabel,\n MapPopup,\n MapControls,\n MapRoute,\n MapArc,\n MapGeoJSON,\n MapClusterLayer,\n};\n\nexport type {\n MapRef,\n MapViewport,\n MapStyleOption,\n MapArcDatum,\n MapArcEvent,\n MapGeoJSONData,\n MapGeoJSONFeature,\n MapGeoJSONEvent,\n MapProps,\n MapMarkerProps,\n MarkerContentProps,\n MarkerPopupProps,\n MarkerTooltipProps,\n MarkerLabelProps,\n MapControlsProps,\n MapPopupProps,\n MapRouteProps,\n MapArcProps,\n MapGeoJSONProps,\n MapClusterLayerProps,\n};\n",
+ "content": "\"use client\";\n\nimport * as MapLibreGL from \"maplibre-gl\";\nimport type { PopupOptions, MarkerOptions } from \"maplibre-gl\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\nimport type * as GeoJSON from \"geojson\";\nimport {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useEffect,\n useId,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { X, Minus, Plus, Locate, Maximize, Loader2 } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nif (typeof window !== \"undefined\" && !MapLibreGL.getWorkerUrl()) {\n MapLibreGL.setWorkerUrl(\n `https://unpkg.com/maplibre-gl@${MapLibreGL.getVersion()}/dist/maplibre-gl-worker.mjs`,\n );\n}\n\nconst defaultStyles = {\n dark: \"https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json\",\n light: \"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json\",\n};\n\n// A tile-less, dependency-free style with a transparent background. Use it for\n// data visualizations (choropleths, world arcs, dot maps) where you draw your\n// own layers and don't need a street basemap. The easiest way to opt in is the\n// `blank` prop:\n// <Map blank>...</Map>\n// The transparent background lets the themed container show through.\nconst blankMapStyle: MapLibreGL.StyleSpecification = {\n version: 8,\n sources: {},\n layers: [\n {\n id: \"background\",\n type: \"background\",\n paint: { \"background-color\": \"rgba(0, 0, 0, 0)\" },\n },\n ],\n};\n\n// Prevent equivalent inline style objects from triggering a full map style reload.\nfunction useStableValue<T>(value: T): T {\n const key = useMemo(() => JSON.stringify(value) ?? \"\", [value]);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n return useMemo(() => value, [key]);\n}\n\nfunction mergeHoverPaint<T extends Record<string, unknown>>(\n paint: T,\n hoverPaint: T | undefined,\n): T {\n if (!hoverPaint) return paint;\n const merged: Record<string, unknown> = { ...paint };\n for (const [key, hoverValue] of Object.entries(hoverPaint)) {\n if (hoverValue === undefined) continue;\n const baseValue = merged[key];\n merged[key] =\n baseValue === undefined\n ? hoverValue\n : [\n \"case\",\n [\"boolean\", [\"feature-state\", \"hover\"], false],\n hoverValue,\n baseValue,\n ];\n }\n return merged as T;\n}\n\ntype Theme = \"light\" | \"dark\";\n\n// Check the document for an explicit theme (works with next-themes, etc.).\n// Covers both `attribute=\"class\"` (the default) and `attribute=\"data-theme\"`.\nfunction getDocumentTheme(): Theme | null {\n if (typeof document === \"undefined\") return null;\n const root = document.documentElement;\n if (root.classList.contains(\"dark\")) return \"dark\";\n if (root.classList.contains(\"light\")) return \"light\";\n const dataTheme = root.dataset.theme;\n if (dataTheme === \"dark\" || dataTheme === \"light\") return dataTheme;\n return null;\n}\n\n// Get system preference\nfunction getSystemTheme(): Theme {\n if (typeof window === \"undefined\") return \"light\";\n return window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n ? \"dark\"\n : \"light\";\n}\n\nfunction useResolvedTheme(themeProp?: \"light\" | \"dark\"): Theme {\n const [detectedTheme, setDetectedTheme] = useState<Theme>(\n () => getDocumentTheme() ?? getSystemTheme(),\n );\n\n useEffect(() => {\n if (themeProp) return; // Skip detection if theme is provided via prop\n\n // Watch for document theme changes (e.g., next-themes toggling the class\n // or the data-theme attribute).\n const observer = new MutationObserver(() => {\n const docTheme = getDocumentTheme();\n if (docTheme) {\n setDetectedTheme(docTheme);\n }\n });\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"class\", \"data-theme\"],\n });\n\n // Also watch for system preference changes\n const mediaQuery = window.matchMedia(\"(prefers-color-scheme: dark)\");\n const handleSystemChange = (e: MediaQueryListEvent) => {\n // Only use system preference if no document class is set\n if (!getDocumentTheme()) {\n setDetectedTheme(e.matches ? \"dark\" : \"light\");\n }\n };\n mediaQuery.addEventListener(\"change\", handleSystemChange);\n\n return () => {\n observer.disconnect();\n mediaQuery.removeEventListener(\"change\", handleSystemChange);\n };\n }, [themeProp]);\n\n return themeProp ?? detectedTheme;\n}\n\ntype MapContextValue = {\n map: MapLibreGL.Map | null;\n isLoaded: boolean;\n resolvedTheme: Theme;\n};\n\nconst MapContext = createContext<MapContextValue | null>(null);\n\nfunction useMap() {\n const context = useContext(MapContext);\n if (!context) {\n throw new Error(\"useMap must be used within a Map component\");\n }\n return context;\n}\n\n/** Map viewport state */\ntype MapViewport = {\n /** Center coordinates [longitude, latitude] */\n center: [number, number];\n /** Zoom level */\n zoom: number;\n /** Bearing (rotation) in degrees */\n bearing: number;\n /** Pitch (tilt) in degrees */\n pitch: number;\n};\n\ntype MapStyleOption = string | MapLibreGL.StyleSpecification;\n\ntype MapRef = MapLibreGL.Map;\n\ntype MapProps = {\n children?: ReactNode;\n /** Additional CSS classes for the map container */\n className?: string;\n /**\n * Theme for the map. If not provided, automatically detects system preference.\n * Pass your theme value here.\n */\n theme?: Theme;\n /** Custom map styles for light and dark themes. Overrides the default Carto styles. */\n styles?: {\n light?: MapStyleOption;\n dark?: MapStyleOption;\n };\n /**\n * Use a transparent, tile-less basemap instead of the default Carto street\n * basemap — a blank canvas. Used alone it renders nothing; add your own\n * layers on top (`<MapGeoJSON>`, `<MapArc>`, markers, etc.). Ideal for data\n * visualizations (choropleths, arcs, dot maps).\n * Ignored when an explicit `styles` prop is provided.\n */\n blank?: boolean;\n /** Map projection type. Use `{ type: \"globe\" }` for 3D globe view. */\n projection?: MapLibreGL.ProjectionSpecification;\n /**\n * Controlled viewport. When provided with onViewportChange,\n * the map becomes controlled and viewport is driven by this prop.\n */\n viewport?: Partial<MapViewport>;\n /**\n * Callback fired continuously as the viewport changes (pan, zoom, rotate, pitch).\n * Can be used standalone to observe changes, or with `viewport` prop\n * to enable controlled mode where the map viewport is driven by your state.\n */\n onViewportChange?: (viewport: MapViewport) => void;\n /** Show a loading indicator on the map */\n loading?: boolean;\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\n\nfunction DefaultLoader() {\n return (\n <div className=\"bg-background/50 absolute inset-0 z-10 flex items-center justify-center backdrop-blur-xs\">\n <div className=\"flex gap-1\">\n <span className=\"bg-muted-foreground/60 size-1.5 animate-pulse rounded-full\" />\n <span className=\"bg-muted-foreground/60 size-1.5 animate-pulse rounded-full [animation-delay:150ms]\" />\n <span className=\"bg-muted-foreground/60 size-1.5 animate-pulse rounded-full [animation-delay:300ms]\" />\n </div>\n </div>\n );\n}\n\nfunction getViewport(map: MapLibreGL.Map): MapViewport {\n const center = map.getCenter();\n return {\n center: [center.lng, center.lat],\n zoom: map.getZoom(),\n bearing: map.getBearing(),\n pitch: map.getPitch(),\n };\n}\n\nconst Map = forwardRef<MapRef, MapProps>(function Map(\n {\n children,\n className,\n theme: themeProp,\n styles,\n blank = false,\n projection,\n viewport,\n onViewportChange,\n loading = false,\n ...props\n },\n ref,\n) {\n const containerRef = useRef<HTMLDivElement>(null);\n const [mapInstance, setMapInstance] = useState<MapLibreGL.Map | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [isStyleLoaded, setIsStyleLoaded] = useState(false);\n const [pendingStyle, setPendingStyle] = useState<MapStyleOption | null>(null);\n const currentStyleRef = useRef<MapStyleOption | null>(null);\n const styleSwapInFlightRef = useRef(false);\n const internalUpdateRef = useRef(false);\n const resolvedTheme = useResolvedTheme(themeProp);\n\n const isControlled = viewport !== undefined && onViewportChange !== undefined;\n\n const onViewportChangeRef = useRef(onViewportChange);\n onViewportChangeRef.current = onViewportChange;\n\n const stableStyles = useStableValue(styles);\n\n const mapStyles = useMemo(() => {\n // Explicit styles win. Otherwise `blank` opts into the transparent\n // tile-less basemap; with neither, fall back to the Carto defaults.\n if (stableStyles) {\n return {\n dark: stableStyles.dark ?? defaultStyles.dark,\n light: stableStyles.light ?? defaultStyles.light,\n };\n }\n if (blank) {\n return { dark: blankMapStyle, light: blankMapStyle };\n }\n return defaultStyles;\n }, [stableStyles, blank]);\n\n // Expose the map instance to the parent component\n useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);\n\n // Initialize the map\n useEffect(() => {\n if (!containerRef.current) return;\n\n const initialStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n currentStyleRef.current = initialStyle;\n\n const map = new MapLibreGL.Map({\n container: containerRef.current,\n style: initialStyle,\n renderWorldCopies: false,\n attributionControl: {\n compact: true,\n },\n ...props,\n ...viewport,\n });\n\n const styleLoadHandler = () => {\n styleSwapInFlightRef.current = false;\n setIsStyleLoaded(true);\n };\n const loadHandler = () => setIsLoaded(true);\n\n // Viewport change handler - skip if triggered by internal update\n const handleMove = () => {\n if (internalUpdateRef.current) return;\n onViewportChangeRef.current?.(getViewport(map));\n };\n\n map.on(\"load\", loadHandler);\n map.on(\"style.load\", styleLoadHandler);\n map.on(\"move\", handleMove);\n setMapInstance(map);\n\n return () => {\n map.off(\"load\", loadHandler);\n map.off(\"style.load\", styleLoadHandler);\n map.off(\"move\", handleMove);\n map.remove();\n setIsLoaded(false);\n setIsStyleLoaded(false);\n setMapInstance(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Sync controlled viewport to map\n useEffect(() => {\n if (!mapInstance || !isControlled || !viewport) return;\n if (mapInstance.isMoving()) return;\n\n const current = getViewport(mapInstance);\n const next = {\n center: viewport.center ?? current.center,\n zoom: viewport.zoom ?? current.zoom,\n bearing: viewport.bearing ?? current.bearing,\n pitch: viewport.pitch ?? current.pitch,\n };\n\n if (\n next.center[0] === current.center[0] &&\n next.center[1] === current.center[1] &&\n next.zoom === current.zoom &&\n next.bearing === current.bearing &&\n next.pitch === current.pitch\n ) {\n return;\n }\n\n internalUpdateRef.current = true;\n mapInstance.jumpTo(next);\n internalUpdateRef.current = false;\n }, [mapInstance, isControlled, viewport]);\n\n // Handle style change: close the gate (so layer children tear down and\n // re-add on the incoming style) - the swap itself is staged to the effect below.\n useEffect(() => {\n if (!mapInstance || !resolvedTheme) return;\n\n const newStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n if (currentStyleRef.current === newStyle) return;\n\n currentStyleRef.current = newStyle;\n setIsStyleLoaded(false);\n setPendingStyle(newStyle);\n }, [mapInstance, resolvedTheme, mapStyles]);\n\n useEffect(() => {\n if (!mapInstance || !pendingStyle) return;\n\n setPendingStyle(null);\n styleSwapInFlightRef.current = true;\n // Full reload (no diff) so `style.load` fires deterministically. A\n // successful diff would never fire it, leaving isStyleLoaded stuck false.\n mapInstance.setStyle(pendingStyle, { diff: false });\n }, [mapInstance, pendingStyle]);\n\n // Sync projection when the prop changes after mount.\n useEffect(() => {\n if (!mapInstance || !isStyleLoaded || !projection) return;\n if (styleSwapInFlightRef.current) return;\n mapInstance.setProjection(projection);\n }, [mapInstance, isStyleLoaded, projection]);\n\n const contextValue = useMemo(\n () => ({\n map: mapInstance,\n isLoaded: isLoaded && isStyleLoaded,\n resolvedTheme,\n }),\n [mapInstance, isLoaded, isStyleLoaded, resolvedTheme],\n );\n\n return (\n <MapContext.Provider value={contextValue}>\n <div\n ref={containerRef}\n className={cn(\"relative h-full w-full\", className)}\n >\n {(!isLoaded || loading) && <DefaultLoader />}\n {/* SSR-safe: children render only when map is loaded on client */}\n {mapInstance && children}\n </div>\n </MapContext.Provider>\n );\n});\n\ntype MarkerContextValue = {\n marker: MapLibreGL.Marker;\n map: MapLibreGL.Map | null;\n};\n\nconst MarkerContext = createContext<MarkerContextValue | null>(null);\n\nfunction useMarkerContext() {\n const context = useContext(MarkerContext);\n if (!context) {\n throw new Error(\"Marker components must be used within MapMarker\");\n }\n return context;\n}\n\ntype MapMarkerProps = {\n /** Longitude coordinate for marker position */\n longitude: number;\n /** Latitude coordinate for marker position */\n latitude: number;\n /** Marker subcomponents (MarkerContent, MarkerPopup, MarkerTooltip, MarkerLabel) */\n children: ReactNode;\n /** Callback when marker is clicked */\n onClick?: (e: MouseEvent) => void;\n /** Callback when mouse enters marker */\n onMouseEnter?: (e: MouseEvent) => void;\n /** Callback when mouse leaves marker */\n onMouseLeave?: (e: MouseEvent) => void;\n /** Callback when marker drag starts (requires draggable: true) */\n onDragStart?: (lngLat: { lng: number; lat: number }) => void;\n /** Callback during marker drag (requires draggable: true) */\n onDrag?: (lngLat: { lng: number; lat: number }) => void;\n /** Callback when marker drag ends (requires draggable: true) */\n onDragEnd?: (lngLat: { lng: number; lat: number }) => void;\n} & Omit<MarkerOptions, \"element\">;\n\nfunction MapMarker({\n longitude,\n latitude,\n children,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n draggable = false,\n ...markerOptions\n}: MapMarkerProps) {\n const { map } = useMap();\n\n const callbacksRef = useRef({\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n });\n callbacksRef.current = {\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n };\n\n const marker = useMemo(() => {\n const markerInstance = new MapLibreGL.Marker({\n ...markerOptions,\n element: document.createElement(\"div\"),\n draggable,\n }).setLngLat([longitude, latitude]);\n\n const handleClick = (e: MouseEvent) => callbacksRef.current.onClick?.(e);\n const handleMouseEnter = (e: MouseEvent) =>\n callbacksRef.current.onMouseEnter?.(e);\n const handleMouseLeave = (e: MouseEvent) =>\n callbacksRef.current.onMouseLeave?.(e);\n\n markerInstance.getElement()?.addEventListener(\"click\", handleClick);\n markerInstance\n .getElement()\n ?.addEventListener(\"mouseenter\", handleMouseEnter);\n markerInstance\n .getElement()\n ?.addEventListener(\"mouseleave\", handleMouseLeave);\n\n const handleDragStart = () => {\n const lngLat = markerInstance.getLngLat();\n callbacksRef.current.onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDrag = () => {\n const lngLat = markerInstance.getLngLat();\n callbacksRef.current.onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDragEnd = () => {\n const lngLat = markerInstance.getLngLat();\n callbacksRef.current.onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n\n markerInstance.on(\"dragstart\", handleDragStart);\n markerInstance.on(\"drag\", handleDrag);\n markerInstance.on(\"dragend\", handleDragEnd);\n\n return markerInstance;\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n marker.addTo(map);\n\n return () => {\n marker.remove();\n };\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n const { offset, rotation, rotationAlignment, pitchAlignment } = markerOptions;\n\n useEffect(() => {\n const current = marker.getLngLat();\n if (current.lng !== longitude || current.lat !== latitude) {\n marker.setLngLat([longitude, latitude]);\n }\n\n if (marker.isDraggable() !== draggable) {\n marker.setDraggable(draggable);\n }\n\n const currentOffset = marker.getOffset();\n const newOffset = offset ?? [0, 0];\n const [newOffsetX, newOffsetY] = Array.isArray(newOffset)\n ? newOffset\n : [newOffset.x, newOffset.y];\n if (currentOffset.x !== newOffsetX || currentOffset.y !== newOffsetY) {\n marker.setOffset(newOffset);\n }\n\n if (marker.getRotation() !== (rotation ?? 0)) {\n marker.setRotation(rotation ?? 0);\n }\n if (marker.getRotationAlignment() !== (rotationAlignment ?? \"auto\")) {\n marker.setRotationAlignment(rotationAlignment ?? \"auto\");\n }\n if (marker.getPitchAlignment() !== (pitchAlignment ?? \"auto\")) {\n marker.setPitchAlignment(pitchAlignment ?? \"auto\");\n }\n }, [\n marker,\n longitude,\n latitude,\n draggable,\n offset,\n rotation,\n rotationAlignment,\n pitchAlignment,\n ]);\n\n return (\n <MarkerContext.Provider value={{ marker, map }}>\n {children}\n </MarkerContext.Provider>\n );\n}\n\ntype MarkerContentProps = {\n /** Custom marker content. Defaults to a blue dot if not provided */\n children?: ReactNode;\n /** Additional CSS classes for the marker container */\n className?: string;\n};\n\nfunction MarkerContent({ children, className }: MarkerContentProps) {\n const { marker } = useMarkerContext();\n\n return createPortal(\n <div className={cn(\"relative cursor-pointer\", className)}>\n {children || <DefaultMarkerIcon />}\n </div>,\n marker.getElement(),\n );\n}\n\nfunction DefaultMarkerIcon() {\n return (\n <div className=\"relative h-4 w-4 rounded-full border-2 border-white bg-blue-500 shadow-lg\" />\n );\n}\n\nfunction PopupCloseButton({ onClick }: { onClick: () => void }) {\n return (\n <button\n type=\"button\"\n onClick={onClick}\n aria-label=\"Close popup\"\n className=\"focus-visible:ring-ring hover:bg-muted text-foreground absolute top-1 right-1 z-10 inline-flex size-5 cursor-pointer items-center justify-center rounded-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-inset\"\n >\n <X className=\"size-3.5\" />\n </button>\n );\n}\n\ntype MarkerPopupProps = {\n /** Popup content */\n children: ReactNode;\n /** Additional CSS classes for the popup container */\n className?: string;\n /** Show a close button in the popup (default: false) */\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\" | \"closeButton\">;\n\nfunction MarkerPopup({\n children,\n className,\n closeButton = false,\n ...popupOptions\n}: MarkerPopupProps) {\n const { marker, map } = useMarkerContext();\n const container = useMemo(() => document.createElement(\"div\"), []);\n const { offset, maxWidth } = popupOptions;\n\n const popup = useMemo(() => {\n const popupInstance = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n return popupInstance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n popup.setDOMContent(container);\n marker.setPopup(popup);\n\n return () => {\n marker.setPopup(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n // Sync popup options when they change.\n useEffect(() => {\n popup.setOffset(offset ?? 16);\n if (maxWidth) {\n popup.setMaxWidth(maxWidth);\n }\n }, [popup, offset, maxWidth]);\n\n const handleClose = () => popup.remove();\n\n return createPortal(\n <div\n className={cn(\n \"bg-popover text-popover-foreground relative max-w-62 rounded-md border p-3 shadow-md\",\n \"animate-in fade-in-0 zoom-in-95 duration-200 ease-out\",\n className,\n )}\n >\n {closeButton && <PopupCloseButton onClick={handleClose} />}\n {children}\n </div>,\n container,\n );\n}\n\ntype MarkerTooltipProps = {\n /** Tooltip content */\n children: ReactNode;\n /** Additional CSS classes for the tooltip container */\n className?: string;\n} & Omit<PopupOptions, \"className\" | \"closeButton\" | \"closeOnClick\">;\n\nfunction MarkerTooltip({\n children,\n className,\n ...popupOptions\n}: MarkerTooltipProps) {\n const { marker, map } = useMarkerContext();\n const container = useMemo(() => document.createElement(\"div\"), []);\n const { offset, maxWidth } = popupOptions;\n\n const tooltip = useMemo(() => {\n const tooltipInstance = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeOnClick: true,\n closeButton: false,\n }).setMaxWidth(\"none\");\n\n return tooltipInstance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n tooltip.setDOMContent(container);\n\n const handleMouseEnter = () => {\n tooltip.setLngLat(marker.getLngLat()).addTo(map);\n };\n const handleMouseLeave = () => tooltip.remove();\n\n marker.getElement()?.addEventListener(\"mouseenter\", handleMouseEnter);\n marker.getElement()?.addEventListener(\"mouseleave\", handleMouseLeave);\n\n return () => {\n marker.getElement()?.removeEventListener(\"mouseenter\", handleMouseEnter);\n marker.getElement()?.removeEventListener(\"mouseleave\", handleMouseLeave);\n tooltip.remove();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n // Sync tooltip options when they change.\n useEffect(() => {\n tooltip.setOffset(offset ?? 16);\n if (maxWidth) {\n tooltip.setMaxWidth(maxWidth);\n }\n }, [tooltip, offset, maxWidth]);\n\n return createPortal(\n <div\n className={cn(\n \"bg-foreground text-background pointer-events-none rounded-md px-2 py-1 text-xs text-balance shadow-md\",\n \"animate-in fade-in-0 zoom-in-95 duration-200 ease-out\",\n className,\n )}\n >\n {children}\n </div>,\n container,\n );\n}\n\ntype MarkerLabelProps = {\n /** Label text content */\n children: ReactNode;\n /** Additional CSS classes for the label */\n className?: string;\n /** Position of the label relative to the marker (default: \"top\") */\n position?: \"top\" | \"bottom\";\n};\n\nfunction MarkerLabel({\n children,\n className,\n position = \"top\",\n}: MarkerLabelProps) {\n const positionClasses = {\n top: \"bottom-full mb-1\",\n bottom: \"top-full mt-1\",\n };\n\n return (\n <div\n className={cn(\n \"absolute left-1/2 -translate-x-1/2 whitespace-nowrap\",\n \"text-foreground text-[10px] font-medium\",\n positionClasses[position],\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\ntype MapControlsProps = {\n /** Position of the controls on the map (default: \"bottom-right\") */\n position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\";\n /** Show zoom in/out buttons (default: true) */\n showZoom?: boolean;\n /** Show compass button to reset bearing (default: false) */\n showCompass?: boolean;\n /** Show locate button to find user's location (default: false) */\n showLocate?: boolean;\n /** Show fullscreen toggle button (default: false) */\n showFullscreen?: boolean;\n /** Additional CSS classes for the controls container */\n className?: string;\n /** Callback with user coordinates when located */\n onLocate?: (coords: { longitude: number; latitude: number }) => void;\n};\n\nconst positionClasses = {\n \"top-left\": \"top-2 left-2\",\n \"top-right\": \"top-2 right-2\",\n \"bottom-left\": \"bottom-2 left-2\",\n \"bottom-right\": \"bottom-10 right-2\",\n};\n\nfunction ControlGroup({ children }: { children: React.ReactNode }) {\n return (\n <div className=\"border-border bg-background [&>button:not(:last-child)]:border-border flex flex-col overflow-hidden rounded-md border shadow-sm [&>button:not(:last-child)]:border-b\">\n {children}\n </div>\n );\n}\n\nfunction ControlButton({\n onClick,\n label,\n children,\n disabled = false,\n}: {\n onClick: () => void;\n label: string;\n children: React.ReactNode;\n disabled?: boolean;\n}) {\n return (\n <button\n onClick={onClick}\n aria-label={label}\n type=\"button\"\n className={cn(\n \"flex size-8 items-center justify-center transition-colors\",\n \"first:rounded-t-md last:rounded-b-md\",\n \"hover:bg-accent dark:hover:bg-accent/40\",\n \"focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none focus-visible:ring-inset\",\n \"disabled:pointer-events-none disabled:opacity-50\",\n )}\n disabled={disabled}\n >\n {children}\n </button>\n );\n}\n\nfunction MapControls({\n position = \"bottom-right\",\n showZoom = true,\n showCompass = false,\n showLocate = false,\n showFullscreen = false,\n className,\n onLocate,\n}: MapControlsProps) {\n const { map } = useMap();\n const [waitingForLocation, setWaitingForLocation] = useState(false);\n\n const handleZoomIn = useCallback(() => {\n map?.zoomTo(map.getZoom() + 1, { duration: 300 });\n }, [map]);\n\n const handleZoomOut = useCallback(() => {\n map?.zoomTo(map.getZoom() - 1, { duration: 300 });\n }, [map]);\n\n const handleResetBearing = useCallback(() => {\n map?.resetNorthPitch({ duration: 300 });\n }, [map]);\n\n const handleLocate = useCallback(() => {\n if (!(\"geolocation\" in navigator)) return;\n setWaitingForLocation(true);\n navigator.geolocation.getCurrentPosition(\n (pos) => {\n const coords = {\n longitude: pos.coords.longitude,\n latitude: pos.coords.latitude,\n };\n map?.flyTo({\n center: [coords.longitude, coords.latitude],\n zoom: 14,\n duration: 1500,\n });\n onLocate?.(coords);\n setWaitingForLocation(false);\n },\n (error) => {\n console.error(\"Error getting location:\", error);\n setWaitingForLocation(false);\n },\n // Without a timeout the spec default is Infinity: a dismissed permission\n // prompt would leave the button disabled forever.\n { timeout: 10000 },\n );\n }, [map, onLocate]);\n\n const handleFullscreen = useCallback(() => {\n const container = map?.getContainer();\n if (!container) return;\n if (document.fullscreenElement) {\n document.exitFullscreen();\n } else {\n container.requestFullscreen();\n }\n }, [map]);\n\n return (\n <div\n className={cn(\n \"absolute z-10 flex flex-col gap-1.5\",\n positionClasses[position],\n className,\n )}\n >\n {showZoom && (\n <ControlGroup>\n <ControlButton onClick={handleZoomIn} label=\"Zoom in\">\n <Plus className=\"size-4\" />\n </ControlButton>\n <ControlButton onClick={handleZoomOut} label=\"Zoom out\">\n <Minus className=\"size-4\" />\n </ControlButton>\n </ControlGroup>\n )}\n {showCompass && (\n <ControlGroup>\n <CompassButton onClick={handleResetBearing} />\n </ControlGroup>\n )}\n {showLocate && (\n <ControlGroup>\n <ControlButton\n onClick={handleLocate}\n label=\"Find my location\"\n disabled={waitingForLocation}\n >\n {waitingForLocation ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n <Locate className=\"size-4\" />\n )}\n </ControlButton>\n </ControlGroup>\n )}\n {showFullscreen && (\n <ControlGroup>\n <ControlButton onClick={handleFullscreen} label=\"Toggle fullscreen\">\n <Maximize className=\"size-4\" />\n </ControlButton>\n </ControlGroup>\n )}\n </div>\n );\n}\n\nfunction CompassButton({ onClick }: { onClick: () => void }) {\n const { map } = useMap();\n const compassRef = useRef<SVGSVGElement>(null);\n\n useEffect(() => {\n if (!map || !compassRef.current) return;\n\n const compass = compassRef.current;\n\n const updateRotation = () => {\n const bearing = map.getBearing();\n const pitch = map.getPitch();\n compass.style.transform = `rotateX(${pitch}deg) rotateZ(${-bearing}deg)`;\n };\n\n map.on(\"rotate\", updateRotation);\n map.on(\"pitch\", updateRotation);\n updateRotation();\n\n return () => {\n map.off(\"rotate\", updateRotation);\n map.off(\"pitch\", updateRotation);\n };\n }, [map]);\n\n return (\n <ControlButton onClick={onClick} label=\"Reset bearing to north\">\n <svg\n ref={compassRef}\n viewBox=\"0 0 24 24\"\n className=\"size-5\"\n style={{ transformStyle: \"preserve-3d\" }}\n >\n <path d=\"M12 2L16 12H12V2Z\" className=\"fill-red-500\" />\n <path d=\"M12 2L8 12H12V2Z\" className=\"fill-red-300\" />\n <path d=\"M12 22L16 12H12V22Z\" className=\"fill-muted-foreground/60\" />\n <path d=\"M12 22L8 12H12V22Z\" className=\"fill-muted-foreground/30\" />\n </svg>\n </ControlButton>\n );\n}\n\ntype MapPopupProps = {\n /** Longitude coordinate for popup position */\n longitude: number;\n /** Latitude coordinate for popup position */\n latitude: number;\n /** Callback when popup is closed */\n onClose?: () => void;\n /** Popup content */\n children: ReactNode;\n /** Additional CSS classes for the popup container */\n className?: string;\n /** Show a close button in the popup (default: false) */\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\" | \"closeButton\">;\n\nfunction MapPopup({\n longitude,\n latitude,\n onClose,\n children,\n className,\n closeButton = false,\n ...popupOptions\n}: MapPopupProps) {\n const { map } = useMap();\n const onCloseRef = useRef(onClose);\n onCloseRef.current = onClose;\n const container = useMemo(() => document.createElement(\"div\"), []);\n const { offset, maxWidth } = popupOptions;\n\n const popup = useMemo(() => {\n const popupInstance = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setLngLat([longitude, latitude]);\n\n return popupInstance;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!map) return;\n\n const onCloseProp = () => onCloseRef.current?.();\n\n popup.on(\"close\", onCloseProp);\n\n popup.setDOMContent(container);\n popup.addTo(map);\n\n return () => {\n popup.off(\"close\", onCloseProp);\n if (popup.isOpen()) {\n popup.remove();\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [map]);\n\n // Sync popup position and options when they change.\n useEffect(() => {\n const current = popup.getLngLat();\n if (!current || current.lng !== longitude || current.lat !== latitude) {\n popup.setLngLat([longitude, latitude]);\n }\n popup.setOffset(offset ?? 16);\n if (maxWidth) {\n popup.setMaxWidth(maxWidth);\n }\n }, [popup, longitude, latitude, offset, maxWidth]);\n\n const handleClose = () => {\n popup.remove();\n };\n\n return createPortal(\n <div\n className={cn(\n \"bg-popover text-popover-foreground relative max-w-62 rounded-md border p-3 shadow-md\",\n \"animate-in fade-in-0 zoom-in-95 duration-200 ease-out\",\n className,\n )}\n >\n {closeButton && <PopupCloseButton onClick={handleClose} />}\n {children}\n </div>,\n container,\n );\n}\n\n/** A position along a route: an endpoint, the progress cut, or a 0-1 fraction. */\ntype RouteAnchor = \"start\" | \"end\" | \"progress\" | number;\n\ntype RouteMeasure = {\n /** Distance from the first coordinate to each vertex. */\n cumulative: number[];\n /** Length of the whole route. `0` for routes with fewer than two vertices. */\n total: number;\n};\n\nconst EMPTY_ROUTE_MEASURE: RouteMeasure = { cumulative: [], total: 0 };\nconst EMPTY_COORDINATES: [number, number][] = [];\n\n/**\n * `beforeId`, but only when that layer is actually in the style. MapLibre's\n * `addLayer` fires an error and returns *without adding the layer* when\n * `before` is missing, which would silently drop the route — easy to hit with\n * a `beforeId` that exists in one basemap but not another.\n */\nfunction resolveBeforeId(map: MapLibreGL.Map, beforeId: string | undefined) {\n return beforeId && map.getLayer(beforeId) ? beforeId : undefined;\n}\n\nfunction clampFraction(value: number) {\n if (!Number.isFinite(value)) return 0;\n return Math.min(1, Math.max(0, value));\n}\n\n/**\n * Cumulative length along the route. Segment lengths use an equirectangular\n * approximation (longitude scaled by cos(latitude)) — accurate enough for\n * splitting a route at a fraction, and much cheaper than haversine.\n */\nfunction measureRoute(coordinates: [number, number][]): RouteMeasure {\n if (coordinates.length < 2) return EMPTY_ROUTE_MEASURE;\n\n const cumulative = [0];\n let total = 0;\n\n for (let i = 1; i < coordinates.length; i += 1) {\n const [lng1, lat1] = coordinates[i - 1];\n const [lng2, lat2] = coordinates[i];\n const midLat = ((lat1 + lat2) / 2) * (Math.PI / 180);\n total += Math.hypot((lng2 - lng1) * Math.cos(midLat), lat2 - lat1);\n cumulative.push(total);\n }\n\n return { cumulative, total };\n}\n\n/** Index of the segment that contains `distance`, clamped to the route. */\nfunction findSegmentIndex(cumulative: number[], distance: number) {\n let low = 0;\n let high = cumulative.length - 1;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n if (cumulative[mid] < distance) low = mid + 1;\n else high = mid;\n }\n\n return Math.min(low === 0 ? 0 : low - 1, cumulative.length - 2);\n}\n\n/** The [longitude, latitude] sitting `fraction` of the way along the route. */\nfunction pointAtFraction(\n coordinates: [number, number][],\n measure: RouteMeasure,\n fraction: number,\n): [number, number] | null {\n if (coordinates.length === 0) return null;\n if (coordinates.length === 1 || measure.total === 0) return coordinates[0];\n\n const target = measure.total * clampFraction(fraction);\n const index = findSegmentIndex(measure.cumulative, target);\n const [lng1, lat1] = coordinates[index];\n const [lng2, lat2] = coordinates[index + 1];\n const segment = measure.cumulative[index + 1] - measure.cumulative[index];\n const ratio =\n segment === 0 ? 0 : (target - measure.cumulative[index]) / segment;\n\n return [lng1 + (lng2 - lng1) * ratio, lat1 + (lat2 - lat1) * ratio];\n}\n\n/**\n * The portion of the route up to `fraction`. The final point is interpolated,\n * so the slice ends exactly at the fraction rather than at the nearest vertex.\n */\nfunction sliceAtFraction(\n coordinates: [number, number][],\n measure: RouteMeasure,\n fraction: number,\n): [number, number][] {\n if (coordinates.length < 2) return [];\n\n const t = clampFraction(fraction);\n if (t <= 0 || measure.total === 0) return [];\n if (t >= 1) return coordinates;\n\n const target = measure.total * t;\n const index = findSegmentIndex(measure.cumulative, target);\n const point = pointAtFraction(coordinates, measure, t);\n const traveled = coordinates.slice(0, index + 1);\n if (point) traveled.push(point);\n\n return traveled;\n}\n\ntype RouteContextValue = {\n /** Resolved route id — child layers namespace themselves with it. */\n id: string;\n /** True once the base source and layer are on the map. */\n ready: boolean;\n coordinates: [number, number][];\n /** The traveled slice of the route. Empty when `progress` is unset. */\n traveled: [number, number][];\n progress: number | undefined;\n /** Base line style, with `active` overrides already applied. */\n color: string;\n width: number;\n opacity: number;\n dashArray: [number, number] | undefined;\n /** Layer the route sits below. Child layers insert before it too. */\n beforeId: string | undefined;\n /**\n * Resolves an anchor to a coordinate. `null` when the route is empty, or\n * for `\"progress\"` while `progress` is unset.\n */\n pointAt: (at: RouteAnchor) => [number, number] | null;\n /** Registers a child layer so it follows the route when `active` flips. */\n registerLayer: (layerId: string) => () => void;\n};\n\nconst RouteContext = createContext<RouteContextValue | null>(null);\n\nfunction useMapRoute() {\n const context = useContext(RouteContext);\n if (!context) {\n throw new Error(\"Route components must be used within MapRoute\");\n }\n return context;\n}\n\ntype MapRouteProps = {\n /** Optional unique identifier for the route layer */\n id?: string;\n /**\n * The route as [longitude, latitude] pairs. This is the only input the\n * component needs, so any routing service works: fetch in the parent and\n * pass the geometry (for GeoJSON responses, `route.geometry.coordinates`).\n */\n coordinates: [number, number][];\n /** Line color as CSS color value (default: \"#4285F4\") */\n color?: string;\n /** Line width in pixels (default: 3) */\n width?: number;\n /** Line opacity from 0 to 1 (default: 0.8) */\n opacity?: number;\n /** Dash pattern [dash length, gap length] for dashed lines */\n dashArray?: [number, number];\n /**\n * Fraction of the route already covered, from 0 to 1. Drives `RouteProgress`\n * and the `\"progress\"` anchor on `RouteMarker`.\n */\n progress?: number;\n /**\n * Marks this route as the selected one: it moves above sibling routes and\n * switches to the `active*` styles below. (default: false)\n */\n active?: boolean;\n /** Line color while `active`. Falls back to `color`. */\n activeColor?: string;\n /** Line width while `active`. Falls back to `width`. */\n activeWidth?: number;\n /** Line opacity while `active`. Falls back to `opacity`. */\n activeOpacity?: number;\n /** Dash pattern while `active`. Falls back to `dashArray`. */\n activeDashArray?: [number, number];\n /** Optional MapLibre layer id to insert the route layers before (z-order control). */\n beforeId?: string;\n /** Callback when the route line is clicked */\n onClick?: () => void;\n /** Callback when mouse enters the route line */\n onMouseEnter?: () => void;\n /** Callback when mouse leaves the route line */\n onMouseLeave?: () => void;\n /** Whether the route is interactive - shows pointer cursor on hover (default: true) */\n interactive?: boolean;\n /** Route subcomponents (RouteProgress, RouteMarker) */\n children?: ReactNode;\n};\n\nfunction MapRoute({\n id: propId,\n coordinates: coordinatesProp,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n progress,\n active = false,\n activeColor,\n activeWidth,\n activeOpacity,\n activeDashArray,\n beforeId,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive = true,\n children,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `route-source-${id}`;\n const layerId = `route-layer-${id}`;\n const [ready, setReady] = useState(false);\n\n // Callers often pass `data?.coordinates ?? []`, a fresh array each render.\n // Collapse empties to one shared instance so nothing downstream re-runs.\n const coordinates =\n coordinatesProp.length > 0 ? coordinatesProp : EMPTY_COORDINATES;\n\n const resolvedColor = active ? (activeColor ?? color) : color;\n const resolvedWidth = active ? (activeWidth ?? width) : width;\n const resolvedOpacity = active ? (activeOpacity ?? opacity) : opacity;\n const resolvedDashArray = active ? (activeDashArray ?? dashArray) : dashArray;\n\n const measure = useMemo(() => measureRoute(coordinates), [coordinates]);\n const traveled = useMemo(\n () =>\n progress === undefined\n ? []\n : sliceAtFraction(coordinates, measure, progress),\n [coordinates, measure, progress],\n );\n\n const pointAt = useCallback(\n (at: RouteAnchor) => {\n if (coordinates.length === 0) return null;\n if (at === \"start\") return coordinates[0];\n if (at === \"end\") return coordinates[coordinates.length - 1];\n if (at === \"progress\") {\n if (progress === undefined) return null;\n return pointAtFraction(coordinates, measure, progress);\n }\n return pointAtFraction(coordinates, measure, at);\n },\n [coordinates, measure, progress],\n );\n\n // Child layers, in the order they mounted. Kept in a ref so registering one\n // doesn't re-render the route.\n const childLayersRef = useRef<string[]>([]);\n const registerLayer = useCallback((childLayerId: string) => {\n childLayersRef.current = [...childLayersRef.current, childLayerId];\n return () => {\n childLayersRef.current = childLayersRef.current.filter(\n (entry) => entry !== childLayerId,\n );\n };\n }, []);\n\n // Add source and layer on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: {\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates: [] },\n },\n });\n\n map.addLayer(\n {\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: { \"line-join\": \"round\", \"line-cap\": \"round\" },\n paint: {\n \"line-color\": resolvedColor,\n \"line-width\": resolvedWidth,\n \"line-opacity\": resolvedOpacity,\n ...(resolvedDashArray && { \"line-dasharray\": resolvedDashArray }),\n },\n },\n resolveBeforeId(map, beforeId),\n );\n\n // Children add their layers once this is set, which keeps them above the\n // base line: child effects would otherwise run before this one.\n setReady(true);\n\n return () => {\n setReady(false);\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // When coordinates change, update the source data\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData({\n type: \"Feature\",\n properties: {},\n geometry: {\n type: \"LineString\",\n coordinates: coordinates.length < 2 ? [] : coordinates,\n },\n });\n }\n }, [isLoaded, map, coordinates, sourceId]);\n\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n\n map.setPaintProperty(layerId, \"line-color\", resolvedColor);\n map.setPaintProperty(layerId, \"line-width\", resolvedWidth);\n map.setPaintProperty(layerId, \"line-opacity\", resolvedOpacity);\n map.setPaintProperty(layerId, \"line-dasharray\", resolvedDashArray);\n }, [\n isLoaded,\n map,\n layerId,\n resolvedColor,\n resolvedWidth,\n resolvedOpacity,\n resolvedDashArray,\n ]);\n\n // Raise the active route (and anything it owns) above its siblings. With a\n // `beforeId` it moves to the top of the group below that layer instead.\n // Siblings that mount later (alternatives arriving from a request) add\n // their layers on top, so the raise also re-runs on style changes.\n useEffect(() => {\n if (!ready || !map || !active) return;\n\n // Which layers exist, ignoring their order.\n let lastLayerSet = \"\";\n\n const raise = () => {\n const order = map.getLayersOrder();\n\n // React only when layers are added or removed, never to a reorder.\n // `moveLayer` fires \"styledata\" itself, so reacting to order would loop\n // — with one route against its own move, and with two `active` routes\n // against each other, forever.\n const layerSet = [...order].sort().join(\"|\");\n if (layerSet === lastLayerSet) return;\n lastLayerSet = layerSet;\n\n const owned = [layerId, ...childLayersRef.current].filter((entry) =>\n map.getLayer(entry),\n );\n if (owned.length === 0) return;\n\n const before = resolveBeforeId(map, beforeId);\n const limit = before ? order.indexOf(before) : order.length;\n const top = order.slice(Math.max(0, limit - owned.length), limit);\n if (owned.every((entry, index) => top[index] === entry)) return;\n\n for (const entry of owned) map.moveLayer(entry, before);\n };\n\n raise();\n map.on(\"styledata\", raise);\n\n return () => {\n map.off(\"styledata\", raise);\n };\n }, [ready, map, active, layerId, beforeId]);\n\n // Handle click and hover events\n useEffect(() => {\n if (!isLoaded || !map || !interactive) return;\n\n const handleClick = () => {\n onClick?.();\n };\n const handleMouseEnter = () => {\n map.getCanvas().style.cursor = \"pointer\";\n onMouseEnter?.();\n };\n const handleMouseLeave = () => {\n map.getCanvas().style.cursor = \"\";\n onMouseLeave?.();\n };\n\n map.on(\"click\", layerId, handleClick);\n map.on(\"mouseenter\", layerId, handleMouseEnter);\n map.on(\"mouseleave\", layerId, handleMouseLeave);\n\n return () => {\n map.off(\"click\", layerId, handleClick);\n map.off(\"mouseenter\", layerId, handleMouseEnter);\n map.off(\"mouseleave\", layerId, handleMouseLeave);\n };\n }, [\n isLoaded,\n map,\n layerId,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive,\n ]);\n\n const contextValue = useMemo(\n () => ({\n id,\n ready,\n coordinates,\n traveled,\n progress,\n color: resolvedColor,\n width: resolvedWidth,\n opacity: resolvedOpacity,\n dashArray: resolvedDashArray,\n beforeId,\n pointAt,\n registerLayer,\n }),\n [\n id,\n ready,\n coordinates,\n traveled,\n progress,\n resolvedColor,\n resolvedWidth,\n resolvedOpacity,\n resolvedDashArray,\n beforeId,\n pointAt,\n registerLayer,\n ],\n );\n\n return (\n <RouteContext.Provider value={contextValue}>\n {children}\n </RouteContext.Provider>\n );\n}\n\ntype RouteProgressProps = {\n /** Line color for the traveled portion. Defaults to the route's color. */\n color?: string;\n /** Line width in pixels. Defaults to the route's width. */\n width?: number;\n /** Line opacity from 0 to 1. Defaults to the route's opacity. */\n opacity?: number;\n /** Dash pattern [dash length, gap length] for dashed lines. */\n dashArray?: [number, number];\n};\n\n/**\n * Draws the traveled portion of the parent `MapRoute` on top of the base line.\n * Renders nothing until the route has a `progress` value.\n */\nfunction RouteProgress({\n color,\n width,\n opacity,\n dashArray,\n}: RouteProgressProps) {\n const { map, isLoaded } = useMap();\n const route = useMapRoute();\n const { ready, traveled, registerLayer, beforeId } = route;\n\n const sourceId = `route-progress-source-${route.id}`;\n const layerId = `route-progress-layer-${route.id}`;\n\n const resolvedColor = color ?? route.color;\n const resolvedWidth = width ?? route.width;\n const resolvedOpacity = opacity ?? route.opacity;\n\n // Added only once the parent's layer exists, so this always paints above it.\n useEffect(() => {\n if (!ready || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: {\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates: [] },\n },\n });\n\n // Sits directly above the parent line: same `beforeId` boundary, added\n // after it.\n map.addLayer(\n {\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: { \"line-join\": \"round\", \"line-cap\": \"round\" },\n paint: {\n \"line-color\": resolvedColor,\n \"line-width\": resolvedWidth,\n \"line-opacity\": resolvedOpacity,\n ...(dashArray && { \"line-dasharray\": dashArray }),\n },\n },\n resolveBeforeId(map, beforeId),\n );\n\n const unregister = registerLayer(layerId);\n\n return () => {\n unregister();\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ready, map]);\n\n useEffect(() => {\n if (!ready || !map) return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData({\n type: \"Feature\",\n properties: {},\n geometry: {\n type: \"LineString\",\n coordinates: traveled.length < 2 ? [] : traveled,\n },\n });\n }\n }, [ready, map, traveled, sourceId]);\n\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n\n map.setPaintProperty(layerId, \"line-color\", resolvedColor);\n map.setPaintProperty(layerId, \"line-width\", resolvedWidth);\n map.setPaintProperty(layerId, \"line-opacity\", resolvedOpacity);\n map.setPaintProperty(layerId, \"line-dasharray\", dashArray);\n }, [\n isLoaded,\n map,\n layerId,\n resolvedColor,\n resolvedWidth,\n resolvedOpacity,\n dashArray,\n ]);\n\n return null;\n}\n\ntype RouteMarkerProps = {\n /**\n * Where to pin the marker: an endpoint, the route's progress point, or a\n * 0-1 fraction along the line.\n */\n at: RouteAnchor;\n} & Omit<MapMarkerProps, \"longitude\" | \"latitude\">;\n\n/**\n * A `MapMarker` anchored to a position along the parent `MapRoute`. Takes the\n * same children as `MapMarker` (`MarkerContent`, `MarkerPopup`, ...).\n */\nfunction RouteMarker({ at, children, ...markerProps }: RouteMarkerProps) {\n const { pointAt } = useMapRoute();\n const position = pointAt(at);\n\n // Nothing to pin to yet: the route is empty (coordinates usually arrive\n // from a request), or `at=\"progress\"` is waiting on a `progress` value.\n if (!position) return null;\n\n return (\n <MapMarker longitude={position[0]} latitude={position[1]} {...markerProps}>\n {children}\n </MapMarker>\n );\n}\n\ntype MapGeoJSONData<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> =\n | GeoJSON.FeatureCollection<GeoJSON.Geometry, P>\n | GeoJSON.Feature<GeoJSON.Geometry, P>\n | GeoJSON.Geometry\n | string;\n\ntype MapFillPaint = NonNullable<MapLibreGL.FillLayerSpecification[\"paint\"]>;\ntype MapLinePaint = NonNullable<MapLibreGL.LineLayerSpecification[\"paint\"]>;\n\n/** A rendered feature with strongly-typed `properties`. */\ntype MapGeoJSONFeature<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = Omit<MapLibreGL.MapGeoJSONFeature, \"properties\"> & { properties: P };\n\n/** Event payload passed to MapGeoJSON interaction callbacks. */\ntype MapGeoJSONEvent<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = {\n /** The feature under the cursor, with its typed GeoJSON properties. */\n feature: MapGeoJSONFeature<P>;\n /** Longitude of the cursor at the time of the event. */\n longitude: number;\n /** Latitude of the cursor at the time of the event. */\n latitude: number;\n /** The underlying MapLibre mouse event for advanced use cases. */\n originalEvent: MapLibreGL.MapLayerMouseEvent;\n};\n\ntype MapGeoJSONProps<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = {\n /** GeoJSON data (FeatureCollection, Feature, Geometry) or a URL to fetch it from. */\n data: MapGeoJSONData<P>;\n /** Optional unique identifier prefix for the source/layers. Auto-generated if not provided. */\n id?: string;\n /**\n * Feature property to promote to the feature `id`. Required for hover\n * feature-state (`fillHoverPaint`) and stable `onHover`/`onClick` payloads.\n */\n promoteId?: string;\n /**\n * Paint for the polygon fill layer. Merged on top of a theme-aware monochrome\n * surface tone (`fill-color`). Pass `false` to omit the fill layer entirely\n * (e.g. outlines only).\n */\n fillPaint?: MapFillPaint | false;\n /**\n * Paint for the outline layer. Merged on top of a hairline default\n * (`line-color` = a near-surface neutral, `line-width` = 0.5) for thin\n * separators. Override `line-color` if your container differs, or pass\n * `false` to omit the layer.\n */\n linePaint?: MapLinePaint | false;\n /**\n * Paint merged onto the fill layer for the feature under the cursor, applied\n * as a `case` expression keyed on hover feature-state. Requires `promoteId`.\n */\n fillHoverPaint?: MapFillPaint;\n /** Callback when a feature is clicked. */\n onClick?: (e: MapGeoJSONEvent<P>) => void;\n /** Callback fired when the hovered feature changes; `null` when the cursor leaves. */\n onHover?: (e: MapGeoJSONEvent<P> | null) => void;\n /** Whether features respond to mouse events (default: false). */\n interactive?: boolean;\n /** Optional MapLibre layer id to insert the layers before (z-order control). */\n beforeId?: string;\n};\n\n// Monochrome defaults: a neutral-gray fill (hex of the grayscale chart tokens)\n// with a fixed near-surface line for thin separators. Colors are hardcoded (not\n// theme tokens), tuned for a typical light/dark surface. Override via\n// `fillPaint` / `linePaint`.\nconst GEOJSON_DEFAULT_COLORS = {\n light: { fill: \"#d4d4d4\", line: \"#ffffff\" },\n dark: { fill: \"#404040\", line: \"#171717\" },\n} satisfies Record<Theme, { fill: string; line: string }>;\n\n/**\n * Renders arbitrary GeoJSON as fill + outline layers on the map. Composes like\n * `MapRoute` / `MapArc` — drop it inside `<Map>` (typically with `blank`) for\n * choropleths and region/data maps. For full control over expressions and\n * multiple layers, manage layers directly via `useMap()` instead.\n */\nfunction MapGeoJSON<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n>({\n data,\n id: propId,\n promoteId,\n fillPaint,\n linePaint,\n fillHoverPaint,\n onClick,\n onHover,\n interactive = false,\n beforeId,\n}: MapGeoJSONProps<P>) {\n const { map, isLoaded, resolvedTheme } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `geojson-source-${id}`;\n const fillLayerId = `geojson-fill-${id}`;\n const lineLayerId = `geojson-line-${id}`;\n\n const defaults = GEOJSON_DEFAULT_COLORS[resolvedTheme];\n\n const showFill = fillPaint !== false;\n const showLine = linePaint !== false;\n\n const mergedFillPaint = useMemo(\n () =>\n mergeHoverPaint(\n { \"fill-color\": defaults.fill, ...(fillPaint || {}) },\n fillHoverPaint,\n ),\n [defaults.fill, fillPaint, fillHoverPaint],\n );\n const mergedLinePaint = useMemo(\n () => ({\n \"line-color\": defaults.line,\n \"line-width\": 0.5,\n ...(linePaint || {}),\n }),\n [defaults.line, linePaint],\n );\n const latestRef = useRef({ onClick, onHover });\n latestRef.current = { onClick, onHover };\n\n // Add source on mount.\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data,\n ...(promoteId ? { promoteId } : {}),\n });\n\n return () => {\n try {\n if (map.getLayer(lineLayerId)) map.removeLayer(lineLayerId);\n if (map.getLayer(fillLayerId)) map.removeLayer(fillLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // style may be mid-reload\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // Sync data when it changes.\n useEffect(() => {\n if (!isLoaded || !map) return;\n const source = map.getSource(sourceId) as\n | MapLibreGL.GeoJSONSource\n | undefined;\n source?.setData(data as never);\n }, [isLoaded, map, data, sourceId]);\n\n // Sync layers and paint when visibility or styling changes.\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const source = map.getSource(sourceId);\n if (!source) return;\n\n if (showFill && !map.getLayer(fillLayerId)) {\n map.addLayer(\n {\n id: fillLayerId,\n type: \"fill\",\n source: sourceId,\n paint: mergedFillPaint,\n },\n beforeId,\n );\n } else if (!showFill && map.getLayer(fillLayerId)) {\n map.removeLayer(fillLayerId);\n }\n\n if (showLine && !map.getLayer(lineLayerId)) {\n map.addLayer(\n {\n id: lineLayerId,\n type: \"line\",\n source: sourceId,\n paint: mergedLinePaint,\n },\n beforeId,\n );\n } else if (!showLine && map.getLayer(lineLayerId)) {\n map.removeLayer(lineLayerId);\n }\n\n if (showFill && map.getLayer(fillLayerId)) {\n for (const [key, value] of Object.entries(mergedFillPaint)) {\n map.setPaintProperty(\n fillLayerId,\n key as keyof MapFillPaint,\n value as never,\n );\n }\n }\n if (showLine && map.getLayer(lineLayerId)) {\n for (const [key, value] of Object.entries(mergedLinePaint)) {\n map.setPaintProperty(\n lineLayerId,\n key as keyof MapLinePaint,\n value as never,\n );\n }\n }\n }, [\n isLoaded,\n map,\n sourceId,\n fillLayerId,\n lineLayerId,\n showFill,\n showLine,\n mergedFillPaint,\n mergedLinePaint,\n beforeId,\n ]);\n\n // Interaction handlers (bound to the fill layer).\n useEffect(() => {\n if (!isLoaded || !map || !interactive || !showFill) return;\n\n let hoveredId: string | number | null = null;\n\n const setHover = (next: string | number | null) => {\n if (next === hoveredId) return;\n const sourceExists = !!map.getSource(sourceId);\n if (hoveredId != null && sourceExists) {\n map.setFeatureState(\n { source: sourceId, id: hoveredId },\n { hover: false },\n );\n }\n hoveredId = next;\n if (next != null && sourceExists) {\n map.setFeatureState({ source: sourceId, id: next }, { hover: true });\n }\n };\n\n const handleMouseMove = (e: MapLibreGL.MapLayerMouseEvent) => {\n const feature = e.features?.[0];\n if (!feature) return;\n map.getCanvas().style.cursor = \"pointer\";\n\n const featureId = feature.id;\n if (featureId === hoveredId) return;\n setHover(featureId ?? null);\n latestRef.current.onHover?.({\n feature: feature as unknown as MapGeoJSONFeature<P>,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n };\n\n const handleMouseLeave = () => {\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n latestRef.current.onHover?.(null);\n };\n\n const handleClick = (e: MapLibreGL.MapLayerMouseEvent) => {\n const feature = e.features?.[0];\n if (!feature) return;\n latestRef.current.onClick?.({\n feature: feature as unknown as MapGeoJSONFeature<P>,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n };\n\n map.on(\"mousemove\", fillLayerId, handleMouseMove);\n map.on(\"mouseleave\", fillLayerId, handleMouseLeave);\n map.on(\"click\", fillLayerId, handleClick);\n\n return () => {\n map.off(\"mousemove\", fillLayerId, handleMouseMove);\n map.off(\"mouseleave\", fillLayerId, handleMouseLeave);\n map.off(\"click\", fillLayerId, handleClick);\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n };\n }, [isLoaded, map, fillLayerId, sourceId, interactive, showFill]);\n\n return null;\n}\n\n/** A single arc to render inside <MapArc data={...}>. */\ntype MapArcDatum = {\n /** Unique identifier for this arc. Required for hover state tracking and event payloads. */\n id: string | number;\n /** Start coordinate as [longitude, latitude]. */\n from: [number, number];\n /** End coordinate as [longitude, latitude]. */\n to: [number, number];\n};\n\n/** Event payload passed to MapArc interaction callbacks. */\ntype MapArcEvent<T extends MapArcDatum = MapArcDatum> = {\n /** The arc datum that was hovered or clicked. */\n arc: T;\n /** Longitude of the cursor at the time of the event. */\n longitude: number;\n /** Latitude of the cursor at the time of the event. */\n latitude: number;\n /** The underlying MapLibre mouse event for advanced use cases. */\n originalEvent: MapLibreGL.MapMouseEvent;\n};\n\ntype MapArcLinePaint = NonNullable<MapLibreGL.LineLayerSpecification[\"paint\"]>;\ntype MapArcLineLayout = NonNullable<\n MapLibreGL.LineLayerSpecification[\"layout\"]\n>;\n\ntype MapArcProps<T extends MapArcDatum = MapArcDatum> = {\n /** Array of arcs to render. Each arc must have a unique `id`. */\n data: T[];\n /** Optional unique identifier prefix for the arc source/layers. Auto-generated if not provided. */\n id?: string;\n /**\n * How far each arc bows away from a straight line. `0` renders straight\n * lines; higher values bend further. Negative values bend to the opposite\n * side. Arcs are computed as a quadratic Bézier in lng/lat space; the\n * destination longitude is unwrapped relative to the origin so that arcs\n * cross the antimeridian via the shorter great-circle direction. (default: 0.2)\n */\n curvature?: number;\n /** Number of samples used to render each curve. Higher = smoother. (default: 64) */\n samples?: number;\n /**\n * MapLibre paint properties for the arc layer. Merged on top of sensible\n * defaults (`line-color: #4285F4`, `line-width: 2`, `line-opacity: 0.85`).\n * Any value can be a MapLibre expression for per-feature styling, every\n * field on each arc datum (besides `from`/`to`) is exposed via `[\"get\", ...]`.\n */\n paint?: MapArcLinePaint;\n /** MapLibre layout properties for the arc layer. Defaults to rounded joins/caps. */\n layout?: MapArcLineLayout;\n /**\n * Paint properties applied to the arc currently under the cursor. Each key\n * is merged into `paint` as a `case` expression keyed on per-feature hover\n * state, so only the hovered arc changes appearance.\n */\n hoverPaint?: MapArcLinePaint;\n /** Callback when an arc is clicked. */\n onClick?: (e: MapArcEvent<T>) => void;\n /**\n * Callback fired when the hovered arc changes. Receives the cursor's\n * lng/lat at the moment of entry, and `null` when the cursor leaves the\n * last hovered arc.\n */\n onHover?: (e: MapArcEvent<T> | null) => void;\n /** Whether arcs respond to mouse events (default: true). */\n interactive?: boolean;\n /** Optional MapLibre layer id to insert the arc layers before (z-order control). */\n beforeId?: string;\n};\n\nconst DEFAULT_ARC_CURVATURE = 0.2;\nconst DEFAULT_ARC_SAMPLES = 64;\nconst ARC_HIT_MIN_WIDTH = 12;\nconst ARC_HIT_PADDING = 6;\n\nconst DEFAULT_ARC_PAINT: MapArcLinePaint = {\n \"line-color\": \"#4285F4\",\n \"line-width\": 2,\n \"line-opacity\": 0.85,\n};\n\nconst DEFAULT_ARC_LAYOUT: MapArcLineLayout = {\n \"line-join\": \"round\",\n \"line-cap\": \"round\",\n};\n\nfunction buildArcCoordinates(\n from: [number, number],\n to: [number, number],\n curvature: number,\n samples: number,\n): [number, number][] {\n const [x0, y0] = from;\n const [xTo, y2] = to;\n // Unwrap the destination longitude so |dx| <= 180. This makes arcs that\n // straddle the antimeridian (e.g. Tokyo -> San Francisco) bow the short way\n // across the Pacific instead of the long way around the globe. Resulting\n // longitudes may fall outside [-180, 180]; MapLibre renders them correctly\n // on the globe projection, and on mercator when world copies are enabled.\n const rawDx = xTo - x0;\n const x2 = rawDx > 180 ? xTo - 360 : rawDx < -180 ? xTo + 360 : xTo;\n const dx = x2 - x0;\n const dy = y2 - y0;\n const distance = Math.hypot(dx, dy);\n\n if (distance === 0 || curvature === 0) return [from, [x2, y2]];\n\n const mx = (x0 + x2) / 2;\n const my = (y0 + y2) / 2;\n const nx = -dy / distance;\n const ny = dx / distance;\n const offset = distance * curvature;\n const cx = mx + nx * offset;\n const cy = my + ny * offset;\n\n const points: [number, number][] = [];\n const segments = Math.max(2, Math.floor(samples));\n for (let i = 0; i <= segments; i += 1) {\n const t = i / segments;\n const inv = 1 - t;\n const x = inv * inv * x0 + 2 * inv * t * cx + t * t * x2;\n const y = inv * inv * y0 + 2 * inv * t * cy + t * t * y2;\n points.push([x, y]);\n }\n return points;\n}\n\nfunction MapArc<T extends MapArcDatum = MapArcDatum>({\n data,\n id: propId,\n curvature = DEFAULT_ARC_CURVATURE,\n samples = DEFAULT_ARC_SAMPLES,\n paint,\n layout,\n hoverPaint,\n onClick,\n onHover,\n interactive = true,\n beforeId,\n}: MapArcProps<T>) {\n const { map, isLoaded } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `arc-source-${id}`;\n const layerId = `arc-layer-${id}`;\n const hitLayerId = `arc-hit-layer-${id}`;\n\n const mergedPaint = useMemo(\n () => mergeHoverPaint({ ...DEFAULT_ARC_PAINT, ...paint }, hoverPaint),\n [paint, hoverPaint],\n );\n const mergedLayout = useMemo(\n () => ({ ...DEFAULT_ARC_LAYOUT, ...layout }),\n [layout],\n );\n\n const hitWidth = useMemo(() => {\n const w = paint?.[\"line-width\"] ?? DEFAULT_ARC_PAINT[\"line-width\"];\n const base = typeof w === \"number\" ? w : ARC_HIT_MIN_WIDTH;\n return Math.max(base + ARC_HIT_PADDING, ARC_HIT_MIN_WIDTH);\n }, [paint]);\n\n const geoJSON = useMemo<GeoJSON.FeatureCollection<GeoJSON.LineString>>(\n () => ({\n type: \"FeatureCollection\",\n features: data.map((arc) => {\n const { from, to, ...properties } = arc;\n return {\n type: \"Feature\",\n properties,\n geometry: {\n type: \"LineString\",\n coordinates: buildArcCoordinates(from, to, curvature, samples),\n },\n };\n }),\n }),\n [data, curvature, samples],\n );\n\n const latestRef = useRef({ data, onClick, onHover });\n latestRef.current = { data, onClick, onHover };\n\n // Add source and layers on mount.\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: geoJSON,\n promoteId: \"id\",\n });\n\n map.addLayer(\n {\n id: hitLayerId,\n type: \"line\",\n source: sourceId,\n layout: DEFAULT_ARC_LAYOUT,\n paint: {\n \"line-color\": \"rgba(0, 0, 0, 0)\",\n \"line-width\": hitWidth,\n \"line-opacity\": 1,\n },\n },\n beforeId,\n );\n\n map.addLayer(\n {\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: mergedLayout,\n paint: mergedPaint,\n },\n beforeId,\n );\n\n return () => {\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getLayer(hitLayerId)) map.removeLayer(hitLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // Sync features when data / curvature / samples change.\n useEffect(() => {\n if (!isLoaded || !map) return;\n const source = map.getSource(sourceId) as\n | MapLibreGL.GeoJSONSource\n | undefined;\n source?.setData(geoJSON);\n }, [isLoaded, map, geoJSON, sourceId]);\n\n // Sync paint/layout when they change.\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n for (const [key, value] of Object.entries(mergedPaint)) {\n map.setPaintProperty(\n layerId,\n key as keyof MapArcLinePaint,\n value as never,\n );\n }\n for (const [key, value] of Object.entries(mergedLayout)) {\n map.setLayoutProperty(\n layerId,\n key as keyof MapArcLineLayout,\n value as never,\n );\n }\n if (map.getLayer(hitLayerId)) {\n map.setPaintProperty(hitLayerId, \"line-width\", hitWidth);\n }\n }, [isLoaded, map, layerId, hitLayerId, mergedPaint, mergedLayout, hitWidth]);\n\n // Interaction handlers\n useEffect(() => {\n if (!isLoaded || !map || !interactive) return;\n\n let hoveredId: string | number | null = null;\n\n const setHover = (next: string | number | null) => {\n if (next === hoveredId) return;\n const sourceExists = !!map.getSource(sourceId);\n if (hoveredId != null && sourceExists) {\n map.setFeatureState(\n { source: sourceId, id: hoveredId },\n { hover: false },\n );\n }\n hoveredId = next;\n if (next != null && sourceExists) {\n map.setFeatureState({ source: sourceId, id: next }, { hover: true });\n }\n };\n\n const findArc = (featureId: string | number | undefined) =>\n featureId == null\n ? undefined\n : latestRef.current.data.find(\n (arc) => String(arc.id) === String(featureId),\n );\n\n const handleMouseMove = (e: MapLibreGL.MapLayerMouseEvent) => {\n const featureId = e.features?.[0]?.id as string | number | undefined;\n if (featureId == null || featureId === hoveredId) return;\n\n setHover(featureId);\n map.getCanvas().style.cursor = \"pointer\";\n\n const arc = findArc(featureId);\n if (arc) {\n latestRef.current.onHover?.({\n arc: arc as T,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n }\n };\n\n const handleMouseLeave = () => {\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n latestRef.current.onHover?.(null);\n };\n\n const handleClick = (e: MapLibreGL.MapLayerMouseEvent) => {\n const arc = findArc(e.features?.[0]?.id as string | number | undefined);\n if (!arc) return;\n latestRef.current.onClick?.({\n arc: arc as T,\n longitude: e.lngLat.lng,\n latitude: e.lngLat.lat,\n originalEvent: e,\n });\n };\n\n map.on(\"mousemove\", hitLayerId, handleMouseMove);\n map.on(\"mouseleave\", hitLayerId, handleMouseLeave);\n map.on(\"click\", hitLayerId, handleClick);\n\n return () => {\n map.off(\"mousemove\", hitLayerId, handleMouseMove);\n map.off(\"mouseleave\", hitLayerId, handleMouseLeave);\n map.off(\"click\", hitLayerId, handleClick);\n setHover(null);\n map.getCanvas().style.cursor = \"\";\n };\n }, [isLoaded, map, hitLayerId, sourceId, interactive]);\n\n return null;\n}\n\ntype MapClusterLayerProps<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n> = {\n /** GeoJSON FeatureCollection data or URL to fetch GeoJSON from */\n data: string | GeoJSON.FeatureCollection<GeoJSON.Point, P>;\n /** Maximum zoom level to cluster points on (default: 14) */\n clusterMaxZoom?: number;\n /** Radius of each cluster when clustering points in pixels (default: 50) */\n clusterRadius?: number;\n /** Colors for cluster circles: [small, medium, large] based on point count (default: [\"#3b82f6\", \"#1d4ed8\", \"#1e3a8a\"]) */\n clusterColors?: [string, string, string];\n /** Point count thresholds for color/size steps: [medium, large] (default: [100, 750]) */\n clusterThresholds?: [number, number];\n /** Color for unclustered individual points (default: \"#3b82f6\") */\n pointColor?: string;\n /** Callback when an unclustered point is clicked */\n onPointClick?: (\n feature: GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates: [number, number],\n ) => void;\n /** Callback when a cluster is clicked. If not provided, zooms into the cluster */\n onClusterClick?: (\n clusterId: number,\n coordinates: [number, number],\n pointCount: number,\n ) => void;\n};\n\nconst DEFAULT_CLUSTER_COLORS: [string, string, string] = [\n \"#3b82f6\",\n \"#1d4ed8\",\n \"#1e3a8a\",\n];\nconst DEFAULT_CLUSTER_THRESHOLDS: [number, number] = [100, 750];\n\nfunction MapClusterLayer<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,\n>({\n data,\n clusterMaxZoom = 14,\n clusterRadius = 50,\n clusterColors = DEFAULT_CLUSTER_COLORS,\n clusterThresholds = DEFAULT_CLUSTER_THRESHOLDS,\n pointColor = \"#3b82f6\",\n onPointClick,\n onClusterClick,\n}: MapClusterLayerProps<P>) {\n const { map, isLoaded } = useMap();\n const id = useId();\n const sourceId = `cluster-source-${id}`;\n const clusterLayerId = `clusters-${id}`;\n const clusterCountLayerId = `cluster-count-${id}`;\n const unclusteredLayerId = `unclustered-point-${id}`;\n\n const stylePropsRef = useRef({\n clusterColors,\n clusterThresholds,\n pointColor,\n });\n\n // Add source and layers on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Add clustered GeoJSON source\n map.addSource(sourceId, {\n type: \"geojson\",\n data,\n cluster: true,\n clusterMaxZoom,\n clusterRadius,\n });\n\n // Add cluster circles layer\n map.addLayer({\n id: clusterLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n paint: {\n \"circle-color\": [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ],\n \"circle-radius\": [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ],\n \"circle-stroke-width\": 0.75,\n \"circle-stroke-color\": \"#fff\",\n \"circle-opacity\": 0.85,\n },\n });\n\n // Add cluster count text layer\n map.addLayer({\n id: clusterCountLayerId,\n type: \"symbol\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n layout: {\n \"text-field\": \"{point_count_abbreviated}\",\n \"text-font\": [\"Open Sans Semibold\"],\n \"text-size\": 12,\n },\n paint: {\n \"text-color\": \"#fff\",\n },\n });\n\n // Add unclustered point layer\n map.addLayer({\n id: unclusteredLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"!\", [\"has\", \"point_count\"]],\n paint: {\n \"circle-color\": pointColor,\n \"circle-radius\": 5,\n \"circle-stroke-width\": 2,\n \"circle-stroke-color\": \"#fff\",\n },\n });\n\n return () => {\n try {\n if (map.getLayer(clusterCountLayerId))\n map.removeLayer(clusterCountLayerId);\n if (map.getLayer(unclusteredLayerId))\n map.removeLayer(unclusteredLayerId);\n if (map.getLayer(clusterLayerId)) map.removeLayer(clusterLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map, sourceId]);\n\n // Update source data when data prop changes (only for non-URL data)\n useEffect(() => {\n if (!isLoaded || !map || typeof data === \"string\") return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData(data);\n }\n }, [isLoaded, map, data, sourceId]);\n\n // Update layer styles when props change\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const prev = stylePropsRef.current;\n const colorsChanged =\n prev.clusterColors !== clusterColors ||\n prev.clusterThresholds !== clusterThresholds;\n\n // Update cluster layer colors and sizes\n if (map.getLayer(clusterLayerId) && colorsChanged) {\n map.setPaintProperty(clusterLayerId, \"circle-color\", [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ]);\n map.setPaintProperty(clusterLayerId, \"circle-radius\", [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ]);\n }\n\n // Update unclustered point layer color\n if (map.getLayer(unclusteredLayerId) && prev.pointColor !== pointColor) {\n map.setPaintProperty(unclusteredLayerId, \"circle-color\", pointColor);\n }\n\n stylePropsRef.current = { clusterColors, clusterThresholds, pointColor };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n clusterColors,\n clusterThresholds,\n pointColor,\n ]);\n\n // Handle click events\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Cluster click handler - zoom into cluster\n const handleClusterClick = async (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n },\n ) => {\n const features = map.queryRenderedFeatures(e.point, {\n layers: [clusterLayerId],\n });\n if (!features.length) return;\n\n const feature = features[0];\n const clusterId = feature.properties?.cluster_id as number;\n const pointCount = feature.properties?.point_count as number;\n const coordinates = (feature.geometry as GeoJSON.Point).coordinates as [\n number,\n number,\n ];\n\n if (onClusterClick) {\n onClusterClick(clusterId, coordinates, pointCount);\n } else {\n // Default behavior: zoom to cluster expansion zoom\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n const zoom = await source.getClusterExpansionZoom(clusterId);\n map.easeTo({\n center: coordinates,\n zoom,\n });\n }\n };\n\n // Unclustered point click handler\n const handlePointClick = (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n },\n ) => {\n if (!onPointClick || !e.features?.length) return;\n\n const feature = e.features[0];\n const coordinates = (\n feature.geometry as GeoJSON.Point\n ).coordinates.slice() as [number, number];\n\n // Handle world copies\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n onPointClick(\n feature as unknown as GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates,\n );\n };\n\n // Cursor style handlers\n const handleMouseEnterCluster = () => {\n map.getCanvas().style.cursor = \"pointer\";\n };\n const handleMouseLeaveCluster = () => {\n map.getCanvas().style.cursor = \"\";\n };\n const handleMouseEnterPoint = () => {\n if (onPointClick) {\n map.getCanvas().style.cursor = \"pointer\";\n }\n };\n const handleMouseLeavePoint = () => {\n map.getCanvas().style.cursor = \"\";\n };\n\n map.on(\"click\", clusterLayerId, handleClusterClick);\n map.on(\"click\", unclusteredLayerId, handlePointClick);\n map.on(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.on(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.on(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.on(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n\n return () => {\n map.off(\"click\", clusterLayerId, handleClusterClick);\n map.off(\"click\", unclusteredLayerId, handlePointClick);\n map.off(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.off(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.off(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.off(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n sourceId,\n onClusterClick,\n onPointClick,\n ]);\n\n return null;\n}\n\nexport {\n Map,\n useMap,\n MapMarker,\n MarkerContent,\n MarkerPopup,\n MarkerTooltip,\n MarkerLabel,\n MapPopup,\n MapControls,\n MapRoute,\n RouteProgress,\n RouteMarker,\n useMapRoute,\n MapArc,\n MapGeoJSON,\n MapClusterLayer,\n};\n\nexport type {\n MapRef,\n MapViewport,\n MapStyleOption,\n MapArcDatum,\n MapArcEvent,\n MapGeoJSONData,\n MapGeoJSONFeature,\n MapGeoJSONEvent,\n MapProps,\n MapMarkerProps,\n MarkerContentProps,\n MarkerPopupProps,\n MarkerTooltipProps,\n MarkerLabelProps,\n MapControlsProps,\n MapPopupProps,\n MapRouteProps,\n RouteProgressProps,\n RouteMarkerProps,\n RouteAnchor,\n MapArcProps,\n MapGeoJSONProps,\n MapClusterLayerProps,\n};\n",
"type": "registry:ui",
"target": "components/ui/map.tsx"
}
diff --git a/src/app/(main)/(home)/_components/agent-prompt.tsx b/src/app/(main)/(home)/_components/agent-prompt.tsx
index 2f1555e..7fc9ec4 100644
--- a/src/app/(main)/(home)/_components/agent-prompt.tsx
+++ b/src/app/(main)/(home)/_components/agent-prompt.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
-import { Check } from "lucide-react";
+import { Check, Copy } from "lucide-react";
import { mapInstallAgentPrompt } from "@/lib/llm-prompts";
import { Button } from "@/components/ui/button";
@@ -28,12 +28,10 @@ export function AgentPrompt() {
aria-live="polite"
variant="ghost"
size="xs"
- className="border-border/50 text-muted-foreground hover:text-foreground hover:bg-muted/50 h-7 gap-1.5 rounded-full border"
+ className="text-muted-foreground hover:text-foreground border-border/50 h-7 border px-2.5"
>
- {copied && <Check />}
- {copied
- ? "Copied - paste it into your coding agent"
- : "Building with an agent? Copy the prompt"}
+ {copied ? <Check /> : <Copy />}
+ {copied ? "Copied — paste in your agent" : "Copy prompt for agents"}
</Button>
);
}
diff --git a/src/app/(main)/docs/_components/code-block.tsx b/src/app/(main)/docs/_components/code-block.tsx
index 5bb9e33..b84a1f4 100644
--- a/src/app/(main)/docs/_components/code-block.tsx
+++ b/src/app/(main)/docs/_components/code-block.tsx
@@ -23,7 +23,7 @@ export async function CodeBlock({
return (
<div className="relative w-full overflow-hidden rounded-lg">
{filename ? (
- <div className="bg-code border-border/60 flex items-center justify-between gap-3 border-b py-1 pr-1.5 pl-4">
+ <div className="bg-code border-border/60 flex items-center justify-between gap-3 border-b py-1 pr-2 pl-4">
<span className="text-muted-foreground truncate font-mono text-xs">
{filename}
</span>
diff --git a/src/app/(main)/docs/_components/component-preview-client.tsx b/src/app/(main)/docs/_components/component-preview-client.tsx
index d6a98ca..b13126f 100644
--- a/src/app/(main)/docs/_components/component-preview-client.tsx
+++ b/src/app/(main)/docs/_components/component-preview-client.tsx
@@ -43,12 +43,12 @@ export function ComponentPreviewClient({
className={cn(
expanded
? "max-h-[420px] overflow-auto"
- : "max-h-36 overflow-hidden",
+ : "max-h-32 overflow-hidden",
)}
html={highlightedCode}
/>
{!expanded && (
- <div className="from-surface to-surface/0 pointer-events-none absolute inset-x-0 bottom-0 flex w-full items-center justify-center bg-linear-to-t pt-22 pb-4">
+ <div className="from-surface to-surface/0 pointer-events-none absolute inset-x-0 bottom-0 flex w-full items-center justify-center bg-linear-to-t pt-20 pb-4">
<Button
variant="outline"
size="sm"
diff --git a/src/app/(main)/docs/_components/docs-sidebar.tsx b/src/app/(main)/docs/_components/docs-sidebar.tsx
index 1e8be8d..7bfaecc 100644
--- a/src/app/(main)/docs/_components/docs-sidebar.tsx
+++ b/src/app/(main)/docs/_components/docs-sidebar.tsx
@@ -22,7 +22,7 @@ export function DocsSidebar() {
return (
<Sidebar
- className="sticky top-14 z-30 hidden h-[calc(100svh-3.5rem)] overscroll-none bg-transparent lg:flex"
+ className="sticky top-14 z-30 hidden h-[calc(100svh-3.5rem)] w-55 shrink-0 overscroll-none bg-transparent lg:flex"
collapsible="none"
>
<SidebarContent className="pt-10">
diff --git a/src/app/(main)/docs/_components/docs-toc.tsx b/src/app/(main)/docs/_components/docs-toc.tsx
index 904ac26..3b2f322 100644
--- a/src/app/(main)/docs/_components/docs-toc.tsx
+++ b/src/app/(main)/docs/_components/docs-toc.tsx
@@ -4,7 +4,9 @@ import * as React from "react";
import { cn } from "@/lib/utils";
function useActiveItem(itemIds: string[]) {
- const [activeId, setActiveId] = React.useState<string | null>(null);
+ const [activeId, setActiveId] = React.useState<string | null>(
+ () => itemIds[0] ?? null,
+ );
React.useEffect(() => {
const observer = new IntersectionObserver(
diff --git a/src/app/(main)/docs/_components/docs.tsx b/src/app/(main)/docs/_components/docs.tsx
index c005e55..d811c11 100644
--- a/src/app/(main)/docs/_components/docs.tsx
+++ b/src/app/(main)/docs/_components/docs.tsx
@@ -88,7 +88,7 @@ export function DocsLayout({
const tocItems = toc ?? collectToc(children);
return (
- <div className="flex size-full">
+ <div className="flex min-w-0 flex-1">
<div className="mx-auto flex max-w-[50rem] min-w-0 flex-1 flex-col pt-10 pb-20 lg:px-4">
<DocsTitle title={title} description={description} />
<div className="mt-12 mb-12 space-y-12">{children}</div>
diff --git a/src/app/(main)/docs/_components/examples/osrm-route-example.tsx b/src/app/(main)/docs/_components/examples/osrm-route-example.tsx
index 24dd156..d5c92c9 100644
--- a/src/app/(main)/docs/_components/examples/osrm-route-example.tsx
+++ b/src/app/(main)/docs/_components/examples/osrm-route-example.tsx
@@ -1,19 +1,18 @@
"use client";
import { useEffect, useState } from "react";
-import {
- Map,
- MapMarker,
- MarkerContent,
- MapRoute,
- MarkerLabel,
-} from "@/registry/map";
-import { Loader2, Clock, Route } from "lucide-react";
-import { Button } from "@/components/ui/button";
+import { Map, MapMarker, MarkerContent, MapRoute } from "@/registry/map";
+import { cn } from "@/lib/utils";
const start = { name: "Amsterdam", lng: 4.9041, lat: 52.3676 };
const end = { name: "Rotterdam", lng: 4.4777, lat: 51.9244 };
+// One color for every route: the selected one separates itself by weight and
+// opacity, not hue. Shared by the lines and the list, so a swatch always
+// matches its route.
+const routeColor = "#3b82f6";
+const inactiveOpacity = 0.35;
+
interface RouteData {
coordinates: [number, number][];
duration: number; // seconds
@@ -42,7 +41,7 @@ export function OsrmRouteExample() {
async function fetchRoutes() {
try {
const response = await fetch(
- `https://router.project-osrm.org/route/v1/driving/${start.lng},${start.lat};${end.lng},${end.lat}?overview=full&geometries=geojson&alternatives=true`
+ `https://router.project-osrm.org/route/v1/driving/${start.lng},${start.lat};${end.lng},${end.lat}?overview=full&geometries=geojson&alternatives=true`,
);
const data = await response.json();
@@ -56,7 +55,7 @@ export function OsrmRouteExample() {
coordinates: route.geometry.coordinates,
duration: route.duration,
distance: route.distance,
- })
+ }),
);
setRoutes(routeData);
}
@@ -70,86 +69,80 @@ export function OsrmRouteExample() {
fetchRoutes();
}, []);
- // Sort routes: non-selected first, selected last (renders on top)
- const sortedRoutes = routes
- .map((route, index) => ({ route, index }))
- .sort((a, b) => {
- if (a.index === selectedIndex) return 1;
- if (b.index === selectedIndex) return -1;
- return 0;
- });
-
return (
- <div className="h-[500px] w-full relative">
- <Map center={[4.69, 52.14]} zoom={8.5}>
- {sortedRoutes.map(({ route, index }) => {
- const isSelected = index === selectedIndex;
- return (
- <MapRoute
- key={index}
- coordinates={route.coordinates}
- color={isSelected ? "#6366f1" : "#94a3b8"}
- width={isSelected ? 6 : 5}
- opacity={isSelected ? 1 : 0.6}
- onClick={() => setSelectedIndex(index)}
- />
- );
- })}
+ <div className="relative h-[500px] w-full">
+ <Map center={[4.69, 52.14]} zoom={8.5} loading={isLoading}>
+ {routes.map((route, index) => (
+ <MapRoute
+ key={index}
+ coordinates={route.coordinates}
+ active={index === selectedIndex}
+ color={routeColor}
+ width={5}
+ opacity={inactiveOpacity}
+ activeWidth={6}
+ activeOpacity={1}
+ onClick={() => setSelectedIndex(index)}
+ />
+ ))}
<MapMarker longitude={start.lng} latitude={start.lat}>
<MarkerContent>
- <div className="size-5 rounded-full bg-green-500 border-2 border-white shadow-lg" />
- <MarkerLabel position="top">{start.name}</MarkerLabel>
+ <div className="border-foreground bg-background size-3.5 rounded-full border-2 shadow-md" />
</MarkerContent>
</MapMarker>
<MapMarker longitude={end.lng} latitude={end.lat}>
<MarkerContent>
- <div className="size-5 rounded-full bg-red-500 border-2 border-white shadow-lg" />
- <MarkerLabel position="bottom">{end.name}</MarkerLabel>
+ <div className="bg-foreground ring-background size-3.5 rounded-full shadow-md ring-2" />
</MarkerContent>
</MapMarker>
</Map>
{routes.length > 0 && (
- <div className="absolute top-3 left-3 flex flex-col gap-2">
+ <div
+ role="radiogroup"
+ aria-label="Route options"
+ className="bg-background/95 border-border/50 absolute top-3 left-3 w-48 space-y-0.5 rounded-lg border p-1 shadow-lg backdrop-blur-md"
+ >
{routes.map((route, index) => {
const isActive = index === selectedIndex;
- const isFastest = index === 0;
+
return (
- <Button
+ <button
key={index}
- variant={isActive ? "default" : "secondary"}
- size="sm"
+ type="button"
+ role="radio"
+ aria-checked={isActive}
onClick={() => setSelectedIndex(index)}
- className="justify-start gap-3"
+ className={cn(
+ "flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 transition-colors",
+ isActive ? "bg-muted" : "hover:bg-muted/50",
+ )}
>
- <div className="flex items-center gap-1.5">
- <Clock className="size-3.5" />
- <span className="font-medium">
- {formatDuration(route.duration)}
- </span>
- </div>
- <div className="flex items-center gap-1.5 text-xs opacity-80">
- <Route className="size-3" />
+ <span
+ className="h-4 w-0.5 shrink-0 rounded-full"
+ style={{
+ backgroundColor: routeColor,
+ opacity: isActive ? 1 : inactiveOpacity,
+ }}
+ />
+ <span
+ className={cn(
+ "text-sm font-medium tabular-nums",
+ !isActive && "text-muted-foreground",
+ )}
+ >
+ {formatDuration(route.duration)}
+ </span>
+ <span className="text-muted-foreground ml-auto text-xs tabular-nums">
{formatDistance(route.distance)}
- </div>
- {isFastest && (
- <span className="text-[10px] px-1.5 py-0.5 rounded font-medium bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300">
- Fastest
- </span>
- )}
- </Button>
+ </span>
+ </button>
);
})}
</div>
)}
-
- {isLoading && (
- <div className="absolute inset-0 flex items-center justify-center bg-background/50">
- <Loader2 className="size-6 animate-spin text-muted-foreground" />
- </div>
- )}
</div>
);
}
diff --git a/src/app/(main)/docs/_components/examples/route-progress-example.tsx b/src/app/(main)/docs/_components/examples/route-progress-example.tsx
new file mode 100644
index 0000000..ed1d841
--- /dev/null
+++ b/src/app/(main)/docs/_components/examples/route-progress-example.tsx
@@ -0,0 +1,106 @@
+"use client";
+
+import { useState } from "react";
+import {
+ Map,
+ MapRoute,
+ MarkerContent,
+ MarkerLabel,
+ RouteMarker,
+ RouteProgress,
+} from "@/registry/map";
+import { Car } from "lucide-react";
+import { Slider } from "@/components/ui/slider";
+
+const route: [number, number][] = [
+ [-122.394, 37.7953],
+ [-122.3952, 37.7967],
+ [-122.397, 37.7986],
+ [-122.3975, 37.7992],
+ [-122.3976, 37.7993],
+ [-122.3981, 37.799],
+ [-122.3984, 37.7989],
+ [-122.4066, 37.7979],
+ [-122.4071, 37.7981],
+ [-122.4072, 37.7982],
+ [-122.4072, 37.7984],
+ [-122.4082, 37.8034],
+ [-122.4064, 37.8037],
+ [-122.4063, 37.8036],
+ [-122.4063, 37.8034],
+ [-122.4067, 37.8032],
+ [-122.4067, 37.803],
+ [-122.4067, 37.8028],
+ [-122.4064, 37.8025],
+ [-122.4062, 37.802],
+ [-122.406, 37.8019],
+ [-122.4058, 37.8018],
+ [-122.4056, 37.8018],
+ [-122.4055, 37.8019],
+ [-122.4054, 37.8021],
+ [-122.4056, 37.8025],
+];
+
+export function RouteProgressExample() {
+ const [progress, setProgress] = useState(0.45);
+
+ return (
+ <div className="relative h-[420px] w-full">
+ <Map center={[-122.4008, 37.7996]} zoom={14.2}>
+ <MapRoute
+ coordinates={route}
+ progress={progress}
+ color="#94a3b8"
+ width={5}
+ opacity={0.8}
+ dashArray={[0.5, 1.5]}
+ >
+ <RouteProgress color="#3b82f6" width={5} opacity={1} />
+
+ <RouteMarker at="start">
+ <MarkerContent>
+ <div className="border-foreground bg-background size-3.5 rounded-full border-2 shadow-md" />
+ </MarkerContent>
+ </RouteMarker>
+
+ <RouteMarker at="progress">
+ <MarkerContent>
+ <div className="ring-background grid size-6 place-items-center rounded-full bg-blue-500 shadow-md ring-2">
+ <Car className="size-3 text-white" />
+ </div>
+ <MarkerLabel
+ position="top"
+ className="bg-background/90 border-border/50 rounded-md border px-1.5 py-0.5 tabular-nums shadow-sm"
+ >
+ {Math.round(progress * 100)}%
+ </MarkerLabel>
+ </MarkerContent>
+ </RouteMarker>
+
+ <RouteMarker at="end">
+ <MarkerContent>
+ <div className="bg-foreground ring-background size-3.5 rounded-full shadow-md ring-2" />
+ </MarkerContent>
+ </RouteMarker>
+ </MapRoute>
+ </Map>
+
+ <div className="bg-background/95 border-border/50 absolute bottom-3 left-3 w-56 rounded-lg border p-3 shadow-lg backdrop-blur-md">
+ <div className="mb-2 flex items-center justify-between text-xs">
+ <span className="font-medium">Progress</span>
+ <span className="text-muted-foreground tabular-nums">
+ {Math.round(progress * 100)}%
+ </span>
+ </div>
+ <Slider
+ value={[progress]}
+ onValueChange={([value]) => setProgress(value)}
+ min={0}
+ max={1}
+ step={0.01}
+ aria-label="Route progress"
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/(main)/docs/api-reference/page.tsx b/src/app/(main)/docs/api-reference/page.tsx
index 0ae2882..b1052b1 100644
--- a/src/app/(main)/docs/api-reference/page.tsx
+++ b/src/app/(main)/docs/api-reference/page.tsx
@@ -24,7 +24,14 @@ const anatomyCode = `<Map>
<MapPopup longitude={...} latitude={...} />
<MapControls />
- <MapRoute coordinates={...} />
+
+ <MapRoute coordinates={...} progress={...}>
+ <RouteProgress />
+ <RouteMarker at="progress">
+ <MarkerContent />
+ </RouteMarker>
+ </MapRoute>
+
<MapArc data={...} />
<MapGeoJSON data={...} />
<MapClusterLayer data={...} />
@@ -488,6 +495,17 @@ export default function ApiReferencePage() {
used inside <DocsCode>Map</DocsCode>. Supports click and hover
interactions for building route selection UIs.
</p>
+ <p>
+ Pass <DocsCode>progress</DocsCode> to split the line into covered and
+ remaining sections, then style the covered part with a{" "}
+ <DocsCode>RouteProgress</DocsCode> child. For alternative routes, mark
+ one <DocsCode>active</DocsCode> — it moves above its siblings and
+ switches to the <DocsCode>active*</DocsCode> styles. Children can also
+ read the route directly with <DocsCode>useMapRoute()</DocsCode>, which
+ returns the coordinates, the traveled slice, the resolved style and{" "}
+ <DocsCode>beforeId</DocsCode>, and a{" "}
+ <DocsCode>pointAt(anchor)</DocsCode> helper.
+ </p>
<DocsPropTable
props={[
{
@@ -526,6 +544,49 @@ export default function ApiReferencePage() {
description:
"Dash pattern [dash length, gap length] for dashed lines.",
},
+ {
+ name: "progress",
+ type: "number",
+ description:
+ 'Fraction of the route already covered (0 to 1). Drives RouteProgress and the "progress" anchor on RouteMarker.',
+ },
+ {
+ name: "active",
+ type: "boolean",
+ default: "false",
+ description:
+ "Marks this route as the selected one: it moves above sibling routes and switches to the active* styles.",
+ },
+ {
+ name: "activeColor",
+ type: "string",
+ default: "color",
+ description: "Line color while active.",
+ },
+ {
+ name: "activeWidth",
+ type: "number",
+ default: "width",
+ description: "Line width while active.",
+ },
+ {
+ name: "activeOpacity",
+ type: "number",
+ default: "opacity",
+ description: "Line opacity while active.",
+ },
+ {
+ name: "activeDashArray",
+ type: "[number, number]",
+ default: "dashArray",
+ description: "Dash pattern while active.",
+ },
+ {
+ name: "beforeId",
+ type: "string",
+ description:
+ "MapLibre layer id to insert the route layers before (z-order control).",
+ },
{
name: "onClick",
type: "() => void",
@@ -544,10 +605,95 @@ export default function ApiReferencePage() {
{
name: "interactive",
type: "boolean",
- default: "false",
+ default: "true",
description:
"Respond to mouse events (hover, cursor, callbacks).",
},
+ {
+ name: "children",
+ type: "ReactNode",
+ description: "Route subcomponents (RouteProgress, RouteMarker).",
+ },
+ ]}
+ />
+ </DocsSection>
+
+ {/* RouteProgress */}
+ <DocsSection title="RouteProgress">
+ <p>
+ Draws the covered portion of the parent <DocsCode>MapRoute</DocsCode>{" "}
+ on top of the base line, ending exactly at the route&apos;s{" "}
+ <DocsCode>progress</DocsCode> fraction rather than at the nearest
+ vertex. Must be used inside <DocsCode>MapRoute</DocsCode>. Renders
+ nothing until the route has a <DocsCode>progress</DocsCode> value, and
+ inherits the route&apos;s <DocsCode>beforeId</DocsCode> so both layers
+ stay below the same boundary.
+ </p>
+ <DocsPropTable
+ props={[
+ {
+ name: "color",
+ type: "string",
+ default: "the route's color",
+ description: "Line color for the covered portion.",
+ },
+ {
+ name: "width",
+ type: "number",
+ default: "the route's width",
+ description: "Line width in pixels.",
+ },
+ {
+ name: "opacity",
+ type: "number",
+ default: "the route's opacity",
+ description: "Line opacity (0 to 1).",
+ },
+ {
+ name: "dashArray",
+ type: "[number, number]",
+ description:
+ "Dash pattern [dash length, gap length] for dashed lines.",
+ },
+ ]}
+ />
+ </DocsSection>
+
+ {/* RouteMarker */}
+ <DocsSection title="RouteMarker">
+ <p>
+ A <DocsCode>MapMarker</DocsCode> pinned to a position along the parent{" "}
+ <DocsCode>MapRoute</DocsCode>, so you never compute the coordinate
+ yourself. Must be used inside <DocsCode>MapRoute</DocsCode>. Accepts
+ every <DocsCode>MapMarker</DocsCode> prop except{" "}
+ <DocsCode>longitude</DocsCode> and <DocsCode>latitude</DocsCode>, and
+ the same children (<DocsCode>MarkerContent</DocsCode>,{" "}
+ <DocsCode>MarkerPopup</DocsCode>, <DocsCode>MarkerTooltip</DocsCode>,{" "}
+ <DocsCode>MarkerLabel</DocsCode>). Renders nothing while the route is
+ still empty — useful when coordinates arrive from an async request —
+ or, for <DocsCode>at=&quot;progress&quot;</DocsCode>, until the route
+ has a <DocsCode>progress</DocsCode> value.
+ </p>
+ <DocsPropTable
+ props={[
+ {
+ name: "at",
+ type: '"start" | "end" | "progress" | number',
+ description:
+ 'Where to pin the marker. A number is a fraction along the line (0 to 1); "progress" tracks the route\'s progress value.',
+ },
+ {
+ name: "children",
+ type: "ReactNode",
+ description:
+ "Marker subcomponents (MarkerContent, MarkerPopup, MarkerTooltip, MarkerLabel).",
+ },
+ {
+ name: "...props",
+ type: "MapMarkerProps",
+ description:
+ "Any other MapMarker prop (offset, onClick, draggable, rotation, ...).",
+ },
]}
/>
</DocsSection>
diff --git a/src/app/(main)/docs/layout.tsx b/src/app/(main)/docs/layout.tsx
index e2219a7..a321141 100644
--- a/src/app/(main)/docs/layout.tsx
+++ b/src/app/(main)/docs/layout.tsx
@@ -10,7 +10,7 @@ export default function DocsLayout({
<div className="flex flex-1">
<SidebarProvider className="container min-h-min px-0">
<DocsSidebar />
- <main className="size-full">{children}</main>
+ <main className="flex min-w-0 flex-1">{children}</main>
</SidebarProvider>
</div>
);
diff --git a/src/app/(main)/docs/routes/page.tsx b/src/app/(main)/docs/routes/page.tsx
index 3635d7d..0dcaf75 100644
--- a/src/app/(main)/docs/routes/page.tsx
+++ b/src/app/(main)/docs/routes/page.tsx
@@ -6,6 +6,7 @@ import {
} from "../_components/docs";
import { ComponentPreview } from "../_components/component-preview";
import { RouteExample } from "../_components/examples/route-example";
+import { RouteProgressExample } from "../_components/examples/route-progress-example";
import { OsrmRouteExample } from "../_components/examples/osrm-route-example";
import { getExampleSource } from "../_components/get-example-source";
import { Metadata } from "next";
@@ -16,6 +17,7 @@ export const metadata: Metadata = {
export default function RoutesPage() {
const routeSource = getExampleSource("route-example.tsx");
+ const routeProgressSource = getExampleSource("route-progress-example.tsx");
const osrmRouteSource = getExampleSource("osrm-route-example.tsx");
return (
@@ -40,14 +42,25 @@ export default function RoutesPage() {
</ComponentPreview>
</DocsSection>
+ <DocsSection title="Route Progress">
+ <p>
+ Pass <DocsCode>progress</DocsCode> (0 to 1) and a{" "}
+ <DocsCode>RouteProgress</DocsCode> child paints the covered part of
+ the line. <DocsCode>RouteMarker</DocsCode> pins a marker at{" "}
+ <DocsCode>&quot;start&quot;</DocsCode>,{" "}
+ <DocsCode>&quot;end&quot;</DocsCode>,{" "}
+ <DocsCode>&quot;progress&quot;</DocsCode>, or any fraction.
+ </p>
+ <ComponentPreview code={routeProgressSource}>
+ <RouteProgressExample />
+ </ComponentPreview>
+ </DocsSection>
+
<DocsSection title="Route Planning">
<p>
- Display multiple route options and let users select between them. This
- example fetches real driving directions from the{" "}
- <DocsLink href="https://project-osrm.org/" external>
- OSRM API
- </DocsLink>
- . Click on a route or use the buttons to switch.
+ Render one <DocsCode>MapRoute</DocsCode> per option and mark the
+ selected one <DocsCode>active</DocsCode>, it moves on top and uses the{" "}
+ <DocsCode>active*</DocsCode> styles. Click a line or a row to switch.
</p>
<ComponentPreview code={osrmRouteSource} height="500px">
<OsrmRouteExample />
diff --git a/src/components/command-search.tsx b/src/components/command-search.tsx
index 6d8e86e..8850d3d 100644
--- a/src/components/command-search.tsx
+++ b/src/components/command-search.tsx
@@ -52,13 +52,15 @@ export function CommandSearch({ className }: { className?: string }) {
onClick={() => setOpen(true)}
aria-label="Jump to pages, components, and docs"
className={cn(
- "bg-muted dark:bg-muted/50 text-muted-foreground hover:bg-muted/60 dark:hover:bg-muted/60 hover:text-foreground mr-2.5 hidden w-48 md:flex",
+ "bg-muted dark:bg-muted/40 text-muted-foreground hover:bg-muted dark:hover:bg-muted/60 hover:text-foreground mr-2.5 hidden w-36 md:flex",
className,
)}
>
<SearchIcon className="size-3.5" />
- <span>Search...</span>
- <Kbd className="ml-auto bg-transparent">⌘K</Kbd>
+ <span>Search</span>
+ <Kbd className="text-muted-foreground/70 ml-auto bg-transparent">
+ ⌘K
+ </Kbd>
</Button>
<CommandDialog
open={open}
diff --git a/src/components/ui/slider.tsx b/src/components/ui/slider.tsx
new file mode 100644
index 0000000..46ebc4b
--- /dev/null
+++ b/src/components/ui/slider.tsx
@@ -0,0 +1,63 @@
+"use client"
+
+import * as React from "react"
+import { Slider as SliderPrimitive } from "radix-ui"
+
+import { cn } from "@/lib/utils"
+
+function Slider({
+ className,
+ defaultValue,
+ value,
+ min = 0,
+ max = 100,
+ ...props
+}: React.ComponentProps<typeof SliderPrimitive.Root>) {
+ const _values = React.useMemo(
+ () =>
+ Array.isArray(value)
+ ? value
+ : Array.isArray(defaultValue)
+ ? defaultValue
+ : [min, max],
+ [value, defaultValue, min, max]
+ )
+
+ return (
+ <SliderPrimitive.Root
+ data-slot="slider"
+ defaultValue={defaultValue}
+ value={value}
+ min={min}
+ max={max}
+ className={cn(
+ "relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track
+ data-slot="slider-track"
+ className={cn(
+ "relative grow overflow-hidden rounded-full bg-muted data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
+ )}
+ >
+ <SliderPrimitive.Range
+ data-slot="slider-range"
+ className={cn(
+ "absolute bg-primary data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
+ )}
+ />
+ </SliderPrimitive.Track>
+ {Array.from({ length: _values.length }, (_, index) => (
+ <SliderPrimitive.Thumb
+ data-slot="slider-thumb"
+ key={index}
+ className="block size-4 shrink-0 rounded-full border border-primary bg-white shadow-sm ring-ring/50 transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
+ />
+ ))}
+ </SliderPrimitive.Root>
+ )
+}
+
+export { Slider }
diff --git a/src/registry/blocks/delivery-tracker/page.tsx b/src/registry/blocks/delivery-tracker/page.tsx
index 183505c..654f4f7 100644
--- a/src/registry/blocks/delivery-tracker/page.tsx
+++ b/src/registry/blocks/delivery-tracker/page.tsx
@@ -1,10 +1,17 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { useTheme } from "next-themes";
import { Clock3, House, Store, Utensils, Truck, UserRound } from "lucide-react";
-import { Map, MapMarker, MapRoute, MarkerContent } from "@/registry/map";
+import {
+ Map,
+ MapMarker,
+ MapRoute,
+ MarkerContent,
+ RouteMarker,
+ RouteProgress,
+} from "@/registry/map";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -67,14 +74,6 @@ export default function Page() {
fetchRoute();
}, []);
- const progressCoordinates = useMemo(() => {
- const total = routeData?.coordinates?.length ?? 0;
- const progressCount = Math.max(2, Math.floor(total * progressFraction));
- return routeData?.coordinates?.slice(0, progressCount) ?? [];
- }, [routeData]);
-
- const courierPosition = progressCoordinates[progressCoordinates.length - 1];
-
return (
<div className="flex min-h-screen items-center justify-center p-8">
<div className="bg-sidebar mx-auto grid w-[1200px] rounded-xl border md:grid-cols-[1.05fr_1fr]">
@@ -167,28 +166,21 @@ export default function Page() {
maxZoom={mapView.maxZoom}
>
<MapRoute
- id="delivery-full-route"
+ id="delivery-route"
coordinates={routeData?.coordinates ?? []}
+ progress={progressFraction}
color={remainingRouteColor}
width={routeStyle.remaining.width}
opacity={routeStyle.remaining.opacity}
interactive={false}
- />
- <MapRoute
- id="delivery-progress-route"
- coordinates={progressCoordinates}
- color={routeStyle.progress.color}
- width={routeStyle.progress.width}
- opacity={routeStyle.progress.opacity}
- interactive={false}
- />
-
- {courierPosition && (
- <MapMarker
- longitude={courierPosition[0]}
- latitude={courierPosition[1]}
- offset={[0, 10]}
- >
+ >
+ <RouteProgress
+ color={routeStyle.progress.color}
+ width={routeStyle.progress.width}
+ opacity={routeStyle.progress.opacity}
+ />
+
+ <RouteMarker at="progress" offset={[0, 10]}>
<MarkerContent>
<div
className="relative grid size-9 place-items-center rounded-full shadow-md"
@@ -201,8 +193,8 @@ export default function Page() {
</div>
</div>
</MarkerContent>
- </MapMarker>
- )}
+ </RouteMarker>
+ </MapRoute>
<MapMarker longitude={pickup.lng} latitude={pickup.lat}>
<MarkerContent>
diff --git a/src/registry/map.tsx b/src/registry/map.tsx
index 2a7ba41..1dd8e1b 100644
--- a/src/registry/map.tsx
+++ b/src/registry/map.tsx
@@ -1104,10 +1104,157 @@ function MapPopup({
);
}
+/** A position along a route: an endpoint, the progress cut, or a 0-1 fraction. */
+type RouteAnchor = "start" | "end" | "progress" | number;
+
+type RouteMeasure = {
+ /** Distance from the first coordinate to each vertex. */
+ cumulative: number[];
+ /** Length of the whole route. `0` for routes with fewer than two vertices. */
+ total: number;
+};
+
+const EMPTY_ROUTE_MEASURE: RouteMeasure = { cumulative: [], total: 0 };
+const EMPTY_COORDINATES: [number, number][] = [];
+
+/**
+ * `beforeId`, but only when that layer is actually in the style. MapLibre's
+ * `addLayer` fires an error and returns *without adding the layer* when
+ * `before` is missing, which would silently drop the route — easy to hit with
+ * a `beforeId` that exists in one basemap but not another.
+ */
+function resolveBeforeId(map: MapLibreGL.Map, beforeId: string | undefined) {
+ return beforeId && map.getLayer(beforeId) ? beforeId : undefined;
+}
+
+function clampFraction(value: number) {
+ if (!Number.isFinite(value)) return 0;
+ return Math.min(1, Math.max(0, value));
+}
+
+/**
+ * Cumulative length along the route. Segment lengths use an equirectangular
+ * approximation (longitude scaled by cos(latitude)) — accurate enough for
+ * splitting a route at a fraction, and much cheaper than haversine.
+ */
+function measureRoute(coordinates: [number, number][]): RouteMeasure {
+ if (coordinates.length < 2) return EMPTY_ROUTE_MEASURE;
+
+ const cumulative = [0];
+ let total = 0;
+
+ for (let i = 1; i < coordinates.length; i += 1) {
+ const [lng1, lat1] = coordinates[i - 1];
+ const [lng2, lat2] = coordinates[i];
+ const midLat = ((lat1 + lat2) / 2) * (Math.PI / 180);
+ total += Math.hypot((lng2 - lng1) * Math.cos(midLat), lat2 - lat1);
+ cumulative.push(total);
+ }
+
+ return { cumulative, total };
+}
+
+/** Index of the segment that contains `distance`, clamped to the route. */
+function findSegmentIndex(cumulative: number[], distance: number) {
+ let low = 0;
+ let high = cumulative.length - 1;
+
+ while (low < high) {
+ const mid = Math.floor((low + high) / 2);
+ if (cumulative[mid] < distance) low = mid + 1;
+ else high = mid;
+ }
+
+ return Math.min(low === 0 ? 0 : low - 1, cumulative.length - 2);
+}
+
+/** The [longitude, latitude] sitting `fraction` of the way along the route. */
+function pointAtFraction(
+ coordinates: [number, number][],
+ measure: RouteMeasure,
+ fraction: number,
+): [number, number] | null {
+ if (coordinates.length === 0) return null;
+ if (coordinates.length === 1 || measure.total === 0) return coordinates[0];
+
+ const target = measure.total * clampFraction(fraction);
+ const index = findSegmentIndex(measure.cumulative, target);
+ const [lng1, lat1] = coordinates[index];
+ const [lng2, lat2] = coordinates[index + 1];
+ const segment = measure.cumulative[index + 1] - measure.cumulative[index];
+ const ratio =
+ segment === 0 ? 0 : (target - measure.cumulative[index]) / segment;
+
+ return [lng1 + (lng2 - lng1) * ratio, lat1 + (lat2 - lat1) * ratio];
+}
+
+/**
+ * The portion of the route up to `fraction`. The final point is interpolated,
+ * so the slice ends exactly at the fraction rather than at the nearest vertex.
+ */
+function sliceAtFraction(
+ coordinates: [number, number][],
+ measure: RouteMeasure,
+ fraction: number,
+): [number, number][] {
+ if (coordinates.length < 2) return [];
+
+ const t = clampFraction(fraction);
+ if (t <= 0 || measure.total === 0) return [];
+ if (t >= 1) return coordinates;
+
+ const target = measure.total * t;
+ const index = findSegmentIndex(measure.cumulative, target);
+ const point = pointAtFraction(coordinates, measure, t);
+ const traveled = coordinates.slice(0, index + 1);
+ if (point) traveled.push(point);
+
+ return traveled;
+}
+
+type RouteContextValue = {
+ /** Resolved route id — child layers namespace themselves with it. */
+ id: string;
+ /** True once the base source and layer are on the map. */
+ ready: boolean;
+ coordinates: [number, number][];
+ /** The traveled slice of the route. Empty when `progress` is unset. */
+ traveled: [number, number][];
+ progress: number | undefined;
+ /** Base line style, with `active` overrides already applied. */
+ color: string;
+ width: number;
+ opacity: number;
+ dashArray: [number, number] | undefined;
+ /** Layer the route sits below. Child layers insert before it too. */
+ beforeId: string | undefined;
+ /**
+ * Resolves an anchor to a coordinate. `null` when the route is empty, or
+ * for `"progress"` while `progress` is unset.
+ */
+ pointAt: (at: RouteAnchor) => [number, number] | null;
+ /** Registers a child layer so it follows the route when `active` flips. */
+ registerLayer: (layerId: string) => () => void;
+};
+
+const RouteContext = createContext<RouteContextValue | null>(null);
+
+function useMapRoute() {
+ const context = useContext(RouteContext);
+ if (!context) {
+ throw new Error("Route components must be used within MapRoute");
+ }
+ return context;
+}
+
type MapRouteProps = {
/** Optional unique identifier for the route layer */
id?: string;
- /** Array of [longitude, latitude] coordinate pairs defining the route */
+ /**
+ * The route as [longitude, latitude] pairs. This is the only input the
+ * component needs, so any routing service works: fetch in the parent and
+ * pass the geometry (for GeoJSON responses, `route.geometry.coordinates`).
+ */
coordinates: [number, number][];
/** Line color as CSS color value (default: "#4285F4") */
color?: string;
@@ -1117,6 +1264,26 @@ type MapRouteProps = {
opacity?: number;
/** Dash pattern [dash length, gap length] for dashed lines */
dashArray?: [number, number];
+ /**
+ * Fraction of the route already covered, from 0 to 1. Drives `RouteProgress`
+ * and the `"progress"` anchor on `RouteMarker`.
+ */
+ progress?: number;
+ /**
+ * Marks this route as the selected one: it moves above sibling routes and
+ * switches to the `active*` styles below. (default: false)
+ */
+ active?: boolean;
+ /** Line color while `active`. Falls back to `color`. */
+ activeColor?: string;
+ /** Line width while `active`. Falls back to `width`. */
+ activeWidth?: number;
+ /** Line opacity while `active`. Falls back to `opacity`. */
+ activeOpacity?: number;
+ /** Dash pattern while `active`. Falls back to `dashArray`. */
+ activeDashArray?: [number, number];
+ /** Optional MapLibre layer id to insert the route layers before (z-order control). */
+ beforeId?: string;
/** Callback when the route line is clicked */
onClick?: () => void;
/** Callback when mouse enters the route line */
@@ -1125,25 +1292,81 @@ type MapRouteProps = {
onMouseLeave?: () => void;
/** Whether the route is interactive - shows pointer cursor on hover (default: true) */
interactive?: boolean;
+ /** Route subcomponents (RouteProgress, RouteMarker) */
+ children?: ReactNode;
};
function MapRoute({
id: propId,
- coordinates,
+ coordinates: coordinatesProp,
color = "#4285F4",
width = 3,
opacity = 0.8,
dashArray,
+ progress,
+ active = false,
+ activeColor,
+ activeWidth,
+ activeOpacity,
+ activeDashArray,
+ beforeId,
onClick,
onMouseEnter,
onMouseLeave,
interactive = true,
+ children,
}: MapRouteProps) {
const { map, isLoaded } = useMap();
const autoId = useId();
const id = propId ?? autoId;
const sourceId = `route-source-${id}`;
const layerId = `route-layer-${id}`;
+ const [ready, setReady] = useState(false);
+
+ // Callers often pass `data?.coordinates ?? []`, a fresh array each render.
+ // Collapse empties to one shared instance so nothing downstream re-runs.
+ const coordinates =
+ coordinatesProp.length > 0 ? coordinatesProp : EMPTY_COORDINATES;
+
+ const resolvedColor = active ? (activeColor ?? color) : color;
+ const resolvedWidth = active ? (activeWidth ?? width) : width;
+ const resolvedOpacity = active ? (activeOpacity ?? opacity) : opacity;
+ const resolvedDashArray = active ? (activeDashArray ?? dashArray) : dashArray;
+
+ const measure = useMemo(() => measureRoute(coordinates), [coordinates]);
+ const traveled = useMemo(
+ () =>
+ progress === undefined
+ ? []
+ : sliceAtFraction(coordinates, measure, progress),
+ [coordinates, measure, progress],
+ );
+
+ const pointAt = useCallback(
+ (at: RouteAnchor) => {
+ if (coordinates.length === 0) return null;
+ if (at === "start") return coordinates[0];
+ if (at === "end") return coordinates[coordinates.length - 1];
+ if (at === "progress") {
+ if (progress === undefined) return null;
+ return pointAtFraction(coordinates, measure, progress);
+ }
+ return pointAtFraction(coordinates, measure, at);
+ },
+ [coordinates, measure, progress],
+ );
+
+ // Child layers, in the order they mounted. Kept in a ref so registering one
+ // doesn't re-render the route.
+ const childLayersRef = useRef<string[]>([]);
+ const registerLayer = useCallback((childLayerId: string) => {
+ childLayersRef.current = [...childLayersRef.current, childLayerId];
+ return () => {
+ childLayersRef.current = childLayersRef.current.filter(
+ (entry) => entry !== childLayerId,
+ );
+ };
+ }, []);
// Add source and layer on mount
useEffect(() => {
@@ -1158,20 +1381,28 @@ function MapRoute({
},
});
- map.addLayer({
- id: layerId,
- type: "line",
- source: sourceId,
- layout: { "line-join": "round", "line-cap": "round" },
- paint: {
- "line-color": color,
- "line-width": width,
- "line-opacity": opacity,
- ...(dashArray && { "line-dasharray": dashArray }),
+ map.addLayer(
+ {
+ id: layerId,
+ type: "line",
+ source: sourceId,
+ layout: { "line-join": "round", "line-cap": "round" },
+ paint: {
+ "line-color": resolvedColor,
+ "line-width": resolvedWidth,
+ "line-opacity": resolvedOpacity,
+ ...(resolvedDashArray && { "line-dasharray": resolvedDashArray }),
+ },
},
- });
+ resolveBeforeId(map, beforeId),
+ );
+
+ // Children add their layers once this is set, which keeps them above the
+ // base line: child effects would otherwise run before this one.
+ setReady(true);
return () => {
+ setReady(false);
try {
if (map.getLayer(layerId)) map.removeLayer(layerId);
if (map.getSource(sourceId)) map.removeSource(sourceId);
@@ -1184,14 +1415,17 @@ function MapRoute({
// When coordinates change, update the source data
useEffect(() => {
- if (!isLoaded || !map || coordinates.length < 2) return;
+ if (!isLoaded || !map) return;
const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;
if (source) {
source.setData({
type: "Feature",
properties: {},
- geometry: { type: "LineString", coordinates },
+ geometry: {
+ type: "LineString",
+ coordinates: coordinates.length < 2 ? [] : coordinates,
+ },
});
}
}, [isLoaded, map, coordinates, sourceId]);
@@ -1199,11 +1433,61 @@ function MapRoute({
useEffect(() => {
if (!isLoaded || !map || !map.getLayer(layerId)) return;
- map.setPaintProperty(layerId, "line-color", color);
- map.setPaintProperty(layerId, "line-width", width);
- map.setPaintProperty(layerId, "line-opacity", opacity);
- map.setPaintProperty(layerId, "line-dasharray", dashArray);
- }, [isLoaded, map, layerId, color, width, opacity, dashArray]);
+ map.setPaintProperty(layerId, "line-color", resolvedColor);
+ map.setPaintProperty(layerId, "line-width", resolvedWidth);
+ map.setPaintProperty(layerId, "line-opacity", resolvedOpacity);
+ map.setPaintProperty(layerId, "line-dasharray", resolvedDashArray);
+ }, [
+ isLoaded,
+ map,
+ layerId,
+ resolvedColor,
+ resolvedWidth,
+ resolvedOpacity,
+ resolvedDashArray,
+ ]);
+
+ // Raise the active route (and anything it owns) above its siblings. With a
+ // `beforeId` it moves to the top of the group below that layer instead.
+ // Siblings that mount later (alternatives arriving from a request) add
+ // their layers on top, so the raise also re-runs on style changes.
+ useEffect(() => {
+ if (!ready || !map || !active) return;
+
+ // Which layers exist, ignoring their order.
+ let lastLayerSet = "";
+
+ const raise = () => {
+ const order = map.getLayersOrder();
+
+ // React only when layers are added or removed, never to a reorder.
+ // `moveLayer` fires "styledata" itself, so reacting to order would loop
+ // — with one route against its own move, and with two `active` routes
+ // against each other, forever.
+ const layerSet = [...order].sort().join("|");
+ if (layerSet === lastLayerSet) return;
+ lastLayerSet = layerSet;
+
+ const owned = [layerId, ...childLayersRef.current].filter((entry) =>
+ map.getLayer(entry),
+ );
+ if (owned.length === 0) return;
+
+ const before = resolveBeforeId(map, beforeId);
+ const limit = before ? order.indexOf(before) : order.length;
+ const top = order.slice(Math.max(0, limit - owned.length), limit);
+ if (owned.every((entry, index) => top[index] === entry)) return;
+
+ for (const entry of owned) map.moveLayer(entry, before);
+ };
+
+ raise();
+ map.on("styledata", raise);
+
+ return () => {
+ map.off("styledata", raise);
+ };
+ }, [ready, map, active, layerId, beforeId]);
// Handle click and hover events
useEffect(() => {
@@ -1240,9 +1524,184 @@ function MapRoute({
interactive,
]);
+ const contextValue = useMemo(
+ () => ({
+ id,
+ ready,
+ coordinates,
+ traveled,
+ progress,
+ color: resolvedColor,
+ width: resolvedWidth,
+ opacity: resolvedOpacity,
+ dashArray: resolvedDashArray,
+ beforeId,
+ pointAt,
+ registerLayer,
+ }),
+ [
+ id,
+ ready,
+ coordinates,
+ traveled,
+ progress,
+ resolvedColor,
+ resolvedWidth,
+ resolvedOpacity,
+ resolvedDashArray,
+ beforeId,
+ pointAt,
+ registerLayer,
+ ],
+ );
+
+ return (
+ <RouteContext.Provider value={contextValue}>
+ {children}
+ </RouteContext.Provider>
+ );
+}
+
+type RouteProgressProps = {
+ /** Line color for the traveled portion. Defaults to the route's color. */
+ color?: string;
+ /** Line width in pixels. Defaults to the route's width. */
+ width?: number;
+ /** Line opacity from 0 to 1. Defaults to the route's opacity. */
+ opacity?: number;
+ /** Dash pattern [dash length, gap length] for dashed lines. */
+ dashArray?: [number, number];
+};
+
+/**
+ * Draws the traveled portion of the parent `MapRoute` on top of the base line.
+ * Renders nothing until the route has a `progress` value.
+ */
+function RouteProgress({
+ color,
+ width,
+ opacity,
+ dashArray,
+}: RouteProgressProps) {
+ const { map, isLoaded } = useMap();
+ const route = useMapRoute();
+ const { ready, traveled, registerLayer, beforeId } = route;
+
+ const sourceId = `route-progress-source-${route.id}`;
+ const layerId = `route-progress-layer-${route.id}`;
+
+ const resolvedColor = color ?? route.color;
+ const resolvedWidth = width ?? route.width;
+ const resolvedOpacity = opacity ?? route.opacity;
+
+ // Added only once the parent's layer exists, so this always paints above it.
+ useEffect(() => {
+ if (!ready || !map) return;
+
+ map.addSource(sourceId, {
+ type: "geojson",
+ data: {
+ type: "Feature",
+ properties: {},
+ geometry: { type: "LineString", coordinates: [] },
+ },
+ });
+
+ // Sits directly above the parent line: same `beforeId` boundary, added
+ // after it.
+ map.addLayer(
+ {
+ id: layerId,
+ type: "line",
+ source: sourceId,
+ layout: { "line-join": "round", "line-cap": "round" },
+ paint: {
+ "line-color": resolvedColor,
+ "line-width": resolvedWidth,
+ "line-opacity": resolvedOpacity,
+ ...(dashArray && { "line-dasharray": dashArray }),
+ },
+ },
+ resolveBeforeId(map, beforeId),
+ );
+
+ const unregister = registerLayer(layerId);
+
+ return () => {
+ unregister();
+ try {
+ if (map.getLayer(layerId)) map.removeLayer(layerId);
+ if (map.getSource(sourceId)) map.removeSource(sourceId);
+ } catch {
+ // ignore
+ }
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ready, map]);
+
+ useEffect(() => {
+ if (!ready || !map) return;
+
+ const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;
+ if (source) {
+ source.setData({
+ type: "Feature",
+ properties: {},
+ geometry: {
+ type: "LineString",
+ coordinates: traveled.length < 2 ? [] : traveled,
+ },
+ });
+ }
+ }, [ready, map, traveled, sourceId]);
+
+ useEffect(() => {
+ if (!isLoaded || !map || !map.getLayer(layerId)) return;
+
+ map.setPaintProperty(layerId, "line-color", resolvedColor);
+ map.setPaintProperty(layerId, "line-width", resolvedWidth);
+ map.setPaintProperty(layerId, "line-opacity", resolvedOpacity);
+ map.setPaintProperty(layerId, "line-dasharray", dashArray);
+ }, [
+ isLoaded,
+ map,
+ layerId,
+ resolvedColor,
+ resolvedWidth,
+ resolvedOpacity,
+ dashArray,
+ ]);
+
return null;
}
+type RouteMarkerProps = {
+ /**
+ * Where to pin the marker: an endpoint, the route's progress point, or a
+ * 0-1 fraction along the line.
+ */
+ at: RouteAnchor;
+} & Omit<MapMarkerProps, "longitude" | "latitude">;
+
+/**
+ * A `MapMarker` anchored to a position along the parent `MapRoute`. Takes the
+ * same children as `MapMarker` (`MarkerContent`, `MarkerPopup`, ...).
+ */
+function RouteMarker({ at, children, ...markerProps }: RouteMarkerProps) {
+ const { pointAt } = useMapRoute();
+ const position = pointAt(at);
+
+ // Nothing to pin to yet: the route is empty (coordinates usually arrive
+ // from a request), or `at="progress"` is waiting on a `progress` value.
+ if (!position) return null;
+
+ return (
+ <MapMarker longitude={position[0]} latitude={position[1]} {...markerProps}>
+ {children}
+ </MapMarker>
+ );
+}
+
type MapGeoJSONData<
P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties,
> =
@@ -2203,6 +2662,9 @@ export {
MapPopup,
MapControls,
MapRoute,
+ RouteProgress,
+ RouteMarker,
+ useMapRoute,
MapArc,
MapGeoJSON,
MapClusterLayer,
@@ -2226,6 +2688,9 @@ export type {
MapControlsProps,
MapPopupProps,
MapRouteProps,
+ RouteProgressProps,
+ RouteMarkerProps,
+ RouteAnchor,
MapArcProps,
MapGeoJSONProps,
MapClusterLayerProps,