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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
|
import { useQuery } from "@tanstack/react-query";
import { LayoutGrid, List, Map as MapIcon } from "lucide-react";
import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
AttributionControl,
Layer,
Source,
type MapRef,
} from "react-map-gl/maplibre";
import { useParams } from "react-router";
import { fetchRouteDetails } from "~/api/transit";
import { AppMap } from "~/components/shared/AppMap";
import {
useBackButton,
usePageTitle,
usePageTitleNode,
} from "~/contexts/PageTitleContext";
import "../tailwind-full.css";
export default function RouteDetailsPage() {
const { id } = useParams();
const { t, i18n } = useTranslation();
const [selectedPatternId, setSelectedPatternId] = useState<string | null>(
null
);
const [selectedStopId, setSelectedStopId] = useState<string | null>(null);
const [layoutMode, setLayoutMode] = useState<"balanced" | "map" | "list">(
"balanced"
);
const [selectedWeekDate, setSelectedWeekDate] = useState<Date>(
() => new Date()
);
const mapRef = useRef<MapRef>(null);
const stopRefs = useRef<Record<string, HTMLDivElement | null>>({});
const formatDateKey = (value: Date) => {
const year = value.getFullYear();
const month = String(value.getMonth() + 1).padStart(2, "0");
const day = String(value.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
};
const selectedDateKey = useMemo(
() => formatDateKey(selectedWeekDate),
[selectedWeekDate]
);
const { data: route, isLoading } = useQuery({
queryKey: ["route", id, selectedDateKey],
queryFn: () => fetchRouteDetails(id!, selectedDateKey),
enabled: !!id,
});
usePageTitle(
route?.shortName
? `${route.shortName} - ${route.longName}`
: t("routes.details", "Detalles de ruta")
);
const titleNode = useMemo(() => {
if (!route) {
return (
<span className="text-base font-semibold text-text">
{t("routes.details", "Detalles de ruta")}
</span>
);
}
return (
<div className="flex flex-col min-w-0">
<div className="flex items-center gap-2">
<span
className="text-lg font-bold leading-none"
style={{
color: route.color ? `#${route.color}` : "var(--text-color)",
}}
>
{route.shortName || route.longName}
</span>
<span className="text-sm text-text/90 truncate text-wrap tracking-tight leading-none">
{route.longName}
</span>
</div>
</div>
);
}, [route, t]);
usePageTitleNode(titleNode);
useBackButton({ to: "/routes" });
const weekDays = useMemo(() => {
const base = new Date();
return [-2, -1, 0, 1, 2, 3, 4].map((offset) => {
const date = new Date(base);
date.setDate(base.getDate() + offset);
let label: string;
if (offset === -1) {
label = t("routes.day_yesterday", "Ayer");
} else if (offset === 0) {
label = t("routes.day_today", "Hoy");
} else if (offset === 1) {
label = t("routes.day_tomorrow", "Mañana");
} else {
label = date.toLocaleDateString(i18n.language || "es-ES", {
weekday: "short",
day: "numeric",
month: "short",
});
}
return {
key: formatDateKey(date),
date,
label,
};
});
}, [i18n.language, t]);
if (isLoading) {
return (
<div className="flex justify-center py-12">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
</div>
);
}
if (!route) {
return (
<div className="p-4">{t("routes.not_found", "Línea no encontrada")}</div>
);
}
const activePatterns = route.patterns.filter((p) => p.tripCount > 0);
const patternsByDirection = activePatterns.reduce(
(acc, pattern) => {
const dir = pattern.directionId;
if (!acc[dir]) acc[dir] = [];
acc[dir].push(pattern);
return acc;
},
{} as Record<number, typeof route.patterns>
);
const selectedPattern =
activePatterns.find((p) => p.id === selectedPatternId) || activePatterns[0];
const mapHeightClass =
layoutMode === "map"
? "h-[75%] md:h-[75%]"
: layoutMode === "list"
? "h-[25%] md:h-[25%]"
: "h-[50%] md:h-[50%]";
const layoutOptions = [
{
id: "balanced",
label: t("routes.layout_balanced", "Equilibrada"),
icon: LayoutGrid,
},
{
id: "map",
label: t("routes.layout_map", "Mapa"),
icon: MapIcon,
},
{
id: "list",
label: t("routes.layout_list", "Paradas"),
icon: List,
},
] as const;
const handleStopClick = (
stopId: string,
lat: number,
lon: number,
scroll = true
) => {
setSelectedStopId(stopId);
mapRef.current?.flyTo({
center: [lon, lat],
zoom: 15,
duration: 1000,
});
if (scroll) {
stopRefs.current[stopId]?.scrollIntoView({
behavior: "smooth",
block: "center",
});
}
};
const geojson: GeoJSON.FeatureCollection = {
type: "FeatureCollection",
features: selectedPattern?.geometry
? [
{
type: "Feature",
geometry: {
type: "LineString",
coordinates: selectedPattern.geometry,
},
properties: {},
},
]
: [],
};
const stopsGeojson: GeoJSON.FeatureCollection = {
type: "FeatureCollection",
features:
selectedPattern?.stops.map((stop) => ({
type: "Feature",
geometry: {
type: "Point",
coordinates: [stop.lon, stop.lat],
},
properties: {
id: stop.id,
name: stop.name,
code: stop.code,
lat: stop.lat,
lon: stop.lon,
},
})) || [],
};
return (
<div className="flex flex-col h-full overflow-hidden">
<div className="flex-1 flex flex-col overflow-hidden">
<div className="flex-1 flex flex-col relative overflow-hidden">
<div className={`${mapHeightClass} relative`}>
<AppMap
ref={mapRef}
initialViewState={
selectedPattern?.stops[0]
? {
latitude: selectedPattern.stops[0].lat,
longitude: selectedPattern.stops[0].lon,
zoom: 13,
}
: undefined
}
interactiveLayerIds={["stop-circles"]}
onClick={(e) => {
const feature = e.features?.[0];
if (feature && feature.layer.id === "stop-circles") {
const { id, lat, lon } = feature.properties;
handleStopClick(id, lat, lon, true);
}
}}
showTraffic={false}
attributionControl={false}
>
<AttributionControl position="bottom-left" compact={true} />
{selectedPattern?.geometry && (
<Source type="geojson" data={geojson}>
<Layer
id="route-line"
type="line"
paint={{
"line-color": route.color ? `#${route.color}` : "#3b82f6",
"line-width": 4,
"line-opacity": 0.8,
}}
/>
</Source>
)}
<Source type="geojson" data={stopsGeojson}>
<Layer
id="stop-circles"
type="circle"
paint={{
"circle-radius": 6,
"circle-color": "#ffffff",
"circle-stroke-width": 2,
"circle-stroke-color": route.color
? `#${route.color}`
: "#3b82f6",
}}
/>
</Source>
</AppMap>
<div className="absolute top-3 left-3 z-10 flex items-center gap-1 rounded-full border border-border bg-background/90 p-1 shadow-sm backdrop-blur">
{layoutOptions.map((option) => {
const Icon = option.icon;
const isActive = layoutMode === option.id;
return (
<button
key={option.id}
type="button"
onClick={() => setLayoutMode(option.id)}
className={`h-8 w-8 rounded-full flex items-center justify-center transition-colors ${
isActive
? "bg-primary text-white"
: "text-muted hover:text-text"
}`}
aria-label={option.label}
title={option.label}
>
<Icon size={16} />
</button>
);
})}
</div>
</div>
<div className="px-3 py-2 bg-surface border-y border-border">
<div className="flex items-center gap-2">
<select
className="w-full px-3 py-1.5 box-border bg-surface text-text focus:ring-2 focus:ring-primary outline-none text-sm rounded-md border border-border flex-2"
value={selectedPattern?.id}
onChange={(e) => {
setSelectedPatternId(e.target.value);
setSelectedStopId(null);
}}
>
{Object.entries(patternsByDirection).map(([dir, patterns]) => (
<optgroup
key={dir}
label={
dir === "0"
? t("routes.direction_outbound", "Ida")
: t("routes.direction_inbound", "Vuelta")
}
>
{patterns.map((pattern) => (
<option key={pattern.id} value={pattern.id}>
{pattern.code
? `${parseInt(pattern.code.slice(-2)).toString()}: `
: ""}
{pattern.headsign || pattern.name}{" "}
{t("routes.trip_count_short", {
count: pattern.tripCount,
})}
</option>
))}
</optgroup>
))}
</select>
<select
className="w-full px-3 py-1.5 box-border bg-surface text-text focus:ring-2 focus:ring-primary outline-none text-sm rounded-md border border-border flex-1"
value={selectedDateKey}
onChange={(e) => {
const next = weekDays.find(
(day) => day.key === e.target.value
);
if (next) {
setSelectedWeekDate(next.date);
}
}}
aria-label={t("routes.week_date", "Fecha")}
>
{weekDays.map((day) => (
<option key={day.key} value={day.key}>
{day.label}
</option>
))}
</select>
</div>
</div>
<div className="flex-1 overflow-y-auto px-4 py-3 bg-background">
<h3 className="text-base font-semibold mb-3 text-text">
{t("routes.stops", "Paradas")}
</h3>
<div className="space-y-2">
{selectedPattern?.stops.map((stop, idx) => (
<div
key={`${stop.id}-${idx}`}
ref={(el) => {
stopRefs.current[stop.id] = el;
}}
onClick={() =>
handleStopClick(stop.id, stop.lat, stop.lon, false)
}
className={`flex items-start gap-3 p-2.5 rounded-lg border transition-colors cursor-pointer ${
selectedStopId === stop.id
? "bg-primary/5 border-primary"
: "bg-surface border-border hover:border-primary/50"
}`}
>
<div className="flex flex-col items-center">
<div
className={`w-2.5 h-2.5 rounded-full mt-1.5 ${selectedStopId === stop.id ? "bg-primary" : "bg-gray-400"}`}
></div>
{idx < selectedPattern.stops.length - 1 && (
<div className="w-0.5 h-full bg-border -mb-2.5 mt-1"></div>
)}
</div>
<div className="flex-1">
<p className="font-semibold text-text text-sm">
{stop.name}
{stop.code && (
<span className="text-[11px] font-normal text-gray-500 ml-2">
{stop.code}
</span>
)}
</p>
{selectedStopId === stop.id &&
stop.scheduledDepartures.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1">
{stop.scheduledDepartures.map((dep, i) => (
<span
key={i}
className="text-[10px] px-1.5 py-0.5 bg-gray-100 dark:bg-gray-800 rounded"
>
{Math.floor(dep / 3600)
.toString()
.padStart(2, "0")}
:
{Math.floor((dep % 3600) / 60)
.toString()
.padStart(2, "0")}
</span>
))}
</div>
)}
</div>
</div>
))}
</div>
</div>
</div>
</div>
</div>
);
}
|