Refactor departure time calculation to account for walk duration

Introduce `trainWalkDurationSeconds` in `useDepartureTime` hooks for both
mobile and web apps to filter train journeys based on total arrival time
including walking.

Add default origin station constants in core package and use them in mobile
store instead of returning null when no origin is saved.

Normalize HAFAS coordinates in destination station hooks to handle
large integer values.

Update `cleanLocation` to preserve full addresses with commas and remove
the 10KB request body limit on ICS parsing to support larger calendar
files.

Make rate limiting configurable via environment variables to handle
higher API fan-out from calendar event pages.
This commit is contained in:
2026-05-14 12:17:09 +02:00
parent bf252a9e9b
commit 09b5e7725d
29 changed files with 390 additions and 112 deletions
+29 -9
View File
@@ -99,7 +99,6 @@ This client talks to the web app's backend proxy routes. `baseUrl` defaults to a
| Function or method | What it does |
| --- | --- |
| `parseHafasJourneys(json, hafasDate, queryDate)` | Internal parser that converts raw HAFAS `outConL` data into shared `Journey` objects. It parses scheduled and realtime times, computes delay, extracts train names, change count, platform, and cancellation state. |
| `buildUrl(base, path, params)` | Internal helper that builds a URL and encodes query parameters. |
| `ApiClient.constructor(baseUrl?)` | Stores the backend base URL. |
| `ApiClient.getHealth()` | Calls `/api/health` and returns the health payload, throwing on non-OK responses. |
@@ -109,7 +108,7 @@ This client talks to the web app's backend proxy routes. `baseUrl` defaults to a
| `ApiClient.fetchCalendar(url, days?)` | Calls `/api/calendar` for a remote ICS URL and returns normalized `CalendarEvent[]`. |
| `ApiClient.parseCalendarIcs(content)` | POSTs raw ICS content to `/api/calendar/parse` and returns normalized `CalendarEvent[]`. |
| `ApiClient.hafasRequest(body)` | POSTs an arbitrary allowed HAFAS body to `/api/hafas`. Used for `TripSearch` and `LocMatch`. |
| `ApiClient.searchJourneys(fromStationExtId, toStationExtId, date)` | Builds a HAFAS `TripSearch`, sends it to `/api/hafas`, and parses the response into `Journey[]`. |
| `ApiClient.searchJourneys(fromStationExtId, toStationExtId, date)` | Builds a HAFAS `TripSearch`, sends it to `/api/hafas`, and parses the response into `Journey[]` with the shared `parseHafasJourneys` from `@timetoleave/core`. |
| `ApiClient.reverseGeocode(lat, lng)` | Calls `/api/geocode/reverse`. Note: the current web app does not define this route, so callers should tolerate `null` or failures. |
| `ApiClient.findNearbyStops(lat, lng, radius?)` | Calls `/api/wienerlinien/stops` and returns nearby stops. |
| `ApiClient.searchStation(query)` | Uses HAFAS `LocMatch` through `/api/hafas` to search station names. |
@@ -133,7 +132,7 @@ Defines environment-backed service URLs and defaults:
| `OSRM_URL` | Routing endpoint for bike and walk routes. |
| `WIENER_LINIEN_API_URL` | Wiener Linien API base. |
| `DEFAULT_DAYS` | Default calendar import horizon. |
| `DEFAULT_STATION_NAME`, `DEFAULT_STATION_EXT_ID` | Web fallback origin station. |
| `DEFAULT_STATION`, `DEFAULT_STATION_NAME`, `DEFAULT_STATION_EXT_ID` | Web fallback origin. The default origin is Goethegasse 36, 2340 Moedling, using Mödling Bahnhof as the nearest transit station fallback. |
| `APP_VERSION` | Health endpoint version string. |
### `apps/web/src/lib/api-service.ts`
@@ -162,6 +161,12 @@ Generic HTTP helper layer used by service clients.
| `ApiClient.cacheStats()` | Exposes underlying cache stats. |
| `ApiClient.clearCache()` | Clears the underlying cache. |
### `apps/web/src/lib/api.ts`
| Export | What it does |
| --- | --- |
| `api` | Shared browser-side `@timetoleave/api-client` instance with the default same-origin base URL. Web hooks import this singleton instead of creating their own client instances. |
### `apps/web/src/lib/api-guards.ts`
| Function | What it does |
@@ -200,10 +205,9 @@ Generic HTTP helper layer used by service clients.
| Function, class, or method | What it does |
| --- | --- |
| `parseHafasJourneys(json, hafasDate, queryDate)` | Converts raw HAFAS trip responses into shared `Journey[]` using `parseHafasTime`. |
| `HafasClient.constructor(baseUrl?, timeoutMs?)` | Creates an internal retrying `ApiClient` for live HAFAS calls. Caching is disabled because journey data changes often. |
| `HafasClient.searchStation(query)` | Sends HAFAS `LocMatch` and returns matching station names and extIds. |
| `HafasClient.fetchJourneys(from, to, date)` | Sends HAFAS `TripSearch` between two stations for a date and parses the journeys. |
| `HafasClient.fetchJourneys(from, to, date)` | Sends HAFAS `TripSearch` between two stations for a date and parses the journeys with the shared core HAFAS parser. |
| `HafasClient.cacheStats()` | Exposes cache stats from the internal client, mostly for debugging. |
### `apps/web/src/lib/geocoding-client.ts`
@@ -493,19 +497,31 @@ All route functions are Next.js App Router route handlers.
| `apps/mobile/src/store/eventStore.ts` | `reviveDates(json)` | Internal helper that parses stored events and converts event time strings back to `Date`. |
| `apps/mobile/src/store/eventStore.ts` | `getNotificationSettings()` | Internal helper that loads notification settings or returns defaults. |
| `apps/mobile/src/store/eventStore.ts` | `calculateLeaveByTime(event, arrivalBufferMinutes, bufferMinutes)` | Computes a fallback leave-by time from event time minus arrival buffer minus reminder buffer. It currently does not use live journey data. |
| `apps/mobile/src/store/eventStore.ts` | `scheduleEventNotification(event)` | Cancels existing notifications for an event and schedules default reminders 30 minutes, 10 minutes, and 0 minutes before leave-by time when enabled. |
| `apps/mobile/src/store/eventStore.ts` | `fireNotificationsForEvent(event, leaveByTime)` | Internal helper that schedules the standard 30 minute, 10 minute, and leave-now notifications, skipping past triggers and triggers more than two hours before the event. |
| `apps/mobile/src/store/eventStore.ts` | `scheduleEventNotification(event)` | Cancels existing notifications for one event and delegates standard reminder creation to `fireNotificationsForEvent` when notifications are enabled. |
| `apps/mobile/src/store/eventStore.ts` | `loadEvents()` | Loads persisted events from AsyncStorage. |
| `apps/mobile/src/store/eventStore.ts` | `saveEvents(events)` | Persists events to AsyncStorage. |
| `apps/mobile/src/store/eventStore.ts` | `addEvent(event)` | Adds an event, saves the list, and schedules notifications. |
| `apps/mobile/src/store/eventStore.ts` | `updateEvent(id, updates)` | Updates a stored event, saves the list, and reschedules notifications for that event. |
| `apps/mobile/src/store/eventStore.ts` | `removeEvent(id, onDone?)` | Removes an event, cancels its scheduled notifications, and calls an optional completion callback. |
| `apps/mobile/src/store/eventStore.ts` | `loadOriginStation()` | Loads the saved origin station. |
| `apps/mobile/src/store/eventStore.ts` | `loadOriginStation()` | Loads the saved origin station or returns the shared default origin at Goethegasse 36, 2340 Moedling when none is saved. |
| `apps/mobile/src/store/eventStore.ts` | `saveOriginStation(station)` | Persists the selected origin station. |
| `apps/mobile/src/store/eventStore.ts` | `loadNotificationSettings()` | Loads notification settings or returns defaults. |
| `apps/mobile/src/store/eventStore.ts` | `saveNotificationSettings(settings)` | Persists notification settings. |
| `apps/mobile/src/store/eventStore.ts` | `rescheduleAllNotifications()` | Cancels all scheduled notifications and recreates reminders for every stored event using current settings. |
| `apps/mobile/src/store/eventStore.ts` | `rescheduleAllNotifications()` | Loads events and settings together, cancels all scheduled notifications, exits early when notifications are disabled, and recreates reminders for every stored event through `fireNotificationsForEvent`. |
| `apps/mobile/src/polyfills/sharedArrayBuffer.ts` | `toWellFormedString(value)` | Internal polyfill helper that replaces malformed UTF-16 surrogate pairs. The file also polyfills `String.prototype.toWellFormed`, `String.prototype.isWellFormed`, `ArrayBuffer.prototype.resizable`, and `SharedArrayBuffer` when missing. |
### Mobile components
These components were extracted from the mobile detail screen so `EventDetailScreen` now handles orchestration while the display sections stay focused.
| File | Function/component | What it does |
| --- | --- | --- |
| `apps/mobile/src/components/EventHeader.tsx` | `EventHeader({ event, leaveByTime, arrivalBufferMinutes, colors })` | Displays the selected event title, destination, localized event time, source, leave-by time, arrive-by time, and arrival buffer. |
| `apps/mobile/src/components/JourneyList.tsx` | `JourneyList(props)` | Displays train connections, destination-station loading state, empty state based on whether an origin station exists, delay/cancellation badges, and optional final walking route summary. |
| `apps/mobile/src/components/BikeSection.tsx` | `BikeSection({ bikeRoute, loading, origin, colors })` | Displays bike route loading, empty, duration, distance, and a placeholder map area. |
| `apps/mobile/src/components/NearbyStops.tsx` | `NearbyStops({ stops, departures, loading, error, colors })` | Displays nearby destination public-transport stops or the first eight live departures. It hides itself when there is no loading state, no stops, and no error. |
### Mobile screens
| File | Function/component | What it does |
@@ -513,7 +529,7 @@ All route functions are Next.js App Router route handlers.
| `apps/mobile/src/screens/EventListScreen.tsx` | `EventListScreen({ navigation })` | Main mobile list screen. Loads events from AsyncStorage, refreshes on focus and pull-to-refresh, recalculates countdowns every 30 seconds, and lets users navigate to details, edit, delete, settings, or calendar import. Significant inner callbacks: `reload`, `onRefresh`, and `renderItem`. |
| `apps/mobile/src/screens/AddEventScreen.tsx` | `AddEventScreen({ navigation, route })` | Manual add/edit form. Loads an existing event when `editEventId` is present, validates title/destination/date/time, then calls `addEvent` or `updateEvent`. Significant inner functions: `validate` and `handleSave`. |
| `apps/mobile/src/screens/CalendarImportScreen.tsx` | `CalendarImportScreen({ navigation })` | Imports ICS URL events through the backend or syncs native device calendar events. Avoids duplicates by ID before calling `addEvent`. Significant inner functions: `handleImport` and `handleSyncNative`. |
| `apps/mobile/src/screens/EventDetailScreen.tsx` | `EventDetailScreen({ navigation, route })` | Mobile event detail and route screen. Loads event, origin station, settings, resolves destination station, searches journeys, loads bike/walk routes, displays leave-by data, and shows nearby Wiener Linien data. Significant inner functions: `fetchData` and `handleRefresh`. |
| `apps/mobile/src/screens/EventDetailScreen.tsx` | `EventDetailScreen({ navigation, route })` | Mobile event detail orchestrator. Loads event, origin station, settings, resolves destination station, searches journeys, loads bike/walk routes, computes leave-by data, manages train/bike mode selection, and passes display data to `EventHeader`, `JourneyList`, `BikeSection`, and `NearbyStops`. Significant inner functions: `fetchData` and `handleRefresh`. |
| `apps/mobile/src/screens/SettingsScreen.tsx` | `SettingsScreen({ navigation })` | Settings screen for origin station, current-location station lookup, reminder settings, advanced transport toggles, and theme toggle. Significant inner functions: `searchStation`, `onQueryChange`, `selectStation`, `useCurrentLocation`, `toggleNotifications`, `updateBufferMinutes`, `updateArrivalBuffer`, `toggleWalking`, and `toggleBike`. |
## Development Notes for New Contributors
@@ -522,12 +538,16 @@ Use `packages/core` for logic that must behave the same on web and mobile. Time
Use `packages/api-client` for calls from client code to the web backend. If a new backend route is shared by web and mobile, add a method there instead of duplicating `fetch` calls in screens.
Use `apps/web/src/lib/api.ts` when a web hook needs the shared browser API client. Creating ad-hoc `new ApiClient()` instances in each hook is no longer the local pattern.
Use `apps/web/src/lib/*` for server-side integrations and wrappers around external services. These files are the right place for caching, retries, protocol parsing, and API-specific response validation.
Use `apps/web/src/app/api/**/route.ts` for public backend proxy endpoints. Keep validation and size limits close to the route handler, then delegate external service work to `apps/web/src/lib`.
Use hooks for UI-side asynchronous state. Most web and mobile hooks follow the same pattern: inputs, `loading`, `error`, result state, debounce or refresh logic, and cleanup guards to prevent setting state after unmount.
For mobile detail UI, keep orchestration in `EventDetailScreen` and reusable display sections in `apps/mobile/src/components`. The extracted components expect already-loaded data plus the `useColors()` palette.
Be especially careful with HAFAS time handling. HAFAS dates and times are Vienna-local strings. Use `hafasDateTime()` before building requests and `parseHafasTime()` when parsing responses.
Be careful with stored dates. Web localStorage and mobile AsyncStorage serialize `Date` objects to strings, so both apps have helper functions that revive `eventTime` back into `Date`.