Beautiful map components. 100% Free, Zero config, one command setup.
TypeScript
Update: markers performance fix
Anmoldeep Singhdba4da5d9aec
diff --git a/public/maps/map.json b/public/maps/map.jsonindex 7f8790c..1f3b8b1 100644--- a/public/maps/map.json+++ b/public/maps/map.json@@ -12,7 +12,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 { useTheme } from \"next-themes\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useId,\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\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 MapProps = {\n children?: ReactNode;\n /** Custom map styles for light and dark themes. Overrides the default Carto styles. */\n styles?: {\n light?: MapStyleOption;\n dark?: MapStyleOption;\n };\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\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\nfunction Map({ children, styles, ...props }: MapProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<MapLibreGL.Map | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [isStyleLoaded, setIsStyleLoaded] = useState(false);\n const { resolvedTheme } = useTheme();\n\n const mapStyles = useMemo(\n () => ({\n dark: styles?.dark ?? defaultStyles.dark,\n light: styles?.light ?? defaultStyles.light,\n }),\n [styles]\n );\n\n useEffect(() => {\n if (!containerRef.current) return;\n\n const mapStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n const mapInstance = new MapLibreGL.Map({\n container: containerRef.current,\n style: mapStyle,\n renderWorldCopies: false,\n attributionControl: {\n compact: true,\n },\n ...props,\n });\n\n const styleDataHandler = () => setIsStyleLoaded(true);\n const loadHandler = () => setIsLoaded(true);\n\n mapInstance.on(\"load\", loadHandler);\n mapInstance.on(\"styledata\", styleDataHandler);\n mapRef.current = mapInstance;\n\n return () => {\n mapInstance.off(\"load\", loadHandler);\n mapInstance.off(\"styledata\", styleDataHandler);\n mapInstance.remove();\n mapRef.current = null;\n setIsLoaded(false);\n setIsStyleLoaded(false);\n };\n }, []);\n\n useEffect(() => {\n if (mapRef.current) {\n setIsStyleLoaded(false);\n mapRef.current.setStyle(\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light,\n { diff: true }\n );\n }\n }, [resolvedTheme, mapStyles]);\n\n const isLoading = !isLoaded || !isStyleLoaded;\n\n const contextValue = useMemo(\n () => ({\n map: mapRef.current,\n isLoaded: isLoaded && isStyleLoaded,\n }),\n [isLoaded, isStyleLoaded]\n );\n\n return (\n <MapContext.Provider value={contextValue}>\n <div ref={containerRef} className=\"relative w-full h-full\">\n {isLoading && <DefaultLoader />}\n {/* SSR-safe: children render only when map exists on client */}\n {mapRef.current && children}\n </div>\n </MapContext.Provider>\n );\n}\n\ntype MarkerContextValue = {\n markerRef: React.RefObject<MapLibreGL.Marker | null>;\n markerElementRef: React.RefObject<HTMLDivElement | null>;\n map: MapLibreGL.Map | null;\n isReady: boolean;\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, isLoaded } = useMap();\n const markerRef = useRef<MapLibreGL.Marker | null>(null);\n const markerElementRef = useRef<HTMLDivElement | null>(null);\n const [isReady, setIsReady] = useState(false);\n const markerOptionsRef = useRef(markerOptions);\n\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const container = document.createElement(\"div\");\n markerElementRef.current = container;\n\n const marker = new MapLibreGL.Marker({\n ...markerOptions,\n element: container,\n draggable,\n })\n .setLngLat([longitude, latitude])\n .addTo(map);\n\n markerRef.current = marker;\n\n const handleClick = (e: MouseEvent) => onClick?.(e);\n const handleMouseEnter = (e: MouseEvent) => onMouseEnter?.(e);\n const handleMouseLeave = (e: MouseEvent) => onMouseLeave?.(e);\n\n container.addEventListener(\"click\", handleClick);\n container.addEventListener(\"mouseenter\", handleMouseEnter);\n container.addEventListener(\"mouseleave\", handleMouseLeave);\n\n const handleDragStart = () => {\n const lngLat = marker.getLngLat();\n onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDrag = () => {\n const lngLat = marker.getLngLat();\n onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDragEnd = () => {\n const lngLat = marker.getLngLat();\n onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n\n marker.on(\"dragstart\", handleDragStart);\n marker.on(\"drag\", handleDrag);\n marker.on(\"dragend\", handleDragEnd);\n\n setIsReady(true);\n\n return () => {\n container.removeEventListener(\"click\", handleClick);\n container.removeEventListener(\"mouseenter\", handleMouseEnter);\n container.removeEventListener(\"mouseleave\", handleMouseLeave);\n\n marker.off(\"dragstart\", handleDragStart);\n marker.off(\"drag\", handleDrag);\n marker.off(\"dragend\", handleDragEnd);\n\n marker.remove();\n markerRef.current = null;\n markerElementRef.current = null;\n setIsReady(false);\n };\n }, [map, isLoaded]);\n\n useEffect(() => {\n markerRef.current?.setLngLat([longitude, latitude]);\n }, [longitude, latitude]);\n\n useEffect(() => {\n markerRef.current?.setDraggable(draggable);\n }, [draggable]);\n\n useEffect(() => {\n if (!markerRef.current) return;\n const prev = markerOptionsRef.current;\n\n if (prev.offset !== markerOptions.offset) {\n markerRef.current.setOffset(markerOptions.offset ?? [0, 0]);\n }\n if (prev.rotation !== markerOptions.rotation) {\n markerRef.current.setRotation(markerOptions.rotation ?? 0);\n }\n if (prev.rotationAlignment !== markerOptions.rotationAlignment) {\n markerRef.current.setRotationAlignment(\n markerOptions.rotationAlignment ?? \"auto\"\n );\n }\n if (prev.pitchAlignment !== markerOptions.pitchAlignment) {\n markerRef.current.setPitchAlignment(\n markerOptions.pitchAlignment ?? \"auto\"\n );\n }\n\n markerOptionsRef.current = markerOptions;\n }, [markerOptions]);\n\n return (\n <MarkerContext.Provider\n value={{ markerRef, markerElementRef, map, isReady }}\n >\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 { markerElementRef, isReady } = useMarkerContext();\n\n if (!isReady || !markerElementRef.current) return null;\n\n return createPortal(\n <div className={cn(\"relative cursor-pointer\", className)}>\n {children || <DefaultMarkerIcon />}\n </div>,\n markerElementRef.current\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 { markerRef, isReady } = useMarkerContext();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n const popupOptionsRef = useRef(popupOptions);\n\n useEffect(() => {\n if (!isReady || !markerRef.current) return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n popupRef.current = popup;\n markerRef.current.setPopup(popup);\n setMounted(true);\n\n return () => {\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isReady]);\n\n useEffect(() => {\n if (!popupRef.current) return;\n const prev = popupOptionsRef.current;\n\n if (prev.offset !== popupOptions.offset) {\n popupRef.current.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popupRef.current.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n popupOptionsRef.current = popupOptions;\n }, [popupOptions]);\n\n const handleClose = () => popupRef.current?.remove();\n\n if (!mounted || !containerRef.current) return null;\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 containerRef.current\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 { markerRef, markerElementRef, map, isReady } = useMarkerContext();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n const popupOptionsRef = useRef(popupOptions);\n\n useEffect(() => {\n if (!isReady || !markerRef.current || !markerElementRef.current || !map)\n return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeOnClick: true,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n popupRef.current = popup;\n\n const markerElement = markerElementRef.current;\n const marker = markerRef.current;\n\n const handleMouseEnter = () => {\n popup.setLngLat(marker.getLngLat()).addTo(map);\n };\n const handleMouseLeave = () => popup.remove();\n\n markerElement.addEventListener(\"mouseenter\", handleMouseEnter);\n markerElement.addEventListener(\"mouseleave\", handleMouseLeave);\n setMounted(true);\n\n return () => {\n markerElement.removeEventListener(\"mouseenter\", handleMouseEnter);\n markerElement.removeEventListener(\"mouseleave\", handleMouseLeave);\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isReady, map]);\n\n useEffect(() => {\n if (!popupRef.current) return;\n const prev = popupOptionsRef.current;\n\n if (prev.offset !== popupOptions.offset) {\n popupRef.current.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popupRef.current.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n popupOptionsRef.current = popupOptions;\n }, [popupOptions]);\n\n if (!mounted || !containerRef.current) return null;\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 containerRef.current\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, isLoaded } = 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 if (!isLoaded) return null;\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 { isLoaded, map } = useMap();\n const compassRef = useRef<SVGSVGElement>(null);\n\n useEffect(() => {\n if (!isLoaded || !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 }, [isLoaded, 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 popupRef = useRef<MapLibreGL.Popup | null>(null);\n const popupOptionsRef = useRef(popupOptions);\n\n const container = useMemo(() => document.createElement(\"div\"), []);\n\n useEffect(() => {\n if (!map) return;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container)\n .setLngLat([longitude, latitude])\n .addTo(map);\n\n const onCloseProp = () => onClose?.();\n\n popup.on(\"close\", onCloseProp);\n\n popupRef.current = popup;\n\n return () => {\n popup.off(\"close\", onCloseProp);\n if (popup.isOpen()) {\n popup.remove();\n }\n popupRef.current = null;\n };\n }, [map]);\n\n useEffect(() => {\n popupRef.current?.setLngLat([longitude, latitude]);\n }, [longitude, latitude]);\n\n useEffect(() => {\n if (!popupRef.current) return;\n const prev = popupOptionsRef.current;\n\n if (prev.offset !== popupOptions.offset) {\n popupRef.current.setOffset(popupOptions.offset ?? 16);\n }\n if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {\n popupRef.current.setMaxWidth(popupOptions.maxWidth ?? \"none\");\n }\n\n popupOptionsRef.current = popupOptions;\n }, [popupOptions]);\n\n const handleClose = () => {\n popupRef.current?.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 /** 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};\n\nfunction MapRoute({\n coordinates,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const id = useId();\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 }, [isLoaded, map, sourceId, layerId]);\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 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: typeof data === \"string\" ? data : 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 }, [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",+ "content": "\"use client\";\n\nimport MapLibreGL, { type PopupOptions, type MarkerOptions } from \"maplibre-gl\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\nimport { useTheme } from \"next-themes\";\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\";\nimport React from \"react\";\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 MapProps = {\n children?: ReactNode;\n /** Custom map styles for light and dark themes. Overrides the default Carto styles. */\n styles?: {\n light?: MapStyleOption;\n dark?: MapStyleOption;\n };\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, styles, ...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 { resolvedTheme } = useTheme();\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 useEffect(() => {\n if (!containerRef.current) return;\n\n const mapStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n const mapInstance = new MapLibreGL.Map({\n container: containerRef.current,\n style: mapStyle,\n renderWorldCopies: false,\n attributionControl: {\n compact: true,\n },\n ...props,\n });\n\n const styleDataHandler = () => setIsStyleLoaded(true);\n const loadHandler = () => setIsLoaded(true);\n\n mapInstance.on(\"load\", loadHandler);\n mapInstance.on(\"styledata\", styleDataHandler);\n setMapInstance(mapInstance);\n\n return () => {\n mapInstance.off(\"load\", loadHandler);\n mapInstance.off(\"styledata\", styleDataHandler);\n mapInstance.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) return;\n\n const rafId = requestAnimationFrame(() => {\n setIsStyleLoaded(false);\n mapInstance.setStyle(\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light,\n { diff: true }\n );\n });\n\n return () => cancelAnimationFrame(rafId);\n }, [mapInstance, resolvedTheme, mapStyles]);\n\n const isLoading = !isLoaded || !isStyleLoaded;\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 {isLoading && <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, isLoaded } = 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 if (!isLoaded) return null;\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 { isLoaded, map } = useMap();\n const compassRef = useRef<SVGSVGElement>(null);\n\n useEffect(() => {\n if (!isLoaded || !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 }, [isLoaded, 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 /** 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 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 sourceId = `route-source-${autoId}`;\n const layerId = `route-layer-${autoId}`;\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 = (e: MapLibreGL.MapMouseEvent) => {\n e.originalEvent.stopImmediatePropagation();\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","type": "registry:ui","target": "components/ui/map.tsx"}diff --git a/src/app/(home)/_components/examples.tsx b/src/app/(home)/_components/examples.tsxindex 50c40db..7ffd999 100644--- a/src/app/(home)/_components/examples.tsx+++ b/src/app/(home)/_components/examples.tsx@@ -100,7 +100,7 @@ export function Examples() {</div></div>- <Map center={[0, 30]} zoom={0.8}>+ <Map center={[0, 30]} zoom={0.5}>{analyticsData.map((loc) => (<MapMarker key={loc.city} longitude={loc.lng} latitude={loc.lat}><MarkerContent>diff --git a/src/app/(home)/_components/hero.tsx b/src/app/(home)/_components/hero.tsxindex 91bee8a..8b42b9b 100644--- a/src/app/(home)/_components/hero.tsx+++ b/src/app/(home)/_components/hero.tsx@@ -35,34 +35,35 @@ function CopyButton({ text }: { text: string }) {export function Hero() {return (<div className="space-y-8">- <div className="text-center space-y-4">- <h1 className="text-4xl sm:text-5xl md:text-6xl font-semibold tracking-tight animate-fade-up">+ <div className="space-y-4 text-center">+ <h1 className="text-4xl sm:text-5xl md:text-6xl font-semibold tracking-tight animate-fade-up text-primary">Beautiful maps, made simple.</h1>- <p className="text-foreground/80 text-lg max-w-xl mx-auto animate-fade-up delay-100">- Beautifully designed, Open source map components. Zero config. One- command setup.+ <p className="text-foreground/80 text-lg max-w-xl mx-auto leading-relaxed animate-fade-up delay-100">+ Beautiful, ready to use, and customizable map components built on+ MapLibre. Styled with Tailwind. Zero config. One command setup.</p></div>-- <div className="flex justify-center animate-fade-up delay-200 w-full px-4">- <div className="inline-flex items-center gap-3 bg-secondary/50 border border-border/50 rounded-full px-5 py-2.5 font-mono text-sm max-w-full overflow-x-auto">- <span className="text-muted-foreground shrink-0">$</span>- <code>{installCommand}</code>+ <div className="animate-fade-up delay-200 text-center">+ <div className="inline-flex items-center gap-3 bg-secondary/60 border border-border/40 rounded-full px-4 py-2.5 font-mono text-sm max-w-full overflow-x-auto">+ <span className="text-muted-foreground/60 shrink-0">$</span>+ <code className="text-foreground/90 truncate">{installCommand}</code><CopyButton text={installCommand} /></div></div>-+ {/* CTA Buttons */}<div className="flex flex-wrap justify-center items-center gap-3 animate-fade-up delay-300"><Button asChild><Link href="/docs">Get Started <ArrowRight className="size-4" /></Link></Button>- <Button variant="outline" size="lg" asChild>- <Link href="/docs/basic-map">View Examples</Link>+ <Button variant="ghost" asChild>+ <Link href="/docs/basic-map" className="text-muted-foreground">+ View Examples+ </Link></Button>- </div>+ </div>{" "}</div>);}diff --git a/src/app/docs/_components/docs.tsx b/src/app/docs/_components/docs.tsxindex d84e288..7c8762a 100644--- a/src/app/docs/_components/docs.tsx+++ b/src/app/docs/_components/docs.tsx@@ -18,7 +18,9 @@ interface DocsHeaderProps {export function DocsHeader({ title, description }: DocsHeaderProps) {return (<div className="space-y-3">- <h1 className="text-3xl font-semibold tracking-tight">{title}</h1>+ <h1 className="text-3xl font-semibold tracking-tight text-primary">+ {title}+ </h1><p className="text-lg text-muted-foreground leading-relaxed">{description}</p>@@ -90,7 +92,9 @@ export function DocsSection({ title, children }: DocsSectionProps) {return (<section className="space-y-5">{title && (- <h2 className="text-xl font-semibold tracking-tight">{title}</h2>+ <h2 className="text-xl font-semibold tracking-tight text-primary">+ {title}+ </h2>)}<div className="text-muted-foreground leading-7 space-y-4 [&>ul]:list-disc [&>ul]:pl-6 [&>ul]:space-y-2">{children}diff --git a/src/app/docs/_components/examples/draggable-marker-example.tsx b/src/app/docs/_components/examples/draggable-marker-example.tsxindex f1ff029..082ca3c 100644--- a/src/app/docs/_components/examples/draggable-marker-example.tsx+++ b/src/app/docs/_components/examples/draggable-marker-example.tsx@@ -12,7 +12,7 @@ export function DraggableMarkerExample() {return (<div className="h-[400px] w-full">- <Map center={[-73.98, 40.76]} zoom={12}>+ <Map center={[-73.98, 40.75]} zoom={12}><MapMarkerdraggablelongitude={draggableMarker.lng}diff --git a/src/app/docs/api-reference/page.tsx b/src/app/docs/api-reference/page.tsxindex 9956c3d..ecde318 100644--- a/src/app/docs/api-reference/page.tsx+++ b/src/app/docs/api-reference/page.tsx@@ -443,7 +443,8 @@ export default function ApiReferencePage() {<DocsSection title="MapRoute"><p>Renders a line/route on the map connecting coordinate points. Must be- used inside <DocsCode>Map</DocsCode>.+ used inside <DocsCode>Map</DocsCode>. Supports click and hover+ interactions for building route selection UIs.</p><DocsPropTableprops={[@@ -476,6 +477,28 @@ export default function ApiReferencePage() {description:"Dash pattern [dash length, gap length] for dashed lines.",},+ {+ name: "onClick",+ type: "() => void",+ description: "Callback when the route line is clicked.",+ },+ {+ name: "onMouseEnter",+ type: "() => void",+ description: "Callback when mouse enters the route line.",+ },+ {+ name: "onMouseLeave",+ type: "() => void",+ description: "Callback when mouse leaves the route line.",+ },+ {+ name: "interactive",+ type: "boolean",+ default: "true",+ description:+ "Whether the route is interactive (shows pointer cursor on hover).",+ },]}/></DocsSection>diff --git a/src/app/globals.css b/src/app/globals.cssindex 0213332..b719b58 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -123,6 +123,10 @@body {@apply bg-background text-foreground font-sans;}+ button:not(:disabled),+ [role="button"]:not(:disabled) {+ cursor: pointer;+ }.maplibregl-popup-content {@apply bg-transparent! shadow-none! p-0! rounded-none!;}diff --git a/src/components/github-button.tsx b/src/components/github-button.tsxindex fcf92d1..8d75e1d 100644--- a/src/components/github-button.tsx+++ b/src/components/github-button.tsx@@ -5,7 +5,7 @@ import { Skeleton } from "@/components/ui/skeleton";export async function GitHubButton() {return (- <Button variant="ghost" size="sm" className="h-8 px-2 gap-1.5" asChild>+ <Button variant="ghost" size="sm" className="h-8 px-2 gap-2" asChild><Linkhref="https://github.com/AnmolSaini16/mapcn"target="_blank"@@ -44,7 +44,7 @@ export async function StarCount() {return (<>{formattedCount && (- <span className="text-xs text-muted-foreground tabular-nums">+ <span className="text-sm text-muted-foreground tabular-nums">{formattedCount}</span>)}diff --git a/src/components/header.tsx b/src/components/header.tsxindex 370aa9b..020fe35 100644--- a/src/components/header.tsx+++ b/src/components/header.tsx@@ -25,7 +25,7 @@ export function Header({ className, leftContent }: HeaderProps) {<span className="font-semibold tracking-tight">mapcn</span></Link></div>- <div className="flex items-center gap-1.5 h-4">+ <div className="flex items-center gap-1.5 h-4.5"><GitHubButton /><Separator orientation="vertical" /><ThemeToggle />diff --git a/src/registry/map.tsx b/src/registry/map.tsxindex 471a4f4..53de9fc 100644--- a/src/registry/map.tsx+++ b/src/registry/map.tsx@@ -5,10 +5,12 @@ import "maplibre-gl/dist/maplibre-gl.css";import { useTheme } from "next-themes";import {createContext,+ forwardRef,useCallback,useContext,useEffect,useId,+ useImperativeHandle,useMemo,useRef,useState,@@ -18,6 +20,7 @@ import { createPortal } from "react-dom";import { X, Minus, Plus, Locate, Maximize, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";+import React from "react";type MapContextValue = {map: MapLibreGL.Map | null;@@ -50,6 +53,8 @@ type MapProps = {};} & Omit<MapLibreGL.MapOptions, "container" | "style">;+type MapRef = MapLibreGL.Map;+const DefaultLoader = () => (<div className="absolute inset-0 flex items-center justify-center"><div className="flex gap-1">@@ -60,9 +65,12 @@ const DefaultLoader = () => (</div>);-function Map({ children, styles, ...props }: MapProps) {+const Map = forwardRef<MapRef, MapProps>(function Map(+ { children, styles, ...props },+ ref+) {const containerRef = useRef<HTMLDivElement>(null);- const mapRef = useRef<MapLibreGL.Map | null>(null);+ const [mapInstance, setMapInstance] = useState<MapLibreGL.Map | null>(null);const [isLoaded, setIsLoaded] = useState(false);const [isStyleLoaded, setIsStyleLoaded] = useState(false);const { resolvedTheme } = useTheme();@@ -75,6 +83,8 @@ function Map({ children, styles, ...props }: MapProps) {[styles]);+ useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);+useEffect(() => {if (!containerRef.current) return;@@ -96,54 +106,57 @@ function Map({ children, styles, ...props }: MapProps) {mapInstance.on("load", loadHandler);mapInstance.on("styledata", styleDataHandler);- mapRef.current = mapInstance;+ setMapInstance(mapInstance);return () => {mapInstance.off("load", loadHandler);mapInstance.off("styledata", styleDataHandler);mapInstance.remove();- mapRef.current = null;setIsLoaded(false);setIsStyleLoaded(false);+ setMapInstance(null);};+ // eslint-disable-next-line react-hooks/exhaustive-deps}, []);useEffect(() => {- if (mapRef.current) {+ if (!mapInstance) return;++ const rafId = requestAnimationFrame(() => {setIsStyleLoaded(false);- mapRef.current.setStyle(+ mapInstance.setStyle(resolvedTheme === "dark" ? mapStyles.dark : mapStyles.light,{ diff: true });- }- }, [resolvedTheme, mapStyles]);+ });++ return () => cancelAnimationFrame(rafId);+ }, [mapInstance, resolvedTheme, mapStyles]);const isLoading = !isLoaded || !isStyleLoaded;const contextValue = useMemo(() => ({- map: mapRef.current,+ map: mapInstance,isLoaded: isLoaded && isStyleLoaded,}),- [isLoaded, isStyleLoaded]+ [mapInstance, isLoaded, isStyleLoaded]);return (<MapContext.Provider value={contextValue}><div ref={containerRef} className="relative w-full h-full">{isLoading && <DefaultLoader />}- {/* SSR-safe: children render only when map exists on client */}- {mapRef.current && children}+ {/* SSR-safe: children render only when map is loaded on client */}+ {mapInstance && children}</div></MapContext.Provider>);-}+});type MarkerContextValue = {- markerRef: React.RefObject<MapLibreGL.Marker | null>;- markerElementRef: React.RefObject<HTMLDivElement | null>;+ marker: MapLibreGL.Marker;map: MapLibreGL.Map | null;- isReady: boolean;};const MarkerContext = createContext<MarkerContextValue | null>(null);@@ -190,107 +203,92 @@ function MapMarker({draggable = false,...markerOptions}: MapMarkerProps) {- const { map, isLoaded } = useMap();- const markerRef = useRef<MapLibreGL.Marker | null>(null);- const markerElementRef = useRef<HTMLDivElement | null>(null);- const [isReady, setIsReady] = useState(false);- const markerOptionsRef = useRef(markerOptions);-- useEffect(() => {- if (!isLoaded || !map) return;-- const container = document.createElement("div");- markerElementRef.current = container;+ const { map } = useMap();- const marker = new MapLibreGL.Marker({+ const marker = useMemo(() => {+ const markerInstance = new MapLibreGL.Marker({...markerOptions,- element: container,+ element: document.createElement("div"),draggable,- })- .setLngLat([longitude, latitude])- .addTo(map);-- markerRef.current = marker;+ }).setLngLat([longitude, latitude]);const handleClick = (e: MouseEvent) => onClick?.(e);const handleMouseEnter = (e: MouseEvent) => onMouseEnter?.(e);const handleMouseLeave = (e: MouseEvent) => onMouseLeave?.(e);- container.addEventListener("click", handleClick);- container.addEventListener("mouseenter", handleMouseEnter);- container.addEventListener("mouseleave", handleMouseLeave);+ markerInstance.getElement()?.addEventListener("click", handleClick);+ markerInstance+ .getElement()+ ?.addEventListener("mouseenter", handleMouseEnter);+ markerInstance+ .getElement()+ ?.addEventListener("mouseleave", handleMouseLeave);const handleDragStart = () => {- const lngLat = marker.getLngLat();+ const lngLat = markerInstance.getLngLat();onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });};const handleDrag = () => {- const lngLat = marker.getLngLat();+ const lngLat = markerInstance.getLngLat();onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });};const handleDragEnd = () => {- const lngLat = marker.getLngLat();+ const lngLat = markerInstance.getLngLat();onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });};- marker.on("dragstart", handleDragStart);- marker.on("drag", handleDrag);- marker.on("dragend", handleDragEnd);+ markerInstance.on("dragstart", handleDragStart);+ markerInstance.on("drag", handleDrag);+ markerInstance.on("dragend", handleDragEnd);- setIsReady(true);+ return markerInstance;- return () => {- container.removeEventListener("click", handleClick);- container.removeEventListener("mouseenter", handleMouseEnter);- container.removeEventListener("mouseleave", handleMouseLeave);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);- marker.off("dragstart", handleDragStart);- marker.off("drag", handleDrag);- marker.off("dragend", handleDragEnd);+ useEffect(() => {+ if (!map) return;+ marker.addTo(map);++ return () => {marker.remove();- markerRef.current = null;- markerElementRef.current = null;- setIsReady(false);};- }, [map, isLoaded]);-- useEffect(() => {- markerRef.current?.setLngLat([longitude, latitude]);- }, [longitude, latitude]);- useEffect(() => {- markerRef.current?.setDraggable(draggable);- }, [draggable]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [map]);- useEffect(() => {- if (!markerRef.current) return;- const prev = markerOptionsRef.current;+ if (+ marker.getLngLat().lng !== longitude ||+ marker.getLngLat().lat !== latitude+ ) {+ marker.setLngLat([longitude, latitude]);+ }+ if (marker.isDraggable() !== draggable) {+ marker.setDraggable(draggable);+ }- if (prev.offset !== markerOptions.offset) {- markerRef.current.setOffset(markerOptions.offset ?? [0, 0]);- }- if (prev.rotation !== markerOptions.rotation) {- markerRef.current.setRotation(markerOptions.rotation ?? 0);- }- if (prev.rotationAlignment !== markerOptions.rotationAlignment) {- markerRef.current.setRotationAlignment(- markerOptions.rotationAlignment ?? "auto"- );- }- if (prev.pitchAlignment !== markerOptions.pitchAlignment) {- markerRef.current.setPitchAlignment(- markerOptions.pitchAlignment ?? "auto"- );- }+ const currentOffset = marker.getOffset();+ const newOffset = markerOptions.offset ?? [0, 0];+ const [newOffsetX, newOffsetY] = Array.isArray(newOffset)+ ? newOffset+ : [newOffset.x, newOffset.y];+ if (currentOffset.x !== newOffsetX || currentOffset.y !== newOffsetY) {+ marker.setOffset(newOffset);+ }- markerOptionsRef.current = markerOptions;- }, [markerOptions]);+ if (marker.getRotation() !== markerOptions.rotation) {+ marker.setRotation(markerOptions.rotation ?? 0);+ }+ if (marker.getRotationAlignment() !== markerOptions.rotationAlignment) {+ marker.setRotationAlignment(markerOptions.rotationAlignment ?? "auto");+ }+ if (marker.getPitchAlignment() !== markerOptions.pitchAlignment) {+ marker.setPitchAlignment(markerOptions.pitchAlignment ?? "auto");+ }return (- <MarkerContext.Provider- value={{ markerRef, markerElementRef, map, isReady }}- >+ <MarkerContext.Provider value={{ marker, map }}>{children}</MarkerContext.Provider>);@@ -304,15 +302,13 @@ type MarkerContentProps = {};function MarkerContent({ children, className }: MarkerContentProps) {- const { markerElementRef, isReady } = useMarkerContext();-- if (!isReady || !markerElementRef.current) return null;+ const { marker } = useMarkerContext();return createPortal(<div className={cn("relative cursor-pointer", className)}>{children || <DefaultMarkerIcon />}</div>,- markerElementRef.current+ marker.getElement());}@@ -337,19 +333,12 @@ function MarkerPopup({closeButton = false,...popupOptions}: MarkerPopupProps) {- const { markerRef, isReady } = useMarkerContext();- const containerRef = useRef<HTMLDivElement | null>(null);- const popupRef = useRef<MapLibreGL.Popup | null>(null);- const [mounted, setMounted] = useState(false);- const popupOptionsRef = useRef(popupOptions);-- useEffect(() => {- if (!isReady || !markerRef.current) return;-- const container = document.createElement("div");- containerRef.current = container;+ const { marker, map } = useMarkerContext();+ const container = useMemo(() => document.createElement("div"), []);+ const prevPopupOptions = useRef(popupOptions);- const popup = new MapLibreGL.Popup({+ const popup = useMemo(() => {+ const popupInstance = new MapLibreGL.Popup({offset: 16,...popupOptions,closeButton: false,@@ -357,35 +346,36 @@ function MarkerPopup({.setMaxWidth("none").setDOMContent(container);- popupRef.current = popup;- markerRef.current.setPopup(popup);- setMounted(true);+ return popupInstance;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ if (!map) return;++ popup.setDOMContent(container);+ marker.setPopup(popup);return () => {- popup.remove();- popupRef.current = null;- containerRef.current = null;- setMounted(false);+ marker.setPopup(null);};- }, [isReady]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [map]);- useEffect(() => {- if (!popupRef.current) return;- const prev = popupOptionsRef.current;+ if (popup.isOpen()) {+ const prev = prevPopupOptions.current;if (prev.offset !== popupOptions.offset) {- popupRef.current.setOffset(popupOptions.offset ?? 16);+ popup.setOffset(popupOptions.offset ?? 16);}if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {- popupRef.current.setMaxWidth(popupOptions.maxWidth ?? "none");+ popup.setMaxWidth(popupOptions.maxWidth ?? "none");}- popupOptionsRef.current = popupOptions;- }, [popupOptions]);-- const handleClose = () => popupRef.current?.remove();+ prevPopupOptions.current = popupOptions;+ }- if (!mounted || !containerRef.current) return null;+ const handleClose = () => popup.remove();return createPortal(<div@@ -407,7 +397,7 @@ function MarkerPopup({)}{children}</div>,- containerRef.current+ container);}@@ -423,67 +413,55 @@ function MarkerTooltip({className,...popupOptions}: MarkerTooltipProps) {- const { markerRef, markerElementRef, map, isReady } = useMarkerContext();- const containerRef = useRef<HTMLDivElement | null>(null);- const popupRef = useRef<MapLibreGL.Popup | null>(null);- const [mounted, setMounted] = useState(false);- const popupOptionsRef = useRef(popupOptions);-- useEffect(() => {- if (!isReady || !markerRef.current || !markerElementRef.current || !map)- return;-- const container = document.createElement("div");- containerRef.current = container;+ const { marker, map } = useMarkerContext();+ const container = useMemo(() => document.createElement("div"), []);+ const prevTooltipOptions = useRef(popupOptions);- const popup = new MapLibreGL.Popup({+ const tooltip = useMemo(() => {+ const tooltipInstance = new MapLibreGL.Popup({offset: 16,...popupOptions,closeOnClick: true,closeButton: false,- })- .setMaxWidth("none")- .setDOMContent(container);+ }).setMaxWidth("none");- popupRef.current = popup;+ return tooltipInstance;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);- const markerElement = markerElementRef.current;- const marker = markerRef.current;+ useEffect(() => {+ if (!map) return;++ tooltip.setDOMContent(container);const handleMouseEnter = () => {- popup.setLngLat(marker.getLngLat()).addTo(map);+ tooltip.setLngLat(marker.getLngLat()).addTo(map);};- const handleMouseLeave = () => popup.remove();+ const handleMouseLeave = () => tooltip.remove();- markerElement.addEventListener("mouseenter", handleMouseEnter);- markerElement.addEventListener("mouseleave", handleMouseLeave);- setMounted(true);+ marker.getElement()?.addEventListener("mouseenter", handleMouseEnter);+ marker.getElement()?.addEventListener("mouseleave", handleMouseLeave);return () => {- markerElement.removeEventListener("mouseenter", handleMouseEnter);- markerElement.removeEventListener("mouseleave", handleMouseLeave);- popup.remove();- popupRef.current = null;- containerRef.current = null;- setMounted(false);+ marker.getElement()?.removeEventListener("mouseenter", handleMouseEnter);+ marker.getElement()?.removeEventListener("mouseleave", handleMouseLeave);+ tooltip.remove();};- }, [isReady, map]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [map]);- useEffect(() => {- if (!popupRef.current) return;- const prev = popupOptionsRef.current;+ if (tooltip.isOpen()) {+ const prev = prevTooltipOptions.current;if (prev.offset !== popupOptions.offset) {- popupRef.current.setOffset(popupOptions.offset ?? 16);+ tooltip.setOffset(popupOptions.offset ?? 16);}if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {- popupRef.current.setMaxWidth(popupOptions.maxWidth ?? "none");+ tooltip.setMaxWidth(popupOptions.maxWidth ?? "none");}- popupOptionsRef.current = popupOptions;- }, [popupOptions]);-- if (!mounted || !containerRef.current) return null;+ prevTooltipOptions.current = popupOptions;+ }return createPortal(<div@@ -494,7 +472,7 @@ function MarkerTooltip({>{children}</div>,- containerRef.current+ container);}@@ -767,59 +745,61 @@ function MapPopup({...popupOptions}: MapPopupProps) {const { map } = useMap();- const popupRef = useRef<MapLibreGL.Popup | null>(null);const popupOptionsRef = useRef(popupOptions);-const container = useMemo(() => document.createElement("div"), []);- useEffect(() => {- if (!map) return;-- const popup = new MapLibreGL.Popup({+ const popup = useMemo(() => {+ const popupInstance = new MapLibreGL.Popup({offset: 16,...popupOptions,closeButton: false,}).setMaxWidth("none")- .setDOMContent(container)- .setLngLat([longitude, latitude])- .addTo(map);+ .setLngLat([longitude, latitude]);- const onCloseProp = () => onClose?.();+ return popupInstance;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+ useEffect(() => {+ if (!map) return;++ const onCloseProp = () => onClose?.();popup.on("close", onCloseProp);- popupRef.current = popup;+ popup.setDOMContent(container);+ popup.addTo(map);return () => {popup.off("close", onCloseProp);if (popup.isOpen()) {popup.remove();}- popupRef.current = null;};+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [map]);- useEffect(() => {- popupRef.current?.setLngLat([longitude, latitude]);- }, [longitude, latitude]);-- useEffect(() => {- if (!popupRef.current) return;+ if (popup.isOpen()) {const prev = popupOptionsRef.current;+ if (+ popup.getLngLat().lng !== longitude ||+ popup.getLngLat().lat !== latitude+ ) {+ popup.setLngLat([longitude, latitude]);+ }+if (prev.offset !== popupOptions.offset) {- popupRef.current.setOffset(popupOptions.offset ?? 16);+ popup.setOffset(popupOptions.offset ?? 16);}if (prev.maxWidth !== popupOptions.maxWidth && popupOptions.maxWidth) {- popupRef.current.setMaxWidth(popupOptions.maxWidth ?? "none");+ popup.setMaxWidth(popupOptions.maxWidth ?? "none");}-popupOptionsRef.current = popupOptions;- }, [popupOptions]);+ }const handleClose = () => {- popupRef.current?.remove();+ popup.remove();onClose?.();};@@ -858,6 +838,14 @@ type MapRouteProps = {opacity?: number;/** Dash pattern [dash length, gap length] for dashed lines */dashArray?: [number, number];+ /** Callback when the route line is clicked */+ onClick?: () => void;+ /** Callback when mouse enters the route line */+ onMouseEnter?: () => void;+ /** Callback when mouse leaves the route line */+ onMouseLeave?: () => void;+ /** Whether the route is interactive - shows pointer cursor on hover (default: true) */+ interactive?: boolean;};function MapRoute({@@ -866,11 +854,15 @@ function MapRoute({width = 3,opacity = 0.8,dashArray,+ onClick,+ onMouseEnter,+ onMouseLeave,+ interactive = true,}: MapRouteProps) {const { map, isLoaded } = useMap();- const id = useId();- const sourceId = `route-source-${id}`;- const layerId = `route-layer-${id}`;+ const autoId = useId();+ const sourceId = `route-source-${autoId}`;+ const layerId = `route-layer-${autoId}`;// Add source and layer on mountuseEffect(() => {@@ -906,7 +898,8 @@ function MapRoute({// ignore}};- }, [isLoaded, map, sourceId, layerId]);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [isLoaded, map]);// When coordinates change, update the source datauseEffect(() => {@@ -933,6 +926,42 @@ function MapRoute({}}, [isLoaded, map, layerId, color, width, opacity, dashArray]);+ // Handle click and hover events+ useEffect(() => {+ if (!isLoaded || !map || !interactive) return;++ const handleClick = (e: MapLibreGL.MapMouseEvent) => {+ e.originalEvent.stopImmediatePropagation();+ onClick?.();+ };+ const handleMouseEnter = () => {+ map.getCanvas().style.cursor = "pointer";+ onMouseEnter?.();+ };+ const handleMouseLeave = () => {+ map.getCanvas().style.cursor = "";+ onMouseLeave?.();+ };++ map.on("click", layerId, handleClick);+ map.on("mouseenter", layerId, handleMouseEnter);+ map.on("mouseleave", layerId, handleMouseLeave);++ return () => {+ map.off("click", layerId, handleClick);+ map.off("mouseenter", layerId, handleMouseEnter);+ map.off("mouseleave", layerId, handleMouseLeave);+ };+ }, [+ isLoaded,+ map,+ layerId,+ onClick,+ onMouseEnter,+ onMouseLeave,+ interactive,+ ]);+return null;}@@ -996,7 +1025,7 @@ function MapClusterLayer<// Add clustered GeoJSON sourcemap.addSource(sourceId, {type: "geojson",- data: typeof data === "string" ? data : data,+ data,cluster: true,clusterMaxZoom,clusterRadius,@@ -1069,9 +1098,10 @@ function MapClusterLayer<// ignore}};+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [isLoaded, map, sourceId]);- // Update source data when data prop changes (only for non-URL data )+ // Update source data when data prop changes (only for non-URL data)useEffect(() => {if (!isLoaded || !map || typeof data === "string") return;