Skip to content

armgit / mapcn

Public Imported from GitHub
0

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

TypeScript

Add controlled viewport API, new examples, and docs UI improvements

Anmoldeep Singh61727bb8afe4
diff --git a/public/maps/map.json b/public/maps/map.json
index 07384b8..9444244 100644
--- a/public/maps/map.json
+++ b/public/maps/map.json
@@ -11,7 +11,7 @@
"files": [
{
"path": "src/registry/map.tsx",
- "content": "\"use client\";\n\nimport MapLibreGL, { type PopupOptions, type MarkerOptions } from \"maplibre-gl\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\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\n// Check document class for theme (works with next-themes, etc.)\nfunction getDocumentTheme(): Theme | null {\n if (typeof document === \"undefined\") return null;\n if (document.documentElement.classList.contains(\"dark\")) return \"dark\";\n if (document.documentElement.classList.contains(\"light\")) return \"light\";\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\"): \"light\" | \"dark\" {\n const [detectedTheme, setDetectedTheme] = useState<\"light\" | \"dark\">(\n () => getDocumentTheme() ?? getSystemTheme()\n );\n\n useEffect(() => {\n if (themeProp) return; // Skip detection if theme is provided via prop\n\n // Watch for document class changes (e.g., next-themes toggling dark class)\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\"],\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};\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\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\ntype MapStyleOption = string | MapLibreGL.StyleSpecification;\n\ntype Theme = \"light\" | \"dark\";\n\ntype MapProps = {\n children?: ReactNode;\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 /** Map projection type. Use `{ type: \"globe\" }` for 3D globe view. */\n projection?: MapLibreGL.ProjectionSpecification;\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\n\ntype MapRef = MapLibreGL.Map;\n\nconst DefaultLoader = () => (\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"flex gap-1\">\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:150ms]\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:300ms]\" />\n </div>\n </div>\n);\n\nconst Map = forwardRef<MapRef, MapProps>(function Map(\n { children, theme: themeProp, styles, projection, ...props },\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 currentStyleRef = useRef<MapStyleOption | null>(null);\n const styleTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const resolvedTheme = useResolvedTheme(themeProp);\n\n const mapStyles = useMemo(\n () => ({\n dark: styles?.dark ?? defaultStyles.dark,\n light: styles?.light ?? defaultStyles.light,\n }),\n [styles]\n );\n\n useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);\n\n const clearStyleTimeout = useCallback(() => {\n if (styleTimeoutRef.current) {\n clearTimeout(styleTimeoutRef.current);\n styleTimeoutRef.current = null;\n }\n }, []);\n\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 });\n\n const styleDataHandler = () => {\n clearStyleTimeout();\n // Delay to ensure style is fully processed before allowing layer operations\n // This is a workaround to avoid race conditions with the style loading\n // else we have to force update every layer on setStyle change\n styleTimeoutRef.current = setTimeout(() => {\n setIsStyleLoaded(true);\n if (projection) {\n map.setProjection(projection);\n }\n }, 100);\n };\n const loadHandler = () => setIsLoaded(true);\n\n map.on(\"load\", loadHandler);\n map.on(\"styledata\", styleDataHandler);\n setMapInstance(map);\n\n return () => {\n clearStyleTimeout();\n map.off(\"load\", loadHandler);\n map.off(\"styledata\", styleDataHandler);\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 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 clearStyleTimeout();\n currentStyleRef.current = newStyle;\n setIsStyleLoaded(false);\n\n mapInstance.setStyle(newStyle, { diff: true });\n }, [mapInstance, resolvedTheme, mapStyles, clearStyleTimeout]);\n\n const contextValue = useMemo(\n () => ({\n map: mapInstance,\n isLoaded: isLoaded && isStyleLoaded,\n }),\n [mapInstance, isLoaded, isStyleLoaded]\n );\n\n return (\n <MapContext.Provider value={contextValue}>\n <div ref={containerRef} className=\"relative w-full h-full\">\n {!isLoaded && <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 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) => onClick?.(e);\n const handleMouseEnter = (e: MouseEvent) => onMouseEnter?.(e);\n const handleMouseLeave = (e: MouseEvent) => 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 onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDrag = () => {\n const lngLat = markerInstance.getLngLat();\n onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDragEnd = () => {\n const lngLat = markerInstance.getLngLat();\n 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 if (\n marker.getLngLat().lng !== longitude ||\n marker.getLngLat().lat !== latitude\n ) {\n marker.setLngLat([longitude, latitude]);\n }\n if (marker.isDraggable() !== draggable) {\n marker.setDraggable(draggable);\n }\n\n const currentOffset = marker.getOffset();\n const newOffset = markerOptions.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() !== markerOptions.rotation) {\n marker.setRotation(markerOptions.rotation ?? 0);\n }\n if (marker.getRotationAlignment() !== markerOptions.rotationAlignment) {\n marker.setRotationAlignment(markerOptions.rotationAlignment ?? \"auto\");\n }\n if (marker.getPitchAlignment() !== markerOptions.pitchAlignment) {\n marker.setPitchAlignment(markerOptions.pitchAlignment ?? \"auto\");\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\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 prevPopupOptions = useRef(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 if (popup.isOpen()) {\n const prev = prevPopupOptions.current;\n\n if (prev.offset !== popupOptions.offset) {\n popup.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popup.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n prevPopupOptions.current = popupOptions;\n }\n\n const handleClose = () => popup.remove();\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\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 prevTooltipOptions = useRef(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 if (tooltip.isOpen()) {\n const prev = prevTooltipOptions.current;\n\n if (prev.offset !== popupOptions.offset) {\n tooltip.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n tooltip.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n prevTooltipOptions.current = popupOptions;\n }\n\n return createPortal(\n <div\n className={cn(\n \"rounded-md bg-foreground px-2 py-1 text-xs text-background shadow-md animate-in fade-in-0 zoom-in-95\",\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-[10px] font-medium text-foreground\",\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=\"flex flex-col rounded-md border border-border bg-background shadow-sm overflow-hidden [&>button:not(:last-child)]:border-b [&>button:not(:last-child)]:border-border\">\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 items-center justify-center size-8 hover:bg-accent dark:hover:bg-accent/40 transition-colors\",\n disabled && \"opacity-50 pointer-events-none cursor-not-allowed\"\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 setWaitingForLocation(true);\n if (\"geolocation\" in navigator) {\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 );\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 transition-transform duration-200\"\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 popupOptionsRef = useRef(popupOptions);\n const container = useMemo(() => document.createElement(\"div\"), []);\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 = () => onClose?.();\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 if (popup.isOpen()) {\n const prev = popupOptionsRef.current;\n\n if (\n popup.getLngLat().lng !== longitude ||\n popup.getLngLat().lat !== latitude\n ) {\n popup.setLngLat([longitude, latitude]);\n }\n\n if (prev.offset !== popupOptions.offset) {\n popup.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popup.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n popupOptionsRef.current = popupOptions;\n }\n\n const handleClose = () => {\n popup.remove();\n onClose?.();\n };\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\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 if (dashArray) {\n map.setPaintProperty(layerId, \"line-dasharray\", dashArray);\n }\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 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: [\"#51bbd6\", \"#f1f075\", \"#f28cb1\"]) */\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\nfunction MapClusterLayer<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties\n>({\n data,\n clusterMaxZoom = 14,\n clusterRadius = 50,\n clusterColors = [\"#51bbd6\", \"#f1f075\", \"#f28cb1\"],\n clusterThresholds = [100, 750],\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 },\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-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\": 6,\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 MapClusterLayer,\n};\n\nexport type { MapRef };\n",
+ "content": "\"use client\";\n\nimport MapLibreGL, { type PopupOptions, type MarkerOptions } from \"maplibre-gl\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\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\n// Check document class for theme (works with next-themes, etc.)\nfunction getDocumentTheme(): Theme | null {\n if (typeof document === \"undefined\") return null;\n if (document.documentElement.classList.contains(\"dark\")) return \"dark\";\n if (document.documentElement.classList.contains(\"light\")) return \"light\";\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\"): \"light\" | \"dark\" {\n const [detectedTheme, setDetectedTheme] = useState<\"light\" | \"dark\">(\n () => getDocumentTheme() ?? getSystemTheme()\n );\n\n useEffect(() => {\n if (themeProp) return; // Skip detection if theme is provided via prop\n\n // Watch for document class changes (e.g., next-themes toggling dark class)\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\"],\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};\n\nconst MapContext = createContext<MapContextValue | null>(null);\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\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\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\ntype MapStyleOption = string | MapLibreGL.StyleSpecification;\n\ntype Theme = \"light\" | \"dark\";\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 MapProps = {\n children?: ReactNode;\n /** Additional CSS classes for the map container */\n className?: string;\n /** Custom loading component. Defaults to animated dots */\n loader?: ReactNode;\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 /** 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 * When used with `viewport` prop, enables controlled mode.\n * Receives the new viewport state to update your state.\n */\n onViewportChange?: (viewport: MapViewport) => void;\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\n\ntype MapRef = MapLibreGL.Map;\n\nconst DefaultLoader = () => (\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"flex gap-1\">\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:150ms]\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:300ms]\" />\n </div>\n </div>\n);\n\nconst Map = forwardRef<MapRef, MapProps>(function Map(\n {\n children,\n className,\n loader,\n theme: themeProp,\n styles,\n projection,\n viewport,\n onViewportChange,\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 currentStyleRef = useRef<MapStyleOption | null>(null);\n const styleTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\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 mapStyles = useMemo(\n () => ({\n dark: styles?.dark ?? defaultStyles.dark,\n light: styles?.light ?? defaultStyles.light,\n }),\n [styles]\n );\n\n // Expose the map instance to the parent component\n useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);\n\n const clearStyleTimeout = useCallback(() => {\n if (styleTimeoutRef.current) {\n clearTimeout(styleTimeoutRef.current);\n styleTimeoutRef.current = null;\n }\n }, []);\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 styleDataHandler = () => {\n clearStyleTimeout();\n // Delay to ensure style is fully processed before allowing layer operations\n // This is a workaround to avoid race conditions with the style loading\n // else we have to force update every layer on setStyle change\n styleTimeoutRef.current = setTimeout(() => {\n setIsStyleLoaded(true);\n if (projection) {\n map.setProjection(projection);\n }\n }, 100);\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(\"styledata\", styleDataHandler);\n map.on(\"move\", handleMove);\n setMapInstance(map);\n\n return () => {\n clearStyleTimeout();\n map.off(\"load\", loadHandler);\n map.off(\"styledata\", styleDataHandler);\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 internalUpdateRef.current = true;\n mapInstance.jumpTo({\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 internalUpdateRef.current = false;\n }, [mapInstance, isControlled, viewport]);\n\n // Handle style change\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 clearStyleTimeout();\n currentStyleRef.current = newStyle;\n setIsStyleLoaded(false);\n\n mapInstance.setStyle(newStyle, { diff: true });\n }, [mapInstance, resolvedTheme, mapStyles, clearStyleTimeout]);\n\n const contextValue = useMemo(\n () => ({\n map: mapInstance,\n isLoaded: isLoaded && isStyleLoaded,\n }),\n [mapInstance, isLoaded, isStyleLoaded]\n );\n\n return (\n <MapContext.Provider value={contextValue}>\n <div\n ref={containerRef}\n className={cn(\"relative w-full h-full\", className)}\n >\n {!isLoaded && (loader ?? <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 if (\n marker.getLngLat().lng !== longitude ||\n marker.getLngLat().lat !== latitude\n ) {\n marker.setLngLat([longitude, latitude]);\n }\n if (marker.isDraggable() !== draggable) {\n marker.setDraggable(draggable);\n }\n\n const currentOffset = marker.getOffset();\n const newOffset = markerOptions.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() !== markerOptions.rotation) {\n marker.setRotation(markerOptions.rotation ?? 0);\n }\n if (marker.getRotationAlignment() !== markerOptions.rotationAlignment) {\n marker.setRotationAlignment(markerOptions.rotationAlignment ?? \"auto\");\n }\n if (marker.getPitchAlignment() !== markerOptions.pitchAlignment) {\n marker.setPitchAlignment(markerOptions.pitchAlignment ?? \"auto\");\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\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 prevPopupOptions = useRef(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 if (popup.isOpen()) {\n const prev = prevPopupOptions.current;\n\n if (prev.offset !== popupOptions.offset) {\n popup.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popup.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n prevPopupOptions.current = popupOptions;\n }\n\n const handleClose = () => popup.remove();\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\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 prevTooltipOptions = useRef(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 if (tooltip.isOpen()) {\n const prev = prevTooltipOptions.current;\n\n if (prev.offset !== popupOptions.offset) {\n tooltip.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n tooltip.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n prevTooltipOptions.current = popupOptions;\n }\n\n return createPortal(\n <div\n className={cn(\n \"rounded-md bg-foreground px-2 py-1 text-xs text-background shadow-md animate-in fade-in-0 zoom-in-95\",\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-[10px] font-medium text-foreground\",\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=\"flex flex-col rounded-md border border-border bg-background shadow-sm overflow-hidden [&>button:not(:last-child)]:border-b [&>button:not(:last-child)]:border-border\">\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 items-center justify-center size-8 hover:bg-accent dark:hover:bg-accent/40 transition-colors\",\n disabled && \"opacity-50 pointer-events-none cursor-not-allowed\"\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 setWaitingForLocation(true);\n if (\"geolocation\" in navigator) {\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 );\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 transition-transform duration-200\"\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 popupOptionsRef = useRef(popupOptions);\n const onCloseRef = useRef(onClose);\n onCloseRef.current = onClose;\n const container = useMemo(() => document.createElement(\"div\"), []);\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 if (popup.isOpen()) {\n const prev = popupOptionsRef.current;\n\n if (\n popup.getLngLat().lng !== longitude ||\n popup.getLngLat().lat !== latitude\n ) {\n popup.setLngLat([longitude, latitude]);\n }\n\n if (prev.offset !== popupOptions.offset) {\n popup.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popup.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n popupOptionsRef.current = popupOptions;\n }\n\n const handleClose = () => {\n popup.remove();\n };\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\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 if (dashArray) {\n map.setPaintProperty(layerId, \"line-dasharray\", dashArray);\n }\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 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: [\"#22c55e\", \"#eab308\", \"#ef4444\"]) */\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\nfunction MapClusterLayer<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties\n>({\n data,\n clusterMaxZoom = 14,\n clusterRadius = 50,\n clusterColors = [\"#22c55e\", \"#eab308\", \"#ef4444\"],\n clusterThresholds = [100, 750],\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\": 1,\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-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 MapClusterLayer,\n};\n\nexport type { MapRef, MapViewport };\n",
"type": "registry:ui",
"target": "components/ui/map.tsx"
}
diff --git a/src/app/(home)/_components/hero.tsx b/src/app/(home)/_components/hero.tsx
index cb0f3e8..0b924ee 100644
--- a/src/app/(home)/_components/hero.tsx
+++ b/src/app/(home)/_components/hero.tsx
@@ -34,18 +34,14 @@ function CopyButton({ text }: { text: string }) {
export function Hero() {
return (
<div className="relative">
- <div className="absolute inset-0 -z-10 overflow-hidden">
+ <div className="absolute inset-x-0 -inset-y-32 -z-10 overflow-hidden">
<div
- className="absolute inset-0 opacity-[0.4] dark:opacity-[0.15]"
+ className="absolute inset-0 opacity-[0.3] dark:opacity-[0.15]"
style={{
backgroundImage: `radial-gradient(circle, currentColor 1px, transparent 1px)`,
backgroundSize: "24px 24px",
}}
/>
-
- <div className="absolute -top-40 -right-40 size-96 bg-emerald-500/10 rounded-full blur-3xl" />
- <div className="absolute -bottom-40 -left-40 size-96 bg-sky-500/10 rounded-full blur-3xl" />
-
<div className="absolute inset-0 bg-linear-to-b from-background via-transparent to-background" />
</div>
@@ -63,11 +59,11 @@ export function Hero() {
</p>
<div className="mt-8 animate-fade-up delay-300 w-full max-w-xl">
- <div className="bg-card border border-border rounded-lg shadow-sm overflow-hidden">
+ <div className="bg-card border border-border rounded-lg shadow-xs overflow-hidden">
<div className="flex items-center gap-1.5 px-3 py-2 border-b border-border/50">
- <span className="size-2.5 rounded-full bg-red-500/40" />
- <span className="size-2.5 rounded-full bg-yellow-500/40" />
- <span className="size-2.5 rounded-full bg-green-500/40" />
+ <span className="size-2 rounded-full bg-foreground/20" />
+ <span className="size-2 rounded-full bg-foreground/20" />
+ <span className="size-2 rounded-full bg-foreground/20" />
</div>
<div className="flex items-center gap-3 px-4 py-3 font-mono text-sm">
@@ -88,9 +84,7 @@ export function Hero() {
</Link>
</Button>
<Button variant="ghost" size="lg" asChild>
- <Link href="/docs/basic-map" className="text-muted-foreground">
- View Components
- </Link>
+ <Link href="/docs/basic-map">View Components</Link>
</Button>
</div>
</div>
diff --git a/src/app/(home)/page.tsx b/src/app/(home)/page.tsx
index 7849d90..152392d 100644
--- a/src/app/(home)/page.tsx
+++ b/src/app/(home)/page.tsx
@@ -4,15 +4,15 @@ import { ExamplesGrid } from "./_components/examples-grid";
export default function Page() {
return (
- <div className="flex flex-col pb-28">
+ <div className="flex flex-col pb-32">
<Header className="border-b border-transparent" />
<main className="flex-1">
- <section className="relative w-full py-20">
+ <section className="relative w-full py-24">
<Hero />
</section>
- <section className="container px-6">
+ <section className="container">
<ExamplesGrid />
</section>
</main>
diff --git a/src/app/docs/_components/docs-sidebar.tsx b/src/app/docs/_components/docs-sidebar.tsx
index f712b2b..035152b 100644
--- a/src/app/docs/_components/docs-sidebar.tsx
+++ b/src/app/docs/_components/docs-sidebar.tsx
@@ -33,7 +33,7 @@ export function DocsSidebar() {
<SidebarContent className="pt-8 no-scrollbar overflow-x-hidden">
{docsNavigation.map((group) => (
<SidebarGroup key={group.title} className="px-1">
- <SidebarGroupLabel className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
+ <SidebarGroupLabel className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80">
{group.title}
</SidebarGroupLabel>
<SidebarGroupContent>
diff --git a/src/app/docs/_components/docs-toc.tsx b/src/app/docs/_components/docs-toc.tsx
index 928fa7d..8444182 100644
--- a/src/app/docs/_components/docs-toc.tsx
+++ b/src/app/docs/_components/docs-toc.tsx
@@ -57,28 +57,33 @@ export function DocsToc({ items, className }: DocsTocProps) {
}
return (
- <div className={cn("flex flex-col gap-2.5 text-sm", className)}>
- <p className="text-muted-foreground text-xs font-medium mb-1">
- On This Page
- </p>
- {items.map((item) => (
- <a
- key={item.slug}
- href={`#${item.slug}`}
- onClick={(e) => {
- e.preventDefault();
- document.getElementById(item.slug)?.scrollIntoView({
- behavior: "smooth",
- });
- }}
- className={cn(
- "text-muted-foreground hover:text-foreground text-[0.8rem] no-underline transition-colors",
- item.slug === activeHeading && "text-foreground"
- )}
- >
- {item.title}
- </a>
- ))}
+ <div className={cn("flex flex-col gap-1", className)}>
+ <p className="text-foreground text-xs font-medium mb-2">On This Page</p>
+ <div className="relative">
+ <div className="absolute left-0 top-1 bottom-1 w-px bg-border" />
+ <div className="flex flex-col gap-1">
+ {items.map((item) => {
+ const isActive = item.slug === activeHeading;
+ return (
+ <a
+ key={item.slug}
+ href={`#${item.slug}`}
+ className={cn(
+ "relative pl-3 py-1 text-[13px] no-underline transition-colors",
+ isActive
+ ? "text-foreground"
+ : "text-muted-foreground hover:text-foreground"
+ )}
+ >
+ {isActive && (
+ <div className="absolute left-0 top-1 bottom-1 w-px bg-foreground rounded-full" />
+ )}
+ {item.title}
+ </a>
+ );
+ })}
+ </div>
+ </div>
</div>
);
}
diff --git a/src/app/docs/_components/docs.tsx b/src/app/docs/_components/docs.tsx
index 7b2560c..ce197ad 100644
--- a/src/app/docs/_components/docs.tsx
+++ b/src/app/docs/_components/docs.tsx
@@ -30,7 +30,7 @@ interface DocsHeaderProps {
export function DocsHeader({ title, description }: DocsHeaderProps) {
return (
- <div className="space-y-2">
+ <div className="space-y-3">
<h1 className="text-3xl font-semibold tracking-tight text-foreground">
{title}
</h1>
@@ -61,17 +61,17 @@ export function DocsLayout({
}: DocsLayoutProps) {
return (
<div className="flex gap-8">
- <div className="flex-1 min-w-0 max-w-[720px] mx-auto py-8 pb-20">
+ <div className="flex-1 min-w-0 max-w-[720px] mx-auto pt-10 pb-20">
<DocsHeader title={title} description={description} />
- <div className="mt-10 space-y-10">{children}</div>
+ <div className="mt-12 space-y-12">{children}</div>
{(prev || next) && (
- <div className="flex items-center justify-between gap-4 mt-12">
+ <div className="flex items-center justify-between gap-4 mt-16">
{prev ? (
<Link
href={prev.href}
- className="group flex flex-col items-start gap-1"
+ className="group flex flex-col items-start gap-1.5"
>
<span className="text-xs text-muted-foreground">Previous</span>
<span className="text-sm font-medium group-hover:underline underline-offset-4">
@@ -84,7 +84,7 @@ export function DocsLayout({
{next && (
<Link
href={next.href}
- className="group flex flex-col items-end gap-1"
+ className="group flex flex-col items-end gap-1.5"
>
<span className="text-xs text-muted-foreground">Next</span>
<span className="text-sm font-medium group-hover:underline underline-offset-4">
@@ -96,7 +96,7 @@ export function DocsLayout({
)}
</div>
- <aside className="hidden xl:block w-44 shrink-0">
+ <aside className="hidden xl:block w-48 shrink-0">
<nav className="sticky top-28">
{toc.length > 0 && <DocsToc items={toc} />}
</nav>
@@ -114,13 +114,13 @@ interface DocsSectionProps {
export function DocsSection({ title, children }: DocsSectionProps) {
const id = title ? slugify(title) : undefined;
return (
- <section className="space-y-4 scroll-mt-20" id={id}>
+ <section className="space-y-5 scroll-mt-24" id={id}>
{title && (
<h2 className="text-xl font-semibold tracking-tight text-foreground">
{title}
</h2>
)}
- <div className="text-foreground/80 text-base sm:text-[15px] leading-7 space-y-3 [&_p]:leading-7 [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:space-y-1.5 [&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:space-y-1.5 [&_li]:leading-7 [&_strong]:text-foreground [&_strong]:font-medium [&_em]:text-muted-foreground">
+ <div className="text-foreground/80 text-[15px] leading-7 space-y-4 [&_p]:leading-7 [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:space-y-2 [&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:space-y-2 [&_li]:leading-7 [&_strong]:text-foreground [&_strong]:font-medium [&_em]:text-muted-foreground">
{children}
</div>
</section>
@@ -134,7 +134,7 @@ interface DocsNoteProps {
export function DocsNote({ children }: DocsNoteProps) {
return (
- <div className="rounded-lg border bg-muted/40 px-4 py-3 text-[14px] leading-relaxed text-foreground/70 [&_strong]:text-foreground [&_strong]:font-medium">
+ <div className="rounded-lg border bg-muted/30 px-5 py-4 text-[14px] leading-relaxed text-foreground/70 [&_strong]:text-foreground [&_strong]:font-medium">
{children}
</div>
);
diff --git a/src/app/docs/_components/examples/cluster-example.tsx b/src/app/docs/_components/examples/cluster-example.tsx
index 336523b..3ca7ef5 100644
--- a/src/app/docs/_components/examples/cluster-example.tsx
+++ b/src/app/docs/_components/examples/cluster-example.tsx
@@ -22,8 +22,8 @@ export default function ClusterExample() {
data="https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
clusterRadius={50}
clusterMaxZoom={14}
- clusterColors={["#22c55e", "#eab308", "#ef4444"]}
- pointColor="#3b82f6"
+ clusterColors={["#1d8cf8", "#6d5dfc", "#e23670"]}
+ pointColor="#1d8cf8"
onPointClick={(feature, coordinates) => {
setSelectedPoint({
coordinates,
diff --git a/src/app/docs/_components/examples/controlled-map-example.tsx b/src/app/docs/_components/examples/controlled-map-example.tsx
new file mode 100644
index 0000000..a4e156c
--- /dev/null
+++ b/src/app/docs/_components/examples/controlled-map-example.tsx
@@ -0,0 +1,41 @@
+"use client";
+
+import { useState } from "react";
+import { Map, type MapViewport } from "@/registry/map";
+
+export function ControlledMapExample() {
+ const [viewport, setViewport] = useState<MapViewport>({
+ center: [-74.006, 40.7128],
+ zoom: 8,
+ bearing: 0,
+ pitch: 0,
+ });
+
+ return (
+ <div className="h-[400px] relative w-full">
+ <Map viewport={viewport} onViewportChange={setViewport} />
+ <div className="absolute top-2 left-2 z-10 flex flex-wrap gap-x-3 gap-y-1 text-xs font-mono bg-background/80 backdrop-blur px-2 py-1.5 rounded border">
+ <span>
+ <span className="text-muted-foreground">lng:</span>{" "}
+ {viewport.center[0].toFixed(3)}
+ </span>
+ <span>
+ <span className="text-muted-foreground">lat:</span>{" "}
+ {viewport.center[1].toFixed(3)}
+ </span>
+ <span>
+ <span className="text-muted-foreground">zoom:</span>{" "}
+ {viewport.zoom.toFixed(1)}
+ </span>
+ <span>
+ <span className="text-muted-foreground">bearing:</span>{" "}
+ {viewport.bearing.toFixed(1)}°
+ </span>
+ <span>
+ <span className="text-muted-foreground">pitch:</span>{" "}
+ {viewport.pitch.toFixed(1)}°
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/docs/_components/examples/custom-style-example.tsx b/src/app/docs/_components/examples/custom-style-example.tsx
new file mode 100644
index 0000000..4ed6f3e
--- /dev/null
+++ b/src/app/docs/_components/examples/custom-style-example.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import { Map, type MapRef } from "@/registry/map";
+
+const styles = {
+ default: undefined,
+ openstreetmap: "https://tiles.openfreemap.org/styles/bright",
+ openstreetmap3d: "https://tiles.openfreemap.org/styles/liberty",
+};
+
+type StyleKey = keyof typeof styles;
+
+export function CustomStyleExample() {
+ const mapRef = useRef<MapRef>(null);
+ const [style, setStyle] = useState<StyleKey>("default");
+ const selectedStyle = styles[style];
+ const is3D = style === "openstreetmap3d";
+
+ useEffect(() => {
+ mapRef.current?.easeTo({ pitch: is3D ? 60 : 0, duration: 500 });
+ }, [is3D]);
+
+ return (
+ <div className="h-[400px] relative w-full">
+ <Map
+ ref={mapRef}
+ center={[-0.1276, 51.5074]}
+ zoom={15}
+ styles={
+ selectedStyle
+ ? { light: selectedStyle, dark: selectedStyle }
+ : undefined
+ }
+ />
+ <div className="absolute top-2 right-2 z-10">
+ <select
+ value={style}
+ onChange={(e) => setStyle(e.target.value as StyleKey)}
+ className="bg-background text-foreground border rounded-md px-2 py-1 text-sm shadow"
+ >
+ <option value="default">Default (Carto)</option>
+ <option value="openstreetmap">OpenStreetMap</option>
+ <option value="openstreetmap3d">OpenStreetMap 3D</option>
+ </select>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/docs/advanced-usage/page.tsx b/src/app/docs/advanced-usage/page.tsx
index cbef3a6..007b2b0 100644
--- a/src/app/docs/advanced-usage/page.tsx
+++ b/src/app/docs/advanced-usage/page.tsx
@@ -130,23 +130,21 @@ export default function AdvancedPage() {
map&apos;s pitch and bearing, and listen to map events to display
real-time values.
</p>
+ <ComponentPreview code={advancedSource}>
+ <AdvancedUsageExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={advancedSource}>
- <AdvancedUsageExample />
- </ComponentPreview>
-
<DocsSection title="Example: Custom GeoJSON Layer">
<p>
Add custom GeoJSON data as layers with fill and outline styles. This
example shows NYC parks with hover interactions.
</p>
+ <ComponentPreview code={customLayerSource}>
+ <CustomLayerExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={customLayerSource}>
- <CustomLayerExample />
- </ComponentPreview>
-
<DocsSection title="Example: Markers via Layers">
<p>
When displaying hundreds or thousands of markers, use GeoJSON layers
@@ -154,12 +152,11 @@ export default function AdvancedPage() {
approach renders markers on the WebGL canvas, providing significantly
better performance.
</p>
+ <ComponentPreview code={layerMarkersSource}>
+ <LayerMarkersExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={layerMarkersSource}>
- <LayerMarkersExample />
- </ComponentPreview>
-
<DocsSection title="Extend to Build">
<p>You can extend this to build custom features like:</p>
<ul>
diff --git a/src/app/docs/api-reference/page.tsx b/src/app/docs/api-reference/page.tsx
index 33a0c5e..225f7c5 100644
--- a/src/app/docs/api-reference/page.tsx
+++ b/src/app/docs/api-reference/page.tsx
@@ -101,6 +101,17 @@ export default function ApiReferencePage() {
description:
"Child components (markers, popups, controls, routes).",
},
+ {
+ name: "className",
+ type: "string",
+ description: "Additional CSS classes for the map container.",
+ },
+ {
+ name: "loader",
+ type: "ReactNode",
+ description:
+ "Custom loading component. Defaults to animated dots. Pass null to disable.",
+ },
{
name: "theme",
type: '"light" | "dark"',
@@ -119,6 +130,18 @@ export default function ApiReferencePage() {
description:
'Map projection type. Use { type: "globe" } for 3D globe view.',
},
+ {
+ name: "viewport",
+ type: "Partial<MapViewport>",
+ description:
+ "Controlled viewport state. When used with onViewportChange, enables controlled mode. Can also be used alone for initial viewport.",
+ },
+ {
+ name: "onViewportChange",
+ type: "(viewport: MapViewport) => void",
+ description:
+ "Callback fired continuously as the viewport changes (during pan, zoom, rotate). When used with viewport prop, enables controlled mode where viewport is driven by your state.",
+ },
]}
/>
</DocsSection>
@@ -569,7 +592,7 @@ export default function ApiReferencePage() {
{
name: "clusterColors",
type: "[string, string, string]",
- default: '["#51bbd6", "#f1f075", "#f28cb1"]',
+ default: '["#22c55e", "#eab308", "#ef4444"]',
description:
"Colors for cluster circles: [small, medium, large] based on point count.",
},
diff --git a/src/app/docs/basic-map/page.tsx b/src/app/docs/basic-map/page.tsx
index f90a3df..e566ab0 100644
--- a/src/app/docs/basic-map/page.tsx
+++ b/src/app/docs/basic-map/page.tsx
@@ -1,6 +1,13 @@
-import { DocsLayout, DocsSection, DocsCode } from "../_components/docs";
+import {
+ DocsLayout,
+ DocsSection,
+ DocsCode,
+ DocsLink,
+} from "../_components/docs";
import { ComponentPreview } from "../_components/component-preview";
import { BasicMapExample } from "../_components/examples/basic-map-example";
+import { ControlledMapExample } from "../_components/examples/controlled-map-example";
+import { CustomStyleExample } from "../_components/examples/custom-style-example";
import { getExampleSource } from "@/lib/get-example-source";
import { Metadata } from "next";
@@ -10,6 +17,8 @@ export const metadata: Metadata = {
export default function BasicMapPage() {
const basicMapSource = getExampleSource("basic-map-example.tsx");
+ const controlledMapSource = getExampleSource("controlled-map-example.tsx");
+ const customStyleSource = getExampleSource("custom-style-example.tsx");
return (
<DocsLayout
@@ -17,17 +26,47 @@ export default function BasicMapPage() {
description="The simplest way to add an interactive map to your application."
prev={{ title: "API Reference", href: "/docs/api-reference" }}
next={{ title: "Controls", href: "/docs/controls" }}
+ toc={[
+ { title: "Basic Usage", slug: "basic-usage" },
+ { title: "Controlled Mode", slug: "controlled-mode" },
+ { title: "Custom Styles", slug: "custom-styles" },
+ ]}
>
- <DocsSection>
+ <DocsSection title="Basic Usage">
<p>
The <DocsCode>Map</DocsCode> component handles MapLibre GL setup,
theming, and provides context for child components.
</p>
+ <ComponentPreview code={basicMapSource}>
+ <BasicMapExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={basicMapSource}>
- <BasicMapExample />
- </ComponentPreview>
+ <DocsSection title="Controlled Mode">
+ <p>
+ Use the <DocsCode>viewport</DocsCode> and{" "}
+ <DocsCode>onViewportChange</DocsCode> props to control the map&apos;s
+ viewport externally. This is useful when you need to sync the map
+ state with your application or respond to viewport changes.
+ </p>
+ <ComponentPreview code={controlledMapSource}>
+ <ControlledMapExample />
+ </ComponentPreview>
+ </DocsSection>
+
+ <DocsSection title="Custom Styles">
+ <p>
+ Use the <DocsCode>styles</DocsCode> prop to provide custom map styles.
+ This example uses free vector tiles from{" "}
+ <DocsLink href="https://openfreemap.org" external>
+ OpenFreeMap
+ </DocsLink>
+ , an open-source project, the data comes from OpenStreetMap.
+ </p>
+ <ComponentPreview code={customStyleSource}>
+ <CustomStyleExample />
+ </ComponentPreview>
+ </DocsSection>
</DocsLayout>
);
}
diff --git a/src/app/docs/clusters/page.tsx b/src/app/docs/clusters/page.tsx
index b6cfc95..ad8a7c8 100644
--- a/src/app/docs/clusters/page.tsx
+++ b/src/app/docs/clusters/page.tsx
@@ -32,11 +32,10 @@ export default function ClustersPage() {
Click on clusters to zoom in. Click individual points to see details
in a popup.
</p>
+ <ComponentPreview code={clusterSource}>
+ <ClusterExample />
+ </ComponentPreview>
</DocsSection>
-
- <ComponentPreview code={clusterSource}>
- <ClusterExample />
- </ComponentPreview>
</DocsLayout>
);
}
diff --git a/src/app/docs/controls/page.tsx b/src/app/docs/controls/page.tsx
index 063650a..b91673f 100644
--- a/src/app/docs/controls/page.tsx
+++ b/src/app/docs/controls/page.tsx
@@ -23,11 +23,10 @@ export default function ControlsPage() {
The <DocsCode>MapControls</DocsCode> component provides a set of
interactive controls that can be positioned on any corner of the map.
</p>
+ <ComponentPreview code={controlsSource}>
+ <MapControlsExample />
+ </ComponentPreview>
</DocsSection>
-
- <ComponentPreview code={controlsSource}>
- <MapControlsExample />
- </ComponentPreview>
</DocsLayout>
);
}
diff --git a/src/app/docs/layout.tsx b/src/app/docs/layout.tsx
index c7422b8..7b26b30 100644
--- a/src/app/docs/layout.tsx
+++ b/src/app/docs/layout.tsx
@@ -14,9 +14,11 @@ export default function DocsLayout({
className="sticky top-0 z-50 bg-background/95 border-b backdrop-blur supports-backdrop-filter:bg-background/60"
leftContent={<MobileSidebarTrigger />}
/>
- <div className="flex flex-1 container">
- <DocsSidebar />
- <main className="flex-1 w-full">{children}</main>
+ <div className="container flex-1">
+ <div className="flex">
+ <DocsSidebar />
+ <main className="flex-1 w-full">{children}</main>
+ </div>
</div>
</div>
</SidebarProvider>
diff --git a/src/app/docs/markers/page.tsx b/src/app/docs/markers/page.tsx
index d476a73..dc1bde6 100644
--- a/src/app/docs/markers/page.tsx
+++ b/src/app/docs/markers/page.tsx
@@ -57,33 +57,30 @@ export default function MarkersPage() {
<p>
Simple markers with tooltips and popups showing location information.
</p>
+ <ComponentPreview code={markersSource}>
+ <MarkersExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={markersSource}>
- <MarkersExample />
- </ComponentPreview>
-
<DocsSection title="Rich Popups">
<p>
Build complex popups with images, ratings, and action buttons using
shadcn/ui components.
</p>
+ <ComponentPreview code={popupSource} className="h-[500px]">
+ <PopupExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={popupSource} className="h-[500px]">
- <PopupExample />
- </ComponentPreview>
-
<DocsSection title="Draggable Marker">
<p>
Create draggable markers that users can move around the map. Click the
marker to see its current coordinates in a popup.
</p>
+ <ComponentPreview code={draggableMarkerSource}>
+ <DraggableMarkerExample />
+ </ComponentPreview>
</DocsSection>
-
- <ComponentPreview code={draggableMarkerSource}>
- <DraggableMarkerExample />
- </ComponentPreview>
</DocsLayout>
);
}
diff --git a/src/app/docs/popups/page.tsx b/src/app/docs/popups/page.tsx
index 294c67a..d9bbab1 100644
--- a/src/app/docs/popups/page.tsx
+++ b/src/app/docs/popups/page.tsx
@@ -24,11 +24,10 @@ export default function PopupsPage() {
on the map. Unlike <DocsCode>MarkerPopup</DocsCode>, standalone popups
are not attached to markers and can be controlled programmatically.
</p>
+ <ComponentPreview code={popupSource}>
+ <StandalonePopupExample />
+ </ComponentPreview>
</DocsSection>
-
- <ComponentPreview code={popupSource}>
- <StandalonePopupExample />
- </ComponentPreview>
</DocsLayout>
);
}
diff --git a/src/app/docs/routes/page.tsx b/src/app/docs/routes/page.tsx
index f3d2d67..e7ca24c 100644
--- a/src/app/docs/routes/page.tsx
+++ b/src/app/docs/routes/page.tsx
@@ -39,12 +39,11 @@ export default function RoutesPage() {
<DocsSection title="Basic Route">
<p>Draw a route with numbered stop markers along the path.</p>
+ <ComponentPreview code={routeSource}>
+ <RouteExample />
+ </ComponentPreview>
</DocsSection>
- <ComponentPreview code={routeSource}>
- <RouteExample />
- </ComponentPreview>
-
<DocsSection title="Route Planning">
<p>
Display multiple route options and let users select between them. This
@@ -54,11 +53,10 @@ export default function RoutesPage() {
</DocsLink>
. Click on a route or use the buttons to switch.
</p>
+ <ComponentPreview code={osrmRouteSource} className="h-[500px]">
+ <OsrmRouteExample />
+ </ComponentPreview>
</DocsSection>
-
- <ComponentPreview code={osrmRouteSource} className="h-[500px]">
- <OsrmRouteExample />
- </ComponentPreview>
</DocsLayout>
);
}
diff --git a/src/app/globals.css b/src/app/globals.css
index f3d0b89..2bf588e 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -118,7 +118,7 @@
@layer base {
* {
- @apply border-border outline-ring/50 overscroll-none;
+ @apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground font-sans;
@@ -136,7 +136,7 @@
}
.container {
- @apply max-w-[1440px] mx-auto px-6;
+ @apply max-w-[1480px] mx-auto px-6;
}
/* animations for the home page */
diff --git a/src/components/command-search.tsx b/src/components/command-search.tsx
index 3ce666f..38c867a 100644
--- a/src/components/command-search.tsx
+++ b/src/components/command-search.tsx
@@ -2,7 +2,13 @@
import * as React from "react";
import { useRouter } from "next/navigation";
-import { Search } from "lucide-react";
+import {
+ ArrowDown,
+ ArrowUp,
+ CornerDownLeft,
+ FileText,
+ SearchIcon,
+} from "lucide-react";
import {
CommandDialog,
@@ -14,6 +20,7 @@ import {
} from "@/components/ui/command";
import { Kbd } from "@/components/ui/kbd";
import { docsNavigation } from "@/lib/docs-navigation";
+import { Button } from "./ui/button";
export function CommandSearch() {
const [open, setOpen] = React.useState(false);
@@ -38,24 +45,35 @@ export function CommandSearch() {
return (
<>
- <button
+ <Button
+ variant="outline"
+ size="sm"
onClick={() => setOpen(true)}
aria-label="Search documentation"
- className="hidden group sm:flex items-center gap-2 h-8 px-3 rounded-full bg-secondary/60 border border-border/40 text-sm text-muted-foreground hover:text-foreground hover:border-border transition-colors"
+ className="hidden group md:flex items-center w-[180px] dark:border-border/50 border-border/70 rounded-lg text-sm font-normal text-muted-foreground"
>
- <Search className="size-3.5" />
- <span className="hidden sm:inline">Search...</span>
- <Kbd className="hidden sm:inline-flex ml-2">⌘K</Kbd>
- </button>
+ <SearchIcon className="size-3.5 shrink-0" />
+ <span>Search docs...</span>
+ <Kbd className="ml-auto">⌘K</Kbd>
+ </Button>
<CommandDialog
open={open}
onOpenChange={setOpen}
title="Search Documentation"
description="Search for documentation pages and components"
+ showCloseButton={false}
>
- <CommandInput placeholder="Type to search..." />
+ <CommandInput
+ placeholder="Search documentation..."
+ className="border-none text-sm h-10"
+ />
<CommandList>
- <CommandEmpty>No results found.</CommandEmpty>
+ <CommandEmpty className="py-8 text-muted-foreground text-sm">
+ <div className="flex flex-col items-center gap-1.5">
+ <FileText className="size-5 opacity-40" />
+ <span>No results found.</span>
+ </div>
+ </CommandEmpty>
{docsNavigation.map((group) => (
<CommandGroup key={group.title} heading={group.title}>
{group.items.map((item) => (
@@ -71,6 +89,29 @@ export function CommandSearch() {
</CommandGroup>
))}
</CommandList>
+ <div className="border-t p-3 text-xs text-muted-foreground/80 flex items-center justify-between">
+ <div className="flex items-center gap-2.5">
+ <span className="flex items-center gap-1.5">
+ <Kbd>
+ <ArrowUp className="size-3" />
+ </Kbd>
+ <Kbd>
+ <ArrowDown className="size-3" />
+ </Kbd>
+ <span>navigate</span>
+ </span>
+ <span className="flex items-center gap-1.5">
+ <Kbd>
+ <CornerDownLeft className="size-3" />
+ </Kbd>
+ <span>select</span>
+ </span>
+ </div>
+ <span className="flex items-baseline gap-1.5">
+ <Kbd>esc</Kbd>
+ <span>close</span>
+ </span>
+ </div>
</CommandDialog>
</>
);
diff --git a/src/components/footer.tsx b/src/components/footer.tsx
index c9222c5..7ebf9cb 100644
--- a/src/components/footer.tsx
+++ b/src/components/footer.tsx
@@ -2,24 +2,24 @@ import Link from "next/link";
export function Footer() {
return (
- <footer className="w-full py-8 border-t border-border/40 bg-muted/20">
- <div className="container flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-muted-foreground">
- <div className="flex items-center gap-2 flex-wrap justify-center sm:justify-start">
- <span>© {new Date().getFullYear()} mapcn</span>
- <span className="text-border">•</span>
+ <footer className="w-full py-6 border-t">
+ <div className="w-full container flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-muted-foreground">
+ <div className="flex items-center gap-2">
+ <span className="font-medium text-foreground">mapcn</span>
+ <span className="text-muted-foreground/80">•</span>
<span>
Built by{" "}
<a
href="https://github.com/AnmolSaini16"
target="_blank"
rel="noopener noreferrer"
- className="font-medium text-foreground hover:underline underline-offset-4"
+ className="font-medium text-foreground underline underline-offset-4"
>
Anmol
</a>
</span>
</div>
- <div className="flex items-center gap-6">
+ <div className="flex items-center gap-5">
<Link
href="/docs"
className="hover:text-foreground transition-colors"
diff --git a/src/components/header.tsx b/src/components/header.tsx
index 8724d20..323f865 100644
--- a/src/components/header.tsx
+++ b/src/components/header.tsx
@@ -34,7 +34,7 @@ export function Header({ className, leftContent }: HeaderProps) {
</div>
<div className="flex items-center gap-2 h-4.5">
<CommandSearch />
- <Separator orientation="vertical" className="hidden sm:block" />
+ <Separator orientation="vertical" className="hidden md:block" />
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="sm" asChild>
@@ -44,7 +44,7 @@ export function Header({ className, leftContent }: HeaderProps) {
rel="noopener noreferrer"
>
<Heart className="size-4 text-pink-500" />
- <span className="hidden sm:inline">Sponsor</span>
+ <span className="hidden md:inline font-normal">Sponsor</span>
</a>
</Button>
</TooltipTrigger>
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 2d051c0..8d27741 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -17,7 +17,7 @@ const buttonVariants = cva(
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
- "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
+ "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/60",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index a6f1cfb..1f0e368 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -5,6 +5,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
function Dialog({
...props
@@ -90,7 +91,14 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
)
}
-function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
+function DialogFooter({
+ className,
+ showCloseButton = false,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showCloseButton?: boolean
+}) {
return (
<div
data-slot="dialog-footer"
@@ -99,7 +107,14 @@ function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
className
)}
{...props}
- />
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close asChild>
+ <Button variant="outline">Close</Button>
+ </DialogPrimitive.Close>
+ )}
+ </div>
)
}
diff --git a/src/registry/map.tsx b/src/registry/map.tsx
index ae9dbaa..c8b2f7f 100644
--- a/src/registry/map.tsx
+++ b/src/registry/map.tsx
@@ -82,6 +82,16 @@ type MapContextValue = {
const MapContext = createContext<MapContextValue | null>(null);
+function getViewport(map: MapLibreGL.Map): MapViewport {
+ const center = map.getCenter();
+ return {
+ center: [center.lng, center.lat],
+ zoom: map.getZoom(),
+ bearing: map.getBearing(),
+ pitch: map.getPitch(),
+ };
+}
+
function useMap() {
const context = useContext(MapContext);
if (!context) {
@@ -99,8 +109,24 @@ type MapStyleOption = string | MapLibreGL.StyleSpecification;
type Theme = "light" | "dark";
+/** Map viewport state */
+type MapViewport = {
+ /** Center coordinates [longitude, latitude] */
+ center: [number, number];
+ /** Zoom level */
+ zoom: number;
+ /** Bearing (rotation) in degrees */
+ bearing: number;
+ /** Pitch (tilt) in degrees */
+ pitch: number;
+};
+
type MapProps = {
children?: ReactNode;
+ /** Additional CSS classes for the map container */
+ className?: string;
+ /** Custom loading component. Defaults to animated dots */
+ loader?: ReactNode;
/**
* Theme for the map. If not provided, automatically detects system preference.
* Pass your theme value here.
@@ -113,6 +139,17 @@ type MapProps = {
};
/** Map projection type. Use `{ type: "globe" }` for 3D globe view. */
projection?: MapLibreGL.ProjectionSpecification;
+ /**
+ * Controlled viewport. When provided with onViewportChange,
+ * the map becomes controlled and viewport is driven by this prop.
+ */
+ viewport?: Partial<MapViewport>;
+ /**
+ * Callback fired continuously as the viewport changes (pan, zoom, rotate, pitch).
+ * When used with `viewport` prop, enables controlled mode.
+ * Receives the new viewport state to update your state.
+ */
+ onViewportChange?: (viewport: MapViewport) => void;
} & Omit<MapLibreGL.MapOptions, "container" | "style">;
type MapRef = MapLibreGL.Map;
@@ -128,7 +165,17 @@ const DefaultLoader = () => (
);
const Map = forwardRef<MapRef, MapProps>(function Map(
- { children, theme: themeProp, styles, projection, ...props },
+ {
+ children,
+ className,
+ loader,
+ theme: themeProp,
+ styles,
+ projection,
+ viewport,
+ onViewportChange,
+ ...props
+ },
ref
) {
const containerRef = useRef<HTMLDivElement>(null);
@@ -137,8 +184,14 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
const [isStyleLoaded, setIsStyleLoaded] = useState(false);
const currentStyleRef = useRef<MapStyleOption | null>(null);
const styleTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const internalUpdateRef = useRef(false);
const resolvedTheme = useResolvedTheme(themeProp);
+ const isControlled = viewport !== undefined && onViewportChange !== undefined;
+
+ const onViewportChangeRef = useRef(onViewportChange);
+ onViewportChangeRef.current = onViewportChange;
+
const mapStyles = useMemo(
() => ({
dark: styles?.dark ?? defaultStyles.dark,
@@ -147,6 +200,7 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
[styles]
);
+ // Expose the map instance to the parent component
useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);
const clearStyleTimeout = useCallback(() => {
@@ -156,6 +210,7 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
}
}, []);
+ // Initialize the map
useEffect(() => {
if (!containerRef.current) return;
@@ -171,6 +226,7 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
compact: true,
},
...props,
+ ...viewport,
});
const styleDataHandler = () => {
@@ -187,14 +243,22 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
};
const loadHandler = () => setIsLoaded(true);
+ // Viewport change handler - skip if triggered by internal update
+ const handleMove = () => {
+ if (internalUpdateRef.current) return;
+ onViewportChangeRef.current?.(getViewport(map));
+ };
+
map.on("load", loadHandler);
map.on("styledata", styleDataHandler);
+ map.on("move", handleMove);
setMapInstance(map);
return () => {
clearStyleTimeout();
map.off("load", loadHandler);
map.off("styledata", styleDataHandler);
+ map.off("move", handleMove);
map.remove();
setIsLoaded(false);
setIsStyleLoaded(false);
@@ -203,6 +267,23 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ // Sync controlled viewport to map
+ useEffect(() => {
+ if (!mapInstance || !isControlled || !viewport) return;
+ if (mapInstance.isMoving()) return;
+
+ const current = getViewport(mapInstance);
+ internalUpdateRef.current = true;
+ mapInstance.jumpTo({
+ center: viewport.center ?? current.center,
+ zoom: viewport.zoom ?? current.zoom,
+ bearing: viewport.bearing ?? current.bearing,
+ pitch: viewport.pitch ?? current.pitch,
+ });
+ internalUpdateRef.current = false;
+ }, [mapInstance, isControlled, viewport]);
+
+ // Handle style change
useEffect(() => {
if (!mapInstance || !resolvedTheme) return;
@@ -228,8 +309,11 @@ const Map = forwardRef<MapRef, MapProps>(function Map(
return (
<MapContext.Provider value={contextValue}>
- <div ref={containerRef} className="relative w-full h-full">
- {!isLoaded && <DefaultLoader />}
+ <div
+ ref={containerRef}
+ className={cn("relative w-full h-full", className)}
+ >
+ {!isLoaded && (loader ?? <DefaultLoader />)}
{/* SSR-safe: children render only when map is loaded on client */}
{mapInstance && children}
</div>
@@ -288,6 +372,23 @@ function MapMarker({
}: MapMarkerProps) {
const { map } = useMap();
+ const callbacksRef = useRef({
+ onClick,
+ onMouseEnter,
+ onMouseLeave,
+ onDragStart,
+ onDrag,
+ onDragEnd,
+ });
+ callbacksRef.current = {
+ onClick,
+ onMouseEnter,
+ onMouseLeave,
+ onDragStart,
+ onDrag,
+ onDragEnd,
+ };
+
const marker = useMemo(() => {
const markerInstance = new MapLibreGL.Marker({
...markerOptions,
@@ -295,9 +396,11 @@ function MapMarker({
draggable,
}).setLngLat([longitude, latitude]);
- const handleClick = (e: MouseEvent) => onClick?.(e);
- const handleMouseEnter = (e: MouseEvent) => onMouseEnter?.(e);
- const handleMouseLeave = (e: MouseEvent) => onMouseLeave?.(e);
+ const handleClick = (e: MouseEvent) => callbacksRef.current.onClick?.(e);
+ const handleMouseEnter = (e: MouseEvent) =>
+ callbacksRef.current.onMouseEnter?.(e);
+ const handleMouseLeave = (e: MouseEvent) =>
+ callbacksRef.current.onMouseLeave?.(e);
markerInstance.getElement()?.addEventListener("click", handleClick);
markerInstance
@@ -309,15 +412,15 @@ function MapMarker({
const handleDragStart = () => {
const lngLat = markerInstance.getLngLat();
- onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });
+ callbacksRef.current.onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });
};
const handleDrag = () => {
const lngLat = markerInstance.getLngLat();
- onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });
+ callbacksRef.current.onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });
};
const handleDragEnd = () => {
const lngLat = markerInstance.getLngLat();
- onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });
+ callbacksRef.current.onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });
};
markerInstance.on("dragstart", handleDragStart);
@@ -827,6 +930,8 @@ function MapPopup({
}: MapPopupProps) {
const { map } = useMap();
const popupOptionsRef = useRef(popupOptions);
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
const container = useMemo(() => document.createElement("div"), []);
const popup = useMemo(() => {
@@ -845,7 +950,8 @@ function MapPopup({
useEffect(() => {
if (!map) return;
- const onCloseProp = () => onClose?.();
+ const onCloseProp = () => onCloseRef.current?.();
+
popup.on("close", onCloseProp);
popup.setDOMContent(container);
@@ -881,7 +987,6 @@ function MapPopup({
const handleClose = () => {
popup.remove();
- onClose?.();
};
return createPortal(
@@ -1058,7 +1163,7 @@ type MapClusterLayerProps<
clusterMaxZoom?: number;
/** Radius of each cluster when clustering points in pixels (default: 50) */
clusterRadius?: number;
- /** Colors for cluster circles: [small, medium, large] based on point count (default: ["#51bbd6", "#f1f075", "#f28cb1"]) */
+ /** Colors for cluster circles: [small, medium, large] based on point count (default: ["#22c55e", "#eab308", "#ef4444"]) */
clusterColors?: [string, string, string];
/** Point count thresholds for color/size steps: [medium, large] (default: [100, 750]) */
clusterThresholds?: [number, number];
@@ -1083,7 +1188,7 @@ function MapClusterLayer<
data,
clusterMaxZoom = 14,
clusterRadius = 50,
- clusterColors = ["#51bbd6", "#f1f075", "#f28cb1"],
+ clusterColors = ["#22c55e", "#eab308", "#ef4444"],
clusterThresholds = [100, 750],
pointColor = "#3b82f6",
onPointClick,
@@ -1140,6 +1245,9 @@ function MapClusterLayer<
clusterThresholds[1],
40,
],
+ "circle-stroke-width": 1,
+ "circle-stroke-color": "#fff",
+ "circle-opacity": 0.85,
},
});
@@ -1166,7 +1274,9 @@ function MapClusterLayer<
filter: ["!", ["has", "point_count"]],
paint: {
"circle-color": pointColor,
- "circle-radius": 6,
+ "circle-radius": 5,
+ "circle-stroke-width": 2,
+ "circle-stroke-color": "#fff",
},
});
@@ -1360,4 +1470,4 @@ export {
MapClusterLayer,
};
-export type { MapRef };
+export type { MapRef, MapViewport };