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
|
import { Edit2, ExternalLink, RefreshCw, Star } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, Navigate, useParams } from "react-router";
import { ErrorDisplay } from "~/components/ErrorDisplay";
import LineIcon from "~/components/LineIcon";
import { PullToRefresh } from "~/components/PullToRefresh";
import {
type ScheduledTable,
SchedulesTable,
} from "~/components/SchedulesTable";
import {
EstimatesGroupedSkeleton,
SchedulesTableSkeleton,
} from "~/components/SchedulesTableSkeleton";
import { StopAlert } from "~/components/StopAlert";
import { TimetableSkeleton } from "~/components/TimetableSkeleton";
import { type RegionId, getRegionConfig } from "~/data/RegionConfig";
import { useAutoRefresh } from "~/hooks/useAutoRefresh";
import { useApp } from "../AppContext";
import { GroupedTable } from "../components/GroupedTable";
import { RegularTable } from "../components/RegularTable";
import StopDataProvider, { type Stop } from "../data/StopDataProvider";
import "./estimates-$id.css";
export interface Estimate {
line: string;
route: string;
minutes: number;
meters: number;
}
interface ErrorInfo {
type: "network" | "server" | "unknown";
status?: number;
message?: string;
}
const loadData = async (
region: RegionId,
stopId: string,
): Promise<Estimate[]> => {
const regionConfig = getRegionConfig(region);
const resp = await fetch(`${regionConfig.estimatesEndpoint}?id=${stopId}`, {
headers: {
Accept: "application/json",
},
});
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
}
return await resp.json();
};
const loadTimetableData = async (
region: RegionId,
stopId: string,
): Promise<ScheduledTable[]> => {
const regionConfig = getRegionConfig(region);
// Check if timetable is available for this region
if (!regionConfig.timetableEndpoint) {
throw new Error("Timetable not available for this region");
}
const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD format
const resp = await fetch(
`${regionConfig.timetableEndpoint}?date=${today}&stopId=${stopId}`,
{
headers: {
Accept: "application/json",
},
},
);
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}: ${resp.statusText}`);
}
return await resp.json();
};
export default function Estimates() {
const { t } = useTranslation();
const params = useParams();
const stopIdNum = parseInt(params.id ?? "");
const [customName, setCustomName] = useState<string | undefined>(undefined);
const [stopData, setStopData] = useState<Stop | undefined>(undefined);
// Estimates data state
const [data, setData] = useState<Estimate[] | null>(null);
const [dataDate, setDataDate] = useState<Date | null>(null);
const [estimatesLoading, setEstimatesLoading] = useState(true);
const [estimatesError, setEstimatesError] = useState<ErrorInfo | null>(null);
// Timetable data state
const [timetableData, setTimetableData] = useState<ScheduledTable[]>([]);
const [timetableLoading, setTimetableLoading] = useState(true);
const [timetableError, setTimetableError] = useState<ErrorInfo | null>(null);
const [favourited, setFavourited] = useState(false);
const [isManualRefreshing, setIsManualRefreshing] = useState(false);
const { tableStyle, region } = useApp();
const regionConfig = getRegionConfig(region);
// Redirect to /stops/$id if table style is experimental_consolidated
if (tableStyle === "experimental_consolidated") {
return <Navigate to={`/stops/${params.id}`} replace />;
}
const parseError = (error: any): ErrorInfo => {
if (!navigator.onLine) {
return { type: "network", message: "No internet connection" };
}
if (
error.message?.includes("Failed to fetch") ||
error.message?.includes("NetworkError")
) {
return { type: "network" };
}
if (error.message?.includes("HTTP")) {
const statusMatch = error.message.match(/HTTP (\d+):/);
const status = statusMatch ? parseInt(statusMatch[1]) : undefined;
return { type: "server", status };
}
return { type: "unknown", message: error.message };
};
const loadEstimatesData = useCallback(async () => {
try {
setEstimatesLoading(true);
setEstimatesError(null);
const body = await loadData(region, params.id!);
setData(body);
setDataDate(new Date());
// Load stop data from StopDataProvider
const stop = await StopDataProvider.getStopById(region, stopIdNum);
setStopData(stop);
setCustomName(StopDataProvider.getCustomName(region, stopIdNum));
} catch (error) {
console.error("Error loading estimates data:", error);
setEstimatesError(parseError(error));
setData(null);
setDataDate(null);
} finally {
setEstimatesLoading(false);
}
}, [params.id, stopIdNum, region]);
const loadTimetableDataAsync = useCallback(async () => {
// Skip loading timetable if not available for this region
if (!regionConfig.timetableEndpoint) {
setTimetableLoading(false);
return;
}
try {
setTimetableLoading(true);
setTimetableError(null);
const timetableBody = await loadTimetableData(region, params.id!);
setTimetableData(timetableBody);
} catch (error) {
console.error("Error loading timetable data:", error);
setTimetableError(parseError(error));
setTimetableData([]);
} finally {
setTimetableLoading(false);
}
}, [params.id, region, regionConfig.timetableEndpoint]);
// Manual refresh function for pull-to-refresh and button
const handleManualRefresh = useCallback(async () => {
try {
setIsManualRefreshing(true);
// Only reload real-time estimates data, not timetable
await loadEstimatesData();
} finally {
setIsManualRefreshing(false);
}
}, [loadEstimatesData]);
// Auto-refresh estimates data every 30 seconds (only if not in error state)
useAutoRefresh({
onRefresh: loadEstimatesData,
interval: 30000,
enabled: !estimatesError,
});
useEffect(() => {
// Initial load
loadEstimatesData();
loadTimetableDataAsync();
StopDataProvider.pushRecent(region, parseInt(params.id ?? ""));
setFavourited(
StopDataProvider.isFavourite(region, parseInt(params.id ?? "")),
);
}, [params.id, region, loadEstimatesData, loadTimetableDataAsync]);
const toggleFavourite = () => {
if (favourited) {
StopDataProvider.removeFavourite(region, stopIdNum);
setFavourited(false);
} else {
StopDataProvider.addFavourite(region, stopIdNum);
setFavourited(true);
}
};
// Helper function to get the display name for the stop
const getStopDisplayName = () => {
if (customName) return customName;
if (stopData?.name.intersect) return stopData.name.intersect;
if (stopData?.name.original) return stopData.name.original;
return `Parada ${stopIdNum}`;
};
const handleRename = () => {
const current = getStopDisplayName();
const input = window.prompt("Custom name for this stop:", current);
if (input === null) return; // cancelled
const trimmed = input.trim();
if (trimmed === "") {
StopDataProvider.removeCustomName(region, stopIdNum);
setCustomName(undefined);
} else {
StopDataProvider.setCustomName(region, stopIdNum, trimmed);
setCustomName(trimmed);
}
};
// Show loading skeleton while initial data is loading
if (estimatesLoading && !data) {
return (
<PullToRefresh
onRefresh={handleManualRefresh}
isRefreshing={isManualRefreshing}
>
<div className="page-container estimates-page">
<div className="estimates-header">
<h1 className="page-title">
<Star className="star-icon" />
<Edit2 className="edit-icon" />
{t("common.loading")}...
</h1>
</div>
<div className="table-responsive">
{tableStyle === "grouped" ? (
<EstimatesGroupedSkeleton />
) : (
<SchedulesTableSkeleton />
)}
</div>
<div className="timetable-section">
<TimetableSkeleton />
</div>
</div>
</PullToRefresh>
);
}
return (
<PullToRefresh
onRefresh={handleManualRefresh}
isRefreshing={isManualRefreshing}
>
<div className="page-container estimates-page">
<div className="estimates-header">
<h1 className="page-title">
<Star
className={`star-icon ${favourited ? "active" : ""}`}
onClick={toggleFavourite}
/>
<Edit2 className="edit-icon" onClick={handleRename} />
{getStopDisplayName()}{" "}
<span className="estimates-stop-id">({stopIdNum})</span>
</h1>
<button
className="manual-refresh-button"
onClick={handleManualRefresh}
disabled={isManualRefreshing || estimatesLoading}
title={t("estimates.reload", "Recargar estimaciones")}
>
<RefreshCw
className={`refresh-icon ${isManualRefreshing ? "spinning" : ""}`}
/>
</button>
</div>
{stopData && stopData.lines && stopData.lines.length > 0 && (
<div className={`estimates-lines-container`}>
{stopData.lines.map((line) => (
<div key={line} className="estimates-line-icon">
<LineIcon line={line} region={region} rounded />
</div>
))}
</div>
)}
{stopData && <StopAlert stop={stopData} />}
<div className="table-responsive">
{estimatesLoading ? (
tableStyle === "grouped" ? (
<EstimatesGroupedSkeleton />
) : (
<SchedulesTableSkeleton />
)
) : estimatesError ? (
<ErrorDisplay
error={estimatesError}
onRetry={loadEstimatesData}
title={t(
"errors.estimates_title",
"Error al cargar estimaciones",
)}
/>
) : data ? (
tableStyle === "grouped" ? (
<GroupedTable
data={data}
dataDate={dataDate}
regionConfig={regionConfig}
/>
) : (
<RegularTable
data={data}
dataDate={dataDate}
regionConfig={regionConfig}
/>
)
) : null}
</div>
<div className="timetable-section">
{timetableLoading ? (
<TimetableSkeleton />
) : timetableError ? (
<ErrorDisplay
error={timetableError}
onRetry={loadTimetableDataAsync}
title={t("errors.timetable_title", "Error al cargar horarios")}
className="compact"
/>
) : timetableData.length > 0 ? (
<>
<SchedulesTable
data={timetableData}
currentTime={new Date().toTimeString().slice(0, 8)} // HH:MM:SS
/>
<div className="timetable-actions">
<Link to={`/timetable/${params.id}`} className="view-all-link">
<ExternalLink className="external-icon" />
{t("timetable.viewAll", "Ver todos los horarios")}
</Link>
</div>
</>
) : null}
</div>
</div>
</PullToRefresh>
);
}
|