aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/app/routes/map.tsx
blob: b8f179cc1a33348f70c4c2a2067065fe52e7c741 (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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import StopDataProvider from "../data/StopDataProvider";
import "./map.css";

import type { FilterSpecification } from "maplibre-gl";
import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Layer,
  Source,
  type MapLayerMouseEvent,
  type MapRef,
} from "react-map-gl/maplibre";
import { useNavigate } from "react-router";
import { useApp } from "~/AppContext";
import {
  StopSummarySheet,
  type StopSheetProps,
} from "~/components/map/StopSummarySheet";
import { PlannerOverlay } from "~/components/PlannerOverlay";
import { AppMap } from "~/components/shared/AppMap";
import { usePageTitle } from "~/contexts/PageTitleContext";
import { usePlanner } from "~/hooks/usePlanner";
import "../tailwind-full.css";

// Componente principal del mapa
export default function StopMap() {
  const { t } = useTranslation();
  const {
    showBusStops: showCitybusStops,
    showCoachStops: showIntercityBusStops,
    showTrainStops,
  } = useApp();
  const navigate = useNavigate();
  usePageTitle(t("navbar.map", "Mapa"));
  const [selectedStop, setSelectedStop] = useState<
    StopSheetProps["stop"] | null
  >(null);
  const [isSheetOpen, setIsSheetOpen] = useState(false);
  const mapRef = useRef<MapRef>(null);

  const { searchRoute } = usePlanner({ autoLoad: false });

  const favouriteIds = useMemo(() => StopDataProvider.getFavouriteIds(), []);

  const favouriteFilter = useMemo(() => {
    if (favouriteIds.length === 0) return ["boolean", false];
    return ["match", ["get", "id"], favouriteIds, true, false];
  }, [favouriteIds]);

  // Handle click events on clusters and individual stops
  const onMapClick = (e: MapLayerMouseEvent) => {
    const features = e.features;
    if (!features || features.length === 0) {
      console.debug(
        "No features found on map click. Position:",
        e.lngLat,
        "Point:",
        e.point
      );
      return;
    }
    const feature = features[0];

    handlePointClick(feature);
  };

  const stopLayerFilter = useMemo(() => {
    const filter: any[] = ["any"];
    if (showCitybusStops) {
      filter.push(["==", ["get", "transitKind"], "bus"]);
    }
    if (showIntercityBusStops) {
      filter.push(["==", ["get", "transitKind"], "coach"]);
    }
    if (showTrainStops) {
      filter.push(["==", ["get", "transitKind"], "train"]);
    }
    return filter as FilterSpecification;
  }, [showCitybusStops, showIntercityBusStops, showTrainStops]);

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

  const handlePointClick = (feature: any) => {
    const props: {
      id: string;
      code: string;
      name: string;
      routes: string;
    } = feature.properties;
    // TODO: Move ID to constant, improve type checking
    if (!props || feature.layer.id.startsWith("stops") === false) {
      console.warn("Invalid feature properties:", props);
      return;
    }

    const stopId = props.id;
    const routes: {
      shortName: string;
      colour: string;
      textColour: string;
    }[] = JSON.parse(props.routes || "[]");

    setSelectedStop({
      stopId: props.id,
      stopCode: props.code,
      name: props.name || "Unknown Stop",
      lines: routes.map((route) => {
        return {
          line: route.shortName,
          colour: route.colour,
          textColour: route.textColour,
        };
      }),
    });
    setIsSheetOpen(true);
  };

  return (
    <div className="relative h-full">
      <PlannerOverlay
        onSearch={(o, d, time, arriveBy) => searchRoute(o, d, time, arriveBy)}
        onNavigateToPlanner={() => navigate("/planner")}
        clearPickerOnOpen={true}
        showLastDestinationWhenCollapsed={false}
        cardBackground="bg-white/95 dark:bg-slate-900/90"
        autoLoad={false}
      />

      <AppMap
        ref={mapRef}
        syncState={true}
        showNavigation={true}
        showGeolocate={true}
        interactiveLayerIds={["stops", "stops-label"]}
        onClick={onMapClick}
        attributionControl={{ compact: false }}
      >
        <Source
          id="stops-source"
          type="vector"
          tiles={[StopDataProvider.getTileUrlTemplate()]}
          minzoom={11}
          maxzoom={20}
        />

        <Layer
          id="stops-favourite-highlight"
          type="circle"
          minzoom={11}
          source="stops-source"
          source-layer="stops"
          filter={["all", stopLayerFilter, favouriteFilter]}
          paint={{
            "circle-color": "#FFD700",
            "circle-radius": [
              "interpolate",
              ["linear"],
              ["zoom"],
              13,
              10,
              16,
              12,
              18,
              16,
            ],
            "circle-opacity": 0.4,
            "circle-stroke-color": "#FFD700",
            "circle-stroke-width": 2,
          }}
        />

        <Layer
          id="stops"
          type="symbol"
          minzoom={11}
          source="stops-source"
          source-layer="stops"
          filter={stopLayerFilter}
          layout={{
            "icon-image": ["get", "icon"],
            "icon-size": [
              "interpolate",
              ["linear"],
              ["zoom"],
              13,
              0.7,
              16,
              0.8,
              18,
              1.2,
            ],
            "icon-allow-overlap": true,
            "icon-ignore-placement": true,
            "symbol-sort-key": [
              "match",
              ["get", "transitKind"],
              "bus",
              3,
              "coach",
              2,
              "train",
              1,
              0,
            ],
          }}
        />

        <Layer
          id="stops-label"
          type="symbol"
          source="stops-source"
          source-layer="stops"
          minzoom={16}
          filter={stopLayerFilter}
          layout={{
            "text-field": ["get", "name"],
            "text-font": ["Noto Sans Bold"],
            "text-offset": [0, 3],
            "text-anchor": "center",
            "text-justify": "center",
            "text-size": ["interpolate", ["linear"], ["zoom"], 11, 8, 22, 16],
          }}
          paint={{
            "text-color": [
              "match",
              ["get", "feed"],
              "vitrasa",
              "#81D002",
              "santiago",
              "#508096",
              "coruna",
              "#E61C29",
              "xunta",
              "#007BC4",
              "renfe",
              "#870164",
              "feve",
              "#EE3D32",
              "#27187D",
            ],
            "text-halo-color": "#FFF",
            "text-halo-width": 1,
          }}
        />

        {selectedStop && (
          <StopSummarySheet
            isOpen={isSheetOpen}
            onClose={() => setIsSheetOpen(false)}
            stop={selectedStop}
          />
        )}
      </AppMap>
    </div>
  );
}