1"use client"
2
3import { cn } from "@/lib/utils"
4import { Button } from "@/registry/new-york-v4/ui/button"
5import { ButtonGroup } from "@/registry/new-york-v4/ui/button-group"
6import {
7 DropdownMenu,
8 DropdownMenuCheckboxItem,
9 DropdownMenuContent,
10 DropdownMenuLabel,
11 DropdownMenuRadioGroup,
12 DropdownMenuRadioItem,
13 DropdownMenuSeparator,
14 DropdownMenuTrigger,
15} from "@/registry/new-york-v4/ui/dropdown-menu"
16import {
17 PlaceAutocomplete,
18 type PlaceAutocompleteProps,
19} from "@/registry/new-york-v4/ui/place-autocomplete"
20import type { CheckboxItem } from "@radix-ui/react-dropdown-menu"
21import type {
22 Circle,
23 CircleMarker,
24 DivIconOptions,
25 Draw,
26 DrawEvents,
27 DrawMap,
28 DrawOptions,
29 EditToolbar,
30 ErrorEvent,
31 FeatureGroup,
32 LatLngExpression,
33 LayerGroup,
34 Map as LeafletMap,
35 LocateOptions,
36 LocationEvent,
37 Marker,
38 MarkerCluster,
39 PointExpression,
40 Polygon,
41 Polyline,
42 Popup,
43 Rectangle,
44 TileLayer,
45 Tooltip,
46} from "leaflet"
47import "leaflet-draw/dist/leaflet.draw.css"
48import "leaflet.fullscreen/dist/Control.FullScreen.css"
49import type {} from "leaflet.markercluster"
50import "leaflet.markercluster/dist/MarkerCluster.css"
51import "leaflet.markercluster/dist/MarkerCluster.Default.css"
52import "leaflet/dist/leaflet.css"
53import {
54 CircleIcon,
55 LayersIcon,
56 LoaderCircleIcon,
57 MapPinIcon,
58 MaximizeIcon,
59 MinimizeIcon,
60 MinusIcon,
61 NavigationIcon,
62 PenLineIcon,
63 PentagonIcon,
64 PlusIcon,
65 SquareIcon,
66 Trash2Icon,
67 Undo2Icon,
68 WaypointsIcon,
69} from "lucide-react"
70import { useTheme } from "next-themes"
71import React, {
72 Suspense,
73 createContext,
74 lazy,
75 useContext,
76 useEffect,
77 useRef,
78 useState,
79 type ComponentType,
80 type ReactNode,
81 type Ref,
82} from "react"
83import { renderToString } from "react-dom/server"
84import {
85 useMap,
86 useMapEvents,
87 type CircleMarkerProps,
88 type CircleProps,
89 type LayerGroupProps,
90 type MapContainerProps,
91 type MarkerProps,
92 type PolygonProps,
93 type PolylineProps,
94 type PopupProps,
95 type RectangleProps,
96 type TileLayerProps,
97 type TooltipProps,
98} from "react-leaflet"
99import type { MarkerClusterGroupProps } from "react-leaflet-markercluster"
100
101function createLazyComponent<T extends ComponentType<any>>(
102 factory: () => Promise<{ default: T }>
103) {
104 const LazyComponent = lazy(factory)
105
106 return (props: React.ComponentProps<T>) => {
107 const [isMounted, setIsMounted] = useState(false)
108
109 useEffect(() => {
110 setIsMounted(true)
111 }, [])
112
113 if (!isMounted) {
114 return null
115 }
116
117 return (
118 <Suspense>
119 <LazyComponent {...props} />
120 </Suspense>
121 )
122 }
123}
124
125const LeafletMapContainer = createLazyComponent(() =>
126 import("react-leaflet").then((mod) => ({
127 default: mod.MapContainer,
128 }))
129)
130const LeafletTileLayer = createLazyComponent(() =>
131 import("react-leaflet").then((mod) => ({
132 default: mod.TileLayer,
133 }))
134)
135const LeafletMarker = createLazyComponent(() =>
136 import("react-leaflet").then((mod) => ({
137 default: mod.Marker,
138 }))
139)
140const LeafletPopup = createLazyComponent(() =>
141 import("react-leaflet").then((mod) => ({
142 default: mod.Popup,
143 }))
144)
145const LeafletTooltip = createLazyComponent(() =>
146 import("react-leaflet").then((mod) => ({
147 default: mod.Tooltip,
148 }))
149)
150const LeafletCircle = createLazyComponent(() =>
151 import("react-leaflet").then((mod) => ({
152 default: mod.Circle,
153 }))
154)
155const LeafletCircleMarker = createLazyComponent(() =>
156 import("react-leaflet").then((mod) => ({
157 default: mod.CircleMarker,
158 }))
159)
160const LeafletPolyline = createLazyComponent(() =>
161 import("react-leaflet").then((mod) => ({
162 default: mod.Polyline,
163 }))
164)
165const LeafletPolygon = createLazyComponent(() =>
166 import("react-leaflet").then((mod) => ({
167 default: mod.Polygon,
168 }))
169)
170const LeafletRectangle = createLazyComponent(() =>
171 import("react-leaflet").then((mod) => ({
172 default: mod.Rectangle,
173 }))
174)
175const LeafletLayerGroup = createLazyComponent(() =>
176 import("react-leaflet").then((mod) => ({
177 default: mod.LayerGroup,
178 }))
179)
180const LeafletFeatureGroup = createLazyComponent(() =>
181 import("react-leaflet").then((mod) => ({
182 default: mod.FeatureGroup,
183 }))
184)
185const LeafletMarkerClusterGroup = createLazyComponent(async () =>
186 import("react-leaflet-markercluster").then((mod) => ({
187 default: mod.default,
188 }))
189)
190
191function Map({
192 zoom = 15,
193 maxZoom = 18,
194 className,
195 ...props
196}: Omit<MapContainerProps, "zoomControl"> & {
197 center: LatLngExpression
198 ref?: Ref<LeafletMap>
199}) {
200 return (
201 <LeafletMapContainer
202 zoom={zoom}
203 maxZoom={maxZoom}
204 attributionControl={false}
205 zoomControl={false}
206 className={cn(
207 "z-50 size-full min-h-96 flex-1 rounded-md",
208 className
209 )}
210 {...props}
211 />
212 )
213}
214
215interface MapTileLayerOption {
216 name: string
217 url: string
218 attribution?: string
219}
220
221interface MapLayerGroupOption
222 extends Pick<React.ComponentProps<typeof CheckboxItem>, "disabled"> {
223 name: string
224}
225
226interface MapLayersContextType {
227 registerTileLayer: (layer: MapTileLayerOption) => void
228 tileLayers: MapTileLayerOption[]
229 selectedTileLayer: string
230 setSelectedTileLayer: (name: string) => void
231 registerLayerGroup: (layer: MapLayerGroupOption) => void
232 layerGroups: MapLayerGroupOption[]
233 activeLayerGroups: string[]
234 setActiveLayerGroups: (names: string[]) => void
235}
236
237const MapLayersContext = createContext<MapLayersContextType | null>(null)
238
239function useMapLayersContext() {
240 return useContext(MapLayersContext)
241}
242
243function MapTileLayer({
244 name = "Default",
245 url,
246 attribution,
247 darkUrl,
248 darkAttribution,
249 ...props
250}: Partial<TileLayerProps> & {
251 name?: string
252 darkUrl?: string
253 darkAttribution?: string
254 ref?: Ref<TileLayer>
255}) {
256 const map = useMap()
257 if (map.attributionControl) {
258 map.attributionControl.setPrefix("")
259 }
260
261 const context = useContext(MapLayersContext)
262 const DEFAULT_URL =
263 "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png"
264 const DEFAULT_DARK_URL =
265 "https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"
266
267 const { resolvedTheme } = useTheme()
268 const resolvedUrl =
269 resolvedTheme === "dark"
270 ? (darkUrl ?? url ?? DEFAULT_DARK_URL)
271 : (url ?? DEFAULT_URL)
272 const resolvedAttribution =
273 resolvedTheme === "dark" && darkAttribution
274 ? darkAttribution
275 : (attribution ??
276 '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, © <a href="https://carto.com/attributions">CARTO</a>')
277
278 useEffect(() => {
279 if (context) {
280 context.registerTileLayer({
281 name,
282 url: resolvedUrl,
283 attribution: resolvedAttribution,
284 })
285 }
286 }, [context, name, url, attribution])
287
288 if (context && context.selectedTileLayer !== name) {
289 return null
290 }
291
292 return (
293 <LeafletTileLayer
294 url={resolvedUrl}
295 attribution={resolvedAttribution}
296 {...props}
297 />
298 )
299}
300
301function MapLayerGroup({
302 name,
303 disabled,
304 ...props
305}: LayerGroupProps & MapLayerGroupOption & { ref?: Ref<LayerGroup> }) {
306 const context = useMapLayersContext()
307
308 useEffect(() => {
309 if (context) {
310 context.registerLayerGroup({
311 name,
312 disabled,
313 })
314 }
315 }, [context, name, disabled])
316
317 if (context && !context.activeLayerGroups.includes(name)) {
318 return null
319 }
320
321 return <LeafletLayerGroup {...props} />
322}
323
324function MapFeatureGroup({
325 name,
326 disabled,
327 ...props
328}: LayerGroupProps & MapLayerGroupOption & { ref?: Ref<FeatureGroup> }) {
329 const context = useMapLayersContext()
330
331 useEffect(() => {
332 if (context) {
333 context.registerLayerGroup({
334 name,
335 disabled,
336 })
337 }
338 }, [context, name, disabled])
339
340 if (context && !context.activeLayerGroups.includes(name)) {
341 return null
342 }
343
344 return <LeafletFeatureGroup {...props} />
345}
346
347function MapLayers({
348 defaultTileLayer,
349 defaultLayerGroups = [],
350 ...props
351}: Omit<React.ComponentProps<typeof MapLayersContext.Provider>, "value"> & {
352 defaultTileLayer?: string
353 defaultLayerGroups?: string[]
354}) {
355 const [tileLayers, setTileLayers] = useState<MapTileLayerOption[]>([])
356 const [selectedTileLayer, setSelectedTileLayer] = useState<string>(
357 defaultTileLayer || ""
358 )
359 const [layerGroups, setLayerGroups] = useState<MapLayerGroupOption[]>([])
360 const [activeLayerGroups, setActiveLayerGroups] =
361 useState<string[]>(defaultLayerGroups)
362
363 function registerTileLayer(tileLayer: MapTileLayerOption) {
364 setTileLayers((prevTileLayers) => {
365 if (prevTileLayers.some((layer) => layer.name === tileLayer.name)) {
366 return prevTileLayers
367 }
368 return [...prevTileLayers, tileLayer]
369 })
370 }
371
372 function registerLayerGroup(layerGroup: MapLayerGroupOption) {
373 setLayerGroups((prevLayerGroups) => {
374 if (
375 prevLayerGroups.some((group) => group.name === layerGroup.name)
376 ) {
377 return prevLayerGroups
378 }
379 return [...prevLayerGroups, layerGroup]
380 })
381 }
382
383 useEffect(() => {
384 // Error: Invalid defaultValue
385 if (
386 defaultTileLayer &&
387 tileLayers.length > 0 &&
388 !tileLayers.some((tileLayer) => tileLayer.name === defaultTileLayer)
389 ) {
390 throw new Error(
391 `Invalid defaultTileLayer "${defaultTileLayer}" provided to MapLayers. It must match a MapTileLayer's name prop.`
392 )
393 }
394
395 // Set initial selected tile layer
396 if (tileLayers.length > 0 && !selectedTileLayer) {
397 const validDefaultValue =
398 defaultTileLayer &&
399 tileLayers.some((layer) => layer.name === defaultTileLayer)
400 ? defaultTileLayer
401 : tileLayers[0].name
402 setSelectedTileLayer(validDefaultValue)
403 }
404
405 // Error: Invalid defaultActiveLayerGroups
406 if (
407 defaultLayerGroups.length > 0 &&
408 layerGroups.length > 0 &&
409 defaultLayerGroups.some(
410 (name) => !layerGroups.some((group) => group.name === name)
411 )
412 ) {
413 throw new Error(
414 `Invalid defaultLayerGroups value provided to MapLayers. All names must match a MapLayerGroup's name prop.`
415 )
416 }
417 }, [
418 tileLayers,
419 defaultTileLayer,
420 selectedTileLayer,
421 layerGroups,
422 defaultLayerGroups,
423 ])
424
425 return (
426 <MapLayersContext.Provider
427 value={{
428 registerTileLayer,
429 tileLayers,
430 selectedTileLayer,
431 setSelectedTileLayer,
432 registerLayerGroup,
433 layerGroups,
434 activeLayerGroups,
435 setActiveLayerGroups,
436 }}
437 {...props}
438 />
439 )
440}
441
442function MapLayersControl({
443 tileLayersLabel = "Map Type",
444 layerGroupsLabel = "Layers",
445 position = "top-1 right-1",
446 className,
447 ...props
448}: React.ComponentProps<"button"> & {
449 tileLayersLabel?: string
450 layerGroupsLabel?: string
451 position?: string
452}) {
453 const layersContext = useMapLayersContext()
454 if (!layersContext) {
455 throw new Error("MapLayersControl must be used within MapLayers")
456 }
457
458 const {
459 tileLayers,
460 selectedTileLayer,
461 setSelectedTileLayer,
462 layerGroups,
463 activeLayerGroups,
464 setActiveLayerGroups,
465 } = layersContext
466
467 if (tileLayers.length === 0 && layerGroups.length === 0) {
468 return null
469 }
470
471 function handleLayerGroupToggle(name: string, checked: boolean) {
472 setActiveLayerGroups(
473 checked
474 ? [...activeLayerGroups, name]
475 : activeLayerGroups.filter((groupName) => groupName !== name)
476 )
477 }
478
479 const showTileLayersDropdown = tileLayers.length > 1
480 const showLayerGroupsDropdown = layerGroups.length > 0
481
482 if (!showTileLayersDropdown && !showLayerGroupsDropdown) {
483 return null
484 }
485
486 return (
487 <DropdownMenu>
488 <DropdownMenuTrigger asChild>
489 <Button
490 type="button"
491 variant="secondary"
492 size="icon-sm"
493 aria-label="Select layers"
494 title="Select layers"
495 className={cn(
496 "absolute z-1000 border",
497 position,
498 className
499 )}
500 {...props}>
501 <LayersIcon />
502 </Button>
503 </DropdownMenuTrigger>
504 <DropdownMenuContent align="end" className="z-1000">
505 {showTileLayersDropdown && (
506 <>
507 <DropdownMenuLabel>{tileLayersLabel}</DropdownMenuLabel>
508 <DropdownMenuRadioGroup
509 value={selectedTileLayer}
510 onValueChange={setSelectedTileLayer}>
511 {tileLayers.map((tileLayer) => (
512 <DropdownMenuRadioItem
513 key={tileLayer.name}
514 value={tileLayer.name}>
515 {tileLayer.name}
516 </DropdownMenuRadioItem>
517 ))}
518 </DropdownMenuRadioGroup>
519 </>
520 )}
521 {showTileLayersDropdown && showLayerGroupsDropdown && (
522 <DropdownMenuSeparator />
523 )}
524 {showLayerGroupsDropdown && (
525 <>
526 <DropdownMenuLabel>
527 {layerGroupsLabel}
528 </DropdownMenuLabel>
529 {layerGroups.map((layerGroup) => (
530 <DropdownMenuCheckboxItem
531 key={layerGroup.name}
532 checked={activeLayerGroups.includes(
533 layerGroup.name
534 )}
535 disabled={layerGroup.disabled}
536 onCheckedChange={(checked) =>
537 handleLayerGroupToggle(
538 layerGroup.name,
539 checked
540 )
541 }>
542 {layerGroup.name}
543 </DropdownMenuCheckboxItem>
544 ))}
545 </>
546 )}
547 </DropdownMenuContent>
548 </DropdownMenu>
549 )
550}
551
552function MapMarker({
553 icon = <MapPinIcon className="size-6" />,
554 iconAnchor = [12, 12],
555 bgPos,
556 popupAnchor,
557 tooltipAnchor,
558 ...props
559}: Omit<MarkerProps, "icon"> &
560 Pick<
561 DivIconOptions,
562 "iconAnchor" | "bgPos" | "popupAnchor" | "tooltipAnchor"
563 > & {
564 icon?: ReactNode
565 ref?: Ref<Marker>
566 }) {
567 const { L } = useLeaflet()
568 if (!L) return null
569
570 return (
571 <LeafletMarker
572 icon={L.divIcon({
573 html: renderToString(icon),
574 iconAnchor,
575 ...(bgPos ? { bgPos } : {}),
576 ...(popupAnchor ? { popupAnchor } : {}),
577 ...(tooltipAnchor ? { tooltipAnchor } : {}),
578 })}
579 riseOnHover
580 {...props}
581 />
582 )
583}
584
585function MapMarkerClusterGroup({
586 polygonOptions = {
587 className: "fill-foreground stroke-foreground stroke-2",
588 },
589 spiderLegPolylineOptions = {
590 className: "fill-foreground stroke-foreground stroke-2",
591 },
592 icon,
593 ...props
594}: Omit<MarkerClusterGroupProps, "iconCreateFunction"> & {
595 children: ReactNode
596 icon?: (markerCount: number) => ReactNode
597}) {
598 const { L } = useLeaflet()
599 if (!L) return null
600
601 const iconCreateFunction = icon
602 ? (cluster: MarkerCluster) => {
603 const markerCount = cluster.getChildCount()
604 const iconNode = icon(markerCount)
605 return L.divIcon({
606 html: renderToString(iconNode),
607 })
608 }
609 : undefined
610
611 return (
612 <LeafletMarkerClusterGroup
613 polygonOptions={polygonOptions}
614 spiderLegPolylineOptions={spiderLegPolylineOptions}
615 iconCreateFunction={iconCreateFunction}
616 {...props}
617 />
618 )
619}
620
621function MapCircle({
622 className,
623 ...props
624}: CircleProps & { ref?: Ref<Circle> }) {
625 return (
626 <LeafletCircle
627 className={cn(
628 "fill-foreground stroke-foreground stroke-2",
629 className
630 )}
631 {...props}
632 />
633 )
634}
635
636function MapCircleMarker({
637 className,
638 ...props
639}: CircleMarkerProps & { ref?: Ref<CircleMarker> }) {
640 return (
641 <LeafletCircleMarker
642 className={cn(
643 "fill-foreground stroke-foreground stroke-2",
644 className
645 )}
646 {...props}
647 />
648 )
649}
650
651function MapPolyline({
652 className,
653 ...props
654}: PolylineProps & { ref?: Ref<Polyline> }) {
655 return (
656 <LeafletPolyline
657 className={cn(
658 "fill-foreground stroke-foreground stroke-2",
659 className
660 )}
661 {...props}
662 />
663 )
664}
665
666function MapPolygon({
667 className,
668 ...props
669}: PolygonProps & { ref?: Ref<Polygon> }) {
670 return (
671 <LeafletPolygon
672 className={cn(
673 "fill-foreground stroke-foreground stroke-2",
674 className
675 )}
676 {...props}
677 />
678 )
679}
680
681function MapRectangle({
682 className,
683 ...props
684}: RectangleProps & { ref?: Ref<Rectangle> }) {
685 return (
686 <LeafletRectangle
687 className={cn(
688 "fill-foreground stroke-foreground stroke-2",
689 className
690 )}
691 {...props}
692 />
693 )
694}
695
696function MapPopup({
697 className,
698 ...props
699}: Omit<PopupProps, "content"> & { ref?: Ref<Popup> }) {
700 return (
701 <LeafletPopup
702 className={cn(
703 "bg-popover text-popover-foreground animate-in fade-out-0 fade-in-0 zoom-out-95 zoom-in-95 slide-in-from-bottom-2 z-50 w-72 rounded-md border p-4 font-sans shadow-md outline-hidden",
704 className
705 )}
706 {...props}
707 />
708 )
709}
710
711function MapTooltip({
712 className,
713 children,
714 side = "top",
715 sideOffset = 15,
716 ...props
717}: Omit<TooltipProps, "offset"> & {
718 side?: "top" | "right" | "bottom" | "left"
719 sideOffset?: number
720 ref?: Ref<Tooltip>
721}) {
722 const ARROW_POSITION_CLASSES = {
723 top: "bottom-0.5 left-1/2 -translate-x-1/2 translate-y-1/2",
724 bottom: "top-0.5 left-1/2 -translate-x-1/2 -translate-y-1/2",
725 left: "right-0.5 top-1/2 translate-x-1/2 -translate-y-1/2",
726 right: "left-0.5 top-1/2 -translate-x-1/2 -translate-y-1/2",
727 }
728 const DEFAULT_OFFSET = {
729 top: [0, -sideOffset] satisfies PointExpression,
730 bottom: [0, sideOffset] satisfies PointExpression,
731 left: [-sideOffset, 0] satisfies PointExpression,
732 right: [sideOffset, 0] satisfies PointExpression,
733 }
734
735 return (
736 <LeafletTooltip
737 className={cn(
738 "animate-in fade-in-0 zoom-in-95 fade-out-0 zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 w-fit text-xs text-balance transition-opacity",
739 className
740 )}
741 data-side={side}
742 direction={side}
743 offset={DEFAULT_OFFSET[side]}
744 opacity={1}
745 {...props}>
746 {children}
747 <div
748 className={cn(
749 "bg-foreground fill-foreground absolute z-50 size-2.5 rotate-45 rounded-[2px]",
750 ARROW_POSITION_CLASSES[side]
751 )}
752 />
753 </LeafletTooltip>
754 )
755}
756
757function MapZoomControl({
758 position = "top-1 left-1",
759 className,
760 ...props
761}: React.ComponentProps<"div"> & { position?: string }) {
762 const map = useMap()
763 const [zoomLevel, setZoomLevel] = useState(map.getZoom())
764
765 useMapEvents({
766 zoomend: () => {
767 setZoomLevel(map.getZoom())
768 },
769 })
770
771 return (
772 <MapControlContainer className={cn(position, className)}>
773 <ButtonGroup
774 orientation="vertical"
775 aria-label="Zoom controls"
776 {...props}>
777 <Button
778 type="button"
779 size="icon-sm"
780 variant="secondary"
781 aria-label="Zoom in"
782 title="Zoom in"
783 className="border"
784 disabled={zoomLevel >= map.getMaxZoom()}
785 onClick={() => map.zoomIn()}>
786 <PlusIcon />
787 </Button>
788 <Button
789 type="button"
790 size="icon-sm"
791 variant="secondary"
792 aria-label="Zoom out"
793 title="Zoom out"
794 className="border"
795 disabled={zoomLevel <= map.getMinZoom()}
796 onClick={() => map.zoomOut()}>
797 <MinusIcon />
798 </Button>
799 </ButtonGroup>
800 </MapControlContainer>
801 )
802}
803
804function MapFullscreenControl({
805 position = "top-1 right-1",
806 className,
807 ...props
808}: React.ComponentProps<"button"> & { position?: string }) {
809 const map = useMap()
810 const [isFullscreen, setIsFullscreen] = useState(false)
811
812 const { L } = useLeaflet()
813
814 useEffect(() => {
815 if (!L) return
816
817 const fullscreenControl = new L.Control.FullScreen()
818 fullscreenControl.addTo(map)
819
820 const container = fullscreenControl.getContainer()
821 if (container) {
822 container.style.display = "none"
823 }
824
825 const handleEnter = () => setIsFullscreen(true)
826 const handleExit = () => setIsFullscreen(false)
827
828 map.on("enterFullscreen", handleEnter)
829 map.on("exitFullscreen", handleExit)
830
831 return () => {
832 fullscreenControl.remove()
833 map.off("enterFullscreen", handleEnter)
834 map.off("exitFullscreen", handleExit)
835 }
836 }, [L, map])
837
838 return (
839 <MapControlContainer className={cn(position, className)}>
840 <Button
841 type="button"
842 size="icon-sm"
843 variant="secondary"
844 onClick={() => map.toggleFullscreen()}
845 aria-label={
846 isFullscreen ? "Exit fullscreen" : "Enter fullscreen"
847 }
848 title={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
849 className="border"
850 {...props}>
851 {isFullscreen ? <MinimizeIcon /> : <MaximizeIcon />}
852 </Button>
853 </MapControlContainer>
854 )
855}
856
857function MapLocatePulseIcon() {
858 return (
859 <div className="absolute -top-1 -right-1 flex size-3 rounded-full">
860 <div className="bg-primary absolute inline-flex size-full animate-ping rounded-full opacity-75" />
861 <div className="bg-primary relative inline-flex size-3 rounded-full" />
862 </div>
863 )
864}
865
866function MapLocateControl({
867 watch = false,
868 onLocationFound,
869 onLocationError,
870 position = "right-1 bottom-1",
871 className,
872 ...props
873}: React.ComponentProps<"button"> &
874 Pick<LocateOptions, "watch"> & {
875 onLocationFound?: (location: LocationEvent) => void
876 onLocationError?: (error: ErrorEvent) => void
877 } & { position?: string }) {
878 const map = useMap()
879 const [isLocating, setIsLocating] = useDebounceLoadingState(200)
880 const [location, setLocation] = useState<LatLngExpression | null>(null)
881
882 function startLocating() {
883 setIsLocating(true)
884 map.locate({ setView: true, maxZoom: map.getMaxZoom(), watch })
885 map.on("locationfound", (location: LocationEvent) => {
886 setLocation(location.latlng)
887 setIsLocating(false)
888 onLocationFound?.(location)
889 })
890 map.on("locationerror", (error: ErrorEvent) => {
891 setLocation(null)
892 setIsLocating(false)
893 onLocationError?.(error)
894 })
895 }
896
897 function stopLocating() {
898 map.stopLocate()
899 map.off("locationfound")
900 map.off("locationerror")
901 setLocation(null)
902 setIsLocating(false)
903 }
904
905 useEffect(() => () => stopLocating(), [])
906
907 return (
908 <MapControlContainer className={cn(position, className)}>
909 <Button
910 type="button"
911 size="icon-sm"
912 variant={location ? "default" : "secondary"}
913 onClick={location ? stopLocating : startLocating}
914 disabled={isLocating}
915 title={
916 isLocating
917 ? "Locating..."
918 : location
919 ? "Stop tracking"
920 : "Track location"
921 }
922 aria-label={
923 isLocating
924 ? "Locating..."
925 : location
926 ? "Stop location tracking"
927 : "Start location tracking"
928 }
929 className="border"
930 {...props}>
931 {isLocating ? (
932 <LoaderCircleIcon className="animate-spin" />
933 ) : (
934 <NavigationIcon />
935 )}
936 </Button>
937 {location && (
938 <MapMarker position={location} icon={<MapLocatePulseIcon />} />
939 )}
940 </MapControlContainer>
941 )
942}
943
944function MapSearchControl({
945 position = "top-1 left-1",
946 className,
947 ...props
948}: PlaceAutocompleteProps & { position?: string }) {
949 return (
950 <MapControlContainer className={cn("z-1001 w-60", position, className)}>
951 <PlaceAutocomplete {...props} />
952 </MapControlContainer>
953 )
954}
955
956type MapDrawShape = "marker" | "polyline" | "circle" | "rectangle" | "polygon"
957type MapDrawAction = "edit" | "delete"
958type MapDrawMode = MapDrawShape | MapDrawAction | null
959interface MapDrawContextType {
960 readonly featureGroup: L.FeatureGroup | null
961 activeMode: MapDrawMode
962 setActiveMode: (mode: MapDrawMode) => void
963 readonly editControlRef: React.RefObject<EditToolbar.Edit | null>
964 readonly deleteControlRef: React.RefObject<EditToolbar.Delete | null>
965 readonly layersCount: number
966}
967
968const MapDrawContext = createContext<MapDrawContextType | null>(null)
969
970function useMapDrawContext() {
971 return useContext(MapDrawContext)
972}
973
974function MapDrawControl({
975 onLayersChange,
976 position = "bottom-1 left-1",
977 className,
978 ...props
979}: React.ComponentProps<"div"> & {
980 onLayersChange?: (layers: L.FeatureGroup) => void
981 position?: string
982}) {
983 const { L, LeafletDraw } = useLeaflet()
984 const map = useMap()
985 const featureGroupRef = useRef<L.FeatureGroup | null>(null)
986 const editControlRef = useRef<EditToolbar.Edit | null>(null)
987 const deleteControlRef = useRef<EditToolbar.Delete | null>(null)
988 const [activeMode, setActiveMode] = useState<MapDrawMode>(null)
989 const [layersCount, setLayersCount] = useState(0)
990
991 function updateLayersCount() {
992 if (featureGroupRef.current) {
993 setLayersCount(featureGroupRef.current.getLayers().length)
994 }
995 }
996
997 function handleDrawCreated(event: DrawEvents.Created) {
998 if (!featureGroupRef.current) return
999 const { layer } = event
1000 featureGroupRef.current.addLayer(layer)
1001 onLayersChange?.(featureGroupRef.current)
1002 updateLayersCount()
1003 setActiveMode(null)
1004 }
1005
1006 function handleDrawEditedOrDeleted() {
1007 if (!featureGroupRef.current) return
1008 onLayersChange?.(featureGroupRef.current)
1009 updateLayersCount()
1010 setActiveMode(null)
1011 }
1012
1013 useEffect(() => {
1014 if (!L || !LeafletDraw || !map) return
1015
1016 map.on(
1017 L.Draw.Event.CREATED,
1018 handleDrawCreated as L.LeafletEventHandlerFn
1019 )
1020 map.on(L.Draw.Event.EDITED, handleDrawEditedOrDeleted)
1021 map.on(L.Draw.Event.DELETED, handleDrawEditedOrDeleted)
1022
1023 return () => {
1024 map.off(
1025 L.Draw.Event.CREATED,
1026 handleDrawCreated as L.LeafletEventHandlerFn
1027 )
1028 map.off(L.Draw.Event.EDITED, handleDrawEditedOrDeleted)
1029 map.off(L.Draw.Event.DELETED, handleDrawEditedOrDeleted)
1030 }
1031 }, [L, LeafletDraw, map, onLayersChange])
1032
1033 return (
1034 <MapDrawContext.Provider
1035 value={{
1036 featureGroup: featureGroupRef.current,
1037 activeMode,
1038 setActiveMode,
1039 editControlRef,
1040 deleteControlRef,
1041 layersCount,
1042 }}>
1043 <LeafletFeatureGroup ref={featureGroupRef} />
1044 <MapControlContainer className={cn(position, className)}>
1045 <ButtonGroup orientation="vertical" {...props} />
1046 </MapControlContainer>
1047 </MapDrawContext.Provider>
1048 )
1049}
1050
1051function MapDrawShapeButton<T extends Draw.Feature>({
1052 drawMode,
1053 createDrawTool,
1054 className,
1055 ...props
1056}: React.ComponentProps<"button"> & {
1057 drawMode: MapDrawShape
1058 createDrawTool: (L: typeof import("leaflet"), map: DrawMap) => T
1059}) {
1060 const drawContext = useMapDrawContext()
1061 if (!drawContext) {
1062 throw new Error("MapDrawShapeButton must be used within MapDrawControl")
1063 }
1064 const { L } = useLeaflet()
1065 const map = useMap()
1066 const controlRef = useRef<T | null>(null)
1067 const { activeMode, setActiveMode } = drawContext
1068 const isActive = activeMode === drawMode
1069
1070 useEffect(() => {
1071 if (!L || !isActive) {
1072 controlRef.current?.disable()
1073 controlRef.current = null
1074 return
1075 }
1076 const control = createDrawTool(L, map as DrawMap)
1077 control.enable()
1078 controlRef.current = control
1079 return () => {
1080 control.disable()
1081 controlRef.current = null
1082 }
1083 }, [L, map, isActive, createDrawTool])
1084
1085 function handleClick() {
1086 setActiveMode(isActive ? null : drawMode)
1087 }
1088
1089 return (
1090 <Button
1091 type="button"
1092 size="icon-sm"
1093 aria-label={`Draw ${drawMode}`}
1094 title={`Draw ${drawMode}`}
1095 className={cn("border", className)}
1096 variant={isActive ? "default" : "secondary"}
1097 disabled={activeMode === "edit" || activeMode === "delete"}
1098 onClick={handleClick}
1099 {...props}
1100 />
1101 )
1102}
1103
1104function MapDrawMarker({ ...props }: DrawOptions.MarkerOptions) {
1105 return (
1106 <MapDrawShapeButton
1107 drawMode="marker"
1108 createDrawTool={(L, map) =>
1109 new L.Draw.Marker(map, {
1110 icon: L.divIcon({
1111 className: "", // For fixing the moving bug when going in and out the edit mode
1112 iconAnchor: [12, 12],
1113 html: renderToString(<MapPinIcon className="size-6" />),
1114 }),
1115 ...props,
1116 })
1117 }>
1118 <MapPinIcon />
1119 </MapDrawShapeButton>
1120 )
1121}
1122
1123function MapDrawPolyline({
1124 showLength = false,
1125 drawError = {
1126 color: "var(--color-destructive)",
1127 },
1128 shapeOptions = {
1129 color: "var(--color-primary)",
1130 opacity: 1,
1131 weight: 2,
1132 },
1133 ...props
1134}: DrawOptions.PolylineOptions) {
1135 const mapDrawHandleIcon = useMapDrawHandleIcon()
1136
1137 return (
1138 <MapDrawShapeButton
1139 drawMode="polyline"
1140 createDrawTool={(L, map) =>
1141 new L.Draw.Polyline(map, {
1142 ...(mapDrawHandleIcon
1143 ? {
1144 icon: mapDrawHandleIcon,
1145 touchIcon: mapDrawHandleIcon,
1146 }
1147 : {}),
1148 showLength,
1149 drawError,
1150 shapeOptions,
1151 ...props,
1152 })
1153 }>
1154 <WaypointsIcon />
1155 </MapDrawShapeButton>
1156 )
1157}
1158
1159function MapDrawCircle({
1160 showRadius = false,
1161 shapeOptions = {
1162 color: "var(--color-primary)",
1163 opacity: 1,
1164 weight: 2,
1165 },
1166 ...props
1167}: DrawOptions.CircleOptions) {
1168 return (
1169 <MapDrawShapeButton
1170 drawMode="circle"
1171 createDrawTool={(L, map) =>
1172 new L.Draw.Circle(map, {
1173 showRadius,
1174 shapeOptions,
1175 ...props,
1176 })
1177 }>
1178 <CircleIcon />
1179 </MapDrawShapeButton>
1180 )
1181}
1182
1183function MapDrawRectangle({
1184 showArea = false,
1185 shapeOptions = {
1186 color: "var(--color-primary)",
1187 opacity: 1,
1188 weight: 2,
1189 },
1190 ...props
1191}: DrawOptions.RectangleOptions) {
1192 return (
1193 <MapDrawShapeButton
1194 drawMode="rectangle"
1195 createDrawTool={(L, map) =>
1196 new L.Draw.Rectangle(map, {
1197 showArea,
1198 shapeOptions,
1199 ...props,
1200 })
1201 }>
1202 <SquareIcon />
1203 </MapDrawShapeButton>
1204 )
1205}
1206
1207function MapDrawPolygon({
1208 drawError = {
1209 color: "var(--color-destructive)",
1210 },
1211 shapeOptions = {
1212 color: "var(--color-primary)",
1213 opacity: 1,
1214 weight: 2,
1215 },
1216 ...props
1217}: DrawOptions.PolygonOptions) {
1218 const mapDrawHandleIcon = useMapDrawHandleIcon()
1219
1220 return (
1221 <MapDrawShapeButton
1222 drawMode="polygon"
1223 createDrawTool={(L, map) =>
1224 new L.Draw.Polygon(map, {
1225 ...(mapDrawHandleIcon
1226 ? {
1227 icon: mapDrawHandleIcon,
1228 touchIcon: mapDrawHandleIcon,
1229 }
1230 : {}),
1231 drawError,
1232 shapeOptions,
1233 ...props,
1234 })
1235 }>
1236 <PentagonIcon />
1237 </MapDrawShapeButton>
1238 )
1239}
1240
1241function MapDrawActionButton<T extends EditToolbar.Edit | EditToolbar.Delete>({
1242 drawAction,
1243 createDrawTool,
1244 controlRef,
1245 className,
1246 ...props
1247}: React.ComponentProps<"button"> & {
1248 drawAction: MapDrawAction
1249 createDrawTool: (
1250 L: typeof import("leaflet"),
1251 map: DrawMap,
1252 featureGroup: L.FeatureGroup
1253 ) => T
1254 controlRef: React.RefObject<T | null>
1255}) {
1256 const drawContext = useMapDrawContext()
1257 if (!drawContext)
1258 throw new Error(
1259 "MapDrawActionButton must be used within MapDrawControl"
1260 )
1261
1262 const { L } = useLeaflet()
1263 const map = useMap()
1264 const { featureGroup, activeMode, setActiveMode, layersCount } = drawContext
1265 const isActive = activeMode === drawAction
1266 const hasFeatures = layersCount > 0
1267
1268 useEffect(() => {
1269 if (!L || !featureGroup || !isActive) {
1270 controlRef.current?.disable?.()
1271 controlRef.current = null
1272 return
1273 }
1274 const control = createDrawTool(L, map as DrawMap, featureGroup)
1275 control.enable?.()
1276 controlRef.current = control
1277 return () => {
1278 control.disable?.()
1279 controlRef.current = null
1280 }
1281 }, [L, map, isActive, featureGroup, createDrawTool])
1282
1283 function handleClick() {
1284 controlRef.current?.save()
1285 setActiveMode(isActive ? null : drawAction)
1286 }
1287
1288 return (
1289 <Button
1290 type="button"
1291 size="icon-sm"
1292 aria-label={`${drawAction === "edit" ? "Edit" : "Remove"} shapes`}
1293 title={`${drawAction === "edit" ? "Edit" : "Remove"} shapes`}
1294 variant={isActive ? "default" : "secondary"}
1295 disabled={!hasFeatures}
1296 onClick={handleClick}
1297 className={cn("border", className)}
1298 {...props}
1299 />
1300 )
1301}
1302
1303function MapDrawEdit({
1304 selectedPathOptions = {
1305 color: "var(--color-primary)",
1306 fillColor: "var(--color-primary)",
1307 weight: 2,
1308 },
1309 ...props
1310}: Omit<EditToolbar.EditHandlerOptions, "featureGroup">) {
1311 const { L } = useLeaflet()
1312 const mapDrawHandleIcon = useMapDrawHandleIcon()
1313 const drawContext = useMapDrawContext()
1314 if (!drawContext) {
1315 throw new Error("MapDrawEdit must be used within MapDrawControl")
1316 }
1317
1318 useEffect(() => {
1319 if (!L || !mapDrawHandleIcon) return
1320
1321 L.Edit.PolyVerticesEdit.mergeOptions({
1322 icon: mapDrawHandleIcon,
1323 touchIcon: mapDrawHandleIcon,
1324 drawError: {
1325 color: "var(--color-destructive)",
1326 },
1327 })
1328 L.Edit.SimpleShape.mergeOptions({
1329 moveIcon: mapDrawHandleIcon,
1330 resizeIcon: mapDrawHandleIcon,
1331 touchMoveIcon: mapDrawHandleIcon,
1332 touchResizeIcon: mapDrawHandleIcon,
1333 })
1334 L.drawLocal.edit.handlers.edit.tooltip = {
1335 text: "Drag handles or markers to edit.",
1336 subtext: "",
1337 }
1338 L.drawLocal.edit.handlers.remove.tooltip = {
1339 text: "Click on a shape to remove.",
1340 }
1341 }, [mapDrawHandleIcon])
1342
1343 return (
1344 <MapDrawActionButton
1345 drawAction="edit"
1346 controlRef={drawContext.editControlRef}
1347 createDrawTool={(L, map, featureGroup) =>
1348 new L.EditToolbar.Edit(map, {
1349 featureGroup,
1350 selectedPathOptions,
1351 ...props,
1352 })
1353 }>
1354 <PenLineIcon />
1355 </MapDrawActionButton>
1356 )
1357}
1358
1359function MapDrawDelete() {
1360 const drawContext = useMapDrawContext()
1361 if (!drawContext) {
1362 throw new Error("MapDrawDelete must be used within MapDrawControl")
1363 }
1364
1365 return (
1366 <MapDrawActionButton
1367 drawAction="delete"
1368 controlRef={drawContext.deleteControlRef}
1369 createDrawTool={(L, map, featureGroup) =>
1370 new L.EditToolbar.Delete(map, { featureGroup })
1371 }>
1372 <Trash2Icon />
1373 </MapDrawActionButton>
1374 )
1375}
1376
1377function MapDrawUndo({ className, ...props }: React.ComponentProps<"button">) {
1378 const drawContext = useMapDrawContext()
1379 if (!drawContext)
1380 throw new Error("MapDrawUndo must be used within MapDrawControl")
1381
1382 const {
1383 activeMode,
1384 setActiveMode,
1385 editControlRef,
1386 deleteControlRef,
1387 layersCount,
1388 } = drawContext
1389 const isInEditMode = activeMode === "edit"
1390 const isInDeleteMode = activeMode === "delete"
1391 const isActive = (isInEditMode || isInDeleteMode) && layersCount > 0
1392
1393 function handleUndo() {
1394 if (isInEditMode) {
1395 editControlRef.current?.revertLayers()
1396 } else if (isInDeleteMode) {
1397 deleteControlRef.current?.revertLayers()
1398 }
1399 setActiveMode(null)
1400 }
1401
1402 return (
1403 <Button
1404 type="button"
1405 size="icon-sm"
1406 variant="secondary"
1407 aria-label={`Undo ${activeMode}`}
1408 title={`Undo ${activeMode}`}
1409 onClick={handleUndo}
1410 disabled={!isActive}
1411 className={cn("border", className)}
1412 {...props}>
1413 <Undo2Icon />
1414 </Button>
1415 )
1416}
1417
1418function MapControlContainer({
1419 className,
1420 ...props
1421}: React.ComponentPropsWithoutRef<"div">) {
1422 const { L } = useLeaflet()
1423 const containerRef = useRef<HTMLDivElement>(null)
1424
1425 useEffect(() => {
1426 if (!L) return
1427 const element = containerRef.current
1428 if (!element) return
1429 L.DomEvent.disableClickPropagation(element)
1430 L.DomEvent.disableScrollPropagation(element)
1431 }, [L])
1432
1433 return (
1434 <div
1435 ref={containerRef}
1436 className={cn("absolute z-1000 size-fit cursor-default", className)}
1437 {...props}
1438 />
1439 )
1440}
1441
1442function useMapDrawHandleIcon() {
1443 const { L } = useLeaflet()
1444 if (!L) return null
1445
1446 return L.divIcon({
1447 iconAnchor: [8, 8],
1448 html: renderToString(
1449 <CircleIcon className="fill-primary stroke-primary size-4 transition-transform hover:scale-110" />
1450 ),
1451 })
1452}
1453
1454function useLeaflet() {
1455 const [L, setL] = useState<typeof import("leaflet") | null>(null)
1456 const [LeafletDraw, setLeafletDraw] = useState<
1457 typeof import("leaflet-draw") | null
1458 >(null)
1459
1460 useEffect(() => {
1461 async function loadLeaflet() {
1462 const leaflet = await import("leaflet")
1463 const leafletFullscreen = await import("leaflet.fullscreen")
1464 const leafletDraw = await import("leaflet-draw")
1465
1466 const L_object = leaflet.default
1467 if (L_object.Control && !L_object.Control.FullScreen) {
1468 L_object.Control.FullScreen =
1469 leafletFullscreen.default || leafletFullscreen
1470 }
1471
1472 setLeafletDraw(leafletDraw)
1473 setL(L_object)
1474 }
1475
1476 if (L && LeafletDraw) return
1477 if (typeof window === "undefined") return
1478
1479 loadLeaflet()
1480 }, [L, LeafletDraw])
1481
1482 return { L, LeafletDraw }
1483}
1484
1485function useDebounceLoadingState(delay = 200) {
1486 const [isLoading, setIsLoading] = useState(false)
1487 const [showLoading, setShowLoading] = useState(false)
1488 const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
1489
1490 useEffect(() => {
1491 if (isLoading) {
1492 timeoutRef.current = setTimeout(() => {
1493 setShowLoading(true)
1494 }, delay)
1495 } else {
1496 if (timeoutRef.current) {
1497 clearTimeout(timeoutRef.current)
1498 timeoutRef.current = null
1499 }
1500 setShowLoading(false)
1501 }
1502
1503 return () => {
1504 if (timeoutRef.current) {
1505 clearTimeout(timeoutRef.current)
1506 }
1507 }
1508 }, [isLoading, delay])
1509
1510 return [showLoading, setIsLoading] as const
1511}
1512
1513export {
1514 Map,
1515 MapCircle,
1516 MapCircleMarker,
1517 MapControlContainer,
1518 MapDrawCircle,
1519 MapDrawControl,
1520 MapDrawDelete,
1521 MapDrawEdit,
1522 MapDrawMarker,
1523 MapDrawPolygon,
1524 MapDrawPolyline,
1525 MapDrawRectangle,
1526 MapDrawUndo,
1527 MapFeatureGroup,
1528 MapFullscreenControl,
1529 MapLayerGroup,
1530 MapLayers,
1531 MapLayersControl,
1532 MapLocateControl,
1533 MapMarker,
1534 MapMarkerClusterGroup,
1535 MapPolygon,
1536 MapPolyline,
1537 MapPopup,
1538 MapRectangle,
1539 MapSearchControl,
1540 MapTileLayer,
1541 MapTooltip,
1542 MapZoomControl,
1543 useLeaflet,
1544}
1545