Skip to content

armgit / mapcn

Public Imported from GitHub
0

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

TypeScript

Update: added map style customization

Anmoldeep Singhcb535f6e213b
diff --git a/public/maps/map.json b/public/maps/map.json
index 8a84cdc..657416a 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 useContext,\n useEffect,\n useId,\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 mapStyles = {\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 MapProps = {\n children?: ReactNode;\n} & Omit<MapLibreGL.MapOptions, \"container\">;\n\nconst DefaultLoader = () => (\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"flex gap-1\">\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:150ms]\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:300ms]\" />\n </div>\n </div>\n);\n\nfunction Map({ children, ...props }: MapProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<MapLibreGL.Map | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [isStyleLoaded, setIsStyleLoaded] = useState(false);\n const { resolvedTheme } = useTheme();\n\n useEffect(() => {\n if (!containerRef.current) return;\n\n const mapStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n const mapInstance = new MapLibreGL.Map({\n container: containerRef.current,\n style: mapStyle,\n attributionControl: false,\n ...props,\n });\n\n const styleDataHandler = () => setIsStyleLoaded(true);\n const loadHandler = () => setIsLoaded(true);\n\n mapInstance.on(\"load\", loadHandler);\n mapInstance.on(\"styledata\", styleDataHandler);\n mapRef.current = mapInstance;\n\n return () => {\n mapInstance.off(\"load\", loadHandler);\n mapInstance.off(\"styledata\", styleDataHandler);\n mapInstance.remove();\n mapRef.current = null;\n };\n }, []);\n\n useEffect(() => {\n if (mapRef.current) {\n setIsStyleLoaded(false);\n mapRef.current.setStyle(\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light,\n { diff: true }\n );\n }\n }, [resolvedTheme]);\n\n const isLoading = !isLoaded || !isStyleLoaded;\n\n return (\n <MapContext.Provider\n value={{ map: mapRef.current, isLoaded: isLoaded && isStyleLoaded }}\n >\n <div ref={containerRef} className=\"relative w-full h-full\">\n {isLoading && <DefaultLoader />}\n {children}\n </div>\n </MapContext.Provider>\n );\n}\n\ntype MarkerContextValue = {\n markerRef: React.RefObject<MapLibreGL.Marker | null>;\n markerElementRef: React.RefObject<HTMLDivElement | null>;\n map: MapLibreGL.Map | null;\n isReady: boolean;\n};\n\nconst MarkerContext = createContext<MarkerContextValue | null>(null);\n\nfunction useMarkerContext() {\n const context = useContext(MarkerContext);\n if (!context) {\n throw new Error(\"Marker components must be used within MapMarker\");\n }\n return context;\n}\n\ntype MapMarkerProps = {\n longitude: number;\n latitude: number;\n children: ReactNode;\n onClick?: (e: MouseEvent) => void;\n onMouseEnter?: (e: MouseEvent) => void;\n onMouseLeave?: (e: MouseEvent) => void;\n onDragStart?: (lngLat: { lng: number; lat: number }) => void;\n onDrag?: (lngLat: { lng: number; lat: number }) => void;\n onDragEnd?: (lngLat: { lng: number; lat: number }) => void;\n} & Omit<MarkerOptions, \"element\">;\n\nfunction MapMarker({\n longitude,\n latitude,\n children,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n draggable = false,\n ...markerOptions\n}: MapMarkerProps) {\n const { map, isLoaded } = useMap();\n const markerRef = useRef<MapLibreGL.Marker | null>(null);\n const markerElementRef = useRef<HTMLDivElement | null>(null);\n const [isReady, setIsReady] = useState(false);\n\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const container = document.createElement(\"div\");\n markerElementRef.current = container;\n\n const marker = new MapLibreGL.Marker({\n ...markerOptions,\n element: container,\n draggable,\n })\n .setLngLat([longitude, latitude])\n .addTo(map);\n\n markerRef.current = marker;\n\n if (onClick) container.addEventListener(\"click\", onClick);\n if (onMouseEnter) container.addEventListener(\"mouseenter\", onMouseEnter);\n if (onMouseLeave) container.addEventListener(\"mouseleave\", onMouseLeave);\n\n const handleDragStart = () => {\n const lngLat = marker.getLngLat();\n onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDrag = () => {\n const lngLat = marker.getLngLat();\n onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDragEnd = () => {\n const lngLat = marker.getLngLat();\n onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n\n if (draggable) {\n marker.on(\"dragstart\", handleDragStart);\n marker.on(\"drag\", handleDrag);\n marker.on(\"dragend\", handleDragEnd);\n }\n\n setIsReady(true);\n\n return () => {\n if (onClick) container.removeEventListener(\"click\", onClick);\n if (onMouseEnter)\n container.removeEventListener(\"mouseenter\", onMouseEnter);\n if (onMouseLeave)\n container.removeEventListener(\"mouseleave\", onMouseLeave);\n if (draggable) {\n marker.off(\"dragstart\", handleDragStart);\n marker.off(\"drag\", handleDrag);\n marker.off(\"dragend\", handleDragEnd);\n }\n marker.remove();\n markerRef.current = null;\n markerElementRef.current = null;\n setIsReady(false);\n };\n }, [isLoaded]);\n\n useEffect(() => {\n markerRef.current?.setLngLat([longitude, latitude]);\n }, [longitude, latitude]);\n\n useEffect(() => {\n markerRef.current?.setDraggable(draggable);\n }, [draggable]);\n\n return (\n <MarkerContext.Provider\n value={{ markerRef, markerElementRef, map, isReady }}\n >\n {children}\n </MarkerContext.Provider>\n );\n}\n\ntype MarkerContentProps = {\n children?: ReactNode;\n className?: string;\n};\n\nfunction MarkerContent({ children, className }: MarkerContentProps) {\n const { markerElementRef, isReady } = useMarkerContext();\n\n if (!isReady || !markerElementRef.current) return null;\n\n return createPortal(\n <div className={cn(\"relative cursor-pointer\", className)}>\n {children || <DefaultMarkerIcon />}\n </div>,\n markerElementRef.current\n );\n}\n\nfunction DefaultMarkerIcon() {\n return (\n <div className=\"relative h-4 w-4 rounded-full border-2 border-white bg-blue-500 shadow-lg\" />\n );\n}\n\ntype MarkerPopupProps = {\n children: ReactNode;\n className?: string;\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\">;\n\nfunction MarkerPopup({\n children,\n className,\n closeButton = false,\n ...popupOptions\n}: MarkerPopupProps) {\n const { markerRef, isReady } = useMarkerContext();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n if (!isReady || !markerRef.current) return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n popupRef.current = popup;\n markerRef.current.setPopup(popup);\n setMounted(true);\n\n return () => {\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isReady]);\n\n const handleClose = () => popupRef.current?.remove();\n\n if (!mounted || !containerRef.current) return null;\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\n {children}\n </div>,\n containerRef.current\n );\n}\n\ntype MarkerTooltipProps = {\n children: ReactNode;\n className?: string;\n} & Omit<PopupOptions, \"className\" | \"closeButton\" | \"closeOnClick\">;\n\nfunction MarkerTooltip({\n children,\n className,\n ...popupOptions\n}: MarkerTooltipProps) {\n const { markerRef, markerElementRef, map, isReady } = useMarkerContext();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n if (!isReady || !markerRef.current || !markerElementRef.current || !map)\n return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeOnClick: true,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n popupRef.current = popup;\n\n const markerElement = markerElementRef.current;\n const marker = markerRef.current;\n\n const handleMouseEnter = () => {\n popup.setLngLat(marker.getLngLat()).addTo(map);\n };\n const handleMouseLeave = () => popup.remove();\n\n markerElement.addEventListener(\"mouseenter\", handleMouseEnter);\n markerElement.addEventListener(\"mouseleave\", handleMouseLeave);\n setMounted(true);\n\n return () => {\n markerElement.removeEventListener(\"mouseenter\", handleMouseEnter);\n markerElement.removeEventListener(\"mouseleave\", handleMouseLeave);\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isReady, map]);\n\n if (!mounted || !containerRef.current) return null;\n\n return createPortal(\n <div\n className={cn(\n \"rounded-md bg-foreground px-2 py-1 text-xs text-background shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {children}\n </div>,\n containerRef.current\n );\n}\n\ntype MarkerLabelProps = {\n children: ReactNode;\n className?: string;\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?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\";\n showZoom?: boolean;\n showCompass?: boolean;\n showLocate?: boolean;\n showFullscreen?: boolean;\n className?: string;\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-2 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 if (!isLoaded) return null;\n\n const handleZoomIn = () => map?.zoomTo(map.getZoom() + 1, { duration: 300 });\n const handleZoomOut = () => map?.zoomTo(map.getZoom() - 1, { duration: 300 });\n const handleResetBearing = () => map?.resetNorthPitch({ duration: 300 });\n\n const handleLocate = () => {\n setWaitingForLocation(true);\n if (\"geolocation\" in navigator) {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n const coords = {\n longitude: position.coords.longitude,\n latitude: position.coords.latitude,\n };\n map?.flyTo({\n center: [coords.longitude, coords.latitude],\n zoom: 14,\n duration: 1500,\n });\n onLocate?.({\n longitude: coords.longitude,\n latitude: coords.latitude,\n });\n setWaitingForLocation(false);\n },\n (error) => {\n console.error(\"Error getting location:\", error);\n setWaitingForLocation(false);\n }\n );\n }\n };\n\n const handleFullscreen = () => {\n const container = map?.getContainer();\n if (!container) return;\n if (document.fullscreenElement) {\n document.exitFullscreen();\n } else {\n container.requestFullscreen();\n }\n };\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 <button\n onClick={onClick}\n aria-label=\"Reset bearing to north\"\n type=\"button\"\n className=\"flex items-center justify-center size-8 hover:bg-accent transition-colors\"\n >\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 </button>\n );\n}\n\ntype MapPopupProps = {\n longitude: number;\n latitude: number;\n open?: boolean;\n onClose?: () => void;\n children: ReactNode;\n className?: string;\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\">;\n\nfunction MapPopup({\n longitude,\n latitude,\n open = true,\n onClose,\n children,\n className,\n closeButton = true,\n ...popupOptions\n}: MapPopupProps) {\n const { map, isLoaded } = useMap();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 12,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container)\n .setLngLat([longitude, latitude]);\n\n popup.on(\"close\", () => onClose?.());\n\n popupRef.current = popup;\n setMounted(true);\n\n return () => {\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isLoaded, map]);\n\n useEffect(() => {\n if (!popupRef.current || !map) return;\n\n if (open) {\n popupRef.current.addTo(map);\n } else {\n popupRef.current.remove();\n }\n }, [open, map, mounted]);\n\n useEffect(() => {\n popupRef.current?.setLngLat([longitude, latitude]);\n }, [longitude, latitude]);\n\n const handleClose = () => {\n popupRef.current?.remove();\n onClose?.();\n };\n\n if (!mounted || !containerRef.current) return null;\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\n {children}\n </div>,\n containerRef.current\n );\n}\n\ntype MapRouteProps = {\n coordinates: [number, number][];\n color?: string;\n width?: number;\n opacity?: number;\n dashArray?: [number, number];\n};\n\nfunction MapRoute({\n coordinates,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const id = useId();\n const sourceId = `route-source-${id}`;\n const layerId = `route-layer-${id}`;\n\n useEffect(() => {\n if (!isLoaded || !map || coordinates.length < 2) return;\n\n const addRoute = () => {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\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\n addRoute();\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 }, [\n isLoaded,\n map,\n coordinates,\n color,\n width,\n opacity,\n dashArray,\n sourceId,\n layerId,\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};\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 useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { X, Minus, Plus, Locate, Maximize, Loader2 } from \"lucide-react\";\n\nimport { cn } from \"@/lib/utils\";\n\ntype MapContextValue = {\n map: MapLibreGL.Map | null;\n isLoaded: boolean;\n};\n\nconst MapContext = createContext<MapContextValue | null>(null);\n\nfunction useMap() {\n const context = useContext(MapContext);\n if (!context) {\n throw new Error(\"useMap must be used within a Map component\");\n }\n return context;\n}\n\nconst defaultStyles = {\n dark: \"https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json\",\n light: \"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json\",\n};\n\ntype MapStyleOption = string | MapLibreGL.StyleSpecification;\n\ntype MapProps = {\n children?: ReactNode;\n /** Custom map styles for light and dark themes. Overrides the default Carto styles. */\n styles?: {\n light?: MapStyleOption;\n dark?: MapStyleOption;\n };\n} & Omit<MapLibreGL.MapOptions, \"container\" | \"style\">;\n\nconst DefaultLoader = () => (\n <div className=\"absolute inset-0 flex items-center justify-center\">\n <div className=\"flex gap-1\">\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:150ms]\" />\n <span className=\"size-1.5 rounded-full bg-muted-foreground/60 animate-pulse [animation-delay:300ms]\" />\n </div>\n </div>\n);\n\nfunction Map({ children, styles, ...props }: MapProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const mapRef = useRef<MapLibreGL.Map | null>(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [isStyleLoaded, setIsStyleLoaded] = useState(false);\n const { resolvedTheme } = useTheme();\n\n const mapStyles = useMemo(\n () => ({\n dark: styles?.dark ?? defaultStyles.dark,\n light: styles?.light ?? defaultStyles.light,\n }),\n [styles]\n );\n\n useEffect(() => {\n if (!containerRef.current) return;\n\n const mapStyle =\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light;\n\n const mapInstance = new MapLibreGL.Map({\n container: containerRef.current,\n style: mapStyle,\n attributionControl: false,\n ...props,\n });\n\n const styleDataHandler = () => setIsStyleLoaded(true);\n const loadHandler = () => setIsLoaded(true);\n\n mapInstance.on(\"load\", loadHandler);\n mapInstance.on(\"styledata\", styleDataHandler);\n mapRef.current = mapInstance;\n\n return () => {\n mapInstance.off(\"load\", loadHandler);\n mapInstance.off(\"styledata\", styleDataHandler);\n mapInstance.remove();\n mapRef.current = null;\n };\n }, []);\n\n useEffect(() => {\n if (mapRef.current) {\n setIsStyleLoaded(false);\n mapRef.current.setStyle(\n resolvedTheme === \"dark\" ? mapStyles.dark : mapStyles.light,\n { diff: true }\n );\n }\n }, [resolvedTheme]);\n\n const isLoading = !isLoaded || !isStyleLoaded;\n\n return (\n <MapContext.Provider\n value={{ map: mapRef.current, isLoaded: isLoaded && isStyleLoaded }}\n >\n <div ref={containerRef} className=\"relative w-full h-full\">\n {isLoading && <DefaultLoader />}\n {children}\n </div>\n </MapContext.Provider>\n );\n}\n\ntype MarkerContextValue = {\n markerRef: React.RefObject<MapLibreGL.Marker | null>;\n markerElementRef: React.RefObject<HTMLDivElement | null>;\n map: MapLibreGL.Map | null;\n isReady: boolean;\n};\n\nconst MarkerContext = createContext<MarkerContextValue | null>(null);\n\nfunction useMarkerContext() {\n const context = useContext(MarkerContext);\n if (!context) {\n throw new Error(\"Marker components must be used within MapMarker\");\n }\n return context;\n}\n\ntype MapMarkerProps = {\n longitude: number;\n latitude: number;\n children: ReactNode;\n onClick?: (e: MouseEvent) => void;\n onMouseEnter?: (e: MouseEvent) => void;\n onMouseLeave?: (e: MouseEvent) => void;\n onDragStart?: (lngLat: { lng: number; lat: number }) => void;\n onDrag?: (lngLat: { lng: number; lat: number }) => void;\n onDragEnd?: (lngLat: { lng: number; lat: number }) => void;\n} & Omit<MarkerOptions, \"element\">;\n\nfunction MapMarker({\n longitude,\n latitude,\n children,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onDragStart,\n onDrag,\n onDragEnd,\n draggable = false,\n ...markerOptions\n}: MapMarkerProps) {\n const { map, isLoaded } = useMap();\n const markerRef = useRef<MapLibreGL.Marker | null>(null);\n const markerElementRef = useRef<HTMLDivElement | null>(null);\n const [isReady, setIsReady] = useState(false);\n\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const container = document.createElement(\"div\");\n markerElementRef.current = container;\n\n const marker = new MapLibreGL.Marker({\n ...markerOptions,\n element: container,\n draggable,\n })\n .setLngLat([longitude, latitude])\n .addTo(map);\n\n markerRef.current = marker;\n\n if (onClick) container.addEventListener(\"click\", onClick);\n if (onMouseEnter) container.addEventListener(\"mouseenter\", onMouseEnter);\n if (onMouseLeave) container.addEventListener(\"mouseleave\", onMouseLeave);\n\n const handleDragStart = () => {\n const lngLat = marker.getLngLat();\n onDragStart?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDrag = () => {\n const lngLat = marker.getLngLat();\n onDrag?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n const handleDragEnd = () => {\n const lngLat = marker.getLngLat();\n onDragEnd?.({ lng: lngLat.lng, lat: lngLat.lat });\n };\n\n if (draggable) {\n marker.on(\"dragstart\", handleDragStart);\n marker.on(\"drag\", handleDrag);\n marker.on(\"dragend\", handleDragEnd);\n }\n\n setIsReady(true);\n\n return () => {\n if (onClick) container.removeEventListener(\"click\", onClick);\n if (onMouseEnter)\n container.removeEventListener(\"mouseenter\", onMouseEnter);\n if (onMouseLeave)\n container.removeEventListener(\"mouseleave\", onMouseLeave);\n if (draggable) {\n marker.off(\"dragstart\", handleDragStart);\n marker.off(\"drag\", handleDrag);\n marker.off(\"dragend\", handleDragEnd);\n }\n marker.remove();\n markerRef.current = null;\n markerElementRef.current = null;\n setIsReady(false);\n };\n }, [isLoaded]);\n\n useEffect(() => {\n markerRef.current?.setLngLat([longitude, latitude]);\n }, [longitude, latitude]);\n\n useEffect(() => {\n markerRef.current?.setDraggable(draggable);\n }, [draggable]);\n\n return (\n <MarkerContext.Provider\n value={{ markerRef, markerElementRef, map, isReady }}\n >\n {children}\n </MarkerContext.Provider>\n );\n}\n\ntype MarkerContentProps = {\n children?: ReactNode;\n className?: string;\n};\n\nfunction MarkerContent({ children, className }: MarkerContentProps) {\n const { markerElementRef, isReady } = useMarkerContext();\n\n if (!isReady || !markerElementRef.current) return null;\n\n return createPortal(\n <div className={cn(\"relative cursor-pointer\", className)}>\n {children || <DefaultMarkerIcon />}\n </div>,\n markerElementRef.current\n );\n}\n\nfunction DefaultMarkerIcon() {\n return (\n <div className=\"relative h-4 w-4 rounded-full border-2 border-white bg-blue-500 shadow-lg\" />\n );\n}\n\ntype MarkerPopupProps = {\n children: ReactNode;\n className?: string;\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\">;\n\nfunction MarkerPopup({\n children,\n className,\n closeButton = false,\n ...popupOptions\n}: MarkerPopupProps) {\n const { markerRef, isReady } = useMarkerContext();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n if (!isReady || !markerRef.current) return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n popupRef.current = popup;\n markerRef.current.setPopup(popup);\n setMounted(true);\n\n return () => {\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isReady]);\n\n const handleClose = () => popupRef.current?.remove();\n\n if (!mounted || !containerRef.current) return null;\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\n {children}\n </div>,\n containerRef.current\n );\n}\n\ntype MarkerTooltipProps = {\n children: ReactNode;\n className?: string;\n} & Omit<PopupOptions, \"className\" | \"closeButton\" | \"closeOnClick\">;\n\nfunction MarkerTooltip({\n children,\n className,\n ...popupOptions\n}: MarkerTooltipProps) {\n const { markerRef, markerElementRef, map, isReady } = useMarkerContext();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n if (!isReady || !markerRef.current || !markerElementRef.current || !map)\n return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 16,\n ...popupOptions,\n closeOnClick: true,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container);\n\n popupRef.current = popup;\n\n const markerElement = markerElementRef.current;\n const marker = markerRef.current;\n\n const handleMouseEnter = () => {\n popup.setLngLat(marker.getLngLat()).addTo(map);\n };\n const handleMouseLeave = () => popup.remove();\n\n markerElement.addEventListener(\"mouseenter\", handleMouseEnter);\n markerElement.addEventListener(\"mouseleave\", handleMouseLeave);\n setMounted(true);\n\n return () => {\n markerElement.removeEventListener(\"mouseenter\", handleMouseEnter);\n markerElement.removeEventListener(\"mouseleave\", handleMouseLeave);\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isReady, map]);\n\n if (!mounted || !containerRef.current) return null;\n\n return createPortal(\n <div\n className={cn(\n \"rounded-md bg-foreground px-2 py-1 text-xs text-background shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {children}\n </div>,\n containerRef.current\n );\n}\n\ntype MarkerLabelProps = {\n children: ReactNode;\n className?: string;\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?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\";\n showZoom?: boolean;\n showCompass?: boolean;\n showLocate?: boolean;\n showFullscreen?: boolean;\n className?: string;\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-2 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 if (!isLoaded) return null;\n\n const handleZoomIn = () => map?.zoomTo(map.getZoom() + 1, { duration: 300 });\n const handleZoomOut = () => map?.zoomTo(map.getZoom() - 1, { duration: 300 });\n const handleResetBearing = () => map?.resetNorthPitch({ duration: 300 });\n\n const handleLocate = () => {\n setWaitingForLocation(true);\n if (\"geolocation\" in navigator) {\n navigator.geolocation.getCurrentPosition(\n (position) => {\n const coords = {\n longitude: position.coords.longitude,\n latitude: position.coords.latitude,\n };\n map?.flyTo({\n center: [coords.longitude, coords.latitude],\n zoom: 14,\n duration: 1500,\n });\n onLocate?.({\n longitude: coords.longitude,\n latitude: coords.latitude,\n });\n setWaitingForLocation(false);\n },\n (error) => {\n console.error(\"Error getting location:\", error);\n setWaitingForLocation(false);\n }\n );\n }\n };\n\n const handleFullscreen = () => {\n const container = map?.getContainer();\n if (!container) return;\n if (document.fullscreenElement) {\n document.exitFullscreen();\n } else {\n container.requestFullscreen();\n }\n };\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 <button\n onClick={onClick}\n aria-label=\"Reset bearing to north\"\n type=\"button\"\n className=\"flex items-center justify-center size-8 hover:bg-accent transition-colors\"\n >\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 </button>\n );\n}\n\ntype MapPopupProps = {\n longitude: number;\n latitude: number;\n open?: boolean;\n onClose?: () => void;\n children: ReactNode;\n className?: string;\n closeButton?: boolean;\n} & Omit<PopupOptions, \"className\">;\n\nfunction MapPopup({\n longitude,\n latitude,\n open = true,\n onClose,\n children,\n className,\n closeButton = true,\n ...popupOptions\n}: MapPopupProps) {\n const { map, isLoaded } = useMap();\n const containerRef = useRef<HTMLDivElement | null>(null);\n const popupRef = useRef<MapLibreGL.Popup | null>(null);\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n if (!isLoaded || !map) return;\n\n const container = document.createElement(\"div\");\n containerRef.current = container;\n\n const popup = new MapLibreGL.Popup({\n offset: 12,\n ...popupOptions,\n closeButton: false,\n })\n .setMaxWidth(\"none\")\n .setDOMContent(container)\n .setLngLat([longitude, latitude]);\n\n popup.on(\"close\", () => onClose?.());\n\n popupRef.current = popup;\n setMounted(true);\n\n return () => {\n popup.remove();\n popupRef.current = null;\n containerRef.current = null;\n setMounted(false);\n };\n }, [isLoaded, map]);\n\n useEffect(() => {\n if (!popupRef.current || !map) return;\n\n if (open) {\n popupRef.current.addTo(map);\n } else {\n popupRef.current.remove();\n }\n }, [open, map, mounted]);\n\n useEffect(() => {\n popupRef.current?.setLngLat([longitude, latitude]);\n }, [longitude, latitude]);\n\n const handleClose = () => {\n popupRef.current?.remove();\n onClose?.();\n };\n\n if (!mounted || !containerRef.current) return null;\n\n return createPortal(\n <div\n className={cn(\n \"relative rounded-md border bg-popover p-3 text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95\",\n className\n )}\n >\n {closeButton && (\n <button\n type=\"button\"\n onClick={handleClose}\n className=\"absolute top-1 right-1 z-10 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2\"\n aria-label=\"Close popup\"\n >\n <X className=\"h-4 w-4\" />\n <span className=\"sr-only\">Close</span>\n </button>\n )}\n {children}\n </div>,\n containerRef.current\n );\n}\n\ntype MapRouteProps = {\n coordinates: [number, number][];\n color?: string;\n width?: number;\n opacity?: number;\n dashArray?: [number, number];\n};\n\nfunction MapRoute({\n coordinates,\n color = \"#4285F4\",\n width = 3,\n opacity = 0.8,\n dashArray,\n}: MapRouteProps) {\n const { map, isLoaded } = useMap();\n const id = useId();\n const sourceId = `route-source-${id}`;\n const layerId = `route-layer-${id}`;\n\n useEffect(() => {\n if (!isLoaded || !map || coordinates.length < 2) return;\n\n const addRoute = () => {\n if (map.getLayer(layerId)) map.removeLayer(layerId);\n if (map.getSource(sourceId)) map.removeSource(sourceId);\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\n addRoute();\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 }, [\n isLoaded,\n map,\n coordinates,\n color,\n width,\n opacity,\n dashArray,\n sourceId,\n layerId,\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};\n",
"type": "registry:ui",
"target": "components/ui/map.tsx"
}
diff --git a/src/app/(home)/_components/footer.tsx b/src/app/(home)/_components/footer.tsx
index 19969c4..c4a1d73 100644
--- a/src/app/(home)/_components/footer.tsx
+++ b/src/app/(home)/_components/footer.tsx
@@ -5,7 +5,7 @@ export function Footer() {
<footer className="w-full px-6 py-6 border-t border-border/40">
<div className="mx-auto max-w-5xl flex items-center justify-between text-xs text-muted-foreground">
<span>
- Made by{" "}
+ Built by{" "}
<a
href="https://github.com/AnmolSaini16"
target="_blank"
diff --git a/src/app/docs/_components/docs-sidebar.tsx b/src/app/docs/_components/docs-sidebar.tsx
new file mode 100644
index 0000000..3a0f6a0
--- /dev/null
+++ b/src/app/docs/_components/docs-sidebar.tsx
@@ -0,0 +1,102 @@
+"use client";
+
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import {
+ Map,
+ BookOpen,
+ Code,
+ Braces,
+ MapPin,
+ MessageSquare,
+ Route,
+ Wrench,
+ Settings,
+} from "lucide-react";
+
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarGroup,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarMenu,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ 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: "Advanced Usage", href: "/docs/advanced-usage", icon: Wrench },
+ ],
+ },
+];
+
+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}>
+ <SidebarGroupLabel className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
+ {group.title}
+ </SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ {group.items.map((item) => (
+ <SidebarMenuItem key={item.href}>
+ <SidebarMenuButton
+ asChild
+ isActive={pathname === item.href}
+ className="text-muted-foreground hover:text-foreground data-[active=true]:text-foreground data-[active=true]:font-medium"
+ >
+ <Link
+ href={item.href}
+ onClick={() => setOpenMobile(false)}
+ >
+ <item.icon className="size-4" />
+ <span>{item.title}</span>
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ))}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+ ))}
+ </SidebarContent>
+ </Sidebar>
+ );
+}
+
+export function MobileSidebarTrigger() {
+ return (
+ <div className="md:hidden">
+ <SidebarTrigger />
+ </div>
+ );
+}
diff --git a/src/app/docs/api-reference/page.tsx b/src/app/docs/api-reference/page.tsx
index 4fed8a6..6c8c600 100644
--- a/src/app/docs/api-reference/page.tsx
+++ b/src/app/docs/api-reference/page.tsx
@@ -75,7 +75,8 @@ export default function ApiReferencePage() {
>
MapOptions
</DocsLink>{" "}
- from MapLibre GL (excluding <DocsCode>container</DocsCode>).
+ from MapLibre GL (excluding <DocsCode>container</DocsCode> and{" "}
+ <DocsCode>style</DocsCode>).
</p>
<DocsPropTable
props={[
@@ -85,6 +86,12 @@ export default function ApiReferencePage() {
description:
"Child components (markers, popups, controls, routes).",
},
+ {
+ name: "styles",
+ type: "{ light?: string | StyleSpecification; dark?: string | StyleSpecification }",
+ description:
+ "Custom map styles for light and dark themes. Overrides the default Carto base map tiles.",
+ },
]}
/>
</DocsSection>
diff --git a/src/app/docs/layout.tsx b/src/app/docs/layout.tsx
index db9ce80..7cde79e 100644
--- a/src/app/docs/layout.tsx
+++ b/src/app/docs/layout.tsx
@@ -1,99 +1,6 @@
-"use client";
-
-import Link from "next/link";
-import { usePathname } from "next/navigation";
-import {
- Map,
- BookOpen,
- Code,
- Settings,
- Braces,
- MapPin,
- MessageSquare,
- Route,
- Wrench,
-} from "lucide-react";
-
-import {
- Sidebar,
- SidebarContent,
- SidebarGroup,
- SidebarGroupContent,
- SidebarGroupLabel,
- SidebarMenu,
- SidebarMenuButton,
- SidebarMenuItem,
- SidebarProvider,
- SidebarTrigger,
- useSidebar,
-} from "@/components/ui/sidebar";
+import { SidebarProvider } from "@/components/ui/sidebar";
import { Header } from "@/components/header";
-
-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: "Advanced Usage", href: "/docs/advanced-usage", icon: Wrench },
- ],
- },
-];
-
-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}>
- <SidebarGroupLabel className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground/70">
- {group.title}
- </SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu>
- {group.items.map((item) => (
- <SidebarMenuItem key={item.href}>
- <SidebarMenuButton
- asChild
- isActive={pathname === item.href}
- className="text-muted-foreground hover:text-foreground data-[active=true]:text-foreground data-[active=true]:font-medium"
- >
- <Link
- href={item.href}
- onClick={() => setOpenMobile(false)}
- >
- <item.icon className="size-4" />
- <span>{item.title}</span>
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- ))}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
- ))}
- </SidebarContent>
- </Sidebar>
- );
-}
+import { DocsSidebar, MobileSidebarTrigger } from "./_components/docs-sidebar";
export default function DocsLayout({
children,
@@ -105,11 +12,7 @@ export default function DocsLayout({
<div className="flex min-h-screen w-full flex-col">
<Header
className="sticky top-0 z-50 border-b bg-background/95 backdrop-blur supports-backdrop-filter:bg-background/60"
- leftContent={
- <div className="md:hidden">
- <SidebarTrigger />
- </div>
- }
+ leftContent={<MobileSidebarTrigger />}
/>
<div className="flex flex-1">
<DocsSidebar />
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index 5e11ae9..fac210c 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -93,12 +93,7 @@ export default function RootLayout({
suppressHydrationWarning
>
<body className="font-sans antialiased">
- <ThemeProvider
- attribute="class"
- defaultTheme="system"
- enableSystem
- disableTransitionOnChange
- >
+ <ThemeProvider>
{children}
<Analytics />
</ThemeProvider>
diff --git a/src/components/github-button.tsx b/src/components/github-button.tsx
new file mode 100644
index 0000000..7120387
--- /dev/null
+++ b/src/components/github-button.tsx
@@ -0,0 +1,47 @@
+import Link from "next/link";
+import { Button } from "@/components/ui/button";
+import { Suspense } from "react";
+import { Skeleton } from "@/components/ui/skeleton";
+
+export async function GitHubButton() {
+ return (
+ <Button variant="ghost" size="sm" className="h-8 px-2 gap-1.5" asChild>
+ <Link
+ href="https://github.com/AnmolSaini16/mapcn"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <svg viewBox="0 0 1024 1024" fill="currentColor" className="size-4">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
+ transform="scale(64)"
+ fill="currentColor"
+ />
+ </svg>
+ <Suspense fallback={<Skeleton className="w-8 h-4 rounded" />}>
+ <StarCount />
+ </Suspense>
+ </Link>
+ </Button>
+ );
+}
+
+export async function StarCount() {
+ const response = await fetch(
+ "https://api.github.com/repos/AnmolSaini16/mapcn",
+ { next: { revalidate: 60 } }
+ );
+
+ const data = await response.json();
+
+ const formattedCount = data.stargazers_count?.toLocaleString();
+ return (
+ <>
+ {formattedCount && (
+ <span className="text-xs text-muted-foreground">{formattedCount}</span>
+ )}
+ </>
+ );
+}
diff --git a/src/components/header.tsx b/src/components/header.tsx
index 870ca08..370aa9b 100644
--- a/src/components/header.tsx
+++ b/src/components/header.tsx
@@ -1,51 +1,10 @@
-"use client";
-
-import { Button } from "@/components/ui/button";
-import { Separator } from "@/components/ui/separator";
import { MapPin } from "lucide-react";
-import { useTheme } from "next-themes";
import Link from "next/link";
-import { useState, useEffect } from "react";
-import { cn } from "@/lib/utils";
-
-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>
- );
-}
-
-function ThemeToggle() {
- const { resolvedTheme, setTheme } = useTheme();
- const [mounted, setMounted] = useState(false);
- useEffect(() => {
- setMounted(true);
- }, []);
-
- if (!mounted) return <div className="size-4" />;
-
- return (
- <Button
- onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
- variant="ghost"
- aria-label="Toggle theme"
- size="icon"
- >
- <ThemeIcon className="size-4" />
- </Button>
- );
-}
+import { Separator } from "@/components/ui/separator";
+import { GitHubButton } from "@/components/github-button";
+import { ThemeToggle } from "@/components/theme-toggle";
+import { cn } from "@/lib/utils";
interface HeaderProps {
className?: string;
@@ -66,28 +25,8 @@ export function Header({ className, leftContent }: HeaderProps) {
<span className="font-semibold tracking-tight">mapcn</span>
</Link>
</div>
- <div className="flex items-center gap-1 h-5">
- <Button variant="ghost" size="icon" asChild>
- <Link
- href="https://github.com/AnmolSaini16/mapcn"
- target="_blank"
- rel="noopener noreferrer"
- >
- <svg
- viewBox="0 0 1024 1024"
- fill="currentColor"
- className="size-4"
- >
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M8 0C3.58 0 0 3.58 0 8C0 11.54 2.29 14.53 5.47 15.59C5.87 15.66 6.02 15.42 6.02 15.21C6.02 15.02 6.01 14.39 6.01 13.72C4 14.09 3.48 13.23 3.32 12.78C3.23 12.55 2.84 11.84 2.5 11.65C2.22 11.5 1.82 11.13 2.49 11.12C3.12 11.11 3.57 11.7 3.72 11.94C4.44 13.15 5.59 12.81 6.05 12.6C6.12 12.08 6.33 11.73 6.56 11.53C4.78 11.33 2.92 10.64 2.92 7.58C2.92 6.71 3.23 5.99 3.74 5.43C3.66 5.23 3.38 4.41 3.82 3.31C3.82 3.31 4.49 3.1 6.02 4.13C6.66 3.95 7.34 3.86 8.02 3.86C8.7 3.86 9.38 3.95 10.02 4.13C11.55 3.09 12.22 3.31 12.22 3.31C12.66 4.41 12.38 5.23 12.3 5.43C12.81 5.99 13.12 6.7 13.12 7.58C13.12 10.65 11.25 11.33 9.47 11.53C9.76 11.78 10.01 12.26 10.01 13.01C10.01 14.08 10 14.94 10 15.21C10 15.42 10.15 15.67 10.55 15.59C13.71 14.53 16 11.53 16 8C16 3.58 12.42 0 8 0Z"
- transform="scale(64)"
- fill="currentColor"
- />
- </svg>
- </Link>
- </Button>
+ <div className="flex items-center gap-1.5 h-4">
+ <GitHubButton />
<Separator orientation="vertical" />
<ThemeToggle />
</div>
diff --git a/src/components/theme-provider.tsx b/src/components/theme-provider.tsx
index 8613a5f..d6ada5f 100644
--- a/src/components/theme-provider.tsx
+++ b/src/components/theme-provider.tsx
@@ -7,5 +7,15 @@ export function ThemeProvider({
children,
...props
}: ComponentProps<typeof NextThemesProvider>) {
- return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
+ return (
+ <NextThemesProvider
+ attribute="class"
+ defaultTheme="system"
+ enableSystem
+ disableTransitionOnChange
+ {...props}
+ >
+ {children}
+ </NextThemesProvider>
+ );
}
diff --git a/src/components/theme-toggle.tsx b/src/components/theme-toggle.tsx
new file mode 100644
index 0000000..800d03c
--- /dev/null
+++ b/src/components/theme-toggle.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { useState, 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>
+ );
+}
+
+export function ThemeToggle() {
+ const { resolvedTheme, setTheme } = useTheme();
+ const [mounted, setMounted] = useState(false);
+
+ useEffect(() => {
+ setMounted(true);
+ }, []);
+
+ if (!mounted) return <div className="size-4" />;
+
+ return (
+ <Button
+ onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
+ variant="ghost"
+ aria-label="Toggle theme"
+ size="icon"
+ >
+ <ThemeIcon className="size-4" />
+ </Button>
+ );
+}
diff --git a/src/registry/map.tsx b/src/registry/map.tsx
index b2c7f30..165dcf5 100644
--- a/src/registry/map.tsx
+++ b/src/registry/map.tsx
@@ -8,6 +8,7 @@ import {
useContext,
useEffect,
useId,
+ useMemo,
useRef,
useState,
type ReactNode,
@@ -32,14 +33,21 @@ function useMap() {
return context;
}
-const mapStyles = {
+const defaultStyles = {
dark: "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json",
light: "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json",
};
+type MapStyleOption = string | MapLibreGL.StyleSpecification;
+
type MapProps = {
children?: ReactNode;
-} & Omit<MapLibreGL.MapOptions, "container">;
+ /** Custom map styles for light and dark themes. Overrides the default Carto styles. */
+ styles?: {
+ light?: MapStyleOption;
+ dark?: MapStyleOption;
+ };
+} & Omit<MapLibreGL.MapOptions, "container" | "style">;
const DefaultLoader = () => (
<div className="absolute inset-0 flex items-center justify-center">
@@ -51,13 +59,21 @@ const DefaultLoader = () => (
</div>
);
-function Map({ children, ...props }: MapProps) {
+function Map({ children, styles, ...props }: MapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<MapLibreGL.Map | null>(null);
const [isLoaded, setIsLoaded] = useState(false);
const [isStyleLoaded, setIsStyleLoaded] = useState(false);
const { resolvedTheme } = useTheme();
+ const mapStyles = useMemo(
+ () => ({
+ dark: styles?.dark ?? defaultStyles.dark,
+ light: styles?.light ?? defaultStyles.light,
+ }),
+ [styles]
+ );
+
useEffect(() => {
if (!containerRef.current) return;