Beautiful map components. 100% Free, Zero config, one command setup.
TypeScript
feat: UI enhacements
Anmoldeep Singha2250f8bdd4d
diff --git a/package-lock.json b/package-lock.jsonindex 355061c..60078a4 100644--- a/package-lock.json+++ b/package-lock.json@@ -15,6 +15,7 @@"@vercel/analytics": "^1.6.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1",+ "cmdk": "^1.1.1","lucide-react": "^0.562.0","maplibre-gl": "^5.15.0","next": "16.1.1",@@ -4809,6 +4810,22 @@"node": ">=6"}},+ "node_modules/cmdk": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.1.1.tgz",+ "integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==",+ "license": "MIT",+ "dependencies": {+ "@radix-ui/react-compose-refs": "^1.1.1",+ "@radix-ui/react-dialog": "^1.1.6",+ "@radix-ui/react-id": "^1.1.0",+ "@radix-ui/react-primitive": "^2.0.2"+ },+ "peerDependencies": {+ "react": "^18 || ^19 || ^19.0.0-rc",+ "react-dom": "^18 || ^19 || ^19.0.0-rc"+ }+ },"node_modules/code-block-writer": {"version": "13.0.3","resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz",diff --git a/package.json b/package.jsonindex cf5c1d7..c031000 100644--- a/package.json+++ b/package.json@@ -17,6 +17,7 @@"@vercel/analytics": "^1.6.1","class-variance-authority": "^0.7.1","clsx": "^2.1.1",+ "cmdk": "^1.1.1","lucide-react": "^0.562.0","maplibre-gl": "^5.15.0","next": "16.1.1",diff --git a/public/maps/map.json b/public/maps/map.jsonindex 12e7c4b..219dc4c 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 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 const currentStyleRef = useRef<MapStyleOption | null>(null);\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 initialStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n currentStyleRef.current = initialStyle;\n\n const map = new MapLibreGL.Map({\n container: containerRef.current,\n style: initialStyle,\n renderWorldCopies: false,\n attributionControl: {\n compact: true,\n },\n ...props,\n });\n\n const styleDataHandler = () => setIsStyleLoaded(true);\n const loadHandler = () => setIsLoaded(true);\n\n map.on(\"load\", loadHandler);\n map.on(\"styledata\", styleDataHandler);\n setMapInstance(map);\n\n return () => {\n map.off(\"load\", loadHandler);\n map.off(\"styledata\", styleDataHandler);\n map.remove();\n setIsLoaded(false);\n setIsStyleLoaded(false);\n setMapInstance(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!mapInstance || !resolvedTheme) return;\n\n const newStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n if (currentStyleRef.current === newStyle) return;\n\n currentStyleRef.current = newStyle;\n setIsStyleLoaded(false);\n\n const frameId = requestAnimationFrame(() => {\n mapInstance.setStyle(newStyle, { diff: true });\n });\n\n return () => cancelAnimationFrame(frameId);\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 /** Optional unique identifier for the route layer */\n id?: string;\n /** Array of [longitude, latitude] coordinate pairs defining the route */\n coordinates: [number, number][];\n /** Line color as CSS color value (default: \"#4285F4\") */\n color?: string;\n /** Line width in pixels (default: 3) */\n width?: number;\n /** Line opacity from 0 to 1 (default: 0.8) */\n opacity?: number;\n /** Dash pattern [dash length, gap length] for dashed lines */\n dashArray?: [number, number];\n /** Callback when the route line is clicked */\n onClick?: () => void;\n /** Callback when mouse enters the route line */\n onMouseEnter?: () => void;\n /** Callback when mouse leaves the route line */\n onMouseLeave?: () => void;\n /** Whether the route is interactive - shows pointer cursor on hover (default: true) */\n interactive?: boolean;\n};\n\nfunction MapRoute({\n id: propId,\n coordinates,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive = true,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `route-source-${id}`;\n const layerId = `route-layer-${id}`;\n\n // Add source and layer on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: {\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates: [] },\n },\n });\n\n map.addLayer({\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: { \"line-join\": \"round\", \"line-cap\": \"round\" },\n paint: {\n \"line-color\": color,\n \"line-width\": width,\n \"line-opacity\": opacity,\n ...(dashArray && { \"line-dasharray\": dashArray }),\n },\n });\n\n return () => {\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // When coordinates change, update the source data\n useEffect(() => {\n if (!isLoaded || !map || coordinates.length < 2) return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData({\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates },\n });\n }\n }, [isLoaded, map, coordinates, sourceId]);\n\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n\n map.setPaintProperty(layerId, \"line-color\", color);\n map.setPaintProperty(layerId, \"line-width\", width);\n map.setPaintProperty(layerId, \"line-opacity\", opacity);\n if (dashArray) {\n map.setPaintProperty(layerId, \"line-dasharray\", dashArray);\n }\n }, [isLoaded, map, layerId, color, width, opacity, dashArray]);\n\n // Handle click and hover events\n useEffect(() => {\n if (!isLoaded || !map || !interactive) return;\n\n const handleClick = () => {\n onClick?.();\n };\n const handleMouseEnter = () => {\n map.getCanvas().style.cursor = \"pointer\";\n onMouseEnter?.();\n };\n const handleMouseLeave = () => {\n map.getCanvas().style.cursor = \"\";\n onMouseLeave?.();\n };\n\n map.on(\"click\", layerId, handleClick);\n map.on(\"mouseenter\", layerId, handleMouseEnter);\n map.on(\"mouseleave\", layerId, handleMouseLeave);\n\n return () => {\n map.off(\"click\", layerId, handleClick);\n map.off(\"mouseenter\", layerId, handleMouseEnter);\n map.off(\"mouseleave\", layerId, handleMouseLeave);\n };\n }, [\n isLoaded,\n map,\n layerId,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive,\n ]);\n\n return null;\n}\n\ntype MapClusterLayerProps<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties\n> = {\n /** GeoJSON FeatureCollection data or URL to fetch GeoJSON from */\n data: string | GeoJSON.FeatureCollection<GeoJSON.Point, P>;\n /** Maximum zoom level to cluster points on (default: 14) */\n clusterMaxZoom?: number;\n /** Radius of each cluster when clustering points in pixels (default: 50) */\n clusterRadius?: number;\n /** Colors for cluster circles: [small, medium, large] based on point count (default: [\"#51bbd6\", \"#f1f075\", \"#f28cb1\"]) */\n clusterColors?: [string, string, string];\n /** Point count thresholds for color/size steps: [medium, large] (default: [100, 750]) */\n clusterThresholds?: [number, number];\n /** Color for unclustered individual points (default: \"#3b82f6\") */\n pointColor?: string;\n /** Callback when an unclustered point is clicked */\n onPointClick?: (\n feature: GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates: [number, number]\n ) => void;\n /** Callback when a cluster is clicked. If not provided, zooms into the cluster */\n onClusterClick?: (\n clusterId: number,\n coordinates: [number, number],\n pointCount: number\n ) => void;\n};\n\nfunction MapClusterLayer<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties\n>({\n data,\n clusterMaxZoom = 14,\n clusterRadius = 50,\n clusterColors = [\"#51bbd6\", \"#f1f075\", \"#f28cb1\"],\n clusterThresholds = [100, 750],\n pointColor = \"#3b82f6\",\n onPointClick,\n onClusterClick,\n}: MapClusterLayerProps<P>) {\n const { map, isLoaded } = useMap();\n const id = useId();\n const sourceId = `cluster-source-${id}`;\n const clusterLayerId = `clusters-${id}`;\n const clusterCountLayerId = `cluster-count-${id}`;\n const unclusteredLayerId = `unclustered-point-${id}`;\n\n const stylePropsRef = useRef({\n clusterColors,\n clusterThresholds,\n pointColor,\n });\n\n // Add source and layers on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Add clustered GeoJSON source\n map.addSource(sourceId, {\n type: \"geojson\",\n data,\n cluster: true,\n clusterMaxZoom,\n clusterRadius,\n });\n\n // Add cluster circles layer\n map.addLayer({\n id: clusterLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n paint: {\n \"circle-color\": [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ],\n \"circle-radius\": [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ],\n },\n });\n\n // Add cluster count text layer\n map.addLayer({\n id: clusterCountLayerId,\n type: \"symbol\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n layout: {\n \"text-field\": \"{point_count_abbreviated}\",\n \"text-size\": 12,\n },\n paint: {\n \"text-color\": \"#fff\",\n },\n });\n\n // Add unclustered point layer\n map.addLayer({\n id: unclusteredLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"!\", [\"has\", \"point_count\"]],\n paint: {\n \"circle-color\": pointColor,\n \"circle-radius\": 6,\n },\n });\n\n return () => {\n try {\n if (map.getLayer(clusterCountLayerId))\n map.removeLayer(clusterCountLayerId);\n if (map.getLayer(unclusteredLayerId))\n map.removeLayer(unclusteredLayerId);\n if (map.getLayer(clusterLayerId)) map.removeLayer(clusterLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map, sourceId]);\n\n // Update source data when data prop changes (only for non-URL data)\n useEffect(() => {\n if (!isLoaded || !map || typeof data === \"string\") return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData(data);\n }\n }, [isLoaded, map, data, sourceId]);\n\n // Update layer styles when props change\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const prev = stylePropsRef.current;\n const colorsChanged =\n prev.clusterColors !== clusterColors ||\n prev.clusterThresholds !== clusterThresholds;\n\n // Update cluster layer colors and sizes\n if (map.getLayer(clusterLayerId) && colorsChanged) {\n map.setPaintProperty(clusterLayerId, \"circle-color\", [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ]);\n map.setPaintProperty(clusterLayerId, \"circle-radius\", [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ]);\n }\n\n // Update unclustered point layer color\n if (map.getLayer(unclusteredLayerId) && prev.pointColor !== pointColor) {\n map.setPaintProperty(unclusteredLayerId, \"circle-color\", pointColor);\n }\n\n stylePropsRef.current = { clusterColors, clusterThresholds, pointColor };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n clusterColors,\n clusterThresholds,\n pointColor,\n ]);\n\n // Handle click events\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Cluster click handler - zoom into cluster\n const handleClusterClick = async (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n }\n ) => {\n const features = map.queryRenderedFeatures(e.point, {\n layers: [clusterLayerId],\n });\n if (!features.length) return;\n\n const feature = features[0];\n const clusterId = feature.properties?.cluster_id as number;\n const pointCount = feature.properties?.point_count as number;\n const coordinates = (feature.geometry as GeoJSON.Point).coordinates as [\n number,\n number\n ];\n\n if (onClusterClick) {\n onClusterClick(clusterId, coordinates, pointCount);\n } else {\n // Default behavior: zoom to cluster expansion zoom\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n const zoom = await source.getClusterExpansionZoom(clusterId);\n map.easeTo({\n center: coordinates,\n zoom,\n });\n }\n };\n\n // Unclustered point click handler\n const handlePointClick = (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n }\n ) => {\n if (!onPointClick || !e.features?.length) return;\n\n const feature = e.features[0];\n const coordinates = (\n feature.geometry as GeoJSON.Point\n ).coordinates.slice() as [number, number];\n\n // Handle world copies\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n onPointClick(\n feature as unknown as GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates\n );\n };\n\n // Cursor style handlers\n const handleMouseEnterCluster = () => {\n map.getCanvas().style.cursor = \"pointer\";\n };\n const handleMouseLeaveCluster = () => {\n map.getCanvas().style.cursor = \"\";\n };\n const handleMouseEnterPoint = () => {\n if (onPointClick) {\n map.getCanvas().style.cursor = \"pointer\";\n }\n };\n const handleMouseLeavePoint = () => {\n map.getCanvas().style.cursor = \"\";\n };\n\n map.on(\"click\", clusterLayerId, handleClusterClick);\n map.on(\"click\", unclusteredLayerId, handlePointClick);\n map.on(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.on(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.on(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.on(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n\n return () => {\n map.off(\"click\", clusterLayerId, handleClusterClick);\n map.off(\"click\", unclusteredLayerId, handlePointClick);\n map.off(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.off(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.off(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.off(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n sourceId,\n onClusterClick,\n onPointClick,\n ]);\n\n return null;\n}\n\nexport {\n Map,\n useMap,\n MapMarker,\n MarkerContent,\n MarkerPopup,\n MarkerTooltip,\n MarkerLabel,\n MapPopup,\n MapControls,\n MapRoute,\n MapClusterLayer,\n};\n\nexport type { MapRef };\n",+ "content": "\"use client\";\n\nimport MapLibreGL, { type PopupOptions, type MarkerOptions } from \"maplibre-gl\";\nimport \"maplibre-gl/dist/maplibre-gl.css\";\nimport { 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\";\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 /** Map projection type. Use `{ type: \"globe\" }` for 3D globe view. */\n projection?: MapLibreGL.ProjectionSpecification;\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\n\ntype MapRef = MapLibreGL.Map;\n\nconst DefaultLoader = () => (\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"flex gap-1\">\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:150ms]\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:300ms]\" />\n </div>\n </div>\n);\n\nconst Map = forwardRef<MapRef, MapProps>(function Map(\n { children, styles, projection, ...props },\n ref\n) {\n const containerRef = useRef<HTMLDivElement>(null);\n const [mapInstance, setMapInstance] = useState<MapLibreGL.Map | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [isStyleLoaded, setIsStyleLoaded] = useState(false);\n const { resolvedTheme } = useTheme();\n const currentStyleRef = useRef<MapStyleOption | null>(null);\n const styleTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const mapStyles = useMemo(\n () => ({\n dark: styles?.dark ?? defaultStyles.dark,\n light: styles?.light ?? defaultStyles.light,\n }),\n [styles]\n );\n\n useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);\n\n const clearStyleTimeout = useCallback(() => {\n if (styleTimeoutRef.current) {\n clearTimeout(styleTimeoutRef.current);\n styleTimeoutRef.current = null;\n }\n }, []);\n\n useEffect(() => {\n if (!containerRef.current) return;\n\n const initialStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n currentStyleRef.current = initialStyle;\n\n const map = new MapLibreGL.Map({\n container: containerRef.current,\n style: initialStyle,\n renderWorldCopies: false,\n attributionControl: {\n compact: true,\n },\n ...props,\n });\n\n const styleDataHandler = () => {\n clearStyleTimeout();\n // Delay to ensure style is fully processed before allowing layer operations\n // This is a workaround to avoid race conditions with the style loading\n styleTimeoutRef.current = setTimeout(() => {\n setIsStyleLoaded(true);\n if (projection) {\n map.setProjection(projection);\n }\n }, 150);\n };\n const loadHandler = () => setIsLoaded(true);\n\n map.on(\"load\", loadHandler);\n map.on(\"styledata\", styleDataHandler);\n setMapInstance(map);\n\n return () => {\n clearStyleTimeout();\n map.off(\"load\", loadHandler);\n map.off(\"styledata\", styleDataHandler);\n map.remove();\n setIsLoaded(false);\n setIsStyleLoaded(false);\n setMapInstance(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (!mapInstance || !resolvedTheme) return;\n\n const newStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n if (currentStyleRef.current === newStyle) return;\n\n clearStyleTimeout();\n currentStyleRef.current = newStyle;\n setIsStyleLoaded(false);\n\n mapInstance.setStyle(newStyle, { diff: true });\n }, [mapInstance, resolvedTheme, mapStyles, clearStyleTimeout]);\n\n const 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 /** Optional unique identifier for the route layer */\n id?: string;\n /** Array of [longitude, latitude] coordinate pairs defining the route */\n coordinates: [number, number][];\n /** Line color as CSS color value (default: \"#4285F4\") */\n color?: string;\n /** Line width in pixels (default: 3) */\n width?: number;\n /** Line opacity from 0 to 1 (default: 0.8) */\n opacity?: number;\n /** Dash pattern [dash length, gap length] for dashed lines */\n dashArray?: [number, number];\n /** Callback when the route line is clicked */\n onClick?: () => void;\n /** Callback when mouse enters the route line */\n onMouseEnter?: () => void;\n /** Callback when mouse leaves the route line */\n onMouseLeave?: () => void;\n /** Whether the route is interactive - shows pointer cursor on hover (default: true) */\n interactive?: boolean;\n};\n\nfunction MapRoute({\n id: propId,\n coordinates,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive = true,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const autoId = useId();\n const id = propId ?? autoId;\n const sourceId = `route-source-${id}`;\n const layerId = `route-layer-${id}`;\n\n // Add source and layer on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n map.addSource(sourceId, {\n type: \"geojson\",\n data: {\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates: [] },\n },\n });\n\n map.addLayer({\n id: layerId,\n type: \"line\",\n source: sourceId,\n layout: { \"line-join\": \"round\", \"line-cap\": \"round\" },\n paint: {\n \"line-color\": color,\n \"line-width\": width,\n \"line-opacity\": opacity,\n ...(dashArray && { \"line-dasharray\": dashArray }),\n },\n });\n\n return () => {\n try {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map]);\n\n // When coordinates change, update the source data\n useEffect(() => {\n if (!isLoaded || !map || coordinates.length < 2) return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData({\n type: \"Feature\",\n properties: {},\n geometry: { type: \"LineString\", coordinates },\n });\n }\n }, [isLoaded, map, coordinates, sourceId]);\n\n useEffect(() => {\n if (!isLoaded || !map || !map.getLayer(layerId)) return;\n\n map.setPaintProperty(layerId, \"line-color\", color);\n map.setPaintProperty(layerId, \"line-width\", width);\n map.setPaintProperty(layerId, \"line-opacity\", opacity);\n if (dashArray) {\n map.setPaintProperty(layerId, \"line-dasharray\", dashArray);\n }\n }, [isLoaded, map, layerId, color, width, opacity, dashArray]);\n\n // Handle click and hover events\n useEffect(() => {\n if (!isLoaded || !map || !interactive) return;\n\n const handleClick = () => {\n onClick?.();\n };\n const handleMouseEnter = () => {\n map.getCanvas().style.cursor = \"pointer\";\n onMouseEnter?.();\n };\n const handleMouseLeave = () => {\n map.getCanvas().style.cursor = \"\";\n onMouseLeave?.();\n };\n\n map.on(\"click\", layerId, handleClick);\n map.on(\"mouseenter\", layerId, handleMouseEnter);\n map.on(\"mouseleave\", layerId, handleMouseLeave);\n\n return () => {\n map.off(\"click\", layerId, handleClick);\n map.off(\"mouseenter\", layerId, handleMouseEnter);\n map.off(\"mouseleave\", layerId, handleMouseLeave);\n };\n }, [\n isLoaded,\n map,\n layerId,\n onClick,\n onMouseEnter,\n onMouseLeave,\n interactive,\n ]);\n\n return null;\n}\n\ntype MapClusterLayerProps<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties\n> = {\n /** GeoJSON FeatureCollection data or URL to fetch GeoJSON from */\n data: string | GeoJSON.FeatureCollection<GeoJSON.Point, P>;\n /** Maximum zoom level to cluster points on (default: 14) */\n clusterMaxZoom?: number;\n /** Radius of each cluster when clustering points in pixels (default: 50) */\n clusterRadius?: number;\n /** Colors for cluster circles: [small, medium, large] based on point count (default: [\"#51bbd6\", \"#f1f075\", \"#f28cb1\"]) */\n clusterColors?: [string, string, string];\n /** Point count thresholds for color/size steps: [medium, large] (default: [100, 750]) */\n clusterThresholds?: [number, number];\n /** Color for unclustered individual points (default: \"#3b82f6\") */\n pointColor?: string;\n /** Callback when an unclustered point is clicked */\n onPointClick?: (\n feature: GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates: [number, number]\n ) => void;\n /** Callback when a cluster is clicked. If not provided, zooms into the cluster */\n onClusterClick?: (\n clusterId: number,\n coordinates: [number, number],\n pointCount: number\n ) => void;\n};\n\nfunction MapClusterLayer<\n P extends GeoJSON.GeoJsonProperties = GeoJSON.GeoJsonProperties\n>({\n data,\n clusterMaxZoom = 14,\n clusterRadius = 50,\n clusterColors = [\"#51bbd6\", \"#f1f075\", \"#f28cb1\"],\n clusterThresholds = [100, 750],\n pointColor = \"#3b82f6\",\n onPointClick,\n onClusterClick,\n}: MapClusterLayerProps<P>) {\n const { map, isLoaded } = useMap();\n const id = useId();\n const sourceId = `cluster-source-${id}`;\n const clusterLayerId = `clusters-${id}`;\n const clusterCountLayerId = `cluster-count-${id}`;\n const unclusteredLayerId = `unclustered-point-${id}`;\n\n const stylePropsRef = useRef({\n clusterColors,\n clusterThresholds,\n pointColor,\n });\n\n // Add source and layers on mount\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Add clustered GeoJSON source\n map.addSource(sourceId, {\n type: \"geojson\",\n data,\n cluster: true,\n clusterMaxZoom,\n clusterRadius,\n });\n\n // Add cluster circles layer\n map.addLayer({\n id: clusterLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n paint: {\n \"circle-color\": [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ],\n \"circle-radius\": [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ],\n },\n });\n\n // Add cluster count text layer\n map.addLayer({\n id: clusterCountLayerId,\n type: \"symbol\",\n source: sourceId,\n filter: [\"has\", \"point_count\"],\n layout: {\n \"text-field\": \"{point_count_abbreviated}\",\n \"text-size\": 12,\n },\n paint: {\n \"text-color\": \"#fff\",\n },\n });\n\n // Add unclustered point layer\n map.addLayer({\n id: unclusteredLayerId,\n type: \"circle\",\n source: sourceId,\n filter: [\"!\", [\"has\", \"point_count\"]],\n paint: {\n \"circle-color\": pointColor,\n \"circle-radius\": 6,\n },\n });\n\n return () => {\n try {\n if (map.getLayer(clusterCountLayerId))\n map.removeLayer(clusterCountLayerId);\n if (map.getLayer(unclusteredLayerId))\n map.removeLayer(unclusteredLayerId);\n if (map.getLayer(clusterLayerId)) map.removeLayer(clusterLayerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\n } catch {\n // ignore\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [isLoaded, map, sourceId]);\n\n // Update source data when data prop changes (only for non-URL data)\n useEffect(() => {\n if (!isLoaded || !map || typeof data === \"string\") return;\n\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n if (source) {\n source.setData(data);\n }\n }, [isLoaded, map, data, sourceId]);\n\n // Update layer styles when props change\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const prev = stylePropsRef.current;\n const colorsChanged =\n prev.clusterColors !== clusterColors ||\n prev.clusterThresholds !== clusterThresholds;\n\n // Update cluster layer colors and sizes\n if (map.getLayer(clusterLayerId) && colorsChanged) {\n map.setPaintProperty(clusterLayerId, \"circle-color\", [\n \"step\",\n [\"get\", \"point_count\"],\n clusterColors[0],\n clusterThresholds[0],\n clusterColors[1],\n clusterThresholds[1],\n clusterColors[2],\n ]);\n map.setPaintProperty(clusterLayerId, \"circle-radius\", [\n \"step\",\n [\"get\", \"point_count\"],\n 20,\n clusterThresholds[0],\n 30,\n clusterThresholds[1],\n 40,\n ]);\n }\n\n // Update unclustered point layer color\n if (map.getLayer(unclusteredLayerId) && prev.pointColor !== pointColor) {\n map.setPaintProperty(unclusteredLayerId, \"circle-color\", pointColor);\n }\n\n stylePropsRef.current = { clusterColors, clusterThresholds, pointColor };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n clusterColors,\n clusterThresholds,\n pointColor,\n ]);\n\n // Handle click events\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n // Cluster click handler - zoom into cluster\n const handleClusterClick = async (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n }\n ) => {\n const features = map.queryRenderedFeatures(e.point, {\n layers: [clusterLayerId],\n });\n if (!features.length) return;\n\n const feature = features[0];\n const clusterId = feature.properties?.cluster_id as number;\n const pointCount = feature.properties?.point_count as number;\n const coordinates = (feature.geometry as GeoJSON.Point).coordinates as [\n number,\n number\n ];\n\n if (onClusterClick) {\n onClusterClick(clusterId, coordinates, pointCount);\n } else {\n // Default behavior: zoom to cluster expansion zoom\n const source = map.getSource(sourceId) as MapLibreGL.GeoJSONSource;\n const zoom = await source.getClusterExpansionZoom(clusterId);\n map.easeTo({\n center: coordinates,\n zoom,\n });\n }\n };\n\n // Unclustered point click handler\n const handlePointClick = (\n e: MapLibreGL.MapMouseEvent & {\n features?: MapLibreGL.MapGeoJSONFeature[];\n }\n ) => {\n if (!onPointClick || !e.features?.length) return;\n\n const feature = e.features[0];\n const coordinates = (\n feature.geometry as GeoJSON.Point\n ).coordinates.slice() as [number, number];\n\n // Handle world copies\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n onPointClick(\n feature as unknown as GeoJSON.Feature<GeoJSON.Point, P>,\n coordinates\n );\n };\n\n // Cursor style handlers\n const handleMouseEnterCluster = () => {\n map.getCanvas().style.cursor = \"pointer\";\n };\n const handleMouseLeaveCluster = () => {\n map.getCanvas().style.cursor = \"\";\n };\n const handleMouseEnterPoint = () => {\n if (onPointClick) {\n map.getCanvas().style.cursor = \"pointer\";\n }\n };\n const handleMouseLeavePoint = () => {\n map.getCanvas().style.cursor = \"\";\n };\n\n map.on(\"click\", clusterLayerId, handleClusterClick);\n map.on(\"click\", unclusteredLayerId, handlePointClick);\n map.on(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.on(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.on(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.on(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n\n return () => {\n map.off(\"click\", clusterLayerId, handleClusterClick);\n map.off(\"click\", unclusteredLayerId, handlePointClick);\n map.off(\"mouseenter\", clusterLayerId, handleMouseEnterCluster);\n map.off(\"mouseleave\", clusterLayerId, handleMouseLeaveCluster);\n map.off(\"mouseenter\", unclusteredLayerId, handleMouseEnterPoint);\n map.off(\"mouseleave\", unclusteredLayerId, handleMouseLeavePoint);\n };\n }, [\n isLoaded,\n map,\n clusterLayerId,\n unclusteredLayerId,\n sourceId,\n onClusterClick,\n onPointClick,\n ]);\n\n return null;\n}\n\nexport {\n Map,\n useMap,\n MapMarker,\n MarkerContent,\n MarkerPopup,\n MarkerTooltip,\n MarkerLabel,\n MapPopup,\n MapControls,\n MapRoute,\n MapClusterLayer,\n};\n\nexport type { MapRef };\n","type": "registry:ui","target": "components/ui/map.tsx"}diff --git a/src/app/(home)/_components/examples-grid.tsx b/src/app/(home)/_components/examples-grid.tsxnew file mode 100644index 0000000..e9939ef--- /dev/null+++ b/src/app/(home)/_components/examples-grid.tsx@@ -0,0 +1,21 @@+import {+ AnalyticsExample,+ DeliveryExample,+ TrendingExample,+ EVChargingExample,+ TrailExample,+} from "./examples/index";+import { FlyToExample } from "./examples/flyto-example";++export function ExamplesGrid() {+ return (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5 animate-fade-in delay-400">+ <AnalyticsExample />+ <TrailExample />+ <FlyToExample />+ <EVChargingExample />+ <TrendingExample />+ <DeliveryExample />+ </div>+ );+}diff --git a/src/app/(home)/_components/examples.tsx b/src/app/(home)/_components/examples.tsxdeleted file mode 100644index 7ffd999..0000000--- a/src/app/(home)/_components/examples.tsx+++ /dev/null@@ -1,352 +0,0 @@-"use client";--import { useState } from "react";-import {- Map,- MapControls,- MapMarker,- MarkerContent,- MarkerLabel,- MarkerTooltip,- MapRoute,-} from "@/registry/map";-import { Truck, Flame, TrendingUp, Zap } from "lucide-react";-import { cn } from "@/lib/utils";--const analyticsData = [- { lng: -74.006, lat: 40.7128, city: "New York", users: 847, size: 14 },- { lng: -0.1276, lat: 51.5074, city: "London", users: 623, size: 12 },- { lng: 139.6917, lat: 35.6895, city: "Tokyo", users: 412, size: 10 },- { lng: -122.4194, lat: 37.7749, city: "San Francisco", users: 298, size: 9 },- { lng: 2.3522, lat: 48.8566, city: "Paris", users: 187, size: 8 },- { lng: 77.209, lat: 28.6139, city: "Delhi", users: 156, size: 7 },- { lng: 151.2093, lat: -33.8688, city: "Sydney", users: 134, size: 7 },- { lng: -43.1729, lat: -22.9068, city: "Rio", users: 89, size: 6 },- { lng: 4.9041, lat: 52.3676, city: "Amsterdam", users: 76, size: 5 },- { lng: 126.978, lat: 37.5665, city: "Seoul", users: 45, size: 5 },-];--function ExampleCard({- label,- className,- delay = "delay-500",- children,-}: {- label: string;- className?: string;- delay?: string;- children: React.ReactNode;-}) {- return (- <div- className={cn(- "rounded-xl overflow-hidden border border-border/50 shadow bg-card relative animate-scale-in",- delay,- className- )}- >- {label && (- <div className="uppercase absolute top-2 left-2 z-10 tracking-wider text-[10px] text-muted-foreground bg-background/90 backdrop-blur-sm rounded px-2 py-1">- {label}- </div>- )}- {children}- </div>- );-}--export function Examples() {- const [userLocation, setUserLocation] = useState<{- longitude: number;- latitude: number;- } | null>(null);-- return (- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 animate-fade-in delay-400">- {/* Widget 1: Analytics */}- <ExampleCard- label=""- className="aspect-square sm:col-span-2 sm:aspect-video lg:aspect-auto"- delay="delay-400"- >- {/* Stats Panel */}- <div className="absolute top-3 left-3 z-10 bg-background/95 backdrop-blur-md rounded-lg p-3 border border-border/50 shadow-lg">- <div className="tracking-wider text-[10px] text-muted-foreground uppercase mb-1">- Active Users- </div>- <div className="text-2xl font-semibold leading-tight">2,847</div>- <div className="flex items-center gap-1 mt-1">- <TrendingUp className="size-3 text-emerald-500" />- <span className="text-xs text-emerald-500">+12.5%</span>- <span className="text-xs text-muted-foreground">vs last hour</span>- </div>- </div>-- {/* Legend */}- <div className="absolute bottom-3 left-3 z-10 bg-background/95 backdrop-blur-md rounded-lg px-3 py-2 border border-border/50 shadow-lg">- <div className="flex items-center gap-4 text-[10px]">- <div className="flex items-center gap-1.5">- <div className="size-3 rounded-full bg-emerald-500" />- <span className="text-muted-foreground">High</span>- </div>- <div className="flex items-center gap-1.5">- <div className="size-2 rounded-full bg-emerald-500" />- <span className="text-muted-foreground">Medium</span>- </div>- <div className="flex items-center gap-1.5">- <div className="size-1.5 rounded-full bg-emerald-500" />- <span className="text-muted-foreground">Low</span>- </div>- </div>- </div>-- <Map center={[0, 30]} zoom={0.5}>- {analyticsData.map((loc) => (- <MapMarker key={loc.city} longitude={loc.lng} latitude={loc.lat}>- <MarkerContent>- <div className="relative flex items-center justify-center">- <div- className="absolute rounded-full bg-emerald-500/20"- style={{- width: loc.size * 2.5,- height: loc.size * 2.5,- }}- />- <div- className="absolute rounded-full bg-emerald-500/40 animate-ping"- style={{- width: loc.size * 1.5,- height: loc.size * 1.5,- animationDuration: "2s",- }}- />- <div- className="relative rounded-full bg-emerald-500 shadow-lg shadow-emerald-500/50"- style={{ width: loc.size, height: loc.size }}- />- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-center">- <div className="font-medium">{loc.city}</div>- <div className="text-emerald-500 font-semibold">- {loc.users}- </div>- <div className="text-[10px] text-muted-foreground">- active users- </div>- </div>- </MarkerTooltip>- </MapMarker>- ))}- </Map>- </ExampleCard>-- {/* Widget 2: Delivery */}- <ExampleCard label="Delivery" className="aspect-square" delay="delay-500">- <Map center={[-0.1076, 51.517]} zoom={12}>- <MapRoute- coordinates={[- [-0.1276, 51.5074],- [-0.12, 51.512],- [-0.105, 51.518],- [-0.095, 51.522],- [-0.0876, 51.5274],- ]}- width={4}- color="#4285F4"- />- <MapMarker longitude={-0.1276} latitude={51.5074}>- <MarkerContent>- <div className="size-3.5 rounded-full bg-blue-500 border-2 border-white shadow-lg" />- <MarkerLabel>Store</MarkerLabel>- </MarkerContent>- </MapMarker>- <MapMarker longitude={-0.105} latitude={51.518}>- <MarkerContent>- <div className="bg-blue-500 rounded-full p-1.5 shadow-lg">- <Truck className="size-3 text-white" />- </div>- </MarkerContent>- <MarkerTooltip>On the way</MarkerTooltip>- </MapMarker>- <MapMarker longitude={-0.0876} latitude={51.5274}>- <MarkerContent>- <div className="size-3.5 rounded-full bg-blue-500 border-2 border-white shadow-lg" />- <MarkerLabel>Home</MarkerLabel>- </MarkerContent>- </MapMarker>- </Map>- </ExampleCard>-- {/* Widget 3: Trending */}- <ExampleCard label="Trending" className="aspect-square" delay="delay-600">- <Map center={[-73.99, 40.735]} zoom={9.5}>- <MapMarker longitude={-73.9857} latitude={40.7484}>- <MarkerContent>- <div className="relative flex items-center justify-center">- <div className="absolute size-12 rounded-full bg-orange-500/30" />- <div className="absolute size-7 rounded-full bg-orange-500/40" />- <div className="bg-linear-to-br from-orange-500 to-red-500 rounded-full p-1.5 shadow-lg shadow-orange-500/50">- <Flame className="size-3.5 text-white" />- </div>- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-center">- <div className="font-medium">Times Square</div>- <div className="flex items-center justify-center gap-1 text-muted-foreground">- <TrendingUp className="size-3 text-green-500" />- <span className="text-xs text-green-500">2.4k visitors</span>- </div>- </div>- </MarkerTooltip>- </MapMarker>- <MapMarker longitude={-73.9654} latitude={40.7829}>- <MarkerContent>- <div className="relative flex items-center justify-center">- <div className="absolute size-10 rounded-full bg-rose-500/30" />- <div className="bg-linear-to-br from-rose-500 to-pink-500 rounded-full p-1.5 shadow-lg shadow-rose-500/50">- <Flame className="size-3 text-white" />- </div>- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-center">- <div className="font-medium">Central Park</div>- <div className="flex items-center justify-center gap-1 text-muted-foreground">- <TrendingUp className="size-3 text-green-500" />- <span className="text-xs text-green-500">1.8k visitors</span>- </div>- </div>- </MarkerTooltip>- </MapMarker>- <MapMarker longitude={-74.0445} latitude={40.6892}>- <MarkerContent>- <div className="relative flex items-center justify-center">- <div className="absolute size-8 rounded-full bg-amber-500/30" />- <div className="bg-linear-to-br from-amber-500 to-yellow-500 rounded-full p-1 shadow-lg shadow-amber-500/50">- <Flame className="size-2.5 text-white" />- </div>- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-center">- <div className="font-medium">Statue of Liberty</div>- <div className="flex items-center justify-center gap-1 text-muted-foreground">- <TrendingUp className="size-3 text-green-500" />- <span className="text-xs text-green-500">890 visitors</span>- </div>- </div>- </MarkerTooltip>- </MapMarker>- </Map>- </ExampleCard>-- {/* Widget 4: EV Charging */}- <ExampleCard- label="EV Charging"- className="aspect-square"- delay="delay-700"- >- <Map center={[-122.425, 37.777]} zoom={11.5}>- <MapMarker longitude={-122.4194} latitude={37.7749}>- <MarkerContent>- <div className="bg-emerald-500 rounded-full p-1.5 shadow-lg shadow-emerald-500/30">- <Zap className="size-3 text-white fill-white" />- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-xs space-y-0.5">- <div className="font-medium">Market St Station</div>- <div className="flex items-center gap-1">- <span className="size-1.5 rounded-full bg-emerald-500" />- <span className="text-emerald-500">Available</span>- </div>- <div className="text-muted-foreground">150 kW • $0.35/kWh</div>- </div>- </MarkerTooltip>- </MapMarker>-- <MapMarker longitude={-122.4094} latitude={37.7849}>- <MarkerContent>- <div className="bg-emerald-500 rounded-full p-1.5 shadow-lg shadow-emerald-500/30">- <Zap className="size-3 text-white fill-white" />- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-xs space-y-0.5">- <div className="font-medium">Union Square</div>- <div className="flex items-center gap-1">- <span className="size-1.5 rounded-full bg-emerald-500" />- <span className="text-emerald-500">2 Available</span>- </div>- <div className="text-muted-foreground">50 kW • $0.28/kWh</div>- </div>- </MarkerTooltip>- </MapMarker>-- <MapMarker longitude={-122.4294} latitude={37.7689}>- <MarkerContent>- <div className="bg-amber-500 rounded-full p-1.5 shadow-lg shadow-amber-500/30">- <Zap className="size-3 text-white fill-white" />- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-xs space-y-0.5">- <div className="font-medium">Castro Station</div>- <div className="flex items-center gap-1">- <span className="size-1.5 rounded-full bg-amber-500" />- <span className="text-amber-500">In Use</span>- </div>- <div className="text-muted-foreground">~15 min remaining</div>- </div>- </MarkerTooltip>- </MapMarker>-- <MapMarker longitude={-122.4394} latitude={37.7809}>- <MarkerContent>- <div className="bg-zinc-400 rounded-full p-1.5 shadow-lg">- <Zap className="size-3 text-white fill-white" />- </div>- </MarkerContent>- <MarkerTooltip>- <div className="text-xs space-y-0.5">- <div className="font-medium">Hayes Valley</div>- <div className="flex items-center gap-1">- <span className="size-1.5 rounded-full bg-zinc-400" />- <span className="text-muted-foreground">Offline</span>- </div>- </div>- </MarkerTooltip>- </MapMarker>- </Map>- </ExampleCard>-- {/* Widget 5: Locate Me */}- <ExampleCard- label="Locate Me"- className="aspect-square"- delay="delay-800"- >- <Map center={[77.5946, 12.9716]} zoom={10.5}>- <MapControls showZoom={false} showLocate onLocate={setUserLocation} />- {userLocation && (- <MapMarker- longitude={userLocation.longitude}- latitude={userLocation.latitude}- >- <MarkerContent>- <div className="relative flex items-center justify-center">- <div className="absolute size-5 rounded-full bg-blue-500/30 animate-ping" />- <div className="size-3 rounded-full bg-blue-500 border-2 border-white shadow-lg" />- </div>- </MarkerContent>- <MarkerTooltip>Your Location</MarkerTooltip>- </MapMarker>- )}- </Map>- </ExampleCard>- </div>- );-}diff --git a/src/app/(home)/_components/examples/analytics-example.tsx b/src/app/(home)/_components/examples/analytics-example.tsxnew file mode 100644index 0000000..4bd47d3--- /dev/null+++ b/src/app/(home)/_components/examples/analytics-example.tsx@@ -0,0 +1,98 @@+"use client";++import { Map, MapMarker, MarkerContent, MarkerTooltip } from "@/registry/map";+import { TrendingUp } from "lucide-react";+import { ExampleCard } from "./example-card";++const analyticsData = [+ { lng: -74.006, lat: 40.7128, city: "New York", users: 847, size: 14 },+ { lng: -0.1276, lat: 51.5074, city: "London", users: 623, size: 12 },+ { lng: 139.6917, lat: 35.6895, city: "Tokyo", users: 412, size: 10 },+ { lng: -122.4194, lat: 37.7749, city: "San Francisco", users: 298, size: 9 },+ { lng: 2.3522, lat: 48.8566, city: "Paris", users: 187, size: 8 },+ { lng: 77.209, lat: 28.6139, city: "Delhi", users: 156, size: 7 },+ { lng: 151.2093, lat: -33.8688, city: "Sydney", users: 134, size: 7 },+ { lng: -43.1729, lat: -22.9068, city: "Rio", users: 89, size: 6 },+ { lng: 4.9041, lat: 52.3676, city: "Amsterdam", users: 76, size: 5 },+ { lng: 126.978, lat: 37.5665, city: "Seoul", users: 45, size: 5 },+];++export function AnalyticsExample() {+ return (+ <ExampleCard+ label=""+ className="aspect-square sm:col-span-2 sm:aspect-video lg:aspect-auto"+ delay="delay-400"+ >+ <div className="absolute top-3 left-3 z-10 bg-background/95 backdrop-blur-md rounded-lg p-3 border border-border/50 shadow-lg">+ <div className="tracking-wider text-[10px] text-muted-foreground uppercase mb-1">+ Active Users+ </div>+ <div className="text-2xl font-semibold leading-tight">2,847</div>+ <div className="flex items-center gap-1 mt-1">+ <TrendingUp className="size-3 text-emerald-500" />+ <span className="text-xs text-emerald-500">+12.5%</span>+ <span className="text-xs text-muted-foreground">vs last hour</span>+ </div>+ </div>++ <div className="absolute bottom-3 left-3 z-10 bg-background/95 backdrop-blur-md rounded-lg px-3 py-2 border border-border/50 shadow-lg">+ <div className="flex items-center gap-4 text-[10px]">+ <div className="flex items-center gap-1.5">+ <div className="size-3 rounded-full bg-emerald-500" />+ <span className="text-muted-foreground">High</span>+ </div>+ <div className="flex items-center gap-1.5">+ <div className="size-2 rounded-full bg-emerald-500" />+ <span className="text-muted-foreground">Medium</span>+ </div>+ <div className="flex items-center gap-1.5">+ <div className="size-1.5 rounded-full bg-emerald-500" />+ <span className="text-muted-foreground">Low</span>+ </div>+ </div>+ </div>++ <Map center={[0, 30]}>+ {analyticsData.map((loc) => (+ <MapMarker key={loc.city} longitude={loc.lng} latitude={loc.lat}>+ <MarkerContent>+ <div className="relative flex items-center justify-center">+ <div+ className="absolute rounded-full bg-emerald-500/20"+ style={{+ width: loc.size * 2.5,+ height: loc.size * 2.5,+ }}+ />+ <div+ className="absolute rounded-full bg-emerald-500/40 animate-ping"+ style={{+ width: loc.size * 1.5,+ height: loc.size * 1.5,+ animationDuration: "2s",+ }}+ />+ <div+ className="relative rounded-full bg-emerald-500 shadow-lg shadow-emerald-500/50"+ style={{ width: loc.size, height: loc.size }}+ />+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-center">+ <div className="font-medium">{loc.city}</div>+ <div className="text-emerald-500 font-semibold">+ {loc.users}+ </div>+ <div className="text-[10px] text-muted-foreground">+ active users+ </div>+ </div>+ </MarkerTooltip>+ </MapMarker>+ ))}+ </Map>+ </ExampleCard>+ );+}diff --git a/src/app/(home)/_components/examples/delivery-example.tsx b/src/app/(home)/_components/examples/delivery-example.tsxnew file mode 100644index 0000000..bff24c4--- /dev/null+++ b/src/app/(home)/_components/examples/delivery-example.tsx@@ -0,0 +1,82 @@+"use client";++import { useEffect, useState } from "react";+import {+ Map,+ MapMarker,+ MarkerContent,+ MarkerLabel,+ MarkerTooltip,+ MapRoute,+} from "@/registry/map";+import { Truck } from "lucide-react";+import { ExampleCard } from "./example-card";++const store = { lng: -0.14, lat: 51.5154 };+const home = { lng: -0.07, lat: 51.51 };++export function DeliveryExample() {+ const [route, setRoute] = useState<[number, number][]>([]);+ const [truckPosition, setTruckPosition] = useState<[number, number] | null>(+ null+ );++ useEffect(() => {+ async function fetchRoute() {+ try {+ const response = await fetch(+ `https://router.project-osrm.org/route/v1/driving/${store.lng},${store.lat};${home.lng},${home.lat}?overview=full&geometries=geojson`+ );+ const data = await response.json();++ if (data.routes?.[0]?.geometry?.coordinates) {+ const coords: [number, number][] =+ data.routes[0].geometry.coordinates;+ setRoute(coords);+ const truckIdx = Math.floor(coords.length * 0.6);+ setTruckPosition(coords[truckIdx]);+ }+ } catch (error) {+ console.error("Failed to fetch route:", error);+ }+ }++ fetchRoute();+ }, []);++ return (+ <ExampleCard+ label="Delivery"+ className="aspect-square sm:col-span-2 sm:aspect-video lg:aspect-auto"+ delay="delay-900"+ >+ <Map center={[-0.105, 51.511]} zoom={12.4}>+ {route.length > 0 && (+ <MapRoute coordinates={route} width={4} color="#4285F4" />+ )}+ <MapMarker longitude={store.lng} latitude={store.lat}>+ <MarkerContent>+ <div className="size-3.5 rounded-full bg-blue-500 border-2 border-white shadow-lg" />+ <MarkerLabel>Store</MarkerLabel>+ </MarkerContent>+ </MapMarker>+ {truckPosition && (+ <MapMarker longitude={truckPosition[0]} latitude={truckPosition[1]}>+ <MarkerContent>+ <div className="bg-blue-500 rounded-full p-1.5 shadow-lg">+ <Truck className="size-3 text-white" />+ </div>+ </MarkerContent>+ <MarkerTooltip>On the way</MarkerTooltip>+ </MapMarker>+ )}+ <MapMarker longitude={home.lng} latitude={home.lat}>+ <MarkerContent>+ <div className="size-3.5 rounded-full bg-blue-500 border-2 border-white shadow-lg" />+ <MarkerLabel>Home</MarkerLabel>+ </MarkerContent>+ </MapMarker>+ </Map>+ </ExampleCard>+ );+}diff --git a/src/app/(home)/_components/examples/ev-charging-example.tsx b/src/app/(home)/_components/examples/ev-charging-example.tsxnew file mode 100644index 0000000..528498e--- /dev/null+++ b/src/app/(home)/_components/examples/ev-charging-example.tsx@@ -0,0 +1,88 @@+"use client";++import { Map, MapMarker, MarkerContent, MarkerTooltip } from "@/registry/map";+import { Zap } from "lucide-react";+import { ExampleCard } from "./example-card";++export function EVChargingExample() {+ return (+ <ExampleCard+ label="EV Charging"+ className="aspect-square"+ delay="delay-700"+ >+ <Map center={[-122.425, 37.777]} zoom={11.5}>+ <MapMarker longitude={-122.4194} latitude={37.7749}>+ <MarkerContent>+ <div className="bg-emerald-500 rounded-full p-1.5 shadow-lg shadow-emerald-500/30">+ <Zap className="size-3 text-white fill-white" />+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-xs space-y-0.5">+ <div className="font-medium">Market St Station</div>+ <div className="flex items-center gap-1">+ <span className="size-1.5 rounded-full bg-emerald-500" />+ <span className="text-emerald-500">Available</span>+ </div>+ <div className="text-muted-foreground">150 kW • $0.35/kWh</div>+ </div>+ </MarkerTooltip>+ </MapMarker>++ <MapMarker longitude={-122.4094} latitude={37.7849}>+ <MarkerContent>+ <div className="bg-emerald-500 rounded-full p-1.5 shadow-lg shadow-emerald-500/30">+ <Zap className="size-3 text-white fill-white" />+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-xs space-y-0.5">+ <div className="font-medium">Union Square</div>+ <div className="flex items-center gap-1">+ <span className="size-1.5 rounded-full bg-emerald-500" />+ <span className="text-emerald-500">2 Available</span>+ </div>+ <div className="text-muted-foreground">50 kW • $0.28/kWh</div>+ </div>+ </MarkerTooltip>+ </MapMarker>++ <MapMarker longitude={-122.4294} latitude={37.7689}>+ <MarkerContent>+ <div className="bg-amber-500 rounded-full p-1.5 shadow-lg shadow-amber-500/30">+ <Zap className="size-3 text-white fill-white" />+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-xs space-y-0.5">+ <div className="font-medium">Castro Station</div>+ <div className="flex items-center gap-1">+ <span className="size-1.5 rounded-full bg-amber-500" />+ <span className="text-amber-500">In Use</span>+ </div>+ <div className="text-muted-foreground">~15 min remaining</div>+ </div>+ </MarkerTooltip>+ </MapMarker>++ <MapMarker longitude={-122.4394} latitude={37.7809}>+ <MarkerContent>+ <div className="bg-zinc-400 rounded-full p-1.5 shadow-lg">+ <Zap className="size-3 text-white fill-white" />+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-xs space-y-0.5">+ <div className="font-medium">Hayes Valley</div>+ <div className="flex items-center gap-1">+ <span className="size-1.5 rounded-full bg-zinc-400" />+ <span className="text-muted-foreground">Offline</span>+ </div>+ </div>+ </MarkerTooltip>+ </MapMarker>+ </Map>+ </ExampleCard>+ );+}diff --git a/src/app/(home)/_components/examples/example-card.tsx b/src/app/(home)/_components/examples/example-card.tsxnew file mode 100644index 0000000..1c95dd7--- /dev/null+++ b/src/app/(home)/_components/examples/example-card.tsx@@ -0,0 +1,34 @@+"use client";++import { cn } from "@/lib/utils";++interface ExampleCardProps {+ label: string;+ className?: string;+ delay?: string;+ children: React.ReactNode;+}++export function ExampleCard({+ label,+ className,+ delay = "delay-500",+ children,+}: ExampleCardProps) {+ return (+ <div+ className={cn(+ "rounded-xl overflow-hidden shadow-sm bg-card border border-border/50 relative animate-scale-in",+ delay,+ className+ )}+ >+ {label && (+ <div className="uppercase absolute top-2 left-2 z-10 tracking-wider text-[10px] text-muted-foreground bg-background/90 backdrop-blur-sm rounded px-2 py-1">+ {label}+ </div>+ )}+ {children}+ </div>+ );+}diff --git a/src/app/(home)/_components/examples/flyto-example.tsx b/src/app/(home)/_components/examples/flyto-example.tsxnew file mode 100644index 0000000..75653e2--- /dev/null+++ b/src/app/(home)/_components/examples/flyto-example.tsx@@ -0,0 +1,69 @@+"use client";++import {+ Map,+ MapMarker,+ MapRef,+ MarkerContent,+ MarkerTooltip,+} from "@/registry/map";+import { useRef } from "react";+import { ExampleCard } from "./example-card";+import { Button } from "@/components/ui/button";+import { Navigation } from "lucide-react";++const destination = {+ name: "New York",+ description: "United States",+ center: [-74.006, 40.7128] as [number, number],+ startCenter: [10, 50] as [number, number],+};++export function FlyToExample() {+ const mapRef = useRef<MapRef>(null);++ return (+ <ExampleCard label="Fly To" className="aspect-square" delay="delay-600">+ <Map+ center={destination.startCenter}+ zoom={0.5}+ ref={mapRef}+ projection={{ type: "globe" }}+ >+ <MapMarker+ longitude={destination.center[0]}+ latitude={destination.center[1]}+ >+ <MarkerContent>+ <div className="relative flex items-center justify-center">+ <div className="absolute size-6 rounded-full bg-cyan-500/20 animate-ping" />+ <div className="size-4 rounded-full bg-cyan-500 border-2 border-white shadow-lg" />+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-center">+ <div className="font-medium">{destination.name}</div>+ <div className="text-[10px] text-muted-foreground">+ {destination.description}+ </div>+ </div>+ </MarkerTooltip>+ </MapMarker>+ </Map>+ <Button+ size="icon-sm"+ variant="secondary"+ className="absolute top-2 right-2"+ onClick={() => {+ mapRef.current?.flyTo({+ center: destination.center,+ zoom: 14,+ duration: 2500,+ });+ }}+ >+ <Navigation className="size-4" />+ </Button>+ </ExampleCard>+ );+}diff --git a/src/app/(home)/_components/examples/index.tsx b/src/app/(home)/_components/examples/index.tsxnew file mode 100644index 0000000..a37c06a--- /dev/null+++ b/src/app/(home)/_components/examples/index.tsx@@ -0,0 +1,6 @@+export { ExampleCard } from "./example-card";+export { AnalyticsExample } from "./analytics-example";+export { DeliveryExample } from "./delivery-example";+export { TrendingExample } from "./trending-example";+export { EVChargingExample } from "./ev-charging-example";+export { TrailExample } from "./trail-example";diff --git a/src/app/(home)/_components/examples/trail-example.tsx b/src/app/(home)/_components/examples/trail-example.tsxnew file mode 100644index 0000000..2c3f676--- /dev/null+++ b/src/app/(home)/_components/examples/trail-example.tsx@@ -0,0 +1,87 @@+"use client";++import { Map, MapRoute, MapMarker, MarkerContent } from "@/registry/map";+import { Bike, Flame, Clock, Route } from "lucide-react";+import { ExampleCard } from "./example-card";++// Central Park cycling route+const trailCoordinates: [number, number][] = [+ [-73.95846730810143, 40.80035246904919],+ [-73.9717593682683, 40.78210942124929],+ [-73.98192123136191, 40.76793032580281],+ [-73.97393759456651, 40.76462909128966],+ [-73.97291537521572, 40.765159628993814],+ [-73.96920618484948, 40.7637106622374],+ [-73.96383691302509, 40.77117117897504],+ [-73.9584024523858, 40.76889223221369],+ [-73.9470773638119, 40.784238113060894],+ [-73.95585246901248, 40.78786547226602],+ [-73.94937945594087, 40.79668351998197],+ [-73.9498273526222, 40.797167598041455],+ [-73.95699644240298, 40.80016017872583],+];+const start = trailCoordinates[0];+const end = trailCoordinates[trailCoordinates.length - 1];++export function TrailExample() {+ return (+ <ExampleCard label="" className="aspect-square" delay="delay-500">+ <div className="absolute top-3 left-3 z-10 bg-background/95 backdrop-blur-md rounded-lg p-3 border border-border/50 shadow-lg">+ <div className="flex items-center gap-1.5 mb-2">+ <Bike className="size-3.5 text-emerald-500" />+ <span className="text-xs font-medium">Central Park Loop</span>+ </div>+ <div className="grid grid-cols-3 gap-3 text-center">+ <div>+ <div className="flex items-center justify-center gap-1 text-muted-foreground mb-0.5">+ <Route className="size-3" />+ </div>+ <div className="text-sm font-semibold">6.2</div>+ <div className="text-[9px] text-muted-foreground uppercase">+ Miles+ </div>+ </div>+ <div>+ <div className="flex items-center justify-center gap-1 text-muted-foreground mb-0.5">+ <Clock className="size-3" />+ </div>+ <div className="text-sm font-semibold">32</div>+ <div className="text-[9px] text-muted-foreground uppercase">+ Mins+ </div>+ </div>+ <div>+ <div className="flex items-center justify-center gap-1 text-muted-foreground mb-0.5">+ <Flame className="size-3" />+ </div>+ <div className="text-sm font-semibold">285</div>+ <div className="text-[9px] text-muted-foreground uppercase">+ Cal+ </div>+ </div>+ </div>+ </div>++ <Map center={[-73.97, 40.782]} zoom={11.8}>+ <MapRoute+ coordinates={trailCoordinates}+ color="#10b981"+ width={3}+ opacity={0.9}+ />++ <MapMarker longitude={start[0]} latitude={start[1]}>+ <MarkerContent>+ <div className="size-3 rounded-full bg-emerald-500 border-2 border-white shadow-lg" />+ </MarkerContent>+ </MapMarker>++ <MapMarker longitude={end[0]} latitude={end[1]}>+ <MarkerContent>+ <div className="size-3 rounded-full bg-red-500 border-2 border-white shadow-lg" />+ </MarkerContent>+ </MapMarker>+ </Map>+ </ExampleCard>+ );+}diff --git a/src/app/(home)/_components/examples/trending-example.tsx b/src/app/(home)/_components/examples/trending-example.tsxnew file mode 100644index 0000000..f69e4e0--- /dev/null+++ b/src/app/(home)/_components/examples/trending-example.tsx@@ -0,0 +1,72 @@+"use client";++import { Map, MapMarker, MarkerContent, MarkerTooltip } from "@/registry/map";+import { Flame, TrendingUp } from "lucide-react";+import { ExampleCard } from "./example-card";++export function TrendingExample() {+ return (+ <ExampleCard label="Trending" className="aspect-square" delay="delay-800">+ <Map center={[-73.99, 40.735]} zoom={10}>+ <MapMarker longitude={-73.9857} latitude={40.7484}>+ <MarkerContent>+ <div className="relative flex items-center justify-center">+ <div className="absolute size-18 rounded-full bg-orange-500/30 pointer-events-none" />+ <div className="absolute size-7 rounded-full bg-orange-500/40" />+ <div className="bg-linear-to-br from-orange-500 to-red-500 rounded-full p-1.5 shadow-lg shadow-orange-500/50">+ <Flame className="size-3.5 text-white" />+ </div>+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-center">+ <div className="font-medium">Times Square</div>+ <div className="flex items-center justify-center gap-1 text-muted-foreground">+ <TrendingUp className="size-3 text-green-500" />+ <span className="text-xs text-green-500">2.4k visitors</span>+ </div>+ </div>+ </MarkerTooltip>+ </MapMarker>+ <MapMarker longitude={-73.9654} latitude={40.7829}>+ <MarkerContent>+ <div className="relative flex items-center justify-center">+ <div className="absolute size-14 rounded-full bg-rose-500/30 pointer-events-none" />+ <div className="bg-linear-to-br from-rose-500 to-pink-500 rounded-full p-1.5 shadow-lg shadow-rose-500/50">+ <Flame className="size-3 text-white" />+ </div>+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-center">+ <div className="font-medium">Central Park</div>+ <div className="flex items-center justify-center gap-1 text-muted-foreground">+ <TrendingUp className="size-3 text-green-500" />+ <span className="text-xs text-green-500">1.8k visitors</span>+ </div>+ </div>+ </MarkerTooltip>+ </MapMarker>+ <MapMarker longitude={-74.0445} latitude={40.6892}>+ <MarkerContent>+ <div className="relative flex items-center justify-center">+ <div className="absolute size-12 rounded-full bg-amber-500/30 pointer-events-none" />+ <div className="bg-linear-to-br from-amber-500 to-yellow-500 rounded-full p-1 shadow-lg shadow-amber-500/50">+ <Flame className="size-2.5 text-white" />+ </div>+ </div>+ </MarkerContent>+ <MarkerTooltip>+ <div className="text-center">+ <div className="font-medium">Statue of Liberty</div>+ <div className="flex items-center justify-center gap-1 text-muted-foreground">+ <TrendingUp className="size-3 text-green-500" />+ <span className="text-xs text-green-500">890 visitors</span>+ </div>+ </div>+ </MarkerTooltip>+ </MapMarker>+ </Map>+ </ExampleCard>+ );+}diff --git a/src/app/(home)/_components/hero.tsx b/src/app/(home)/_components/hero.tsxindex 116de97..cb0f3e8 100644--- a/src/app/(home)/_components/hero.tsx+++ b/src/app/(home)/_components/hero.tsx@@ -6,7 +6,6 @@ import Link from "next/link";import { useState } from "react";const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "site-url-here";-const installCommand = `npx shadcn@latest add ${siteUrl}/maps/map.json`;function CopyButton({ text }: { text: string }) {@@ -34,36 +33,66 @@ function CopyButton({ text }: { text: string }) {export function Hero() {return (- <div className="space-y-8">- <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.+ <div className="relative">+ <div className="absolute inset-0 -z-10 overflow-hidden">+ <div+ className="absolute inset-0 opacity-[0.4] dark:opacity-[0.15]"+ style={{+ backgroundImage: `radial-gradient(circle, currentColor 1px, transparent 1px)`,+ backgroundSize: "24px 24px",+ }}+ />++ <div className="absolute -top-40 -right-40 size-96 bg-emerald-500/10 rounded-full blur-3xl" />+ <div className="absolute -bottom-40 -left-40 size-96 bg-sky-500/10 rounded-full blur-3xl" />++ <div className="absolute inset-0 bg-linear-to-b from-background via-transparent to-background" />+ </div>++ <div className="container flex flex-col items-center text-center">+ <h1 className="text-4xl sm:text-5xl md:text-6xl font-semibold tracking-tight animate-fade-up delay-100">+ <span className="bg-linear-to-b from-foreground to-foreground/60 bg-clip-text text-transparent">+ Beautiful maps, made simple.+ </span></h1>- <p className="text-foreground/80 text-lg max-w-xl mx-auto leading-relaxed animate-fade-up delay-100">- Ready-to-use, customizable map components for React. Built on- MapLibre, styled with Tailwind. Zero config. One command setup.++ <p className="mt-6 text-foreground/80 text-lg md:text-xl leading-relaxed animate-fade-up delay-200 max-w-lg">+ Ready to use, customizable map components for React.+ <br className="hidden sm:block" />+ Built on MapLibre. Styled with Tailwind.</p>- </div>- <div className="animate-fade-up delay-200 flex justify-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-hidden shadow">- <span className="text-emerald-400 shrink-0">$</span>- <code className="text-foreground/90 truncate">{installCommand}</code>- <CopyButton text={installCommand} />+ <div className="mt-8 animate-fade-up delay-300 w-full max-w-xl">+ <div className="bg-card border border-border rounded-lg shadow-sm overflow-hidden">+ <div className="flex items-center gap-1.5 px-3 py-2 border-b border-border/50">+ <span className="size-2.5 rounded-full bg-red-500/40" />+ <span className="size-2.5 rounded-full bg-yellow-500/40" />+ <span className="size-2.5 rounded-full bg-green-500/40" />+ </div>++ <div className="flex items-center gap-3 px-4 py-3 font-mono text-sm">+ <span className="text-emerald-500 shrink-0">$</span>+ <code className="text-foreground/80 truncate flex-1 text-left">+ {installCommand}+ </code>+ <CopyButton text={installCommand} />+ </div>+ </div></div>- </div>- <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="ghost" asChild>- <Link href="/docs/basic-map" className="text-muted-foreground">- View Examples- </Link>- </Button>+ <div className="mt-8 flex flex-wrap justify-center items-center gap-3 animate-fade-up delay-400">+ <Button size="lg" asChild>+ <Link href="/docs">+ Get Started+ <ArrowRight className="size-4" />+ </Link>+ </Button>+ <Button variant="ghost" size="lg" asChild>+ <Link href="/docs/basic-map" className="text-muted-foreground">+ View Components+ </Link>+ </Button>+ </div></div></div>);diff --git a/src/app/(home)/page.tsx b/src/app/(home)/page.tsxindex 1bc62b1..7849d90 100644--- a/src/app/(home)/page.tsx+++ b/src/app/(home)/page.tsx@@ -1,21 +1,21 @@import { Header } from "@/components/header";import { Hero } from "./_components/hero";-import { Examples } from "./_components/examples";-import { Footer } from "./_components/footer";+import { ExamplesGrid } from "./_components/examples-grid";export default function Page() {return (- <div className="min-h-screen bg-background flex flex-col overflow-x-hidden">- <Header className="max-w-5xl mx-auto w-full xl:px-0" />+ <div className="flex flex-col pb-28">+ <Header className="border-b border-transparent" />- <main className="flex-1 px-6 py-20 mx-auto w-full">- <section className="max-w-5xl mx-auto flex flex-col gap-20">+ <main className="flex-1">+ <section className="relative w-full py-20"><Hero />- <Examples /></section>- </main>- <Footer />+ <section className="container px-6">+ <ExamplesGrid />+ </section>+ </main></div>);}diff --git a/src/app/docs/_components/docs-sidebar.tsx b/src/app/docs/_components/docs-sidebar.tsxindex 5b2e0ef..e62b97b 100644--- a/src/app/docs/_components/docs-sidebar.tsx+++ b/src/app/docs/_components/docs-sidebar.tsx@@ -2,18 +2,6 @@import Link from "next/link";import { usePathname } from "next/navigation";-import {- Map,- BookOpen,- Code,- Braces,- MapPin,- MessageSquare,- Route,- Wrench,- Settings,- Layers,-} from "lucide-react";import {Sidebar,@@ -27,43 +15,24 @@ import {SidebarTrigger,useSidebar,} from "@/components/ui/sidebar";--const navigation = [- {- title: "Basics",- items: [- { title: "Getting Started", href: "/docs", icon: BookOpen },- { title: "Installation", href: "/docs/installation", icon: Code },- {- title: "API Reference",- href: "/docs/api-reference",- icon: Braces,- },- ],- },- {- title: "Examples",- items: [- { title: "Basic Map", href: "/docs/basic-map", icon: Map },- { title: "Map Controls", href: "/docs/controls", icon: Settings },- { title: "Markers", href: "/docs/markers", icon: MapPin },- { title: "Popups", href: "/docs/popups", icon: MessageSquare },- { title: "Routes", href: "/docs/routes", icon: Route },- { title: "Clusters", href: "/docs/clusters", icon: Layers },- { title: "Advanced Usage", href: "/docs/advanced-usage", icon: Wrench },- ],- },-];+import { docsNavigation } from "@/lib/docs-navigation";export function DocsSidebar() {const pathname = usePathname();const { setOpenMobile } = useSidebar();return (- <Sidebar className="top-14 border-r bg-transparent **:data-[sidebar=sidebar]:bg-transparent">- <SidebarContent className="pt-4">- {navigation.map((group) => (- <SidebarGroup key={group.title}>+ <Sidebar+ className="sticky top-16 h-[calc(100svh-9.5rem)] border-none bg-transparent **:data-[sidebar=sidebar]:bg-transparent"+ style={+ {+ "--sidebar-width": "12rem",+ } as React.CSSProperties+ }+ >+ <SidebarContent className="pt-8 no-scrollbar overflow-x-hidden">+ {docsNavigation.map((group) => (+ <SidebarGroup key={group.title} className="px-0"><SidebarGroupLabel className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">{group.title}</SidebarGroupLabel>@@ -74,7 +43,7 @@ export function DocsSidebar() {<SidebarMenuButtonasChildisActive={pathname === item.href}- className="text-muted-foreground hover:text-foreground data-[active=true]:text-foreground data-[active=true]:font-medium"+ className="data-[active=true]:bg-accent data-[active=true]:border-accent 3xl:fixed:w-full 3xl:fixed:max-w-48 relative h-[30px] overflow-visible border border-transparent text-[0.8rem] text-muted-foreground font-medium after:absolute after:inset-x-0 after:-inset-y-1 after:z-0 after:rounded-md"><Linkhref={item.href}diff --git a/src/app/docs/_components/docs-toc.tsx b/src/app/docs/_components/docs-toc.tsxnew file mode 100644index 0000000..928fa7d--- /dev/null+++ b/src/app/docs/_components/docs-toc.tsx@@ -0,0 +1,84 @@+"use client";++import * as React from "react";+import { cn } from "@/lib/utils";++function useActiveItem(itemIds: string[]) {+ const [activeId, setActiveId] = React.useState<string | null>(null);++ React.useEffect(() => {+ const observer = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting) {+ setActiveId(entry.target.id);+ }+ }+ },+ { rootMargin: "0% 0% -80% 0%" }+ );++ for (const id of itemIds ?? []) {+ const element = document.getElementById(id);+ if (element) {+ observer.observe(element);+ }+ }++ return () => {+ for (const id of itemIds ?? []) {+ const element = document.getElementById(id);+ if (element) {+ observer.unobserve(element);+ }+ }+ };+ }, [itemIds]);++ return activeId;+}++interface TocItem {+ title: string;+ slug: string;+}++interface DocsTocProps {+ items: TocItem[];+ className?: string;+}++export function DocsToc({ items, className }: DocsTocProps) {+ const itemIds = React.useMemo(() => items.map((item) => item.slug), [items]);+ const activeHeading = useActiveItem(itemIds);++ if (!items?.length) {+ return null;+ }++ return (+ <div className={cn("flex flex-col gap-2.5 text-sm", className)}>+ <p className="text-muted-foreground text-xs font-medium mb-1">+ On This Page+ </p>+ {items.map((item) => (+ <a+ key={item.slug}+ href={`#${item.slug}`}+ onClick={(e) => {+ e.preventDefault();+ document.getElementById(item.slug)?.scrollIntoView({+ behavior: "smooth",+ });+ }}+ className={cn(+ "text-muted-foreground hover:text-foreground text-[0.8rem] no-underline transition-colors",+ item.slug === activeHeading && "text-foreground"+ )}+ >+ {item.title}+ </a>+ ))}+ </div>+ );+}diff --git a/src/app/docs/_components/docs.tsx b/src/app/docs/_components/docs.tsxindex 645fb37..5835afd 100644--- a/src/app/docs/_components/docs.tsx+++ b/src/app/docs/_components/docs.tsx@@ -8,14 +8,20 @@ import {TableRow,} from "@/components/ui/table";import { cn } from "@/lib/utils";+import { DocsToc } from "./docs-toc";-function slugify(text: string): string {+export function slugify(text: string): string {return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");}+interface TocItem {+ title: string;+ slug: string;+}+// DocsHeader - Page title and descriptioninterface DocsHeaderProps {title: string;@@ -24,11 +30,11 @@ interface DocsHeaderProps {export function DocsHeader({ title, description }: DocsHeaderProps) {return (- <div className="space-y-3">- <h1 className="text-3xl font-semibold tracking-tight text-primary">+ <div className="space-y-2">+ <h1 className="text-3xl font-semibold tracking-tight text-foreground">{title}</h1>- <p className="text-lg text-muted-foreground leading-relaxed">+ <p className="text-base text-muted-foreground leading-relaxed">{description}</p></div>@@ -42,6 +48,7 @@ interface DocsLayoutProps {children: React.ReactNode;prev?: { title: string; href: string };next?: { title: string; href: string };+ toc?: TocItem[];}export function DocsLayout({@@ -50,41 +57,50 @@ export function DocsLayout({children,prev,next,+ toc = [],}: DocsLayoutProps) {return (- <div>- <DocsHeader title={title} description={description} />-- <div className="mt-10 space-y-10">{children}</div>-- {(prev || next) && (- <div className="flex items-center justify-between gap-4 mt-14 pt-8 border-t">- {prev ? (- <Link- href={prev.href}- className="group flex flex-col items-start gap-1.5"- >- <span className="text-xs text-muted-foreground">Previous</span>- <span className="text-sm font-medium group-hover:underline underline-offset-4">- {prev.title}- </span>- </Link>- ) : (- <div />- )}- {next && (- <Link- href={next.href}- className="group flex flex-col items-end gap-1.5"- >- <span className="text-xs text-muted-foreground">Next</span>- <span className="text-sm font-medium group-hover:underline underline-offset-4">- {next.title}- </span>- </Link>- )}- </div>- )}+ <div className="flex gap-8">+ <div className="flex-1 min-w-0 max-w-[720px] mx-auto py-8 pb-20">+ <DocsHeader title={title} description={description} />++ <div className="mt-10 space-y-10">{children}</div>++ {(prev || next) && (+ <div className="flex items-center justify-between gap-4 mt-14 pt-8 border-t">+ {prev ? (+ <Link+ href={prev.href}+ className="group flex flex-col items-start gap-1.5"+ >+ <span className="text-xs text-muted-foreground">Previous</span>+ <span className="text-sm font-medium group-hover:underline underline-offset-4">+ {prev.title}+ </span>+ </Link>+ ) : (+ <div />+ )}+ {next && (+ <Link+ href={next.href}+ className="group flex flex-col items-end gap-1.5"+ >+ <span className="text-xs text-muted-foreground">Next</span>+ <span className="text-sm font-medium group-hover:underline underline-offset-4">+ {next.title}+ </span>+ </Link>+ )}+ </div>+ )}+ </div>++ <aside className="hidden xl:block w-44 shrink-0">+ <nav className="sticky top-28">+ {toc.length > 0 && <DocsToc items={toc} />}+ </nav>+ </aside></div>);}@@ -98,13 +114,13 @@ interface DocsSectionProps {export function DocsSection({ title, children }: DocsSectionProps) {const id = title ? slugify(title) : undefined;return (- <section className="space-y-5 scroll-mt-20" id={id}>+ <section className="space-y-4 scroll-mt-20" id={id}>{title && (- <h2 className="text-xl font-semibold tracking-tight text-primary">+ <h2 className="text-xl font-semibold tracking-tight text-foreground">{title}</h2>)}- <div className="text-muted-foreground leading-7 space-y-4 [&>ul]:list-disc [&>ul]:pl-6 [&>ul]:space-y-2">+ <div className="text-foreground/80 text-base sm:text-[15px] leading-7 space-y-3 [&_p]:leading-7 [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:space-y-1.5 [&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:space-y-1.5 [&_li]:leading-7 [&_strong]:text-foreground [&_strong]:font-medium [&_em]:text-muted-foreground">{children}</div></section>@@ -118,7 +134,7 @@ interface DocsNoteProps {export function DocsNote({ children }: DocsNoteProps) {return (- <div className="rounded-lg border bg-muted/40 px-5 py-4 leading-relaxed text-sm text-muted-foreground [&>strong]:text-foreground [&>strong]:font-medium">+ <div className="rounded-lg border bg-muted/40 px-4 py-3 text-[14px] leading-relaxed text-foreground/70 [&_strong]:text-foreground [&_strong]:font-medium">{children}</div>);@@ -176,29 +192,41 @@ interface DocsPropTableProps {export function DocsPropTable({ props }: DocsPropTableProps) {return (- <div className="rounded-lg border overflow-hidden my-4">+ <div className="rounded-lg border overflow-hidden my-6"><Table><TableHeader>- <TableRow className="hover:bg-transparent">- <TableHead className="h-11 px-4 font-medium">Prop</TableHead>- <TableHead className="h-11 px-4 font-medium">Type</TableHead>- <TableHead className="h-11 px-4 font-medium">Default</TableHead>- <TableHead className="h-11 px-4 font-medium">Description</TableHead>+ <TableRow className="hover:bg-transparent bg-muted/30">+ <TableHead className="h-10 px-4 text-xs font-medium">+ Prop+ </TableHead>+ <TableHead className="h-10 px-4 text-xs font-medium">+ Type+ </TableHead>+ <TableHead className="h-10 px-4 text-xs font-medium">+ Default+ </TableHead>+ <TableHead className="h-10 px-4 text-xs font-medium">+ Description+ </TableHead></TableRow></TableHeader><TableBody>{props.map((prop) => (<TableRow key={prop.name}>- <TableCell className="px-4 py-3.5 font-mono text-primary align-top">+ <TableCell className="px-4 py-3 align-top"><DocsCode className="text-[13px]">{prop.name}</DocsCode></TableCell>- <TableCell className="px-4 py-3.5 font-mono text-muted-foreground align-top overflow-hidden whitespace-normal">- <DocsCode className="text-xs">{prop.type}</DocsCode>+ <TableCell className="px-4 py-3 align-top whitespace-normal">+ <DocsCode className="text-xs text-muted-foreground">+ {prop.type}+ </DocsCode></TableCell>- <TableCell className="px-4 py-3.5 font-mono text-muted-foreground align-top whitespace-normal">- <DocsCode className="text-xs">{prop.default ?? "—"}</DocsCode>+ <TableCell className="px-4 py-3 align-top">+ <DocsCode className="text-xs text-muted-foreground whitespace-normal">+ {prop.default ?? "—"}+ </DocsCode></TableCell>- <TableCell className="px-4 py-3.5 text-sm text-muted-foreground whitespace-normal min-w-[180px] leading-relaxed">+ <TableCell className="px-4 py-3 text-sm text-foreground/70 whitespace-normal min-w-[180px] leading-relaxed">{prop.description}</TableCell></TableRow>diff --git a/src/app/docs/_components/examples/standalone-popup-example.tsx b/src/app/docs/_components/examples/standalone-popup-example.tsxindex b00d886..7be4dfb 100644--- a/src/app/docs/_components/examples/standalone-popup-example.tsx+++ b/src/app/docs/_components/examples/standalone-popup-example.tsx@@ -18,6 +18,7 @@ export function StandalonePopupExample() {closeButtonfocusAfterOpen={false}closeOnClick={false}+ className="w-62"><div className="space-y-2"><h3 className="font-semibold text-foreground">New York City</h3>diff --git a/src/app/docs/advanced-usage/page.tsx b/src/app/docs/advanced-usage/page.tsxindex ed84621..cbef3a6 100644--- a/src/app/docs/advanced-usage/page.tsx+++ b/src/app/docs/advanced-usage/page.tsx@@ -14,7 +14,7 @@ import { getExampleSource } from "@/lib/get-example-source";import { Metadata } from "next";export const metadata: Metadata = {- title: "Advanced Usage",+ title: "Advanced",};const refCode = `import { Map, type MapRef } from "@/components/ui/map";@@ -69,9 +69,23 @@ export default function AdvancedPage() {return (<DocsLayout- title="Advanced Usage"+ title="Advanced"description="Access the underlying MapLibre GL instance for advanced customization."prev={{ title: "Clusters", href: "/docs/clusters" }}+ toc={[+ { title: "Using a Ref", slug: "using-a-ref" },+ { title: "Using the Hook", slug: "using-the-hook" },+ { title: "Example: Custom Controls", slug: "example-custom-controls" },+ {+ title: "Example: Custom GeoJSON Layer",+ slug: "example-custom-geojson-layer",+ },+ {+ title: "Example: Markers via Layers",+ slug: "example-markers-via-layers",+ },+ { title: "Extend to Build", slug: "extend-to-build" },+ ]}><DocsSection><p>diff --git a/src/app/docs/api-reference/page.tsx b/src/app/docs/api-reference/page.tsxindex ee43181..8276337 100644--- a/src/app/docs/api-reference/page.tsx+++ b/src/app/docs/api-reference/page.tsx@@ -36,7 +36,21 @@ export default function ApiReferencePage() {title="API Reference"description="Complete reference for all map components and their props."prev={{ title: "Installation", href: "/docs/installation" }}- next={{ title: "Basic Map", href: "/docs/basic-map" }}+ next={{ title: "Map", href: "/docs/basic-map" }}+ toc={[+ { title: "Component Anatomy", slug: "component-anatomy" },+ { title: "Map", slug: "map" },+ { title: "useMap", slug: "usemap" },+ { title: "MapControls", slug: "mapcontrols" },+ { title: "MapMarker", slug: "mapmarker" },+ { title: "MarkerContent", slug: "markercontent" },+ { title: "MarkerPopup", slug: "markerpopup" },+ { title: "MarkerTooltip", slug: "markertooltip" },+ { title: "MarkerLabel", slug: "markerlabel" },+ { title: "MapPopup", slug: "mappopup" },+ { title: "MapRoute", slug: "maproute" },+ { title: "MapClusterLayer", slug: "mapclusterlayer" },+ ]}><DocsNote><strong>Note:</strong> This library is built on top of{" "}@@ -93,6 +107,12 @@ export default function ApiReferencePage() {description:"Custom map styles for light and dark themes. Overrides the default Carto base map tiles.",},+ {+ name: "projection",+ type: "ProjectionSpecification",+ description:+ 'Map projection type. Use { type: "globe" } for 3D globe view.',+ },]}/></DocsSection>diff --git a/src/app/docs/basic-map/page.tsx b/src/app/docs/basic-map/page.tsxindex 92edfa8..f90a3df 100644--- a/src/app/docs/basic-map/page.tsx+++ b/src/app/docs/basic-map/page.tsx@@ -5,7 +5,7 @@ import { getExampleSource } from "@/lib/get-example-source";import { Metadata } from "next";export const metadata: Metadata = {- title: "Basic Map",+ title: "Map",};export default function BasicMapPage() {@@ -13,10 +13,10 @@ export default function BasicMapPage() {return (<DocsLayout- title="Basic Map"+ title="Map"description="The simplest way to add an interactive map to your application."prev={{ title: "API Reference", href: "/docs/api-reference" }}- next={{ title: "Map Controls", href: "/docs/controls" }}+ next={{ title: "Controls", href: "/docs/controls" }}><DocsSection><p>diff --git a/src/app/docs/clusters/page.tsx b/src/app/docs/clusters/page.tsxindex 8db6e36..b6cfc95 100644--- a/src/app/docs/clusters/page.tsx+++ b/src/app/docs/clusters/page.tsx@@ -16,7 +16,7 @@ export default function ClustersPage() {title="Clusters"description="Visualize large datasets with automatic point clustering."prev={{ title: "Routes", href: "/docs/routes" }}- next={{ title: "Advanced Usage", href: "/docs/advanced-usage" }}+ next={{ title: "Advanced", href: "/docs/advanced-usage" }}><DocsSection><p>diff --git a/src/app/docs/controls/page.tsx b/src/app/docs/controls/page.tsxindex ae9130d..063650a 100644--- a/src/app/docs/controls/page.tsx+++ b/src/app/docs/controls/page.tsx@@ -5,7 +5,7 @@ import { getExampleSource } from "@/lib/get-example-source";import { Metadata } from "next";export const metadata: Metadata = {- title: "Map Controls",+ title: "Controls",};export default function ControlsPage() {@@ -13,9 +13,9 @@ export default function ControlsPage() {return (<DocsLayout- title="Map Controls"+ title="Controls"description="Add interactive controls to your map for zoom, compass, location, and fullscreen."- prev={{ title: "Basic Map", href: "/docs/basic-map" }}+ prev={{ title: "Map", href: "/docs/basic-map" }}next={{ title: "Markers", href: "/docs/markers" }}><DocsSection>diff --git a/src/app/docs/installation/page.tsx b/src/app/docs/installation/page.tsxindex a67b859..57cd472 100644--- a/src/app/docs/installation/page.tsx+++ b/src/app/docs/installation/page.tsx@@ -38,6 +38,11 @@ export default function InstallationPage() {description="How to install and set up mapcn in your project."prev={{ title: "Introduction", href: "/docs" }}next={{ title: "API Reference", href: "/docs/api-reference" }}+ toc={[+ { title: "Prerequisites", slug: "prerequisites" },+ { title: "Installation", slug: "installation" },+ { title: "Usage", slug: "usage" },+ ]}><DocsSection title="Prerequisites"><p>diff --git a/src/app/docs/layout.tsx b/src/app/docs/layout.tsxindex 7cde79e..c7422b8 100644--- a/src/app/docs/layout.tsx+++ b/src/app/docs/layout.tsx@@ -9,16 +9,14 @@ export default function DocsLayout({}) {return (<SidebarProvider>- <div className="flex min-h-screen w-full flex-col">+ <div className="flex min-h-screen flex-col w-full"><Header- className="sticky top-0 z-50 border-b bg-background/95 backdrop-blur supports-backdrop-filter:bg-background/60"+ className="sticky top-0 z-50 bg-background/95 border-b backdrop-blur supports-backdrop-filter:bg-background/60"leftContent={<MobileSidebarTrigger />}/>- <div className="flex flex-1">+ <div className="flex flex-1 container"><DocsSidebar />- <main className="flex-1 max-w-3xl mx-auto w-full px-6 py-12">- {children}- </main>+ <main className="flex-1 w-full">{children}</main></div></div></SidebarProvider>diff --git a/src/app/docs/markers/page.tsx b/src/app/docs/markers/page.tsxindex 91a0dcc..d476a73 100644--- a/src/app/docs/markers/page.tsx+++ b/src/app/docs/markers/page.tsx@@ -27,8 +27,13 @@ export default function MarkersPage() {<DocsLayouttitle="Markers"description="Add interactive markers to your map with popups and tooltips."- prev={{ title: "Map Controls", href: "/docs/controls" }}+ prev={{ title: "Controls", href: "/docs/controls" }}next={{ title: "Popups", href: "/docs/popups" }}+ toc={[+ { title: "Basic Example", slug: "basic-example" },+ { title: "Rich Popups", slug: "rich-popups" },+ { title: "Draggable Marker", slug: "draggable-marker" },+ ]}><DocsSection><p>diff --git a/src/app/docs/page.tsx b/src/app/docs/page.tsxindex 94b4fa3..c3d1228 100644--- a/src/app/docs/page.tsx+++ b/src/app/docs/page.tsx@@ -1,4 +1,4 @@-import { Zap, Moon, Puzzle, Code, Box, Palette } from "lucide-react";+import { Zap, Moon, Puzzle, Code, Box, Layers } from "lucide-react";import { DocsLayout, DocsSection, DocsLink } from "./_components/docs";import { Metadata } from "next";@@ -30,9 +30,10 @@ const features = [description: "Own your code. No dependencies, just copy into your project.",},{- icon: Palette,- title: "Customizable",- description: "Styled with Tailwind. Easy to customize and extend.",+ icon: Layers,+ title: "Any Map Style",+ description:+ "Use any MapLibre-compatible tiles: MapTiler, Carto, OpenStreetMap, and more.",},];@@ -46,6 +47,12 @@ export default function IntroductionPage() {title="Introduction"description="Beautiful, accessible map components."next={{ title: "Installation", href: "/docs/installation" }}+ toc={[+ { title: "Why mapcn?", slug: "why-mapcn" },+ { title: "Why MapLibre Directly?", slug: "why-maplibre-directly" },+ { title: "Any Map Style", slug: "any-map-style" },+ { title: "Features", slug: "features" },+ ]}><DocsSection><p>@@ -71,9 +78,95 @@ export default function IntroductionPage() {<p>There's no proper copy-paste, easy-to-use map integration forReact. Most solutions require complex configurations, API keys, or- heavy wrapper libraries. mapcn gives you beautiful maps with a single- command.+ heavy wrapper libraries. mapcn solves this:+ </p>+ <ul>+ <li>+ <strong className="text-foreground">One Command:</strong> Run the+ install, get a working map. No config files, no API keys, no setup.+ </li>+ <li>+ <strong className="text-foreground">Own Your Code:</strong> Copy the+ components into your project. Modify anything.+ </li>+ <li>+ <strong className="text-foreground">No Wrapper Overhead:</strong>{" "}+ Built directly on MapLibre. Drop to the raw API whenever you need.+ </li>+ <li>+ <strong className="text-foreground">Looks Good Already:</strong>{" "}+ Thoughtful defaults with dark mode. Style with Tailwind as needed.+ </li>+ <li>+ <strong className="text-foreground">Works Anywhere:</strong> Bring+ your own tiles — MapTiler, Carto, OSM, or any MapLibre-compatible+ source.+ </li>+ </ul>+ </DocsSection>++ <DocsSection title="Why MapLibre Directly?">+ <p>+ mapcn uses{" "}+ <DocsLink href="https://maplibre.org" external>+ MapLibre+ </DocsLink>{" "}+ directly instead of wrapper libraries like{" "}+ <DocsLink href="https://visgl.github.io/react-map-gl" external>+ react-map-gl+ </DocsLink>+ . This keeps components close to the underlying API — when you copy a+ mapcn component, you fully own the map instance without extra+ framework dependencies.+ </p>+ <p>+ UI elements like markers, popups, and tooltips are rendered via React+ portals, giving you complete styling freedom. You can drop down to raw+ MapLibre APIs anytime without "escaping" a wrapper.+ </p>+ </DocsSection>++ <DocsSection title="Any Map Style">+ <p>+ mapcn works with any{" "}+ <DocsLink href="https://maplibre.org/maplibre-style-spec/" external>+ MapLibre-compatible tiles+ </DocsLink>+ . This means you can use tiles from virtually any provider:</p>+ <ul>+ <li>+ <DocsLink href="https://www.maptiler.com" external>+ MapTiler+ </DocsLink>{" "}+ - Beautiful vector tiles with extensive customization options+ </li>+ <li>+ <DocsLink href="https://carto.com/basemaps" external>+ Carto+ </DocsLink>{" "}+ - Clean, minimal basemaps perfect for data visualization+ </li>+ <li>+ <DocsLink href="https://www.openstreetmap.org" external>+ OpenStreetMap+ </DocsLink>{" "}+ - Community-driven, open-source map data+ </li>+ <li>+ <DocsLink href="https://stadiamaps.com" external>+ Stadia Maps+ </DocsLink>{" "}+ - Fast, reliable tile hosting with multiple styles+ </li>+ <li>+ <DocsLink href="https://www.thunderforest.com" external>+ Thunderforest+ </DocsLink>{" "}+ - Specialized maps for outdoors, cycling, and transport+ </li>+ <li>And any other provider that supports the MapLibre style spec</li>+ </ul></DocsSection><DocsSection title="Features">diff --git a/src/app/docs/routes/page.tsx b/src/app/docs/routes/page.tsxindex 88ef2ce..f3d2d67 100644--- a/src/app/docs/routes/page.tsx+++ b/src/app/docs/routes/page.tsx@@ -24,6 +24,10 @@ export default function RoutesPage() {description="Draw lines and paths connecting coordinates on the map."prev={{ title: "Popups", href: "/docs/popups" }}next={{ title: "Clusters", href: "/docs/clusters" }}+ toc={[+ { title: "Basic Route", slug: "basic-route" },+ { title: "Route Planning", slug: "route-planning" },+ ]}><DocsSection><p>diff --git a/src/app/globals.css b/src/app/globals.cssindex b719b58..f3d0b89 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -135,6 +135,10 @@}}+.container {+ @apply max-w-[1440px] mx-auto px-6;+}+/* animations for the home page */@keyframes fade-up {from {@@ -187,6 +191,7 @@.delay-600 { animation-delay: 600ms; }.delay-700 { animation-delay: 700ms; }.delay-800 { animation-delay: 800ms; }+.delay-900 { animation-delay: 900ms; }/* Shiki dual theme support for code blocks */html .shiki,diff --git a/src/app/layout.tsx b/src/app/layout.tsxindex 262b8c3..116ad73 100644--- a/src/app/layout.tsx+++ b/src/app/layout.tsx@@ -4,6 +4,7 @@ import { Analytics } from "@vercel/analytics/next";import { ThemeProvider } from "@/components/theme-provider";import "./globals.css";+import { Footer } from "@/components/footer";const geist = Geist({subsets: ["latin"],@@ -100,9 +101,10 @@ export default function RootLayout({className={`${geist.variable} ${geistMono.variable}`}suppressHydrationWarning>- <body className="font-sans antialiased">+ <body className="font-sans antialiased min-h-screen flex flex-col"><ThemeProvider>- {children}+ <div className="flex-1">{children}</div>+ <Footer /><Analytics /></ThemeProvider></body>diff --git a/src/components/command-search.tsx b/src/components/command-search.tsxnew file mode 100644index 0000000..3ce666f--- /dev/null+++ b/src/components/command-search.tsx@@ -0,0 +1,77 @@+"use client";++import * as React from "react";+import { useRouter } from "next/navigation";+import { Search } from "lucide-react";++import {+ CommandDialog,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+} from "@/components/ui/command";+import { Kbd } from "@/components/ui/kbd";+import { docsNavigation } from "@/lib/docs-navigation";++export function CommandSearch() {+ const [open, setOpen] = React.useState(false);+ const router = useRouter();++ React.useEffect(() => {+ function handleKeyDown(e: KeyboardEvent) {+ if ((e.metaKey || e.ctrlKey) && e.key === "k") {+ e.preventDefault();+ setOpen((open) => !open);+ }+ }++ document.addEventListener("keydown", handleKeyDown);+ return () => document.removeEventListener("keydown", handleKeyDown);+ }, []);++ function handleSelect(href: string) {+ setOpen(false);+ router.push(href);+ }++ return (+ <>+ <button+ onClick={() => setOpen(true)}+ aria-label="Search documentation"+ className="hidden group sm:flex items-center gap-2 h-8 px-3 rounded-full bg-secondary/60 border border-border/40 text-sm text-muted-foreground hover:text-foreground hover:border-border transition-colors"+ >+ <Search className="size-3.5" />+ <span className="hidden sm:inline">Search...</span>+ <Kbd className="hidden sm:inline-flex ml-2">⌘K</Kbd>+ </button>+ <CommandDialog+ open={open}+ onOpenChange={setOpen}+ title="Search Documentation"+ description="Search for documentation pages and components"+ >+ <CommandInput placeholder="Type to search..." />+ <CommandList>+ <CommandEmpty>No results found.</CommandEmpty>+ {docsNavigation.map((group) => (+ <CommandGroup key={group.title} heading={group.title}>+ {group.items.map((item) => (+ <CommandItem+ key={item.href}+ value={item.title}+ onSelect={() => handleSelect(item.href)}+ >+ <item.icon />+ <span>{item.title}</span>+ </CommandItem>+ ))}+ </CommandGroup>+ ))}+ </CommandList>+ </CommandDialog>+ </>+ );+}diff --git a/src/app/(home)/_components/footer.tsx b/src/components/footer.tsxsimilarity index 84%rename from src/app/(home)/_components/footer.tsxrename to src/components/footer.tsxindex b8c94ee..c9222c5 100644--- a/src/app/(home)/_components/footer.tsx+++ b/src/components/footer.tsx@@ -2,8 +2,8 @@ import Link from "next/link";export function Footer() {return (- <footer className="w-full px-6 py-8 border-t border-border/40 bg-muted/20">- <div className="mx-auto max-w-5xl flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-muted-foreground">+ <footer className="w-full py-8 border-t border-border/40 bg-muted/20">+ <div className="container flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-muted-foreground"><div className="flex items-center gap-2 flex-wrap justify-center sm:justify-start"><span>© {new Date().getFullYear()} mapcn</span><span className="text-border">•</span>diff --git a/src/components/github-button.tsx b/src/components/github-button.tsxindex 8d75e1d..6c51d56 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-2" asChild>+ <Button variant="ghost" size="sm" asChild><Linkhref="https://github.com/AnmolSaini16/mapcn"target="_blank"@@ -44,7 +44,7 @@ export async function StarCount() {return (<>{formattedCount && (- <span className="text-sm text-muted-foreground tabular-nums">+ <span className="text-xs text-muted-foreground tabular-nums pt-0.5">{formattedCount}</span>)}diff --git a/src/components/header.tsx b/src/components/header.tsxindex 020fe35..8724d20 100644--- a/src/components/header.tsx+++ b/src/components/header.tsx@@ -1,9 +1,16 @@-import { MapPin } from "lucide-react";+import { Heart, MapPin } from "lucide-react";import Link from "next/link";+import { Button } from "@/components/ui/button";import { Separator } from "@/components/ui/separator";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";import { GitHubButton } from "@/components/github-button";import { ThemeToggle } from "@/components/theme-toggle";+import { CommandSearch } from "@/components/command-search";import { cn } from "@/lib/utils";interface HeaderProps {@@ -13,8 +20,8 @@ interface HeaderProps {export function Header({ className, leftContent }: HeaderProps) {return (- <header className={cn("w-full px-6 py-4", className)}>- <nav className="flex items-center justify-between">+ <header className={cn("w-full h-16", className)}>+ <nav className="flex size-full items-center justify-between container"><div className="flex items-center gap-4">{leftContent}<Link@@ -25,7 +32,27 @@ 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.5">+ <div className="flex items-center gap-2 h-4.5">+ <CommandSearch />+ <Separator orientation="vertical" className="hidden sm:block" />+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="ghost" size="sm" asChild>+ <a+ href="https://github.com/sponsors/AnmolSaini16"+ target="_blank"+ rel="noopener noreferrer"+ >+ <Heart className="size-4 text-pink-500" />+ <span className="hidden sm:inline">Sponsor</span>+ </a>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>Sponsor this project</p>+ </TooltipContent>+ </Tooltip>+ <Separator orientation="vertical" /><GitHubButton /><Separator orientation="vertical" /><ThemeToggle />diff --git a/src/components/theme-toggle.tsx b/src/components/theme-toggle.tsxindex fdd669c..e7a0647 100644--- a/src/components/theme-toggle.tsx+++ b/src/components/theme-toggle.tsx@@ -1,44 +1,77 @@"use client";-import { useState, useEffect } from "react";+import { useCallback, useEffect } from "react";import { useTheme } from "next-themes";import { Button } from "@/components/ui/button";--function ThemeIcon({ className }: { className?: string }) {- return (- <svg- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- className={className}- >- <circle cx="12" cy="12" r="10" />- <path d="M12 2a10 10 0 0 1 0 20" fill="currentColor" stroke="none" />- </svg>- );-}+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import { Kbd } from "./ui/kbd";export function ThemeToggle() {const { resolvedTheme, setTheme } = useTheme();- const [mounted, setMounted] = useState(false);++ const toggleTheme = useCallback(() => {+ setTheme(resolvedTheme === "dark" ? "light" : "dark");+ }, [resolvedTheme, setTheme]);useEffect(() => {- setMounted(true);- }, []);+ function handleKeyDown(e: KeyboardEvent) {+ // Don't trigger if typing in an input/textarea+ if (+ e.target instanceof HTMLInputElement ||+ e.target instanceof HTMLTextAreaElement ||+ (e.target as HTMLElement)?.isContentEditable+ ) {+ return;+ }++ if ((e.key === "t" || e.key === "T") && !e.metaKey && !e.ctrlKey) {+ e.preventDefault();+ toggleTheme();+ }+ }- if (!mounted) return <div className="size-4" />;+ document.addEventListener("keydown", handleKeyDown);+ return () => document.removeEventListener("keydown", handleKeyDown);+ }, [toggleTheme]);return (- <Button- onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}- variant="ghost"- aria-label="Toggle theme"- size="icon-sm"- >- <ThemeIcon className="size-4" />- </Button>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ onClick={toggleTheme}+ variant="ghost"+ aria-label="Toggle theme"+ size="icon-sm"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className="size-4.5"+ >+ <path stroke="none" d="M0 0h24v24H0z" fill="none" />+ <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0" />+ <path d="M12 3l0 18" />+ <path d="M12 9l4.65 -4.65" />+ <path d="M12 14.3l7.37 -7.37" />+ <path d="M12 19.6l8.85 -8.85" />+ </svg>+ <span className="sr-only">Toggle theme</span>+ </Button>+ </TooltipTrigger>+ <TooltipContent className="flex items-center gap-2 pr-1">+ Toggle Theme <Kbd>T</Kbd>+ </TooltipContent>+ </Tooltip>);}diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsxnew file mode 100644index 0000000..8cb4ca7--- /dev/null+++ b/src/components/ui/command.tsx@@ -0,0 +1,184 @@+"use client"++import * as React from "react"+import { Command as CommandPrimitive } from "cmdk"+import { SearchIcon } from "lucide-react"++import { cn } from "@/lib/utils"+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog"++function Command({+ className,+ ...props+}: React.ComponentProps<typeof CommandPrimitive>) {+ return (+ <CommandPrimitive+ data-slot="command"+ className={cn(+ "bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",+ className+ )}+ {...props}+ />+ )+}++function CommandDialog({+ title = "Command Palette",+ description = "Search for a command to run...",+ children,+ className,+ showCloseButton = true,+ ...props+}: React.ComponentProps<typeof Dialog> & {+ title?: string+ description?: string+ className?: string+ showCloseButton?: boolean+}) {+ return (+ <Dialog {...props}>+ <DialogHeader className="sr-only">+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>+ <DialogContent+ className={cn("overflow-hidden p-0", className)}+ showCloseButton={showCloseButton}+ >+ <Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">+ {children}+ </Command>+ </DialogContent>+ </Dialog>+ )+}++function CommandInput({+ className,+ ...props+}: React.ComponentProps<typeof CommandPrimitive.Input>) {+ return (+ <div+ data-slot="command-input-wrapper"+ className="flex h-9 items-center gap-2 border-b px-3"+ >+ <SearchIcon className="size-4 shrink-0 opacity-50" />+ <CommandPrimitive.Input+ data-slot="command-input"+ className={cn(+ "placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",+ className+ )}+ {...props}+ />+ </div>+ )+}++function CommandList({+ className,+ ...props+}: React.ComponentProps<typeof CommandPrimitive.List>) {+ return (+ <CommandPrimitive.List+ data-slot="command-list"+ className={cn(+ "max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",+ className+ )}+ {...props}+ />+ )+}++function CommandEmpty({+ ...props+}: React.ComponentProps<typeof CommandPrimitive.Empty>) {+ return (+ <CommandPrimitive.Empty+ data-slot="command-empty"+ className="py-6 text-center text-sm"+ {...props}+ />+ )+}++function CommandGroup({+ className,+ ...props+}: React.ComponentProps<typeof CommandPrimitive.Group>) {+ return (+ <CommandPrimitive.Group+ data-slot="command-group"+ className={cn(+ "text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",+ className+ )}+ {...props}+ />+ )+}++function CommandSeparator({+ className,+ ...props+}: React.ComponentProps<typeof CommandPrimitive.Separator>) {+ return (+ <CommandPrimitive.Separator+ data-slot="command-separator"+ className={cn("bg-border -mx-1 h-px", className)}+ {...props}+ />+ )+}++function CommandItem({+ className,+ ...props+}: React.ComponentProps<typeof CommandPrimitive.Item>) {+ return (+ <CommandPrimitive.Item+ data-slot="command-item"+ className={cn(+ "data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",+ className+ )}+ {...props}+ />+ )+}++function CommandShortcut({+ className,+ ...props+}: React.ComponentProps<"span">) {+ return (+ <span+ data-slot="command-shortcut"+ className={cn(+ "text-muted-foreground ml-auto text-xs tracking-widest",+ className+ )}+ {...props}+ />+ )+}++export {+ Command,+ CommandDialog,+ CommandInput,+ CommandList,+ CommandEmpty,+ CommandGroup,+ CommandItem,+ CommandShortcut,+ CommandSeparator,+}diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsxnew file mode 100644index 0000000..a6f1cfb--- /dev/null+++ b/src/components/ui/dialog.tsx@@ -0,0 +1,143 @@+"use client"++import * as React from "react"+import * as DialogPrimitive from "@radix-ui/react-dialog"+import { XIcon } from "lucide-react"++import { cn } from "@/lib/utils"++function Dialog({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Root>) {+ return <DialogPrimitive.Root data-slot="dialog" {...props} />+}++function DialogTrigger({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />+}++function DialogPortal({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Portal>) {+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />+}++function DialogClose({+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Close>) {+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />+}++function DialogOverlay({+ className,+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {+ return (+ <DialogPrimitive.Overlay+ data-slot="dialog-overlay"+ className={cn(+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",+ className+ )}+ {...props}+ />+ )+}++function DialogContent({+ className,+ children,+ showCloseButton = true,+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Content> & {+ showCloseButton?: boolean+}) {+ return (+ <DialogPortal data-slot="dialog-portal">+ <DialogOverlay />+ <DialogPrimitive.Content+ data-slot="dialog-content"+ className={cn(+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",+ className+ )}+ {...props}+ >+ {children}+ {showCloseButton && (+ <DialogPrimitive.Close+ data-slot="dialog-close"+ className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"+ >+ <XIcon />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ )}+ </DialogPrimitive.Content>+ </DialogPortal>+ )+}++function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="dialog-header"+ className={cn("flex flex-col gap-2 text-center sm:text-left", className)}+ {...props}+ />+ )+}++function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <div+ data-slot="dialog-footer"+ className={cn(+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",+ className+ )}+ {...props}+ />+ )+}++function DialogTitle({+ className,+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Title>) {+ return (+ <DialogPrimitive.Title+ data-slot="dialog-title"+ className={cn("text-lg leading-none font-semibold", className)}+ {...props}+ />+ )+}++function DialogDescription({+ className,+ ...props+}: React.ComponentProps<typeof DialogPrimitive.Description>) {+ return (+ <DialogPrimitive.Description+ data-slot="dialog-description"+ className={cn("text-muted-foreground text-sm", className)}+ {...props}+ />+ )+}++export {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogOverlay,+ DialogPortal,+ DialogTitle,+ DialogTrigger,+}diff --git a/src/components/ui/kbd.tsx b/src/components/ui/kbd.tsxnew file mode 100644index 0000000..253c69f--- /dev/null+++ b/src/components/ui/kbd.tsx@@ -0,0 +1,28 @@+import { cn } from "@/lib/utils"++function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {+ return (+ <kbd+ data-slot="kbd"+ className={cn(+ "bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none",+ "[&_svg:not([class*='size-'])]:size-3",+ "[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",+ className+ )}+ {...props}+ />+ )+}++function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {+ return (+ <kbd+ data-slot="kbd-group"+ className={cn("inline-flex items-center gap-1", className)}+ {...props}+ />+ )+}++export { Kbd, KbdGroup }diff --git a/src/components/ui/sidebar.tsx b/src/components/ui/sidebar.tsxindex 30638ac..64b7c84 100644--- a/src/components/ui/sidebar.tsx+++ b/src/components/ui/sidebar.tsx@@ -1,56 +1,56 @@-"use client"--import * as React from "react"-import { Slot } from "@radix-ui/react-slot"-import { cva, type VariantProps } from "class-variance-authority"-import { PanelLeftIcon } from "lucide-react"--import { useIsMobile } from "@/hooks/use-mobile"-import { cn } from "@/lib/utils"-import { Button } from "@/components/ui/button"-import { Input } from "@/components/ui/input"-import { Separator } from "@/components/ui/separator"+"use client";++import * as React from "react";+import { Slot } from "@radix-ui/react-slot";+import { cva, type VariantProps } from "class-variance-authority";+import { PanelLeftIcon } from "lucide-react";++import { useIsMobile } from "@/hooks/use-mobile";+import { cn } from "@/lib/utils";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Separator } from "@/components/ui/separator";import {Sheet,SheetContent,SheetDescription,SheetHeader,SheetTitle,-} from "@/components/ui/sheet"-import { Skeleton } from "@/components/ui/skeleton"+} from "@/components/ui/sheet";+import { Skeleton } from "@/components/ui/skeleton";import {Tooltip,TooltipContent,TooltipProvider,TooltipTrigger,-} from "@/components/ui/tooltip"+} from "@/components/ui/tooltip";-const SIDEBAR_COOKIE_NAME = "sidebar_state"-const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7-const SIDEBAR_WIDTH = "16rem"-const SIDEBAR_WIDTH_MOBILE = "18rem"-const SIDEBAR_WIDTH_ICON = "3rem"-const SIDEBAR_KEYBOARD_SHORTCUT = "b"+const SIDEBAR_COOKIE_NAME = "sidebar_state";+const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;+const SIDEBAR_WIDTH = "16rem";+const SIDEBAR_WIDTH_MOBILE = "18rem";+const SIDEBAR_WIDTH_ICON = "3rem";+const SIDEBAR_KEYBOARD_SHORTCUT = "b";type SidebarContextProps = {- state: "expanded" | "collapsed"- open: boolean- setOpen: (open: boolean) => void- openMobile: boolean- setOpenMobile: (open: boolean) => void- isMobile: boolean- toggleSidebar: () => void-}+ state: "expanded" | "collapsed";+ open: boolean;+ setOpen: (open: boolean) => void;+ openMobile: boolean;+ setOpenMobile: (open: boolean) => void;+ isMobile: boolean;+ toggleSidebar: () => void;+};-const SidebarContext = React.createContext<SidebarContextProps | null>(null)+const SidebarContext = React.createContext<SidebarContextProps | null>(null);function useSidebar() {- const context = React.useContext(SidebarContext)+ const context = React.useContext(SidebarContext);if (!context) {- throw new Error("useSidebar must be used within a SidebarProvider.")+ throw new Error("useSidebar must be used within a SidebarProvider.");}- return context+ return context;}function SidebarProvider({@@ -62,36 +62,36 @@ function SidebarProvider({children,...props}: React.ComponentProps<"div"> & {- defaultOpen?: boolean- open?: boolean- onOpenChange?: (open: boolean) => void+ defaultOpen?: boolean;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;}) {- const isMobile = useIsMobile()- const [openMobile, setOpenMobile] = React.useState(false)+ const isMobile = useIsMobile();+ const [openMobile, setOpenMobile] = React.useState(false);// This is the internal state of the sidebar.// We use openProp and setOpenProp for control from outside the component.- const [_open, _setOpen] = React.useState(defaultOpen)- const open = openProp ?? _open+ const [_open, _setOpen] = React.useState(defaultOpen);+ const open = openProp ?? _open;const setOpen = React.useCallback((value: boolean | ((value: boolean) => boolean)) => {- const openState = typeof value === "function" ? value(open) : value+ const openState = typeof value === "function" ? value(open) : value;if (setOpenProp) {- setOpenProp(openState)+ setOpenProp(openState);} else {- _setOpen(openState)+ _setOpen(openState);}// This sets the cookie to keep the sidebar state.- document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;},[setOpenProp, open]- )+ );// Helper to toggle the sidebar.const toggleSidebar = React.useCallback(() => {- return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)- }, [isMobile, setOpen, setOpenMobile])+ return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);+ }, [isMobile, setOpen, setOpenMobile]);// Adds a keyboard shortcut to toggle the sidebar.React.useEffect(() => {@@ -100,18 +100,18 @@ function SidebarProvider({event.key === SIDEBAR_KEYBOARD_SHORTCUT &&(event.metaKey || event.ctrlKey)) {- event.preventDefault()- toggleSidebar()+ event.preventDefault();+ toggleSidebar();}- }+ };- window.addEventListener("keydown", handleKeyDown)- return () => window.removeEventListener("keydown", handleKeyDown)- }, [toggleSidebar])+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [toggleSidebar]);// We add a state so that we can do data-state="expanded" or "collapsed".// This makes it easier to style the sidebar with Tailwind classes.- const state = open ? "expanded" : "collapsed"+ const state = open ? "expanded" : "collapsed";const contextValue = React.useMemo<SidebarContextProps>(() => ({@@ -124,7 +124,7 @@ function SidebarProvider({toggleSidebar,}),[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]- )+ );return (<SidebarContext.Provider value={contextValue}>@@ -148,7 +148,7 @@ function SidebarProvider({</div></TooltipProvider></SidebarContext.Provider>- )+ );}function Sidebar({@@ -159,11 +159,11 @@ function Sidebar({children,...props}: React.ComponentProps<"div"> & {- side?: "left" | "right"- variant?: "sidebar" | "floating" | "inset"- collapsible?: "offcanvas" | "icon" | "none"+ side?: "left" | "right";+ variant?: "sidebar" | "floating" | "inset";+ collapsible?: "offcanvas" | "icon" | "none";}) {- const { isMobile, state, openMobile, setOpenMobile } = useSidebar()+ const { isMobile, state, openMobile, setOpenMobile } = useSidebar();if (collapsible === "none") {return (@@ -177,7 +177,7 @@ function Sidebar({>{children}</div>- )+ );}if (isMobile) {@@ -187,7 +187,7 @@ function Sidebar({data-sidebar="sidebar"data-slot="sidebar"data-mobile="true"- className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"+ className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-2 [&>button]:hidden"style={{"--sidebar-width": SIDEBAR_WIDTH_MOBILE,@@ -202,7 +202,7 @@ function Sidebar({<div className="flex h-full w-full flex-col">{children}</div></SheetContent></Sheet>- )+ );}return (@@ -250,7 +250,7 @@ function Sidebar({</div></div></div>- )+ );}function SidebarTrigger({@@ -258,7 +258,7 @@ function SidebarTrigger({onClick,...props}: React.ComponentProps<typeof Button>) {- const { toggleSidebar } = useSidebar()+ const { toggleSidebar } = useSidebar();return (<Button@@ -268,19 +268,19 @@ function SidebarTrigger({size="icon"className={cn("size-7", className)}onClick={(event) => {- onClick?.(event)- toggleSidebar()+ onClick?.(event);+ toggleSidebar();}}{...props}><PanelLeftIcon /><span className="sr-only">Toggle Sidebar</span></Button>- )+ );}function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {- const { toggleSidebar } = useSidebar()+ const { toggleSidebar } = useSidebar();return (<button@@ -301,7 +301,7 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {)}{...props}/>- )+ );}function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {@@ -315,7 +315,7 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {)}{...props}/>- )+ );}function SidebarInput({@@ -329,7 +329,7 @@ function SidebarInput({className={cn("bg-background h-8 w-full shadow-none", className)}{...props}/>- )+ );}function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {@@ -340,7 +340,7 @@ function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {className={cn("flex flex-col gap-2 p-2", className)}{...props}/>- )+ );}function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {@@ -351,7 +351,7 @@ function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {className={cn("flex flex-col gap-2 p-2", className)}{...props}/>- )+ );}function SidebarSeparator({@@ -365,7 +365,7 @@ function SidebarSeparator({className={cn("bg-sidebar-border mx-2 w-auto", className)}{...props}/>- )+ );}function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {@@ -379,7 +379,7 @@ function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {)}{...props}/>- )+ );}function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {@@ -390,7 +390,7 @@ function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {className={cn("relative flex w-full min-w-0 flex-col p-2", className)}{...props}/>- )+ );}function SidebarGroupLabel({@@ -398,7 +398,7 @@ function SidebarGroupLabel({asChild = false,...props}: React.ComponentProps<"div"> & { asChild?: boolean }) {- const Comp = asChild ? Slot : "div"+ const Comp = asChild ? Slot : "div";return (<Comp@@ -411,7 +411,7 @@ function SidebarGroupLabel({)}{...props}/>- )+ );}function SidebarGroupAction({@@ -419,7 +419,7 @@ function SidebarGroupAction({asChild = false,...props}: React.ComponentProps<"button"> & { asChild?: boolean }) {- const Comp = asChild ? Slot : "button"+ const Comp = asChild ? Slot : "button";return (<Comp@@ -434,7 +434,7 @@ function SidebarGroupAction({)}{...props}/>- )+ );}function SidebarGroupContent({@@ -448,7 +448,7 @@ function SidebarGroupContent({className={cn("w-full text-sm", className)}{...props}/>- )+ );}function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {@@ -459,7 +459,7 @@ function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {className={cn("flex w-full min-w-0 flex-col gap-1", className)}{...props}/>- )+ );}function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {@@ -470,7 +470,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {className={cn("group/menu-item relative", className)}{...props}/>- )+ );}const sidebarMenuButtonVariants = cva(@@ -493,7 +493,7 @@ const sidebarMenuButtonVariants = cva(size: "default",},}-)+);function SidebarMenuButton({asChild = false,@@ -504,12 +504,12 @@ function SidebarMenuButton({className,...props}: React.ComponentProps<"button"> & {- asChild?: boolean- isActive?: boolean- tooltip?: string | React.ComponentProps<typeof TooltipContent>+ asChild?: boolean;+ isActive?: boolean;+ tooltip?: string | React.ComponentProps<typeof TooltipContent>;} & VariantProps<typeof sidebarMenuButtonVariants>) {- const Comp = asChild ? Slot : "button"- const { isMobile, state } = useSidebar()+ const Comp = asChild ? Slot : "button";+ const { isMobile, state } = useSidebar();const button = (<Comp@@ -520,16 +520,16 @@ function SidebarMenuButton({className={cn(sidebarMenuButtonVariants({ variant, size }), className)}{...props}/>- )+ );if (!tooltip) {- return button+ return button;}if (typeof tooltip === "string") {tooltip = {children: tooltip,- }+ };}return (@@ -542,7 +542,7 @@ function SidebarMenuButton({{...tooltip}/></Tooltip>- )+ );}function SidebarMenuAction({@@ -551,10 +551,10 @@ function SidebarMenuAction({showOnHover = false,...props}: React.ComponentProps<"button"> & {- asChild?: boolean- showOnHover?: boolean+ asChild?: boolean;+ showOnHover?: boolean;}) {- const Comp = asChild ? Slot : "button"+ const Comp = asChild ? Slot : "button";return (<Comp@@ -574,7 +574,7 @@ function SidebarMenuAction({)}{...props}/>- )+ );}function SidebarMenuBadge({@@ -596,7 +596,7 @@ function SidebarMenuBadge({)}{...props}/>- )+ );}function SidebarMenuSkeleton({@@ -604,12 +604,12 @@ function SidebarMenuSkeleton({showIcon = false,...props}: React.ComponentProps<"div"> & {- showIcon?: boolean+ showIcon?: boolean;}) {// Random width between 50 to 90%.const width = React.useMemo(() => {- return `${Math.floor(Math.random() * 40) + 50}%`- }, [])+ return `${Math.floor(Math.random() * 40) + 50}%`;+ }, []);return (<div@@ -634,7 +634,7 @@ function SidebarMenuSkeleton({}/></div>- )+ );}function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {@@ -649,7 +649,7 @@ function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {)}{...props}/>- )+ );}function SidebarMenuSubItem({@@ -663,7 +663,7 @@ function SidebarMenuSubItem({className={cn("group/menu-sub-item relative", className)}{...props}/>- )+ );}function SidebarMenuSubButton({@@ -673,11 +673,11 @@ function SidebarMenuSubButton({className,...props}: React.ComponentProps<"a"> & {- asChild?: boolean- size?: "sm" | "md"- isActive?: boolean+ asChild?: boolean;+ size?: "sm" | "md";+ isActive?: boolean;}) {- const Comp = asChild ? Slot : "a"+ const Comp = asChild ? Slot : "a";return (<Comp@@ -695,7 +695,7 @@ function SidebarMenuSubButton({)}{...props}/>- )+ );}export {@@ -723,4 +723,4 @@ export {SidebarSeparator,SidebarTrigger,useSidebar,-}+};diff --git a/src/components/ui/tooltip.tsx b/src/components/ui/tooltip.tsxindex a4e90d4..d4e6be9 100644--- a/src/components/ui/tooltip.tsx+++ b/src/components/ui/tooltip.tsx@@ -1,9 +1,9 @@-"use client"+"use client";-import * as React from "react"-import * as TooltipPrimitive from "@radix-ui/react-tooltip"+import * as React from "react";+import * as TooltipPrimitive from "@radix-ui/react-tooltip";-import { cn } from "@/lib/utils"+import { cn } from "@/lib/utils";function TooltipProvider({delayDuration = 0,@@ -15,7 +15,7 @@ function TooltipProvider({delayDuration={delayDuration}{...props}/>- )+ );}function Tooltip({@@ -25,13 +25,13 @@ function Tooltip({<TooltipProvider><TooltipPrimitive.Root data-slot="tooltip" {...props} /></TooltipProvider>- )+ );}function TooltipTrigger({...props}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {- return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />+ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;}function TooltipContent({@@ -55,7 +55,7 @@ function TooltipContent({<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" /></TooltipPrimitive.Content></TooltipPrimitive.Portal>- )+ );}-export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };diff --git a/src/lib/docs-navigation.ts b/src/lib/docs-navigation.tsnew file mode 100644index 0000000..f675877--- /dev/null+++ b/src/lib/docs-navigation.ts@@ -0,0 +1,47 @@+import {+ Map,+ BookOpen,+ Code,+ Braces,+ MapPin,+ MessageSquare,+ Route,+ Wrench,+ Settings,+ Layers,+ LucideIcon,+} from "lucide-react";++export interface NavItem {+ title: string;+ href: string;+ icon: LucideIcon;+}++export interface NavGroup {+ title: string;+ items: NavItem[];+}++export const docsNavigation: NavGroup[] = [+ {+ title: "Basics",+ items: [+ { title: "Getting Started", href: "/docs", icon: BookOpen },+ { title: "Installation", href: "/docs/installation", icon: Code },+ { title: "API Reference", href: "/docs/api-reference", icon: Braces },+ ],+ },+ {+ title: "Components",+ items: [+ { title: "Map", href: "/docs/basic-map", icon: Map },+ { title: "Controls", href: "/docs/controls", icon: Settings },+ { title: "Markers", href: "/docs/markers", icon: MapPin },+ { title: "Popups", href: "/docs/popups", icon: MessageSquare },+ { title: "Routes", href: "/docs/routes", icon: Route },+ { title: "Clusters", href: "/docs/clusters", icon: Layers },+ { title: "Advanced", href: "/docs/advanced-usage", icon: Wrench },+ ],+ },+];diff --git a/src/registry/map.tsx b/src/registry/map.tsxindex a4f56a9..ff43963 100644--- a/src/registry/map.tsx+++ b/src/registry/map.tsx@@ -20,7 +20,6 @@ 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;@@ -51,6 +50,8 @@ type MapProps = {light?: MapStyleOption;dark?: MapStyleOption;};+ /** Map projection type. Use `{ type: "globe" }` for 3D globe view. */+ projection?: MapLibreGL.ProjectionSpecification;} & Omit<MapLibreGL.MapOptions, "container" | "style">;type MapRef = MapLibreGL.Map;@@ -66,7 +67,7 @@ const DefaultLoader = () => ();const Map = forwardRef<MapRef, MapProps>(function Map(- { children, styles, ...props },+ { children, styles, projection, ...props },ref) {const containerRef = useRef<HTMLDivElement>(null);@@ -75,6 +76,7 @@ const Map = forwardRef<MapRef, MapProps>(function Map(const [isStyleLoaded, setIsStyleLoaded] = useState(false);const { resolvedTheme } = useTheme();const currentStyleRef = useRef<MapStyleOption | null>(null);+ const styleTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);const mapStyles = useMemo(() => ({@@ -86,6 +88,13 @@ const Map = forwardRef<MapRef, MapProps>(function Map(useImperativeHandle(ref, () => mapInstance as MapLibreGL.Map, [mapInstance]);+ const clearStyleTimeout = useCallback(() => {+ if (styleTimeoutRef.current) {+ clearTimeout(styleTimeoutRef.current);+ styleTimeoutRef.current = null;+ }+ }, []);+useEffect(() => {if (!containerRef.current) return;@@ -103,7 +112,17 @@ const Map = forwardRef<MapRef, MapProps>(function Map(...props,});- const styleDataHandler = () => setIsStyleLoaded(true);+ const styleDataHandler = () => {+ clearStyleTimeout();+ // Delay to ensure style is fully processed before allowing layer operations+ // This is a workaround to avoid race conditions with the style loading+ styleTimeoutRef.current = setTimeout(() => {+ setIsStyleLoaded(true);+ if (projection) {+ map.setProjection(projection);+ }+ }, 150);+ };const loadHandler = () => setIsLoaded(true);map.on("load", loadHandler);@@ -111,6 +130,7 @@ const Map = forwardRef<MapRef, MapProps>(function Map(setMapInstance(map);return () => {+ clearStyleTimeout();map.off("load", loadHandler);map.off("styledata", styleDataHandler);map.remove();@@ -129,15 +149,12 @@ const Map = forwardRef<MapRef, MapProps>(function Map(if (currentStyleRef.current === newStyle) return;+ clearStyleTimeout();currentStyleRef.current = newStyle;setIsStyleLoaded(false);- const frameId = requestAnimationFrame(() => {- mapInstance.setStyle(newStyle, { diff: true });- });-- return () => cancelAnimationFrame(frameId);- }, [mapInstance, resolvedTheme, mapStyles]);+ mapInstance.setStyle(newStyle, { diff: true });+ }, [mapInstance, resolvedTheme, mapStyles, clearStyleTimeout]);const isLoading = !isLoaded || !isStyleLoaded;