aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/components/shared/AppMap.tsx
blob: f4c8658502d7db1923d635f957ed083034c4874a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from "react";
import Map, {
  GeolocateControl,
  NavigationControl,
  type MapLayerMouseEvent,
  type MapRef,
  type StyleSpecification,
} from "react-map-gl/maplibre";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router";
import { useApp } from "~/AppContext";
import { APP_CONSTANTS } from "~/config/constants";
import { DEFAULT_STYLE, loadStyle } from "~/maps/styleloader";

interface AppMapProps {
  children?: React.ReactNode;
  showTraffic?: boolean;
  showCameras?: boolean;
  syncState?: boolean;
  interactiveLayerIds?: string[];
  onClick?: (e: MapLayerMouseEvent) => void;
  initialViewState?: {
    latitude: number;
    longitude: number;
    zoom: number;
  };
  style?: React.CSSProperties;
  maxBounds?: [number, number, number, number] | null;
  attributionControl?: boolean | any;
  showNavigation?: boolean;
  showGeolocate?: boolean;
  onMove?: (e: any) => void;
  onDragStart?: () => void;
  onZoomStart?: () => void;
  onRotateStart?: () => void;
  onPitchStart?: () => void;
  onLoad?: () => void;
  onContextMenu?: (e: MapLayerMouseEvent) => void;
}

export const AppMap = forwardRef<MapRef, AppMapProps>(
  (
    {
      children,
      showTraffic: propShowTraffic,
      showCameras: propShowCameras,
      syncState = false,
      interactiveLayerIds,
      onClick,
      initialViewState,
      style,
      maxBounds = [
        (APP_CONSTANTS.bounds.sw as [number, number])[0],
        (APP_CONSTANTS.bounds.sw as [number, number])[1],
        (APP_CONSTANTS.bounds.ne as [number, number])[0],
        (APP_CONSTANTS.bounds.ne as [number, number])[1],
      ],
      attributionControl = false,
      showNavigation = false,
      showGeolocate = false,
      onMove,
      onDragStart,
      onZoomStart,
      onRotateStart,
      onPitchStart,
      onLoad,
      onContextMenu,
    },
    ref
  ) => {
    const {
      theme,
      mapState,
      updateMapState,
      setUserLocation,
      setLocationPermission,
      showTraffic: settingsShowTraffic,
      showCameras: settingsShowCameras,
      mapPositionMode,
    } = useApp();
    const { i18n } = useTranslation();
    const mapRef = useRef<MapRef>(null);
    const [mapStyle, setMapStyle] = useState<StyleSpecification>(DEFAULT_STYLE);
    const location = useLocation();
    const path = location.pathname;

    // Use prop if provided, otherwise use settings
    const showTraffic =
      propShowTraffic !== undefined ? propShowTraffic : settingsShowTraffic;
    const showCameras =
      propShowCameras !== undefined ? propShowCameras : settingsShowCameras;

    useImperativeHandle(ref, () => mapRef.current!);

    useEffect(() => {
      loadStyle("openfreemap", theme, {
        includeTraffic: showTraffic,
        language: i18n.language,
      })
        .then((style) => setMapStyle(style))
        .catch((error) => console.error("Failed to load map style:", error));
    }, [theme, showTraffic, i18n.language]);

    useEffect(() => {
      const handleMapChange = () => {
        if (!syncState || !mapRef.current) return;
        const map = mapRef.current.getMap();
        if (!map) return;
        const center = map.getCenter();
        const zoom = map.getZoom();
        updateMapState([center.lat, center.lng], zoom, path);
      };

      const handleStyleImageMissing = (e: any) => {
        if (!mapRef.current) return;
        const map = mapRef.current.getMap();
        if (!map || map.hasImage(e.id)) return;

        if (e.id.startsWith("stop-")) {
          console.warn(`Missing icon image: ${e.id}`);
        }

        map.addImage(e.id, {
          width: 1,
          height: 1,
          data: new Uint8Array(4),
        });
      };

      if (mapRef.current) {
        const map = mapRef.current.getMap();
        if (map) {
          map.on("moveend", handleMapChange);
          map.on("styleimagemissing", handleStyleImageMissing);
        }
      }

      return () => {
        if (mapRef.current) {
          const map = mapRef.current.getMap();
          if (map) {
            map.off("moveend", handleMapChange);
            map.off("styleimagemissing", handleStyleImageMissing);
          }
        }
      };
    }, [mapPositionMode, mapRef.current, updateMapState]);

    const getLatitude = (center: any) =>
      Array.isArray(center) ? center[0] : center.lat;
    const getLongitude = (center: any) =>
      Array.isArray(center) ? center[1] : center.lng;

    const viewState = useMemo(() => {
      if (initialViewState) return initialViewState;

      // Prefer the last saved position for this path so navigation doesn't
      // reset the map viewport. GPS mode is only used as a fallback when the
      // user has never visited this path before.
      const pathState = mapState.paths[path];
      if (pathState) {
        return {
          latitude: getLatitude(pathState.center),
          longitude: getLongitude(pathState.center),
          zoom: pathState.zoom,
        };
      }

      if (mapPositionMode === "gps" && mapState.userLocation) {
        return {
          latitude: getLatitude(mapState.userLocation),
          longitude: getLongitude(mapState.userLocation),
          zoom: 16,
        };
      }

      return {
        latitude: getLatitude(APP_CONSTANTS.defaultCenter),
        longitude: getLongitude(APP_CONSTANTS.defaultCenter),
        zoom: APP_CONSTANTS.defaultZoom,
      };
    }, [initialViewState, mapPositionMode, mapState, path]);

    return (
      <Map
        ref={mapRef}
        mapLib={maplibregl}
        mapStyle={mapStyle}
        style={{ width: "100%", height: "100%", ...style }}
        initialViewState={viewState}
        maxBounds={maxBounds || undefined}
        attributionControl={attributionControl}
        interactiveLayerIds={interactiveLayerIds}
        onClick={onClick}
        onMove={onMove}
        onDragStart={onDragStart}
        onZoomStart={onZoomStart}
        onRotateStart={onRotateStart}
        onPitchStart={onPitchStart}
        onLoad={onLoad}
        onContextMenu={onContextMenu}
      >
        {showNavigation && <NavigationControl position="bottom-right" />}
        {showGeolocate && (
          <GeolocateControl
            position="bottom-right"
            positionOptions={{ enableHighAccuracy: false }}
            onGeolocate={(e) => {
              const { latitude, longitude } = e.coords;
              setUserLocation([latitude, longitude]);
              setLocationPermission(true);
            }}
          />
        )}
        {children}
      </Map>
    );
  }
);

AppMap.displayName = "AppMap";