diff --git a/README.md b/README.md index bc346a3..98e745b 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Prepare changes through feature branches and PRs following the [review workflow] ## Data refresh and privacy -Public map/search/routing/transit providers receive the requests sent to them and the user's IP address. For timetables these are GTT (realtime feeds; trip lists and calendars of its static export; per-stop departures only if that setting is enabled) and GitHub (Pages and release assets, configured at build time) for the timetable manifest, checked automatically when a stop board opens (at most every 6 hours) or live data no longer matches the installed package, and on request, and for packages. Route providers receive route coordinates. Favorites remain on-device; no account or cloud history is created. Online services are best effort and may be unavailable. Full provider attribution, data terms, and transit-provider information are available in the app's information screen and [bundled licences and notices](src/data/licenses.json). +Public map/search/routing/transit providers receive the requests sent to them and the user's IP address. For timetables these are GTT (realtime feeds; trip lists and calendars of its static export; per-stop departures only if that setting is enabled) and GitHub (Pages and release assets, configured at build time) for the timetable manifest, checked automatically when a stop board opens (at most every 6 hours) or live data no longer matches the installed package, and on request, and for packages. Route providers receive route coordinates. Transitous receives only the selected rail station's or stop's identifier, and only after an explicit action and its disclosure (rail station boards, **Cerca su Transitous** on a stop board without GTT realtime). Favorites remain on-device; no account or cloud history is created. Online services are best effort and may be unavailable. Full provider attribution, data terms, and transit-provider information are available in the app's information screen and [bundled licences and notices](src/data/licenses.json). The APK bundles a validated GTT timetable package, so stop boards are expected to work offline on first launch; native acceptance of import time and first-launch behaviour is pending. GTT re-issues trip IDs for unchanged trips, so live updates are also joined by schedule identity (route, direction, shape, first departure) using only the trip list, calendars and feed metadata read directly from GTT's export with small ranged requests. Optionally, the app checks a manifest published by this repository's workflow (GitHub Pages, then a data-only prerelease that is never marked latest) and installs newer hashed (not signed) timetable packages after verification, keeping the previous one for rollback. Place data still ships only through a rebuilt APK. Follow the [data preparation workflow](docs/development/data.md) to render the pinned extraction SQL, validate inputs, preserve provenance and prepare reviewed packages. diff --git a/docs/development/data.md b/docs/development/data.md index bf9f234..651da72 100644 --- a/docs/development/data.md +++ b/docs/development/data.md @@ -46,6 +46,8 @@ GTT rotates trip IDs between daily exports while stop IDs stay stable, and most ### Publication +**Status (2026-11): no mirror is configured and the workflow is disabled.** GTT's static-export host refuses connections from GitHub-hosted runners (two runs failed with a TCP connect timeout while the same URL answered from an Italian connection), so the pipeline cannot build in GitHub Actions. `TIMETABLE_MIRRORS` is empty, so devices make no mirror requests; timetable freshness comes with app releases, and rotated trip IDs are handled by the direct GTT identity remap. Re-enabling requires running the pipeline from a host that can reach GTT and listing the mirrors again. + Mirrors are an optional freshness layer: boards work fully without them (bundled package, direct GTT identity remap below, GTT realtime). The app reads an ordered list of mirrors from `TIMETABLE_MIRRORS` in `src/transit-data/config.ts` and uses the next one only when one fails: GitHub Pages (`manifest.json`, `packages/gtt-.json`), then the assets of one rolling GitHub **prerelease** tagged `gtt-timetable` (`manifest.json`, `gtt-.json`; release assets cannot contain `/`). The data prerelease is created with `--prerelease --latest=false`, re-asserted on every run, and its assets are replaced in place (packages first, then the manifest, then stale assets removed), so release trackers such as Obtainium keep following the app's own latest release. Its notes say it is not an app release. `.github/workflows/gtt-timetable.yml` runs at 03:15, 06:15, 12:15 and 18:15 UTC and on manual dispatch. `scripts/gtt-pipeline.py` downloads the ZIP with `If-None-Match`/`If-Modified-Since` from the published manifest, builds and validates the package, and publishes to GitHub Pages only when the package hash changed, or when the published upstream confirmation is older than 20 hours (a manifest-only heartbeat, so devices can tell an unchanged upstream from a stalled pipeline). Previous packages are re-downloaded, re-verified and kept beside the current one. The workflow uses no secrets and never receives signing credentials; the release-mirror job alone has `contents: write` (needed for release assets), checks out no code and only uploads the verified files. The Pages deployment is opt-in: set **Settings → Pages → Build and deployment → Source: GitHub Actions**, then the repository variable `GTT_PAGES_ENABLED` to `true`. Without it only the Releases mirror is updated, and because the pipeline reads the previous manifest from Pages, each run then publishes a fresh package set without carried rollback packages. diff --git a/docs/development/navigation.md b/docs/development/navigation.md index 641b1be..5f37a04 100644 --- a/docs/development/navigation.md +++ b/docs/development/navigation.md @@ -1,6 +1,6 @@ # Android navigation implementation and acceptance -Version 0.1.8 / Android code 9 introduced explicit navigation; the current interface uses **Avvia** for walking, cycling, driving and the selected transit journey. Route previews and saved itineraries remain planning until that action succeeds. Navigation is Android-only; the browser and Expo Go cannot run the native session. +Version 0.1.8 / Android code 9 introduced explicit navigation; the current interface uses **Avvia** for walking, cycling and driving, and **Segui viaggio** for the selected transit journey (in Mezzi the primary action is **Cerca percorsi** until transit alternatives exist; it never starts road guidance). Route previews and saved itineraries remain planning until that action succeeds. Navigation is Android-only; the browser and Expo Go cannot run the native session. The local Expo module uses Ferrostar **0.57.0** for road progress, maneuver triggers and route deviation. Android owns platform positioning (GPS, plus the platform fused and network providers when the system offers them), the location foreground service, bounded FOSSGIS requests and offline Italian text-to-speech. This uses the published native core through UniFFI/JNA, with the existing MapLibre renderer and NativeWind interface. No Ferrostar React Native package, Compose UI, Google location service, account, paid routing provider or application backend is required. @@ -12,14 +12,14 @@ The local Expo module uses Ferrostar **0.57.0** for road progress, maneuver trig | Position quality | Active guidance requires precise permission. The following applies to walking, cycling and driving; transit following starts without a fix and GPS loss only suspends its advisory proximity cues. While waiting, the interface shows elapsed time and the latest fix accuracy against the required bound; after 30 seconds without a usable fix it settles into a stable "position not found" state with Retry and Stop. Every mode may start from a fix of 50 metres or better after 15 seconds, visibly labelled as a reduced-accuracy start. Guidance continues with fixes up to 50 metres; a fix worse than the mode's normal accuracy shows a reduced-precision label instead of pausing. Three consecutive rejected samples (beyond 50 metres, stale, invalid or implausible jumps) or 8 seconds without an accepted one suspend guidance; one accepted fix resumes it (two distinct fixes when driving). GPS and platform-fused copies of the same sample count once. A successful route is never discarded because of a transient poor fix. The interface retains an explicitly labelled last position. | Denied/approximate permission, GPS disabled, tunnels, stale/inaccurate fixes and permission revocation on Android without Play services. | | Voice | Select an installed Italian voice that declares no network requirement. Missing voice leaves visual guidance available. Mute, audio focus and stop flush speech; the app does not download a voice. | Installed/missing offline Italian voice, audio interruption, mute/unmute and prompt timing with the screen off. A successful compile does not establish audible speech. | | Deviation and routing | Android previews, Start and reroutes share one serialized HTTP owner with at least 1.1 seconds between starts. Sustained deviation can request a reroute within a shared cooldown, movement and rolling-attempt budget. HTTP 429 enforces at least one minute or the longer supplied cooldown; cancellation stops queued/in-flight work. | Wrong turn, reconnection, HTTP failure/429, reroute limits and original-preview cancellation on the rebuilt APK. No full offline road routing or live traffic. | -| Transit journey | Start follows the selected MATO itinerary locally, preserving line, direction, stop, timing status and consultation age. Following starts without a position fix or origin check; an aged itinerary starts with its consultation age shown and a refresh offer. A journey whose planned end or next boarding (while aboard: the next connection) is more than one minute past is flagged, including during access walking, with a replanning action; the interface re-evaluates this at least every 15 seconds. Walking/transfer completion, boarding and alighting require explicit confirmation. GPS proximity supplies advisory stop cues; only the provider's explicit same-vehicle flag joins transit legs. | Real walking access, boarding, riding, alighting and transfers. Confirm controls must work without GPS. Loop/nearby-endpoint legs require manual checks; they cannot imply actual onboard presence. | +| Transit journey | Start follows the selected MATO itinerary locally, preserving line, direction, stop, timing status and consultation age. Following starts without a position fix or origin check; an aged itinerary starts with its consultation age shown and a refresh offer. A journey whose planned end or next boarding (while aboard: the next connection) is more than one minute past is flagged, including during access walking, with a replanning action; the interface re-evaluates this at least every 15 seconds. Walking/transfer completion, boarding and alighting require explicit confirmation on a dedicated following screen (access walk, waiting at the stop, riding, transfer, final walk, arrived), each with its next action (**Sono alla fermata**, **Sono a bordo**, **Sono sceso**, **Sono arrivato**) beside Stop. The next boarding shows the GTT board of its validated stop (shared citywide feed, arrivals cadence, foreground only): a departure joined by trip ID or by the same line and scheduled time (only when unique) keeps its board provenance; otherwise it reads **Corsa non confermata**. GPS proximity supplies advisory stop cues; only the provider's explicit same-vehicle flag joins transit legs. | Real walking access, boarding, riding, alighting and transfers. Confirm controls must work without GPS. Loop/nearby-endpoint legs require manual checks; they cannot imply actual onboard presence. | | Transit uncertainty | Missing stop proximity stays unavailable. Walking legs show the supplied map trace and explicitly lack turn instructions. The selected journey ages during guidance; departures, cancellations and connections are not continuously monitored or automatically replanned. Only a cancelled journey requires replanning; age and passed times remain visible advisories. | Compare against the operator and verify stale/missing/cancelled cases. MATO source freshness and reuse/availability limitations remain unresolved. | | Lifetime and stop | Explicit Start promotes a location foreground service with a private generic notification and Stop action. UI remounts attach to the session. Android Back asks whether to continue or stop active guidance; it cancels a pending Start and closes terminal states directly. Stop/arrival release positioning, speech, route work and native resources. Interrupted state is local and requires explicit resume; process restart does not silently restart travel. Notification denial is visible with an in-app Stop action. | Notification Stop, Android Back and its confirmation, UI remount, screen-off/background operation, process/service termination, force-stop, restart, physical GPS and battery use. | | Privacy | One bounded interrupted-session checkpoint stays in app-private no-backup storage. Stop/arrival clear it. Diagnostics retain fixed state/failure codes, without destinations, coordinates, itinerary contents or raw native errors. Online road calculation/rerouting sends current origin and destination to FOSSGIS; MATO planning sends itinerary endpoints to 5T. | Inspect the final manifest, runtime dependency graph, checkpoint cleanup and diagnostic report. Foreground-service permission does not imply background-location permission or reliable OS lifetime. | The native module compiles and the JVM policy/transition tests pass. These checks cover deterministic request spacing/cooldown/cancellation, fix/reroute policies, session lifetime, Italian instructions and transit transitions. **Complete physical-device acceptance of Ferrostar/JNA, GPS, TTS and foreground-service lifetime remains outstanding.** Limited development-client route/position observations do not establish outdoor progress, audible voice or screen-off reliability. Browser simulations exercise the interface; they do not close these native gates. The production browser notice viewer was inspected at 320 and 390 pixels: Ferrostar BSD, desugared OpenJDK GPL/exception and UniFFI MPL texts expand with fetch blocked, with zero fetches and no horizontal overflow. This is offline notice/interface evidence only. Final build, signature, bundled JavaScript, notice presence and 16 KB alignment need inspection on the exact release artifact. Keep observed results in [delivery.md](delivery.md), separate from this source contract. -Road guidance consumes one [packaged policy](../../modules/avoid-navigation/android/src/main/assets/road-guidance-policy.json), shared by native fix admission and the core trajectory tests. Fix admission is per mode: walking starts at 35 metres, cycling and driving at 30 metres. Guidance accepts up to 50 metres in every mode, labelling fixes worse than the normal accuracy (35 metres walking, 25 metres cycling and driving). Fixes older than 15 seconds are rejected. All road modes use Ferrostar's entry-and-snapped-exit progression with per-mode distances: passing a turn does not require a sample inside a tiny point checkpoint, lateral offset alone does not complete it, and a short final step does not require travelling beyond the destination. Step advance and arrival evaluate every fix accepted for guidance; deviation is judged only on fixes of 25 metres or better, coarser fixes neither declare nor clear deviation, and rerouting additionally needs three consecutive tight off-route fixes, so a poor signal cannot trigger a reroute. Native snapshots expose current location confidence separately from retained route/admission errors, so a lost fix cannot silently remain a transit replanning origin. Session transitions, commands and fix decisions are logged under the `AvoidNav` tag as fixed codes with bounded metadata (mode, state flags, accuracy, provider, fix age, counters, plan age in minutes and exception class names), without coordinates, destinations, itinerary contents or raw native messages. +Road guidance consumes one [packaged policy](../../modules/avoid-navigation/android/src/main/assets/road-guidance-policy.json), shared by native fix admission and the core trajectory tests. Fix admission is per mode: walking starts at 35 metres, cycling and driving at 30 metres. Guidance accepts up to 50 metres in every mode, labelling fixes worse than the normal accuracy (35 metres walking, 25 metres cycling and driving). Fixes older than 15 seconds are rejected. All road modes use Ferrostar's entry-and-snapped-exit progression with per-mode distances: passing a turn does not require a sample inside a tiny point checkpoint, lateral offset alone does not complete it, and a short final step does not require travelling beyond the destination. Step advance and arrival evaluate every fix accepted for guidance; deviation is judged only on fixes of 25 metres or better, coarser fixes neither declare nor clear deviation, and rerouting additionally needs three consecutive tight off-route fixes, so a poor signal cannot trigger a reroute. Start payloads are built explicitly (`src/domain/navigation-payload.ts`) from the fields native code reads, with absent optional fields omitted: Expo Modules rejects a nested `undefined` or `null` inside a `Map` argument with ERR_UNEXPECTED before the Kotlin body runs, and the checkpoint's JSON rejects non-finite numbers. Native snapshots expose current location confidence separately from retained route/admission errors, so a lost fix cannot silently remain a transit replanning origin. Session transitions, commands and fix decisions are logged under the `AvoidNav` tag as fixed codes with bounded metadata (mode, state flags, accuracy, provider, fix age, counters, plan age in minutes and exception class names), without coordinates, destinations, itinerary contents or raw native messages. The [host trajectory harness](../../tests/navigation-core/README.md) executes the real Ferrostar 0.57.0 Rust controller against that policy. It covers sparse turn samples, sidewalk offset, progress/deviation at accepted accuracy and a short final step. It does not execute the Android library or UniFFI/JNA bridge; Android runtime and physical-route acceptance remain separate. diff --git a/docs/development/ux.md b/docs/development/ux.md index c157ca0..58a6834 100644 --- a/docs/development/ux.md +++ b/docs/development/ux.md @@ -35,7 +35,7 @@ The basemap follows the resolved appearance: `avoid-light` or `avoid-dark`, both ## Sheet and shared components -`src/ui/Sheet.tsx` is the only importer of the sheet library (`@gorhom/bottom-sheet`). The task sheet rests at **peek**, **half** or **full**; heights are fixed per task and window (`sheet-model.ts`), so loading content never moves it. Lists, stops and routes open at half, a place and the empty search peek, Privacy e fonti opens full. Drag, the header expand/collapse button and the handle (an adjustable control for TalkBack) move between the same snaps. Android Back lowers a sheet the user raised above its resting height, then unwinds the task stack. The header shows Close (to the map) and adds Back only when the task beneath is not the map. Camera padding follows the sheet's target height, re-centred on the camera's actual centre. When a short window gives two snaps the same height, the sheet library sees one detent and the logical snap stays consistent. The sheet is clipped above the navigation bar. Long lists use the sheet's virtualized list. +`src/ui/Sheet.tsx` is the only importer of the sheet library (`@gorhom/bottom-sheet`). The task sheet rests at **peek**, **half** or **full**; heights are fixed per task and window (`sheet-model.ts`), so loading content never moves it. Lists, stops and routes open at half, a place and the empty search peek, Privacy e fonti opens full. Drag, the header expand/collapse button and the handle (an adjustable control for TalkBack) move between the same snaps. Android Back lowers a sheet the user raised above its resting height, then unwinds the task stack. The header shows Close (to the map) and adds Back only when the task beneath is not the map. Camera padding follows the sheet's target height, re-centred on the camera's actual centre. When a short window gives two snaps the same height, the sheet library sees one detent and the logical snap stays consistent. The sheet is clipped above the navigation bar. Full sits just under the search bar. Content scrolls at full; at peek and half a content drag first raises the sheet (the library locks scrolling below the top snap). Every wrapper between the sheet and a scroller must be able to shrink (`SHRINKING_FILL`): the library sizes its content box after the first layout pass, and a plain `flex: 1` wrapper keeps its content height, leaving nothing to scroll. Long lists use the sheet's virtualized list. Build screens from `src/ui`: Button (primary, secondary, quiet), IconButton (48 dp, required label), ListRow, Chip and SegmentedControl, SectionHeader, SheetHeader, Notice (info, caution, danger, success; icon and wording, never colour alone) and TransitLineBadge. Line badges use the operator's route colour when supplied, with an AA text fallback, and distinct shapes and glyphs for metro, tram, bus and rail. GTT departures carry only line names, so only the metro (`M1`) is classified. Body text is 16 sp; departure times are larger tabular numerals. In a stop sheet, departures come first and saving is an icon action. @@ -57,13 +57,19 @@ Frame a planning route once for the requested origin, destination and mode, or w Keep current quality separate from retained coordinates. The native snapshot supplies the last accepted accuracy and current usability/problem, not the accuracy of rejected samples. Label retained numbers **Ultima posizione accettata** and paused maneuvers **Ultima indicazione**; keep their geometry while guidance is suspended. Provider selection and accuracy/age policy are separate concerns. +## Transit journeys + +In Mezzi, alternatives are concise rows: departure–arrival in Geist Mono, line badges in boarding order with change markers (a walk glyph when the change is on foot), total walking, number of changes and one word-labelled timing state (cancellation in red, passed or unconfirmed times in amber; MATO predictions have no source timestamp and are never green). The selected alternative's timeline shows at once: access walk → board (stop, public code, direction, platform when supplied, expected and timetable time with provenance) → ride (intermediate stops when MATO supplies them) → alight → transfer walk … → arrival. Strictly validated GTT endpoints link to their stop boards. The anchored primary action is **Cerca percorsi** before alternatives exist and **Segui viaggio** afterwards; it needs no position fix. + +Trasporti lists the nearest pilot rail stations above the GTT stops; a station opens a Transitous board with departures/arrivals, platforms as published, cancellations and the **Dichiarato in tempo reale · aggiornamento origine non disponibile** label. Metro-only stops say **Solo orari programmati — tempo reale non disponibile**. A stop board without GTT realtime offers **Cerca su Transitous** (see [online services](../research/online-services.md#transitous-rail-station-boards-and-explicit-stop-fallback)). + ## Active guidance -Prioritize the next instruction, map, current problem and Stop action. Present recovery beside the problem. Keep voice status and setup in navigation details. Anchor the active transit confirmation beside Stop. Preserve transit confirmation controls and uncertainty when simplifying the layout. Route previews remain planning; native voice, position and background behavior require the separate [navigation acceptance checks](navigation.md). +Prioritize the next instruction, map, current problem and Stop action. Present recovery beside the problem. Keep voice status and setup in navigation details. Anchor the active transit confirmation beside Stop. Transit following has its own screen, not the road panel: the stage and instruction on top, the next boarding with its live provenance (or **Corsa non confermata**), the stop to get off at, journey age and passed/missed warnings, then the remaining timeline; the large confirmation sits beside Stop. Preserve transit confirmation controls and uncertainty when simplifying the layout. Route previews remain planning; native voice, position and background behavior require the separate [navigation acceptance checks](navigation.md). ## Task model and modules -`src/features/app/task-model.ts` is the source of truth for which task owns the sheet: one root (map, search, Trasporti or Salvati), the detail tasks opened from it (place, stop, planner, journey stop) and Privacy e fonti on top. The sheet's back arrow closes the top task and returns to the task beneath with its context. Android Back first dismisses the keyboard and lets active guidance confirm Stop. Then it cancels origin picking as its own step, unwinds one task, and at a root collapses an expanded sheet before returning to the map. The reducer holds task choices: the selected place, stop and destination, and the planner's chosen origin with its step. Typed text, location requests and their status, fetched payloads and refresh timing stay in feature hooks. +`src/features/app/task-model.ts` is the source of truth for which task owns the sheet: one root (map, search, Trasporti or Salvati), the detail tasks opened from it (place, stop, rail station, planner, journey stop) and Privacy e fonti on top. The sheet's back arrow closes the top task and returns to the task beneath with its context. Android Back first dismisses the keyboard and lets active guidance confirm Stop. Then it cancels origin picking as its own step, unwinds one task, and at a root collapses an expanded sheet before returning to the map. The reducer holds task choices: the selected place, stop and destination, and the planner's chosen origin with its step. Typed text, location requests and their status, fetched payloads and refresh timing stay in feature hooks. Each feature under `src/features/` exposes a hook and context with intent-level actions such as `openPlace`, `openStop`, `beginRoute` and `startGuidance`. Request controllers react to task transitions synchronously: a task moved behind another task suspends, and a closed or replaced planner resets. `AppProviders` composes features in dependency order; `AppShell` lays out the map, controls and sheet. Shared primitives live in `src/ui/`. diff --git a/docs/research/online-services.md b/docs/research/online-services.md index 3e38b4c..6dc01df 100644 --- a/docs/research/online-services.md +++ b/docs/research/online-services.md @@ -55,7 +55,7 @@ Verified 2026-11-01 against the [API policy](https://transitous.org/api/), [priv **Policy.** Transitous is a volunteer, best-effort MOTIS 2 service for open-source, non-commercial projects. Requirements: source code published under an appropriate open-source licence (light prototype testing before that is allowed); an HTTP User-Agent on every request with the application name, client version and a contact (e-mail or website); a visible link to https://transitous.org/sources/ and compliance with the listed source conditions, including OpenStreetMap attribution; coordination in the project's Matrix channel for heavy use. More than about 720 requests per 24 hours of `/plan`, `/one-to-many` or `/one-to-all`, many users and automated requests are the named high-cost cases. Commercial use is not allowed. Staging and internal hosts must not be used by applications. -**Status.** The adapter lives in the services layer and no UI flow invokes it yet. The repository's application source has no licence selected (see the README), so it does not yet meet the open-source condition: until a compatible licence is chosen or Transitous agrees otherwise, use is limited to light prototype testing and the adapter must not be wired into a release. +**Status.** Wired into the interface (2026-11-02): Trasporti lists the nearest pilot rail stations, computed on the device from the bundled mapping, and a station opens a departures/arrivals board; a GTT stop board whose realtime is unavailable or not joinable offers **Cerca su Transitous**, which replaces the board's online source visibly and is never merged with GTT rows. A disclosure listing what is sent precedes the first request; its acknowledgement is stored only on the device. Requests follow explicit actions (opening a station, switching departures/arrivals, the refresh control) and nothing polls. The application source is published under GPL-3.0-or-later, meeting the policy's open-source condition; keep the request volume light and coordinate before any heavier use. **Privacy.** Server logs store IP address, request time, requested URL and User-Agent for up to two days. The URL contains whatever the request sends, so the app sends only the selected stop/station/trip identifier or the typed search text plus fixed parameters identical for every user. It never sends the device position, a place bias, language preference or device data. The User-Agent is `AvoidMaps/ (+https://github.com/avoid-quest/maps)`. diff --git a/docs/research/turin-transit-data.md b/docs/research/turin-transit-data.md index 55d7867..34ccbc7 100644 --- a/docs/research/turin-transit-data.md +++ b/docs/research/turin-transit-data.md @@ -2,7 +2,7 @@ Research date: **2026-10-11**. Endpoint probes were bounded anonymous HTTPS requests; the three GTT real-time feeds were sampled once at about **13:29 UTC / 15:29 Europe/Rome**. Counts below describe that snapshot, not guaranteed coverage, uptime or prediction accuracy. Large downloads stayed outside the repository. This note evaluates regional transit sources for an Android application with local data processing and direct public-data access; each source retains its documented usage terms. -Update 2026-11-01: Transitous (MOTIS) returned Trenitalia SFM/regional departures with declared realtime for Turin stations and GTT stop times with realtime via BusOne. A services-layer adapter is prepared as the online provider for a bounded rail-station pilot and as an explicitly invoked fallback for GTT stop boards; no UI flow invokes it yet, and MATO is not used for these. Endpoints, policy, identifiers and interpretation rules are in [online services](online-services.md#transitous-rail-station-boards-and-explicit-stop-fallback). +Update 2026-11-01: Transitous (MOTIS) returned Trenitalia SFM/regional departures with declared realtime for Turin stations and GTT stop times with realtime via BusOne. A services-layer adapter is prepared as the online provider for a bounded rail-station pilot and as an explicitly invoked fallback for GTT stop boards; both are reachable in the interface only through explicit actions, and MATO is not used for these. Endpoints, policy, identifiers and interpretation rules are in [online services](online-services.md#transitous-rail-station-boards-and-explicit-stop-fallback). ## Update 2026-11-01: rotating trip IDs, delay-only predictions and the timetable package diff --git a/src/domain/navigation-payload.test.ts b/src/domain/navigation-payload.test.ts new file mode 100644 index 0000000..a04a3e0 --- /dev/null +++ b/src/domain/navigation-payload.test.ts @@ -0,0 +1,100 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { parseTransitRoutes, type MatoResponse } from '../services/routing'; +import { createSavedTravel } from '../services/saved-travel'; +import { guidanceStart } from '../features/planner/transit-journey'; +import { BridgePayloadError, bridgeSafetyProblem, nativeRoadStart, nativeTransitPlan, nativeTransitStart } from './navigation-payload'; + +const T = Date.parse('2026-11-02T11:00:00Z'); +const at = (minutes: number) => T + minutes * 60_000; +const place = (name: string, lat: number, lon: number, code?: string) => ({ name, lat, lon, stop: code ? { gtfsId: `gtt:${code}`, name, code, platformCode: null } : null }); +// A Politecnico-style MATO answer: access walk, bus 10N, transfer walk, bus 68 (public stops; synthetic times). +const mato: MatoResponse = { data: { plan: { itineraries: [{ + duration: 1800, startTime: at(0), endTime: at(30), walkTime: 600, walkDistance: 700, waitingTime: 0, + legs: [ + { mode: 'WALK', transitLeg: false, duration: 240, distance: 300, realTime: false, realtimeState: null, interlineWithPreviousLeg: false, startTime: at(0), endTime: at(4), + route: null, trip: null, from: place('Origin', 45.07, 7.68), to: place('PORTA NUOVA', 45.062, 7.678, '1'), legGeometry: { points: '_p~iF~ps|U_ulLnnqC' } }, + { mode: 'BUS', transitLeg: true, duration: 600, distance: 2500, realTime: false, realtimeState: 'SCHEDULED', interlineWithPreviousLeg: false, startTime: at(5), endTime: at(15), + departureDelay: 0, arrivalDelay: 0, serviceDate: '20261102', route: { shortName: '10N', longName: null }, trip: { gtfsId: 'gtt:1U', tripHeadsign: null }, + from: place('PORTA NUOVA', 45.062, 7.678, '1'), to: place('POLITECNICO', 45.063, 7.66, '2'), intermediatePlaces: [], legGeometry: { points: '_p~iF~ps|U_ulLnnqC' } }, + { mode: 'WALK', transitLeg: false, duration: 120, distance: 100, realTime: false, realtimeState: null, interlineWithPreviousLeg: false, startTime: at(15), endTime: at(17), + route: null, trip: null, from: place('POLITECNICO', 45.063, 7.66, '2'), to: place('BOTTA', 45.064, 7.659, '3'), legGeometry: null }, + { mode: 'BUS', transitLeg: true, duration: 600, distance: 2000, realTime: true, realtimeState: 'UPDATED', interlineWithPreviousLeg: false, startTime: at(18), endTime: at(28), + departureDelay: 60, arrivalDelay: 60, serviceDate: '20261102', route: { shortName: '68', longName: null }, trip: { gtfsId: 'gtt:2U', tripHeadsign: 'CAPPUCCINI' }, + from: place('BOTTA', 45.064, 7.659, '3'), to: place('CASTELLO', 45.07, 7.686, '4'), + intermediatePlaces: [{ name: 'X', arrivalTime: at(20), lat: 45.065, lon: 7.66, stop: { gtfsId: 'gtt:5', name: 'X', code: '5', platformCode: null } }], legGeometry: { points: '_p~iF~ps|U_ulLnnqC' } }, + { mode: 'WALK', transitLeg: false, duration: 120, distance: 300, realTime: false, realtimeState: null, interlineWithPreviousLeg: false, startTime: at(28), endTime: at(30), + route: null, trip: null, from: place('CASTELLO', 45.07, 7.686, '4'), to: place('Destination', 45.071, 7.687), legGeometry: { points: '_p~iF~ps|U_ulLnnqC' } }, + ], +}] } } }; +const endpoints = { origin: { latitude: 45.07, longitude: 7.68 }, destination: { latitude: 45.071, longitude: 7.687 } }; + +test('root cause: the UI plan carries undefined fields, which the Expo bridge cannot convert', () => { + const [plan] = parseTransitRoutes(mato, T); + const start = guidanceStart('transit', plan!, false, endpoints); + assert.equal(start?.kind, 'transit'); + // Exactly what startTransitNavigation used to send: walk legs have line/headsign/tripId === undefined. + assert.match(bridgeSafetyProblem(start!.options) ?? '', /^payload\.plan\.legs\[0\]\.line: undefined$/); +}); + +test('the native transit payload is bridge-safe and carries exactly what TransitJourneyEngine reads', () => { + const [plan] = parseTransitRoutes(mato, T); + const start = guidanceStart('transit', plan!, false, endpoints)!; + assert.equal(start.kind, 'transit'); + const payload = nativeTransitStart(start.kind === 'transit' ? start.options : (undefined as never)); + assert.equal(bridgeSafetyProblem(payload), null); + assert.deepEqual(JSON.parse(JSON.stringify(payload)), payload, 'JSON round trip (native checkpoint) changes nothing'); + assert.deepEqual(Object.keys(payload), ['plan', 'origin', 'destination']); + assert.deepEqual(Object.keys(payload.plan), ['mode', 'fetchedAt', 'source', 'geometry', 'legs']); + assert.equal(payload.plan.fetchedAt, T, 'the follow screen matches the session by retrieval time'); + assert.equal(payload.plan.legs.length, plan!.legs.length, 'and by leg count'); + const walk = payload.plan.legs[0]!; + assert.deepEqual(Object.keys(walk).sort(), ['arrivalAt', 'departureAt', 'distanceMeters', 'durationSeconds', 'from', 'geometry', 'interlineWithPreviousLeg', 'mode', 'timingStatus', 'to', 'toStop', 'transitLeg']); + const bus = payload.plan.legs[3]!; + assert.equal(bus.line, '68'); + assert.equal(bus.headsign, 'CAPPUCCINI'); + assert.deepEqual(bus.fromStop, { coordinate: { latitude: 45.064, longitude: 7.659 } }); + assert.equal('intermediateStops' in bus, false); + assert.equal('scheduledDepartureAt' in bus, false); + assert.equal(payload.plan.legs[1]!.headsign, undefined, 'an absent headsign is omitted, not sent'); + assert.equal('headsign' in payload.plan.legs[1]!, false); + for (const leg of payload.plan.legs) assert.ok(leg.departureAt > 0 && leg.arrivalAt >= leg.departureAt); +}); + +test('a journey restored from saved travel is also sent bridge-safe', async () => { + const [plan] = parseTransitRoutes(mato, T); + const values = new Map(); + const storage = { getItem: async (key: string) => values.get(key) ?? null, setItem: async (key: string, value: string) => { values.set(key, value); }, removeItem: async (key: string) => { values.delete(key); } }; + const store = createSavedTravel({ now: () => T + 1000 }); + await store.initialize(storage); + assert.equal(await store.saveJourney({ query: { from: endpoints.origin, to: endpoints.destination, mode: 'transit', transitTime: { kind: 'now' } }, originLabel: 'A', destinationLabel: 'B', plan: plan! }), true); + const reloaded = createSavedTravel(); + await reloaded.initialize(storage); + const restored = reloaded.getSnapshot().journey!.plan; + assert.notEqual(bridgeSafetyProblem({ plan: restored }), null, 'the saved copy keeps undefined optional fields too'); + assert.equal(bridgeSafetyProblem(nativeTransitStart({ plan: restored, ...endpoints })), null); + assert.deepEqual(nativeTransitPlan(restored), nativeTransitPlan(plan!)); +}); + +test('road Start sends only the destination point and mode; unsafe values never reach the bridge', () => { + const destination = Object.assign({ latitude: 45.07, longitude: 7.68 }, { accuracy: undefined, label: null }); + assert.deepEqual(nativeRoadStart({ destination, mode: 'walk' }), { destination: { latitude: 45.07, longitude: 7.68 }, mode: 'walk' }); + assert.throws(() => nativeRoadStart({ destination: { latitude: Number.NaN, longitude: 7 }, mode: 'walk' }), BridgePayloadError); + const [plan] = parseTransitRoutes(mato, T); + assert.throws(() => nativeTransitStart({ plan: { ...plan!, fetchedAt: Number.POSITIVE_INFINITY }, ...endpoints }), (error: unknown) => error instanceof BridgePayloadError && error.code === 'invalid'); + assert.match(bridgeSafetyProblem({ when: new Date(0) }) ?? '', /Date instance/); + assert.match(bridgeSafetyProblem({ list: [1, null] }) ?? '', /list\[1\]: null/); + assert.match(bridgeSafetyProblem({ call: () => 1 }) ?? '', /function/); + assert.match(bridgeSafetyProblem([1, , 3]) ?? '', /hole/); +}); + +test('road and walking-only plans never produce a transit Start, and the platform sends the explicit payloads', () => { + const [plan] = parseTransitRoutes(mato, T); + assert.equal(guidanceStart('walk', plan!, false, endpoints), null); + assert.equal(guidanceStart('transit', plan!, true, endpoints), null); + assert.equal(guidanceStart('transit', { ...plan!, legs: plan!.legs.filter(leg => !leg.transitLeg) }, false, endpoints), null); + const source = readFileSync(new URL('../platform/navigation.ts', import.meta.url), 'utf8'); + assert.match(source, /startNavigation\(nativeRoadStart\(options\)\)/); + assert.match(source, /startTransitNavigation\(nativeTransitStart\(options\)\)/); +}); diff --git a/src/domain/navigation-payload.ts b/src/domain/navigation-payload.ts new file mode 100644 index 0000000..71fa51a --- /dev/null +++ b/src/domain/navigation-payload.ts @@ -0,0 +1,85 @@ +import type { NavigationStart, TransitNavigationStart } from './navigation'; +import type { Coordinate, RouteLeg, RoutePlan, RouteStop } from './types'; + +/** + * Payloads handed to the Android navigation module. + * + * Expo Modules converts a JavaScript object argument typed `Map` with its `Any` + * converter: every nested value must be a boolean, number, string, array or object. A nested + * `undefined` or `null` is not handled there (the converter calls `asObject` on it) and the call is + * rejected with ERR_UNEXPECTED before the Kotlin function body runs. The native checkpoint also + * stores the plan as JSON, which rejects NaN and infinities. So the payloads are built explicitly + * from the fields the native code reads, omitting absent optional fields instead of sending them. + */ +export type BridgeValue = string | number | boolean | BridgeValue[] | { [key: string]: BridgeValue }; + +/** Where a value is not bridge-safe, or null when it is. */ +export function bridgeSafetyProblem(value: unknown, path = 'payload', depth = 0): string | null { + if (depth > 12) return `${path}: too deep`; + if (typeof value === 'string' || typeof value === 'boolean') return null; + if (typeof value === 'number') return Number.isFinite(value) ? null : `${path}: non-finite number`; + if (value === undefined) return `${path}: undefined`; + if (value === null) return `${path}: null`; + if (Array.isArray(value)) { + for (let index = 0; index < value.length; index++) { + if (!(index in value)) return `${path}[${index}]: hole`; + const problem = bridgeSafetyProblem(value[index], `${path}[${index}]`, depth + 1); + if (problem) return problem; + } + return null; + } + if (typeof value === 'object') { + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) return `${path}: ${prototype?.constructor?.name ?? 'class'} instance`; + for (const [key, item] of Object.entries(value)) { + const problem = bridgeSafetyProblem(item, `${path}.${key}`, depth + 1); + if (problem) return problem; + } + return null; + } + return `${path}: ${typeof value}`; +} + +/** A coordinate with only its two numbers, whatever else the source object carries. */ +export const bridgePoint = ({ latitude, longitude }: Coordinate) => ({ latitude, longitude }); +const point = bridgePoint; +function stop(value: RouteStop | undefined): { coordinate: { latitude: number; longitude: number } } | undefined { + // TransitJourneyEngine reads only the stop coordinate (for advisory proximity). + return value?.coordinate ? { coordinate: point(value.coordinate) } : undefined; +} +function defined>(value: T): { [K in keyof T]: Exclude } { + return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as { [K in keyof T]: Exclude }; +} + +/** One leg as TransitJourneyEngine reads it. */ +function nativeLeg(leg: RouteLeg) { + return defined({ + mode: leg.mode, transitLeg: leg.transitLeg, interlineWithPreviousLeg: leg.interlineWithPreviousLeg, timingStatus: leg.timingStatus, + line: leg.line, headsign: leg.headsign, from: leg.from, to: leg.to, + fromStop: stop(leg.fromStop), toStop: stop(leg.toStop), + distanceMeters: leg.distanceMeters, durationSeconds: leg.durationSeconds, departureAt: leg.departureAt, arrivalAt: leg.arrivalAt, + geometry: leg.geometry.map(point), + }); +} + +/** The plan as the native session reads and checkpoints it: mode, retrieval time, source, overview geometry and legs. */ +export function nativeTransitPlan(plan: RoutePlan) { + return { mode: plan.mode, fetchedAt: plan.fetchedAt, source: plan.source, geometry: plan.geometry.map(point), legs: plan.legs.map(nativeLeg) }; +} + +export class BridgePayloadError extends Error { + readonly code = 'invalid'; + constructor(readonly problem: string) { super('invalid'); this.name = 'BridgePayloadError'; } +} +function checked(payload: T): T { + const problem = bridgeSafetyProblem(payload); + if (problem) throw new BridgePayloadError(problem); + return payload; +} + +export function nativeTransitStart(options: TransitNavigationStart) { + return checked({ plan: nativeTransitPlan(options.plan), origin: point(options.origin), destination: point(options.destination) }); +} +export function nativeRoadStart(options: NavigationStart) { + return checked({ destination: point(options.destination), mode: options.mode }); +} diff --git a/src/domain/types.ts b/src/domain/types.ts index d5a9b3d..ba9db18 100644 --- a/src/domain/types.ts +++ b/src/domain/types.ts @@ -21,9 +21,15 @@ export interface RouteStep { instruction: string; distanceMeters: number; coordi export interface RouteStop { id: string; name: string; code?: string; coordinate?: Coordinate; platformCode?: string; } +/** A stop the vehicle serves between boarding and alighting, as supplied by the planner. */ +export interface RouteIntermediateStop { id: string; name: string; code?: string; coordinate?: Coordinate; arrivalAt?: number } export interface RouteLeg { id: string; mode: string; line?: string; headsign?: string; from: string; to: string; fromStop?: RouteStop; toStop?: RouteStop; tripId?: string; serviceDate?: string; + /** Planner-supplied stops between `fromStop` and `toStop`; absent when the request did not ask for them. */ + intermediateStops?: RouteIntermediateStop[]; + /** Timetable times, only when the planner reports a realtime delay that moves `departureAt`/`arrivalAt`. */ + scheduledDepartureAt?: number; scheduledArrivalAt?: number; transitLeg: boolean; interlineWithPreviousLeg: boolean; timingStatus: 'scheduled' | 'prediction' | 'cancelled' | 'unknown'; durationSeconds: number; distanceMeters: number; departureAt?: number; arrivalAt?: number; diff --git a/src/features/app/AppProviders.tsx b/src/features/app/AppProviders.tsx index 71ea92a..6a87e31 100644 --- a/src/features/app/AppProviders.tsx +++ b/src/features/app/AppProviders.tsx @@ -2,6 +2,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage'; import { useEffect, useRef, type ReactNode } from 'react'; import { savedTravel } from '../../services/saved-travel'; import { searchPreferences } from '../../services/search-preferences'; +import { transitousConsent } from '../../services/transitous-consent'; import { useDeviceLocation } from '../map/useDeviceLocation'; import { useMapCamera } from '../map/useMapCamera'; import { MapProvider, useMapModel } from '../map/useMapModel'; @@ -34,7 +35,7 @@ export function AppProviders({ children }: { children: ReactNode }) { const map = useMapModel({ tasks, camera, location }); const places = usePlaces({ tasks, camera, location, sheet, feedback }); const search = useSearch({ tasks, camera, location, sheet, appActive, navigationVisible: navigation.visible }); - const transit = useTransit({ tasks, camera, location, sheet, appActive, navigationVisible: navigation.visible }); + const transit = useTransit({ tasks, camera, location, sheet, appActive, navigation }); const planner = usePlanner({ tasks, camera, location, places, navigation, sheet, appActive, suspendBoard: transit.suspend }); const shell = useShellController({ tasks, camera, location, sheet, search }); suspendActiveWork.current = () => { planner.suspend(); transit.suspend(); }; @@ -42,6 +43,7 @@ export function AppProviders({ children }: { children: ReactNode }) { useEffect(() => { void searchPreferences.initialize(AsyncStorage); void savedTravel.initialize(AsyncStorage); + void transitousConsent.initialize(AsyncStorage); }, []); return ( diff --git a/src/features/app/AppShell.tsx b/src/features/app/AppShell.tsx index b046215..5b70b8e 100644 --- a/src/features/app/AppShell.tsx +++ b/src/features/app/AppShell.tsx @@ -8,10 +8,12 @@ import { formatDistance } from "../../ui/format"; import { mapCameraPadding } from "../map/map-presentation"; import { useMapContext } from "../map/useMapModel"; import { NavigationPanel } from "../navigation/NavigationPanel"; +import { TransitFollowPanel } from "../navigation/TransitFollowPanel"; import { useNavigationContext } from "../navigation/useNavigation"; import { usePlannerContext } from "../planner/usePlanner"; import { SearchField } from "../search/SearchField"; import { useSearchContext } from "../search/useSearch"; +import { useTransitContext } from "../transit/useTransit"; import { AppMap } from "./AppMap"; import { useFeedback } from "./feedback"; import { useSheet } from "./sheet"; @@ -49,6 +51,7 @@ export function AppShell() { const feedback = useFeedback(); const shell = useShellActions(); const planner = usePlannerContext(); + const transit = useTransitContext(); const tab = rootTab(tasks); const panelVisible = sheetVisible(tasks); const heights = sheetHeights({ availableHeight, fontScale, peekContent: peekContentHeight(tasks, search.hasSearch) }); @@ -71,7 +74,12 @@ export function AppShell() { attributionLeft={wide && panelVisible && !navigation.visible ? SIDE_SHEET_WIDTH - 4 : 8} attributionTop={navigation.visible ? Math.min(height * 0.3, 104 * Math.min(fontScale, 1.5)) + 8 : 68} /> - {navigation.visible ? ( + {navigation.visible && (navigation.snapshot.mode === "transit" || (navigation.busy === "start" && navigation.startKind === "transit")) ? ( + { void navigation.stop(); }} onRetry={() => { void navigation.retry(); }} + onConfirm={action => { void navigation.confirmTransit(action); }} onReplan={() => { void planner.replanFromNavigation(); }} + onMute={() => { void navigation.toggleMuted(); }} /> + ) : navigation.visible ? ( { void navigation.stop(); }} onRetry={() => { void navigation.retry(); }} onMute={() => { void navigation.toggleMuted(); }} onConfirmTransit={action => { void navigation.confirmTransit(action); }} onReplan={() => { void planner.replanFromNavigation(); }} /> diff --git a/src/features/app/TaskSheet.tsx b/src/features/app/TaskSheet.tsx index 7684a00..0618a68 100644 --- a/src/features/app/TaskSheet.tsx +++ b/src/features/app/TaskSheet.tsx @@ -1,5 +1,5 @@ import { View } from "react-native"; -import { AppSheet, IconButton, SheetHeader, SheetScrollView, type SheetHeights, type SheetSnap } from "../../ui"; +import { AppSheet, IconButton, SheetHeader, SheetScrollView, SHRINKING_FILL, type SheetHeights, type SheetSnap } from "../../ui"; import { PlaceDetail } from "../places/PlaceDetail"; import { SavedSheet } from "../places/SavedSheet"; import { PlannerSheet } from "../planner/PlannerSheet"; @@ -10,6 +10,7 @@ import { SearchResults } from "../search/SearchResults"; import { useSearchContext, type Search } from "../search/useSearch"; import { SettingsSheet } from "../settings/SettingsSheet"; import { NearbyStops } from "../transit/NearbyStops"; +import { RailStationSheet } from "../transit/RailStationSheet"; import { StopSheet } from "../transit/StopSheet"; import { useSheet } from "./sheet"; import { sheetHeaderNavigation, toggleExpands, toggledSnap } from "./sheet-model"; @@ -21,6 +22,7 @@ function taskTitle(task: Task, search: Search): string { switch (task.kind) { case "settings": return "Privacy e fonti"; case "journeyStop": case "stop": return task.stop.name; + case "station": return task.station.name; case "planner": return task.editing === "origin" ? "Scegli la partenza" : task.editing === "destination" ? "Scegli la destinazione" : "Percorso"; case "place": return task.place.name; case "transit": return "Trasporti"; @@ -39,6 +41,7 @@ function TaskContent({ task, search, now }: { task: Task; search: Search; now: n case "planner": return ; case "place": return ; case "journeyStop": case "stop": return ; + case "station": return ; case "browse": return null; } } @@ -68,7 +71,7 @@ export function TaskSheet({ snap, resting, heights, now }: { snap: SheetSnap; re return ( : undefined} footerHeight={top.kind === "planner" && !top.editing ? ROUTE_ACTIONS_HEIGHT : 0}> - + diff --git a/src/features/app/sheet-model.test.ts b/src/features/app/sheet-model.test.ts index 012d96e..35fe9b6 100644 --- a/src/features/app/sheet-model.test.ts +++ b/src/features/app/sheet-model.test.ts @@ -16,7 +16,7 @@ test('snap heights are ordered, fixed per window and leave the search bar visibl assert.ok(peek >= 120); } const keyboard = sheetHeights({ availableHeight: 380, fontScale: 1, peekContent: 220 }); - assert.equal(keyboard.full, 244, 'a keyboard-shrunk window lowers the full snap rather than covering the search bar'); + assert.equal(keyboard.full, 304, 'a keyboard-shrunk window lowers the full snap rather than covering the search bar'); assert.equal(keyboard.peek, 220); }); @@ -59,8 +59,8 @@ test('the header shows Back only when it leads somewhere other than the map', () test('a short window with shared heights keeps logical snaps, camera padding and controls consistent', async () => { const { logicalSnapAt, physicalIndex, physicalSnaps } = await import('../../ui/sheet-snaps'); const keyboard = sheetHeights({ availableHeight: 380, fontScale: 1, peekContent: 220 }); - assert.deepEqual(keyboard, { peek: 220, half: 220, full: 244 }); - assert.deepEqual(physicalSnaps(keyboard), [220, 244], 'the gesture library never sees duplicate detents'); + assert.deepEqual(keyboard, { peek: 220, half: 220, full: 304 }); + assert.deepEqual(physicalSnaps(keyboard), [220, 304], 'the gesture library never sees duplicate detents'); assert.equal(physicalIndex(keyboard, 'half'), 0); assert.equal(physicalIndex(keyboard, 'peek'), 0); assert.equal(physicalIndex(keyboard, 'full'), 1); @@ -83,3 +83,24 @@ test('only the explicit expand control dismisses the keyboard; library-reported assert.equal(dismissesKeyboard('full', 'full', true), false); assert.equal(dismissesKeyboard('full', 'half', true), false); }); + +test('full sits just under the search bar and every snap is whole dp', () => { + // Emulator geometry: 914.29 dp window, safe-area insets leave 814.48 dp for the map and sheet. + const heights = sheetHeights({ availableHeight: 814.476, fontScale: 1, peekContent: 220 }); + assert.equal(heights.full, 738); + const sheetTop = 814.476 - 8 - heights.full; // the library places the sheet `bottomInset` (8) above the container bottom + assert.ok(sheetTop >= 64 && sheetTop <= 72, `top of the full sheet at ${sheetTop} dp, under the 64 dp search bar`); + for (const value of Object.values(heights)) assert.ok(Number.isInteger(value), `${value} is whole`); +}); + +test('guard: the library\'s exact top-detent comparison holds for every window size', () => { + // Defensive (not the cause of the scroll bug): gorhom unlocks scrolling only on exact equality. + // gorhom: highest = container - full; sheetHeight = container - highest; EXTENDED iff position === container - sheetHeight. + for (let available = 300; available <= 1400; available += 0.37) { + const container = Math.fround(available - 8); // layout sizes arrive as float32 + const { full } = sheetHeights({ availableHeight: available, fontScale: 1, peekContent: 220 }); + const highest = container - full; + const sheetHeight = container - highest; + assert.equal(container - sheetHeight, highest, `window ${available.toFixed(2)} dp keeps content scrolling unlockable`); + } +}); diff --git a/src/features/app/sheet-model.ts b/src/features/app/sheet-model.ts index 3173958..c6d0767 100644 --- a/src/features/app/sheet-model.ts +++ b/src/features/app/sheet-model.ts @@ -3,8 +3,12 @@ import { hasTaskAboveRoot, searchRoot, selectedPlace, sheetVisible, taskReducer, export { SHEET_SNAPS, type SheetHeights, type SheetSnap }; -/** Search bar, map controls and a strip of visible map stay above the fully expanded sheet. */ -export const SHEET_TOP_RESERVE = 136; +/** + * Space kept above the fully expanded sheet, in dp from the safe-area top: the search bar row + * (8 + 48 + 8 = 64), the sheet's own bottom inset (8, which the library subtracts from the top) and + * a 4 dp gap, so "full" sits just under the search bar. + */ +export const SHEET_TOP_RESERVE = 76; const MIN_HEIGHT = 120; const rank = (snap: SheetSnap) => SHEET_SNAPS.indexOf(snap); @@ -20,7 +24,9 @@ export function peekContentHeight(tasks: TaskState, hasSearch: boolean): number * (keyboard, split screen) shrinks the upper snaps first and never inverts their order. */ export function sheetHeights({ availableHeight, fontScale, peekContent }: { availableHeight: number; fontScale: number; peekContent: number }): SheetHeights { - const full = Math.max(MIN_HEIGHT, availableHeight - SHEET_TOP_RESERVE); + // Whole dp: the library unlocks content scrolling only when the sheet position equals its top + // detent exactly (a float comparison); integer snaps keep that comparison exact. + const full = Math.max(MIN_HEIGHT, Math.floor(availableHeight - SHEET_TOP_RESERVE)); const peek = Math.min(full, Math.max(MIN_HEIGHT, Math.round(peekContent * Math.min(Math.max(fontScale, 1), 1.5)))); const half = Math.min(full, Math.max(peek, Math.round(availableHeight * 0.5))); return { peek, half, full }; diff --git a/src/features/app/task-model.test.ts b/src/features/app/task-model.test.ts index 5c493e2..1878215 100644 --- a/src/features/app/task-model.test.ts +++ b/src/features/app/task-model.test.ts @@ -233,6 +233,16 @@ test('every reachable action sequence keeps a valid task stack', () => { assert.deepEqual(kinds(state), ['browse'], 'Back always reaches the map'); }); +test('a rail station board is its own detail task above Trasporti', () => { + const station = { key: 'torino-porta-susa', name: 'Torino Porta Susa', transitousStopId: 'it-trenitalia_00222', transitousName: 'TORINO PORTA SUSA', coordinate: here, transitousModes: [] }; + const state = run({ type: 'openTab', tab: 'transit' }, { type: 'openStation', station }); + assert.deepEqual(kinds(state), ['transit', 'station']); + assert.equal(detailKey(state), 'station:torino-porta-susa'); + assert.equal(boardStop(state), null, 'no GTT board polls for a station'); + assert.deepEqual(kinds(run({ type: 'openTab', tab: 'transit' }, { type: 'openStation', station }, { type: 'back' })), ['transit']); + assert.deepEqual(kinds(run({ type: 'openTab', tab: 'transit' }, { type: 'openStation', station }, { type: 'openStop', stop: porta })), ['transit', 'stop']); +}); + test('planner endpoints: search either field, choose places, swap, and Back closes the editor first', () => { let state = run({ type: 'openPlace', place: cafe }, { type: 'beginRoute', viewport, locating: true }, { type: 'originLocated', coordinate: here }, { type: 'editEndpoint', endpoint: 'destination' }); assert.equal(plannerTask(state)!.editing, 'destination'); diff --git a/src/features/app/task-model.ts b/src/features/app/task-model.ts index 820e538..0f19658 100644 --- a/src/features/app/task-model.ts +++ b/src/features/app/task-model.ts @@ -1,4 +1,5 @@ import type { Coordinate, Place, Stop, TransitTime, TravelMode } from '../../domain/types'; +import type { RailPilotStation } from '../../services/transitous-stations'; /** * Which screen the user is in, as a small stack: one root, the detail tasks opened @@ -32,14 +33,16 @@ export interface PlaceTask { kind: 'place'; place: Place } export interface StopTask { kind: 'stop'; stop: Stop } /** A stop board opened from a journey; closing it returns to its planner. */ export interface JourneyStopTask { kind: 'journeyStop'; stop: Stop } -export type DetailTask = PlaceTask | StopTask | PlannerTask | JourneyStopTask; +/** A rail pilot station's board (Transitous), opened from Trasporti. */ +export interface StationTask { kind: 'station'; station: RailPilotStation } +export type DetailTask = PlaceTask | StopTask | PlannerTask | JourneyStopTask | StationTask; export interface SettingsTask { kind: 'settings' } export type Task = RootTask | DetailTask | SettingsTask; export interface TravelChoice { mode: TravelMode; transitTime: TransitTime } export interface TaskState { root: RootTask; - /** Valid sequences: [], [place], [stop], [place?, planner, journeyStop?]. */ + /** Valid sequences: [], [place], [stop], [station], [place?, planner, journeyStop?]. */ details: readonly DetailTask[]; settings: boolean; /** The last chosen mode and time carry over to the next planner. */ @@ -67,6 +70,7 @@ export type TaskAction = | { type: 'chooseCategory'; category: string } | { type: 'openPlace'; place: Place } | { type: 'openStop'; stop: Stop } + | { type: 'openStation'; station: RailPilotStation } /** Plans to `destination`, or to the open place. `locating` reflects a usable device position. */ | { type: 'beginRoute'; destination?: Place; mode?: TravelMode; viewport: Coordinate; locating: boolean } | { type: 'restoreJourney'; destination: Place; origin: { coordinate: Coordinate; label: string }; travel: TravelChoice } @@ -174,6 +178,8 @@ export function taskReducer(state: TaskState, action: TaskAction): TaskState { return openPlace(state, action.place); case 'openStop': return { ...state, details: [{ kind: 'stop', stop: action.stop }] }; + case 'openStation': + return { ...state, details: [{ kind: 'station', station: action.station }] }; case 'beginRoute': { const base = action.destination ? openPlace(state, action.destination) : state; const place = last(base.details); @@ -283,6 +289,10 @@ export function boardStop(state: TaskState): Stop | null { const task = last(state.details); return task?.kind === 'stop' || task?.kind === 'journeyStop' ? task.stop : null; } +export function selectedStation(state: TaskState): RailPilotStation | null { + const task = last(state.details); + return task?.kind === 'station' ? task.station : null; +} export function selectedStop(state: TaskState): Stop | null { const task = state.details.find((item): item is StopTask => item.kind === 'stop'); return task?.stop ?? null; @@ -315,6 +325,7 @@ export function detailKey(state: TaskState): string { // The endpoint editor is its own content: it opens raised for typing and returns to the plan. case 'planner': return `route:${top.destination.id}${top.editing ? `:${top.editing}` : ''}`; case 'stop': return `stop:${top.stop.id}`; + case 'station': return `station:${top.station.key}`; case 'place': return `place:${top.place.id}`; case 'transit': case 'saved': return `list:${top.kind}`; case 'browse': case 'search': return 'list:explore'; @@ -327,5 +338,5 @@ export function rootTab(state: TaskState): 'explore' | 'transit' | 'saved' { /** Structural invariant of `details`, used by tests and development assertions. */ export function isValidTaskState(state: TaskState): boolean { const kinds = state.details.map(task => task.kind).join(','); - return ['', 'place', 'stop', 'planner', 'place,planner', 'planner,journeyStop', 'place,planner,journeyStop'].includes(kinds); + return ['', 'place', 'stop', 'station', 'planner', 'place,planner', 'planner,journeyStop', 'place,planner,journeyStop'].includes(kinds); } diff --git a/src/features/navigation/TransitFollowPanel.tsx b/src/features/navigation/TransitFollowPanel.tsx new file mode 100644 index 0000000..bc6af3c --- /dev/null +++ b/src/features/navigation/TransitFollowPanel.tsx @@ -0,0 +1,138 @@ +import { ActivityIndicator, Linking, ScrollView, useWindowDimensions, View } from 'react-native'; +import type { TransitConfirmation } from '../../domain/navigation'; +import { navigationLocationForReplan } from '../../domain/navigation'; +import { useThemeColors } from '../../theme'; +import { Button, Display, IconButton, Notice, Num, Text, TransitLineBadge, transitModeFromLineName, useHairlines } from '../../ui'; +import { transitModeFromLeg } from '../../ui/transit-line'; +import { useNow } from '../app/useNow'; +import { journeyTime } from '../planner/journey-presentation'; +import { JourneyTimeline } from '../planner/TransitJourney'; +import type { useStopBoard } from '../transit/useStopBoard'; +import type { NavigationState } from './navigation-controller'; +import { currentStepKey, liveBoarding, sessionPlan, transitFollowModel, voiceControl, type LiveBoarding } from './transit-follow'; +import type { RouteLeg, Stop } from '../../domain/types'; + +const LIVE_TONE: Record = { + live: 'text-live', scheduled: 'text-scheduled', caution: 'text-caution', disruption: 'text-cancelled font-semibold', neutral: 'text-secondary', +}; +export const FOLLOW_ACTIONS_HEIGHT = 80; + +/** + * Following a transit journey: what to do now, the next boarding with its live provenance, and one + * large confirmation beside Stop. Nothing here needs a position fix; GPS distance is advisory only. + */ +export function TransitFollowPanel({ state, following, follow, onRecenter, onStop, onRetry, onConfirm, onReplan, onMute }: { + state: NavigationState; following: boolean; + follow: { leg: RouteLeg | null; stop: Stop | null; board: ReturnType }; + onRecenter: () => void; onStop: () => void; onRetry: () => void; onConfirm: (action: TransitConfirmation) => void; onReplan: () => void; + /** Mutes or restores spoken announcements of the native session. */ + onMute: () => void; +}) { + const colors = useThemeColors(); + const hairlines = useHairlines(); + const { height, fontScale } = useWindowDimensions(); + // Passed/missed times are re-evaluated at least every 15 s, as the native contract requires. + const now = useNow(15_000); + const { snapshot, busy, error } = state; + const starting = busy === 'start' && snapshot.mode !== 'transit'; + const model = transitFollowModel(starting ? { ...snapshot, transit: undefined, instruction: undefined } : snapshot, state.transitPlan, now); + const plan = sessionPlan(snapshot, state.transitPlan); + const terminal = model.stage === 'arrived' || model.stage === 'ended'; + const replanLocation = navigationLocationForReplan(snapshot); + const showReplan = !terminal && !starting && (model.stale || !!model.warning || snapshot.problem === 'transit-replan-needed'); + // Same geometry as road guidance, so the map attribution below it stays in place. + const headerHeight = Math.min(height * 0.3, 104 * Math.min(fontScale, 1.5)); + const voice = voiceControl(snapshot, !!busy); + const live = follow.leg && model.boarding?.leg === follow.leg + ? liveBoarding({ leg: follow.leg, rows: follow.board.board?.rows ?? null, boardAvailable: !!follow.stop, loading: follow.board.arrivalsLoading || follow.board.schedules.phase === 'preparing', error: follow.board.arrivalsError, now }) + : null; + return + + + {starting ? : null} + {model.title} + {model.progress ? {model.progress} : null} + + {model.instruction} + + + + + {voice.visible ? : null} + + + + + {model.warning ? : null} + {error ? : null} + {snapshot.problem === 'transit-replan-needed' && !model.warning ? : null} + {model.boarding ? : null} + {model.alighting ? + Scendi a + {model.alighting.stopName ?? 'Fermata non indicata'} + {model.alighting.arrivalAt ? Arrivo previsto alle {journeyTime(model.alighting.arrivalAt)} · dal piano MATO : null} + : null} + {model.proximity ? {model.proximity} : null} + {model.age}{model.stale ? ' · da aggiornare' : ''} + {showReplan ? : null} + {!terminal && snapshot.sessionId && !snapshot.notificationGranted ? { void Linking.openSettings(); }} /> : null} + {model.stage === 'arrived' ? Viaggio terminato. Verifica l’ingresso sul posto. : null} + {plan && !terminal ? + Il tuo viaggio + + : null} + MATO / 5T · la posizione non conferma salita e discesa: conferma tu ogni passaggio. Corse non monitorate automaticamente. + + + {terminal ? <> + {model.stage === 'ended' && snapshot.canRetry ? : null} + + : <> + + {model.action ? + : } + + + } + + + ; +} + +function BoardingCard({ model, live, stop }: { model: ReturnType; live: LiveBoarding | null; stop: Stop | null }) { + const boarding = model.boarding!; + const mode = boarding.leg ? transitModeFromLeg(boarding.leg.mode) : boarding.line ? transitModeFromLineName(boarding.line) : undefined; + const countdown = live?.live ? /^(\d+) min$/.exec(live.timeText ?? '')?.[1] : undefined; + const planned = boarding.departureAt != null ? journeyTime(boarding.departureAt) : undefined; + return + {boarding.role === 'connection' ? 'Coincidenza' : 'Prossima partenza'} + + + + {boarding.line ? : null} + {boarding.headsign ? `Direzione ${boarding.headsign}` : 'Direzione non fornita'} + + {boarding.stopName ? {boarding.stopName} + {boarding.stopCode ? · fermata {boarding.stopCode} : null} + {boarding.platform ? · banchina {boarding.platform} : null} + : null} + + + {countdown != null ? {countdown}min + : live?.state === 'matched' && live.timeText ? {live.timeText} + : planned ? {planned} : null} + + + {live ? + {live.status ? {live.status} : null} + {live.provenance}{live.state === 'matched' && stop ? <> · fermata {stop.code} : null} + {live.note ? {live.note} : null} + {live.sameLine?.length ? + Altri passaggi della linea {boarding.line} a questa fermata + {live.sameLine.map(item => {item.time} · {item.provenance})} + : null} + {live.state !== 'matched' && planned ? Nel piano: {planned} · {boarding.leg?.timingStatus === 'prediction' ? 'Previsione MATO' : boarding.leg?.timingStatus === 'scheduled' ? 'Orario programmato' : 'Stato non disponibile'} : null} + : planned ? Orario dal piano MATO · partenze dal vivo non disponibili : null} + ; +} diff --git a/src/features/navigation/navigation-controller.test.ts b/src/features/navigation/navigation-controller.test.ts index ff8b62f..3edec9a 100644 --- a/src/features/navigation/navigation-controller.test.ts +++ b/src/features/navigation/navigation-controller.test.ts @@ -2,6 +2,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createNavigationController } from './navigation-controller'; import { idleNavigation, navigationLocationForReplan, type NavigationPlatform, type NavigationSnapshot } from '../../domain/navigation'; +import type { RoutePlan } from '../../domain/types'; function deferred() { let resolve!: (value: T) => void; @@ -440,3 +441,43 @@ test('an ignored Start is recorded and a stale command error can be dismissed', await controller.start(options); assert.deepEqual(recorded, ['start-requested', 'invalid', 'active', 'start-ignored']); }); + +test('a transit Start keeps its plan for the follow screen and a Start while busy is recorded, not dropped silently', async () => { + const recorded: string[] = []; + const pending = deferred(); + const { controller, calls } = fixture({ startTransitNavigation: () => { calls.push('transit-start'); return pending.promise; } }, state => recorded.push(state)); + await Promise.resolve(); + const plan = { id: 'p', fetchedAt: 1 } as unknown as RoutePlan; + const started = controller.startTransit({ plan, origin: options.destination, destination: options.destination }); + assert.equal(controller.getSnapshot().startKind, 'transit'); + assert.equal(controller.getSnapshot().transitPlan, plan); + await controller.start(options); + assert.deepEqual(recorded, ['start-requested', 'start-ignored']); + await Promise.resolve(); await Promise.resolve(); + assert.deepEqual(calls, ['read', 'permission', 'transit-start']); + pending.resolve({ ...snapshot(2, 'navigating'), mode: 'transit' }); + await started; + assert.equal(controller.getSnapshot().busy, null); + assert.equal(controller.getSnapshot().transitPlan, plan, 'the plan stays with the session'); +}); + +test('a call the native bridge rejects (ERR_UNEXPECTED) gets its own message and diagnostic', async () => { + const recorded: string[] = []; + const { controller } = fixture({ startTransitNavigation: async () => { throw Object.assign(new Error('Value is undefined, expected an Object'), { code: 'ERR_UNEXPECTED' }); } }, state => recorded.push(state)); + await Promise.resolve(); + await controller.startTransit({ plan: { fetchedAt: 1 } as unknown as RoutePlan, origin: options.destination, destination: options.destination }); + assert.match(controller.getSnapshot().error ?? '', /^Il viaggio non è stato passato al modulo di navigazione/); + assert.deepEqual(recorded, ['start-requested', 'bridge-error']); +}); + +test('mute applies to a transit session as to road guidance', async () => { + const muted: [string, boolean][] = []; + const { controller, emit } = fixture({ setMuted: async (sessionId, value) => { muted.push([sessionId, value]); return { ...snapshot(6), mode: 'transit', voice: value ? 'muted' : 'ready' }; } }); + await Promise.resolve(); + emit({ ...snapshot(5), mode: 'transit', voice: 'ready' }); + await controller.toggleMuted(); + assert.deepEqual(muted, [['session', true]]); + assert.equal(controller.getSnapshot().snapshot.voice, 'muted'); + await controller.toggleMuted(); + assert.deepEqual(muted, [['session', true], ['session', false]]); +}); diff --git a/src/features/navigation/navigation-controller.ts b/src/features/navigation/navigation-controller.ts index 0651761..eb052a1 100644 --- a/src/features/navigation/navigation-controller.ts +++ b/src/features/navigation/navigation-controller.ts @@ -1,4 +1,5 @@ import { idleNavigation, navigationVisible, type NavigationPlatform, type NavigationSnapshot, type NavigationStart, type TransitConfirmation, type TransitNavigationStart } from '../../domain/navigation'; +import type { RoutePlan } from '../../domain/types'; import type { DiagnosticInput } from '../../services/diagnostics'; type NavigationDiagnostic = Extract['state']; @@ -21,10 +22,18 @@ export interface NavigationState { ready: boolean; busy: 'start' | 'stop' | 'retry' | 'confirm' | null; error: string | null; + /** Kind of the latest submitted Start, so the interface shows the right screen before the first session event. */ + startKind: 'road' | 'transit' | null; + /** + * The plan handed to the latest transit Start. The interface uses it only while the native + * session reports the same retrieval time and leg count; it is never persisted. + */ + transitPlan: RoutePlan | null; } const commandDiagnostics: Partial> = { 'location-permission': 'denied', 'navigation-unavailable': 'service-unavailable', 'service-unavailable': 'service-unavailable', 'engine-unavailable': 'engine-unavailable', 'foreground-required': 'foreground-required', invalid: 'invalid', + ERR_UNEXPECTED: 'bridge-error', }; /** Only short fixed identifiers are ever shown; raw native messages never are. */ const SAFE_CODE = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/; @@ -35,12 +44,14 @@ function failureMessage(error: unknown): string { if (errorCode(error) === 'navigation-unavailable') return 'La navigazione richiede la versione Android con il modulo di navigazione.'; if (errorCode(error) === 'engine-unavailable') return 'Il motore di navigazione non è disponibile. Interrompi la sessione e riapri l’app.'; if (errorCode(error) === 'service-unavailable') return 'Android non ha avviato il servizio di navigazione. Mantieni l’app visibile e riprova.'; + // Expo Modules rejects a call it cannot convert or an unexpected native failure with this code. + if (errorCode(error) === 'ERR_UNEXPECTED') return 'Il viaggio non è stato passato al modulo di navigazione (errore interno dell’app). Riprova; se si ripete, condividi la Diagnostica locale.'; const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' && SAFE_CODE.test(error.code) ? error.code : null; return `Operazione non riuscita${code ? ` (codice ${code})` : ''}. Controlla lo stato della navigazione e riprova.`; } /** Commands and native events meet here, including events arriving before command responses. */ export function createNavigationController(platform: NavigationPlatform, record: (state: NavigationDiagnostic) => void = () => {}) { - let state: NavigationState = { snapshot: idleNavigation, ready: !platform.supported, busy: null, error: null }; + let state: NavigationState = { snapshot: idleNavigation, ready: !platform.supported, busy: null, error: null, startKind: null, transitPlan: null }; let operation = 0; let attachment = 0; let pendingStart: { submitted: boolean; previousSessionId: string | null } | null = null; @@ -95,11 +106,11 @@ export function createNavigationController(platform: NavigationPlatform, record: } finally { if (pendingStart === pending) pendingStart = null; } }); }; - const start = (action: () => Promise) => { - if (state.busy) return Promise.resolve(); + const start = (action: () => Promise, transitPlan: RoutePlan | null) => { // A Start that cannot be submitted is recorded, so a device report shows it never reached native. - if (!state.ready || navigationVisible(state.snapshot)) { record('start-ignored'); return Promise.resolve(); } + if (state.busy || !state.ready || navigationVisible(state.snapshot)) { record('start-ignored'); return Promise.resolve(); } record('start-requested'); + publish({ ...state, startKind: transitPlan ? 'transit' : 'road', transitPlan }); return prepareSessionCommand('start', action, true); }; const stop = async () => { @@ -126,8 +137,8 @@ export function createNavigationController(platform: NavigationPlatform, record: refresh, /** The planner changed: an earlier command failure no longer describes what is on screen. */ dismissError() { if (state.error && !state.busy && state.error !== unavailableStateMessage) publish({ ...state, error: null }); }, - start: (options: NavigationStart) => start(() => platform.startNavigation(options)), - startTransit: (options: TransitNavigationStart) => start(() => platform.startTransitNavigation(options)), + start: (options: NavigationStart) => start(() => platform.startNavigation(options), null), + startTransit: (options: TransitNavigationStart) => start(() => platform.startTransitNavigation(options), options.plan), stop, back(confirm: (stop: () => void) => void) { if (state.busy === 'stop') return true; diff --git a/src/features/navigation/transit-follow.test.ts b/src/features/navigation/transit-follow.test.ts new file mode 100644 index 0000000..3b4f7a6 --- /dev/null +++ b/src/features/navigation/transit-follow.test.ts @@ -0,0 +1,189 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { idleNavigation, type NavigationSnapshot } from '../../domain/navigation'; +import type { RouteLeg, RoutePlan } from '../../domain/types'; +import type { GttBoardRow } from '../../transit-data/board-model'; +import { readFileSync } from 'node:fs'; +import { currentStepKey, followBoarding, liveBoarding, matchBoardingRow, sessionPlan, transitFollowModel, voiceControl } from './transit-follow'; + +const T = Date.parse('2026-11-02T11:00:00Z'); +const min = (value: number) => T + value * 60_000; +const walk = (id: string, from: number, to: number): RouteLeg => ({ id, mode: 'walk', from: 'A', to: 'B', transitLeg: false, interlineWithPreviousLeg: false, timingStatus: 'unknown', realTime: false, + durationSeconds: (to - from) * 60, distanceMeters: 300, departureAt: min(from), arrivalAt: min(to), geometry: [], steps: [] }); +const ride = (id: string, line: string, from: number, to: number, extra: Partial = {}): RouteLeg => ({ id, mode: 'bus', line, headsign: 'NICHELINO', + from: 'STAZIONE LINGOTTO', to: 'GARRONE', fromStop: { id: 'mato:gtt:2603', name: 'STAZIONE LINGOTTO', code: '2603' }, toStop: { id: 'mato:gtt:488', name: 'GARRONE', code: '488' }, + tripId: `mato:gtt:${id}U`, serviceDate: '20261102', transitLeg: true, interlineWithPreviousLeg: false, timingStatus: 'scheduled', realTime: false, + durationSeconds: (to - from) * 60, distanceMeters: 2000, departureAt: min(from), arrivalAt: min(to), geometry: [], steps: [], ...extra }); +const journey: RoutePlan = { + id: 'j', mode: 'transit', distanceMeters: 6000, durationSeconds: 38 * 60, departureAt: min(0), arrivalAt: min(38), + walkingDurationSeconds: 600, walkingDistanceMeters: 900, waitingDurationSeconds: 0, transferCount: 1, geometry: [], source: 'MATO / 5T', warnings: [], fetchedAt: T, + legs: [walk('w1', 0, 4), ride('284', '14', 6, 16), walk('w2', 16, 19), ride('911', '4', 22, 34, { fromStop: { id: 'mato:gtt:470', name: 'CARDUCCI', code: '470' } }), walk('w3', 34, 38)], +}; +type Phase = NonNullable['phase']; +function session(phase: Phase, legIndex: number, extra: Partial> = {}, top: Partial = {}): NavigationSnapshot { + return { + ...idleNavigation, revision: 3, sessionId: 's', status: 'navigating', mode: 'transit', notificationGranted: true, instruction: 'Istruzione nativa', + transit: { + phase, legIndex, legCount: 5, sourceLegIndices: [legIndex], timingStatus: 'scheduled', fetchedAt: T, + canConfirmWalking: phase === 'walk' || phase === 'transfer', canConfirmBoarding: phase === 'board', canConfirmAlighting: phase === 'ride' || phase === 'alight', + journeyArrivalAt: min(38), ...extra, + }, + ...top, + }; +} + +test('each native phase maps to a following stage with its anchored next action', () => { + const cases: [NavigationSnapshot, string, string | undefined][] = [ + [session('walk', 0, { nextBoardingAt: min(6) }), 'access-walk', 'Sono alla fermata'], + [session('board', 1, { nextBoardingAt: min(6) }), 'waiting', 'Sono a bordo'], + [session('ride', 1, { nextBoardingAt: min(22) }), 'riding', 'Sono sceso'], + [session('alight', 1), 'riding', 'Sono sceso'], + [session('transfer', 2, { nextBoardingAt: min(22) }), 'transfer', 'Sono alla fermata'], + [session('walk', 4), 'final-walk', 'Sono arrivato'], + [session('complete', 4, {}, { status: 'arrived' }), 'arrived', undefined], + ]; + for (const [snapshot, stage, label] of cases) { + const model = transitFollowModel(snapshot, journey, min(1)); + assert.equal(model.stage, stage, `${snapshot.transit?.phase}`); + assert.equal(model.action?.label, label, `${snapshot.transit?.phase}`); + } + // Without the plan, the native next boarding still separates access from the final walk. + assert.equal(transitFollowModel(session('walk', 0, { nextBoardingAt: min(6) }), null, T).stage, 'access-walk'); + assert.equal(transitFollowModel(session('walk', 4), null, T).stage, 'final-walk'); +}); + +test('a start in flight and an interrupted session have their own stages', () => { + assert.equal(transitFollowModel({ ...idleNavigation }, journey, T).stage, 'starting'); + const interrupted = transitFollowModel({ ...idleNavigation, sessionId: 's', mode: 'transit', status: 'interrupted', canRetry: true }, journey, T); + assert.equal(interrupted.stage, 'ended'); + assert.equal(interrupted.action, null); +}); + +test('the next boarding comes from the matching plan; while aboard it is the next connection', () => { + const access = followBoarding(session('walk', 0, { nextBoardingAt: min(6) }), journey)!; + assert.equal(access.leg?.id, '284'); + assert.equal(access.role, 'next'); + assert.equal(access.stopCode, '2603'); + assert.equal(followBoarding(session('board', 1), journey)!.leg?.id, '284'); + const aboard = followBoarding(session('ride', 1, { nextBoardingAt: min(22) }), journey)!; + assert.equal(aboard.leg?.id, '911'); + assert.equal(aboard.role, 'connection'); + assert.equal(followBoarding(session('ride', 3), journey), null, 'no connection after the last ride'); + // A different plan (another retrieval) never describes this session. + assert.equal(sessionPlan(session('board', 1), { ...journey, fetchedAt: T - 1 }), null); + assert.equal(followBoarding(session('board', 1, { line: '14', from: 'STAZIONE LINGOTTO' }), { ...journey, fetchedAt: T - 1 })?.leg, null); +}); + +test('journey age, passed boarding and proximity stay advisory and explicit', () => { + const fresh = transitFollowModel(session('board', 1, { nextBoardingAt: min(6) }), journey, min(1)); + assert.equal(fresh.age, 'Viaggio consultato alle 12:00 · 1 min fa'); + assert.equal(fresh.stale, false); + assert.equal(fresh.warning, null); + assert.equal(fresh.proximity, 'Posizione non disponibile: conferma ogni passaggio manualmente.'); + const missed = transitFollowModel(session('board', 1, { nextBoardingAt: min(6) }), journey, min(9)); + assert.equal(missed.stale, true); + assert.match(missed.warning ?? '', /già partita/); + const ended = transitFollowModel(session('ride', 3), journey, min(45)); + assert.match(ended.warning ?? '', /già concluso/); + const near = transitFollowModel(session('board', 1, { proximityAvailable: true }, { locationUsable: true, distanceToManeuverMeters: 123 }), journey, T); + assert.equal(near.proximity, 'Circa 120 m in linea d’aria · solo indicativo'); + const ambiguous = transitFollowModel(session('ride', 1, { proximityAvailable: false }, { locationUsable: true, distanceToManeuverMeters: 50 }), journey, T); + assert.match(ambiguous.proximity ?? '', /conferma manualmente/); + assert.equal(ambiguous.alighting?.stopName, 'GARRONE'); +}); + +function row(extra: Omit, 'gtt'> & { gtt?: Partial } = {}): GttBoardRow { + const { gtt, ...rest } = extra; + return { + id: 'row', provider: 'gtt', upstream: {}, event: 'departure', mode: 'bus', line: '14', headsign: 'NICHELINO', stop: { id: '1765', name: 'STAZIONE LINGOTTO' }, + scheduledAt: min(6), timeBasis: 'scheduled', realtimeState: 'scheduled', tripCancelled: false, retrievedAt: T, + gtt: { routeId: '14U', tripId: 'other', serviceDate: '20261102', realtime: 'no-trip-update', ...gtt }, ...rest, + }; +} + +test('the live row joins by GTT trip ID first, then by line and scheduled time only when unique', () => { + const leg = journey.legs[1]!; + assert.equal(matchBoardingRow([row({ id: 'trip', scheduledAt: min(30), gtt: { tripId: '284U' } })], leg)?.method, 'trip'); + assert.equal(matchBoardingRow([row({ gtt: { tripId: '284U', serviceDate: '20261103' } })], leg)?.method, 'schedule', 'another service day is not the same trip'); + assert.equal(matchBoardingRow([row({ id: 'a' })], leg)?.row.id, 'a'); + assert.equal(matchBoardingRow([row({ id: 'a' }), row({ id: 'b', scheduledAt: min(6) + 20_000 })], leg), null, 'two candidates: no guess'); + assert.equal(matchBoardingRow([row({ line: '15' })], leg), null); + assert.equal(matchBoardingRow([row({ scheduledAt: min(7) })], leg), null); + // A MATO prediction joins on its timetable time, not on the predicted one. + const predicted = { ...leg, timingStatus: 'prediction' as const, realTime: true, departureAt: min(8), scheduledDepartureAt: min(6), tripId: undefined }; + assert.equal(matchBoardingRow([row()], predicted)?.method, 'schedule'); + assert.equal(matchBoardingRow([row()], { ...leg, timingStatus: 'unknown', tripId: undefined }), null, 'an unknown timing state cannot be joined by time'); +}); + +test('live boarding: green only for fresh sourced realtime; otherwise unconfirmed or unavailable in words', () => { + const leg = journey.legs[1]!; + const live = liveBoarding({ leg, boardAvailable: true, loading: false, now: T, rows: [row({ + predictedAt: min(8), realtimeState: 'realtime-with-source-time', timeBasis: 'predicted', sourceUpdatedAt: T - 20_000, + gtt: { tripId: '284U', realtime: 'fresh', delaySeconds: 120 }, + })] }); + assert.equal(live.state, 'matched'); + assert.equal(live.live, true); + assert.equal(live.tone, 'live'); + assert.equal(live.timeText, '8 min'); + assert.equal(live.provenance, 'Tempo reale · GTT'); + const stale = liveBoarding({ leg, boardAvailable: true, loading: false, now: T + 5 * 60_000, rows: [row({ + predictedAt: min(8), realtimeState: 'realtime-with-source-time', timeBasis: 'predicted', sourceUpdatedAt: T - 20_000, + gtt: { tripId: '284U', realtime: 'fresh' }, + })] }); + assert.equal(stale.live, false, 'an aged prediction is never shown as live'); + assert.equal(stale.tone, 'caution'); + const unconfirmed = liveBoarding({ leg, boardAvailable: true, loading: false, now: T, rows: [row({ line: '15' })] }); + assert.equal(unconfirmed.status, 'Corsa non confermata'); + assert.equal(unconfirmed.state, 'unconfirmed'); + assert.equal(liveBoarding({ leg, boardAvailable: false, loading: false, now: T, rows: null }).state, 'unavailable'); + assert.equal(liveBoarding({ leg, boardAvailable: true, loading: true, now: T, rows: null }).state, 'loading'); + const metro = liveBoarding({ leg: { ...leg, line: 'M1', mode: 'subway', tripId: undefined }, boardAvailable: true, loading: false, now: T, + rows: [row({ line: 'M1', mode: 'metro', gtt: { realtime: 'not-provided' } })] }); + assert.equal(metro.status, 'Solo orari programmati — tempo reale non disponibile'); + assert.equal(metro.note, 'Corsa abbinata per linea e orario programmato'); +}); + +test('one timeline step is current, and an unconfirmed service lists the line’s passages separately', () => { + assert.equal(currentStepKey(session('walk', 0), journey), 'walk:w1'); + assert.equal(currentStepKey(session('board', 1), journey), 'board:284'); + assert.equal(currentStepKey(session('alight', 1), journey), 'ride:284'); + assert.equal(currentStepKey(session('board', 1), null), undefined); + const leg = journey.legs[1]!; + const result = liveBoarding({ leg, boardAvailable: true, loading: false, now: T, rows: [row({ id: 'x', scheduledAt: min(9) }), row({ id: 'y', line: '15' })] }); + assert.equal(result.state, 'unconfirmed'); + assert.deepEqual(result.sameLine?.map(item => [item.id, item.time]), [['x', '12:09']]); +}); + +test('a prediction without a known timetable time is never joined by its predicted time', () => { + // The selected service is scheduled at 12:00 and predicted at 12:10; MATO supplied no usable delay. + const delayed = { ...journey.legs[1]!, timingStatus: 'prediction' as const, realTime: true, departureAt: min(10), scheduledDepartureAt: undefined, tripId: 'mato:gtt:not-on-board' }; + // Another service of the same line is scheduled at 12:10 at this stop. + const other = row({ id: 'other', scheduledAt: min(10), gtt: { tripId: '999U' } }); + assert.equal(matchBoardingRow([other], delayed), null); + const live = liveBoarding({ leg: delayed, rows: [other], boardAvailable: true, loading: false, now: T }); + assert.equal(live.state, 'unconfirmed'); + assert.equal(live.status, 'Corsa non confermata'); + // With its timetable time supplied, the same prediction joins the 12:00 service, not the 12:10 one. + const own = row({ id: 'own', scheduledAt: min(0), gtt: { tripId: '998U' } }); + assert.equal(matchBoardingRow([other, own], { ...delayed, scheduledDepartureAt: min(0) })?.row.id, 'own'); + // A trip-ID join still works for a prediction without a delay. + assert.equal(matchBoardingRow([row({ id: 'trip', scheduledAt: min(0), gtt: { tripId: 'not-on-board' } }), other], delayed)?.method, 'trip'); +}); + +test('the follow screen has the road panel’s mute control, unavailable in words without an offline voice', () => { + const live = { sessionId: 's', status: 'navigating' as const }; + assert.deepEqual(voiceControl({ ...live, voice: 'ready' }, false), { visible: true, enabled: true, muted: false, label: 'Disattiva voce', icon: 'volume-high-outline' }); + assert.deepEqual(voiceControl({ ...live, voice: 'muted' }, false), { visible: true, enabled: true, muted: true, label: 'Attiva voce', icon: 'volume-mute-outline' }); + assert.deepEqual(voiceControl({ ...live, voice: 'unavailable' }, false), { visible: true, enabled: false, muted: false, label: 'Voce non disponibile', icon: 'volume-high-outline' }); + assert.equal(voiceControl({ ...live, voice: 'initializing' }, false).label, 'Preparazione voce'); + assert.equal(voiceControl({ ...live, voice: 'initializing' }, false).enabled, false); + assert.equal(voiceControl({ ...live, voice: 'ready' }, true).enabled, false, 'no toggle while a command runs'); + assert.equal(voiceControl({ ...live, status: 'arrived', voice: 'ready' }, false).visible, false); + assert.equal(voiceControl({ sessionId: null, status: 'waiting-for-fix', voice: 'ready' }, false).visible, false, 'a Start in flight has no session to mute'); + // Wiring: the shell passes the controller's toggle and the panel renders the control from this model. + const shell = readFileSync(new URL('../app/AppShell.tsx', import.meta.url), 'utf8'); + assert.match(shell, / \{ void navigation\.toggleMuted\(\); \}\}[\s\S]*?\/>/); + const panel = readFileSync(new URL('./TransitFollowPanel.tsx', import.meta.url), 'utf8'); + assert.match(panel, /const voice = voiceControl\(snapshot, !!busy\)/); + assert.match(panel, //); +}); diff --git a/src/features/navigation/transit-follow.ts b/src/features/navigation/transit-follow.ts new file mode 100644 index 0000000..487977e --- /dev/null +++ b/src/features/navigation/transit-follow.ts @@ -0,0 +1,242 @@ +import { navigationPresentation, type NavigationSnapshot, type TransitConfirmation } from '../../domain/navigation'; +import type { RouteLeg, RoutePlan } from '../../domain/types'; +import type { GttBoardRow } from '../../transit-data/board-model'; +import { rowPresentation, visibleRows } from '../transit/departure-status'; +import { journeyTime } from '../planner/journey-presentation'; +import { PLAN_FRESH_MS } from '../planner/transit-journey'; + +/** + * The transit following screen, derived from the native snapshot (the session's source of truth) + * and, when it is the same journey, the plan the session was started with. GPS cues stay advisory: + * every transition needs the rider's confirmation. + */ +export type FollowStage = 'starting' | 'access-walk' | 'waiting' | 'riding' | 'transfer' | 'final-walk' | 'arrived' | 'ended'; + +export interface FollowAction { confirm: TransitConfirmation; label: string } +export interface FollowBoarding { + /** The plan leg, when the started plan matches the session. */ + leg: RouteLeg | null; + line?: string; + headsign?: string; + stopName?: string; + stopCode?: string; + platform?: string; + /** Planned departure (MATO's expected time). */ + departureAt?: number; + /** "Prossima partenza" before boarding; "Coincidenza" while aboard. */ + role: 'next' | 'connection'; +} +export interface TransitFollowModel { + stage: FollowStage; + title: string; + instruction: string; + action: FollowAction | null; + boarding: FollowBoarding | null; + /** Where to get off while riding. */ + alighting: { stopName?: string; arrivalAt?: number } | null; + /** "Viaggio consultato alle 12:01 · 7 min fa". */ + age: string; + stale: boolean; + /** Passed or missed planned times, from the native journeyEnd/nextBoarding fields. */ + warning: string | null; + /** Straight-line GPS distance or why it is missing; never a confirmation. */ + proximity: string | null; + progress: string; +} + +const STAGE_TITLES: Record = { + starting: 'Avvio del viaggio', 'access-walk': 'Raggiungi la fermata', waiting: 'Attendi alla fermata', riding: 'A bordo', + transfer: 'Cambio', 'final-walk': 'Verso la destinazione', arrived: 'Sei arrivato', ended: 'Viaggio interrotto', +}; +const ACTION_LABELS: Record>> = { + 'walk-complete': { 'access-walk': 'Sono alla fermata', transfer: 'Sono alla fermata', 'final-walk': 'Sono arrivato' }, + board: { waiting: 'Sono a bordo' }, + alight: { riding: 'Sono sceso' }, +}; + +/** The started plan describes this session only when its retrieval time and leg count agree. */ +export function sessionPlan(snapshot: NavigationSnapshot, plan: RoutePlan | null): RoutePlan | null { + const transit = snapshot.transit; + if (!plan || !transit || snapshot.mode !== 'transit') return null; + return plan.fetchedAt === transit.fetchedAt && plan.legs.length === transit.legCount ? plan : null; +} + +function currentLegs(snapshot: NavigationSnapshot): number[] { + const transit = snapshot.transit!; + return transit.sourceLegIndices?.length ? transit.sourceLegIndices : [transit.legIndex]; +} + +function stageOf(snapshot: NavigationSnapshot, plan: RoutePlan | null): FollowStage { + const transit = snapshot.transit; + if (snapshot.status === 'arrived' || transit?.phase === 'complete') return 'arrived'; + if (snapshot.status === 'interrupted' || snapshot.status === 'error') return 'ended'; + if (!transit) return 'starting'; + switch (transit.phase) { + case 'board': return 'waiting'; + case 'ride': case 'alight': return 'riding'; + case 'transfer': return 'transfer'; + case 'walk': { + const last = Math.max(...currentLegs(snapshot)); + const transitAhead = plan ? plan.legs.slice(last + 1).some(leg => leg.transitLeg) : transit.nextBoardingAt != null; + return transitAhead ? 'access-walk' : 'final-walk'; + } + default: return 'starting'; + } +} + +function boardingFor(stage: FollowStage, snapshot: NavigationSnapshot, plan: RoutePlan | null): FollowBoarding | null { + const transit = snapshot.transit; + if (!transit || stage === 'arrived' || stage === 'ended' || stage === 'starting' || stage === 'final-walk') return null; + const legs = currentLegs(snapshot); + const role: FollowBoarding['role'] = stage === 'riding' ? 'connection' : 'next'; + if (plan) { + const from = stage === 'waiting' ? legs[0]! : Math.max(...legs) + 1; + // While aboard, the next connection is the next boarding after this vehicle (not a same-vehicle continuation). + const leg = plan.legs.slice(from).find(item => item.transitLeg && (stage === 'waiting' || !item.interlineWithPreviousLeg)) ?? null; + if (!leg) return null; + return { + leg, line: leg.line, headsign: leg.headsign, stopName: leg.fromStop?.name ?? leg.from, stopCode: leg.fromStop?.code, + platform: leg.fromStop?.platformCode, departureAt: leg.departureAt, role, + }; + } + if (stage === 'waiting') return { leg: null, line: transit.line, headsign: transit.headsign, stopName: transit.from, departureAt: transit.departureAt, role }; + return transit.nextBoardingAt != null ? { leg: null, departureAt: transit.nextBoardingAt, role } : null; +} + +/** The next boarding of the followed journey, without time-dependent wording (for the live board). */ +export function followBoarding(snapshot: NavigationSnapshot, startedPlan: RoutePlan | null): FollowBoarding | null { + const plan = sessionPlan(snapshot, startedPlan); + return boardingFor(stageOf(snapshot, plan), snapshot, plan); +} + +const minutesAgo = (ms: number) => Math.max(0, Math.floor(ms / 60_000)); + +export function transitFollowModel(snapshot: NavigationSnapshot, startedPlan: RoutePlan | null, now: number): TransitFollowModel { + const plan = sessionPlan(snapshot, startedPlan); + const stage = stageOf(snapshot, plan); + const transit = snapshot.transit; + const presentation = navigationPresentation(snapshot, now); + const confirm = transit?.confirmation + ?? (transit?.canConfirmWalking ? 'walk-complete' : transit?.canConfirmBoarding ? 'board' : transit?.canConfirmAlighting ? 'alight' : undefined); + const label = confirm ? ACTION_LABELS[confirm][stage] : undefined; + const action = confirm && label ? { confirm, label } : null; + const fetchedAt = transit?.fetchedAt ?? plan?.fetchedAt; + const ageMs = fetchedAt != null ? now - fetchedAt : 0; + const age = fetchedAt != null + ? `Viaggio consultato alle ${journeyTime(fetchedAt)} · ${minutesAgo(ageMs) < 1 ? 'meno di 1 min fa' : `${minutesAgo(ageMs)} min fa`}` + : 'Consultazione del viaggio non disponibile'; + const alightingLeg = plan && transit && stage === 'riding' ? plan.legs[Math.max(...currentLegs(snapshot))] : undefined; + const alighting = stage === 'riding' ? { stopName: alightingLeg?.toStop?.name ?? alightingLeg?.to ?? transit?.to, arrivalAt: alightingLeg?.arrivalAt ?? transit?.arrivalAt } : null; + let proximity: string | null = null; + if (transit && stage !== 'arrived' && stage !== 'ended') { + if (snapshot.locationUsable === true && transit.proximityAvailable !== false && snapshot.distanceToManeuverMeters != null) { + const meters = snapshot.distanceToManeuverMeters; + proximity = `Circa ${meters < 1000 ? `${Math.round(meters / 10) * 10} m` : `${(meters / 1000).toFixed(1).replace('.', ',')} km`} in linea d’aria · solo indicativo`; + } else if (transit.proximityAvailable === false) proximity = 'Vicinanza non disponibile per questa tratta: conferma manualmente.'; + else proximity = 'Posizione non disponibile: conferma ogni passaggio manualmente.'; + } + return { + stage, title: STAGE_TITLES[stage], + instruction: stage === 'ended' ? presentation.quality : snapshot.instruction ?? (stage === 'starting' ? 'Preparazione del viaggio' : presentation.instruction), + action, boarding: boardingFor(stage, snapshot, plan), alighting, age, stale: ageMs >= PLAN_FRESH_MS, + warning: presentation.transitWarning, proximity, + progress: transit ? `Tratta ${transit.legIndex + 1} di ${transit.legCount}` : '', + }; +} + +// --------------------------------------------------------------------------------------------- +// Live departure for the next boarding, from the stop's GTT board + +export interface BoardingMatch { row: GttBoardRow; method: 'trip' | 'schedule' } + +/** + * Joins the selected service to a GTT board row: by GTT trip ID (and service date), else by the same + * line with the same scheduled departure at this stop when exactly one row qualifies. Anything else + * is unmatched; the rider sees "Corsa non confermata" rather than a guessed vehicle. + */ +export function matchBoardingRow(rows: readonly GttBoardRow[], leg: RouteLeg): BoardingMatch | null { + const trip = /^mato:gtt:([A-Za-z0-9_.-]+)$/.exec(leg.tripId ?? '')?.[1]; + if (trip) { + const exact = rows.filter(row => row.gtt.tripId === trip && (!leg.serviceDate || !row.gtt.serviceDate || row.gtt.serviceDate === leg.serviceDate)); + if (exact.length === 1) return { row: exact[0]!, method: 'trip' }; + } + // Only a known timetable time can identify a service: a scheduled leg's own time, or a prediction's + // supplied timetable time. A predicted time without one would match whatever is scheduled then. + const scheduled = leg.scheduledDepartureAt ?? (leg.timingStatus === 'scheduled' ? leg.departureAt : undefined); + const line = leg.line?.trim().toUpperCase(); + if (scheduled == null || !line) return null; + const candidates = rows.filter(row => row.line?.trim().toUpperCase() === line && row.scheduledAt != null && Math.abs(row.scheduledAt - scheduled) < 60_000); + return candidates.length === 1 ? { row: candidates[0]!, method: 'schedule' } : null; +} + +export interface LiveBoarding { + state: 'matched' | 'unconfirmed' | 'unavailable' | 'loading'; + /** Time to show, from the board row when matched. */ + timeText?: string; + live: boolean; + status?: string; + provenance: string; + note?: string; + tone: 'live' | 'scheduled' | 'caution' | 'disruption' | 'neutral'; + /** When the selected service is unconfirmed: the line's next passages at this stop, never presented as that service. */ + sameLine?: { id: string; time: string; provenance: string; live: boolean }[]; +} + +/** Key of the timeline step being followed, matching `journeyTimeline` keys. */ +export function currentStepKey(snapshot: NavigationSnapshot, plan: RoutePlan | null): string | undefined { + const transit = snapshot.transit; + if (!plan || !transit) return undefined; + const legs = currentLegs(snapshot); + const leg = plan.legs[legs[0]!]; + if (!leg) return undefined; + if (transit.phase === 'board') return `board:${leg.id}`; + if (transit.phase === 'ride' || transit.phase === 'alight') return `ride:${leg.id}`; + if (transit.phase === 'walk' || transit.phase === 'transfer') return `walk:${leg.id}`; + return undefined; +} + +export function liveBoarding(input: { leg: RouteLeg | null; rows: readonly GttBoardRow[] | null; boardAvailable: boolean; loading: boolean; error?: string; now: number }): LiveBoarding { + if (!input.leg || !input.boardAvailable) return { state: 'unavailable', live: false, provenance: 'Partenze dal vivo non disponibili per questa fermata', tone: 'neutral' }; + if (!input.rows) return input.loading + ? { state: 'loading', live: false, provenance: 'Cerco la partenza alla fermata…', tone: 'neutral' } + : { state: 'unavailable', live: false, provenance: input.error || 'Partenze della fermata non disponibili', tone: 'caution' }; + const match = matchBoardingRow(input.rows, input.leg); + if (!match) { + const line = input.leg.line?.trim().toUpperCase(); + const sameLine = line ? visibleRows(input.rows, input.now).filter(row => row.line?.trim().toUpperCase() === line).slice(0, 2).map(row => { + const view = rowPresentation(row, input.now); + return { id: row.id, time: view.timeText, provenance: view.statusText === view.provenance ? view.provenance : `${view.statusText} · ${view.provenance}`, live: view.live }; + }) : []; + return { state: 'unconfirmed', live: false, status: 'Corsa non confermata', provenance: 'La corsa scelta non risulta tra le partenze GTT della fermata', tone: 'caution', ...(sameLine.length ? { sameLine } : {}) }; + } + const view = rowPresentation(match.row, input.now); + const cancelled = view.row.realtimeState === 'cancelled'; + return { + state: 'matched', timeText: view.timeText, live: view.live, status: view.statusText, provenance: view.provenance, + note: match.method === 'schedule' ? 'Corsa abbinata per linea e orario programmato' : undefined, + tone: cancelled ? 'disruption' : view.live ? 'live' : view.row.gtt.realtime === 'stale' ? 'caution' : 'scheduled', + }; +} + +export interface VoiceControl { + visible: boolean; + enabled: boolean; + /** Accessible name: the action when available, otherwise why it is not. */ + label: string; + icon: 'volume-high-outline' | 'volume-mute-outline'; + muted: boolean; +} +/** + * Mute for spoken transit announcements, as in road guidance: shown for a live session, disabled + * while the offline Italian voice is being prepared or when none is installed. + */ +export function voiceControl(snapshot: Pick, busy: boolean): VoiceControl { + const terminal = snapshot.status === 'arrived' || snapshot.status === 'interrupted' || snapshot.status === 'error' || snapshot.status === 'stopped' || snapshot.status === 'idle'; + const muted = snapshot.voice === 'muted'; + const available = snapshot.voice === 'ready' || muted; + return { + visible: !!snapshot.sessionId && !terminal, enabled: available && !busy, muted, + label: muted ? 'Attiva voce' : snapshot.voice === 'ready' ? 'Disattiva voce' : snapshot.voice === 'initializing' ? 'Preparazione voce' : 'Voce non disponibile', + icon: muted ? 'volume-mute-outline' : 'volume-high-outline', + }; +} diff --git a/src/features/planner/JourneyPlanner.tsx b/src/features/planner/JourneyPlanner.tsx deleted file mode 100644 index c9b8643..0000000 --- a/src/features/planner/JourneyPlanner.tsx +++ /dev/null @@ -1,133 +0,0 @@ -import { Pressable, View } from 'react-native'; -import { Text } from '../../ui/Text'; -import type { RouteLeg, RoutePlan, RouteStop, Stop, TransitTime } from '../../domain/types'; -import { useThemeColors } from '../../theme'; -import { Button, Disclosure, Icon, Notice, Num, TransitLineBadge, transitModeFromLeg, useHairlines } from '../../ui'; -import { matchJourneyStop } from '../../services/transit-stop-matching'; -import { - journeyDate, journeyDistance, journeyDuration, journeyTime, journeyTimingLabel, savedJourneyTimeLabel, transitTimeLabel, waitBefore, -} from './journey-presentation'; - -function stopLabel(stop: RouteStop | undefined, fallback: string) { - return `${stop?.name ?? fallback}${stop?.code ? ` · fermata ${stop.code}` : ''}${stop?.platformCode ? ` · banchina ${stop.platformCode}` : ''}`; -} -function legLabel(leg: RouteLeg) { - return leg.transitLeg ? (leg.line ? `Linea ${leg.line}` : 'Mezzo pubblico') : leg.mode === 'walk' ? 'A piedi' : leg.mode === 'bicycle' ? 'In bici' : leg.mode === 'car' ? 'In auto' : 'Tratta'; -} -/** The plan's transit lines as badges in boarding order; walking-only plans say so in words. */ -function LegBadges({ plan }: { plan: RoutePlan }) { - const legs = plan.legs.filter(leg => leg.transitLeg); - if (!legs.length) return A piedi fino alla destinazione; - return - {legs.map((leg, index) => - {index ? › : null} - {leg.line ? : {legLabel(leg)}} - )} - ; -} -function transferLabel(plan: RoutePlan) { - if (!plan.legs.some(leg => leg.transitLeg)) return plan.legs.every(leg => leg.mode === 'walk') ? 'Solo a piedi' : 'Senza mezzi pubblici'; - return plan.transferCount === 0 ? 'Nessun cambio' : `${plan.transferCount} ${plan.transferCount === 1 ? 'cambio' : 'cambi'}`; -} -function timeRange(plan: RoutePlan) { - const overnight = plan.departureAt != null && plan.arrivalAt != null && journeyDate(plan.departureAt) !== journeyDate(plan.arrivalAt); - return `${journeyTime(plan.departureAt)} – ${journeyTime(plan.arrivalAt)}${overnight ? ` del ${journeyDate(plan.arrivalAt!)}` : ''}`; -} - -export function JourneyResults({ plans, selected, onSelect, onRefresh, loading, error, now, query, saved = false, retained = false, onOpenStop }: { - plans: RoutePlan[]; selected: RoutePlan; onSelect: (id: string) => void; onRefresh: () => void; - loading: boolean; error: string; now: number; query: TransitTime; saved?: boolean; retained?: boolean; onOpenStop?: (stop: Stop) => void; -}) { - const colors = useThemeColors(); - const hairlines = useHairlines(); - const age = Math.max(0, Math.floor((now - selected.fetchedAt) / 60_000)); - const stale = saved || retained || now - selected.fetchedAt > 120_000; - return ( - - {saved ? savedJourneyTimeLabel(query, selected.fetchedAt) : transitTimeLabel(query)} - {error ? : null} - {retained ? : null} - - - Consultato il {journeyDate(selected.fetchedAt)} alle {journeyTime(selected.fetchedAt)} - {age === 0 ? ' (meno di 1 min fa).' : ` (${age} min fa).`}{stale ? ' Da aggiornare.' : ''} - - - - - {plans.map((plan, index) => ( - leg.timingStatus === 'cancelled') ? ', include una corsa cancellata' : ''}`} - accessibilityState={{ selected: plan.id === selected.id }} - onPress={() => onSelect(plan.id)} - // Board rows separated by hairlines; the selected option is outlined in the accent and checked. - style={[hairlines.bottom, plan.id === selected.id ? { borderWidth: 1.5, borderColor: colors.action, borderBottomWidth: 1.5, borderBottomColor: colors.action, borderRadius: 12 } : null]} - className="gap-2 px-3 py-3" - > - - - {plan.departureAt != null ? {journeyDate(plan.departureAt)} : null} - {timeRange(plan)} - {journeyDuration(plan.durationSeconds)} · {transferLabel(plan)} - - {plan.id === selected.id ? : null} - - - {plan.legs.some(leg => leg.timingStatus === 'cancelled') ? Include una corsa cancellata : null} - - ))} - - - A piedi {journeyDuration(selected.walkingDurationSeconds)} ({journeyDistance(selected.walkingDistanceMeters)}) · Attese {selected.waitingDurationSeconds ? journeyDuration(selected.waitingDurationSeconds) : 'nessuna'} · Ora italiana - {selected.legs.map((leg, index) => { - const previous = selected.legs[index - 1]; - const next = selected.legs[index + 1]; - const wait = waitBefore(leg, previous); - const boardingStop = leg.transitLeg ? matchJourneyStop(leg.fromStop) : null; - const alightingStop = leg.transitLeg ? matchJourneyStop(leg.toStop) : null; - const overnight = leg.departureAt != null && leg.arrivalAt != null && journeyDate(leg.departureAt) !== journeyDate(leg.arrivalAt); - return ( - - {wait > 0 ? {leg.interlineWithPreviousLeg ? 'Sosta a bordo' : 'Attesa'}: {journeyDuration(wait)} a {previous?.toStop?.name ?? previous?.to ?? leg.from} : null} - - - {leg.transitLeg && leg.line ? : {legLabel(leg)}} - {leg.transitLeg ? {leg.headsign ? `Direzione ${leg.headsign}` : 'Direzione non fornita dal servizio'} : {journeyDuration(leg.durationSeconds)} · {journeyDistance(leg.distanceMeters)}} - - - {journeyTime(leg.departureAt)} · {leg.transitLeg ? leg.timingStatus === 'cancelled' ? 'Partenza cancellata da' : leg.interlineWithPreviousLeg ? 'Rimani a bordo' : 'Sali a' : 'Parti da'} - {stopLabel(leg.fromStop, leg.from)} - {boardingStop && onOpenStop ? : null} - - - {journeyTime(leg.arrivalAt)}{overnight ? ` del ${journeyDate(leg.arrivalAt!)}` : ''} · {leg.transitLeg ? leg.timingStatus === 'cancelled' ? 'Arrivo programmato a' : next?.interlineWithPreviousLeg ? 'Prosegui a bordo da' : 'Scendi a' : 'Arrivi a'} - {stopLabel(leg.toStop, leg.to)} - {alightingStop && onOpenStop ? : null} - - {leg.transitLeg ? {journeyTimingLabel(leg, selected.fetchedAt, now, saved || retained)} · {journeyDuration(leg.durationSeconds)} : null} - - - ); - })} - - {selected.legs.some(leg => leg.timingStatus === 'prediction') ? : null} - {selected.warnings.map((warning, index) => )} - {selected.source} · © OpenStreetMap contributors. Corse non monitorate durante la guida. - - ); -} - -function SelectedMark() { - const colors = useThemeColors(); - return ; -} - -function StopArrivalButton({ stop, onOpen }: { stop: Stop; onOpen: (stop: Stop) => void }) { - return - - ; -} diff --git a/src/features/planner/PlannerSheet.tsx b/src/features/planner/PlannerSheet.tsx index 6a43d00..72a499a 100644 --- a/src/features/planner/PlannerSheet.tsx +++ b/src/features/planner/PlannerSheet.tsx @@ -8,7 +8,7 @@ import { useNavigationContext } from "../navigation/useNavigation"; import { useTransitContext } from "../transit/useTransit"; import { useFeedback } from "../app/feedback"; import { EndpointEditor } from "./EndpointEditor"; -import { JourneyResults } from "./JourneyPlanner"; +import { JourneyResults } from "./TransitJourney"; import { PlannerEndpoints } from "./PlannerEndpoints"; import { TransitTimeControl } from "./TransitTimeControl"; import { journeyDate, journeyTime } from "./journey-presentation"; @@ -43,7 +43,7 @@ function PlannerPreview({ task, now }: { task: PlannerTask; now: number }) { ) : null} {pickingOrigin ? null : mode === "transit" && route ? ( + now={now} query={transitTime} saved={savedJourneyVisible} retained={retainedSelection} destination={task.destination.name} onOpenStop={openJourneyStop} /> ) : (routing && !route) || originPending ? null : error && !route ? ( ) : route ? ( @@ -65,7 +65,7 @@ function PlannerPreview({ task, now }: { task: PlannerTask; now: number }) { ))} {route.source} · senza traffico in tempo reale. Dati © OpenStreetMap contributors. - ) : !originPending ? ( + ) : !originPending && mode !== "transit" ? ( ) : null} {route && !pickingOrigin && !originPending ? ( diff --git a/src/features/planner/RouteActions.tsx b/src/features/planner/RouteActions.tsx index 6d76d7a..b280305 100644 --- a/src/features/planner/RouteActions.tsx +++ b/src/features/planner/RouteActions.tsx @@ -5,11 +5,16 @@ import { formatDistance, formatDuration } from "../../ui/format"; import type { PlannerTask } from "../app/task-model"; import { useMapContext } from "../map/useMapModel"; import { useNavigationContext } from "../navigation/useNavigation"; +import { journeyDuration, journeyTime } from "./journey-presentation"; +import { plannerPrimaryAction } from "./transit-journey"; import { usePlannerContext } from "./usePlanner"; export const ROUTE_ACTIONS_HEIGHT = 72; -/** Summary and Avvia, anchored outside the scrolling details. */ +/** + * Summary and the mode-correct primary action, anchored outside the scrolling details: Avvia for + * road modes; in Mezzi, Cerca percorsi until alternatives exist, then Segui viaggio. + */ export function RouteActions({ task }: { task: PlannerTask }) { const planner = usePlannerContext(); const hairlines = useHairlines(); @@ -18,14 +23,34 @@ export function RouteActions({ task }: { task: PlannerTask }) { const { route, error, loading: routing, retainedSelection } = planner.routes; const originPending = task.originStep === "locating"; const pickingOrigin = task.originStep === "picking"; + const transit = planner.mode === "transit"; + const action = plannerPrimaryAction({ + mode: planner.mode, route, loading: routing, retained: retainedSelection, picking: pickingOrigin, originPending, + originReady: task.origin.ready, supported: navigation.supported, navigationReady: navigation.ready, navigationBusy: navigation.busy === "start", + }); + const summary = originPending || (routing && !route) ? (transit ? "Cerco i percorsi…" : "Calcolo del percorso…") + : pickingOrigin ? "Tocca la partenza" + : route && transit && route.mode === "transit" ? `${journeyTime(route.departureAt)}–${journeyTime(route.arrivalAt)}` + : route ? `${formatDuration(route.durationSeconds)} · ${formatDistance(route.distanceMeters)}` + : error ? "Percorso non disponibile" : transit ? "Nessuna ricerca" : "Anteprima del percorso"; + const status = action.reason && action.kind !== "search" ? action.reason + : routing && route ? "Aggiornamento…" : error && route ? "Aggiornamento non riuscito · percorso precedente" + : planner.savedJourneyVisible ? "Viaggio salvato · da aggiornare" : retainedSelection ? "Selezione da aggiornare" + : transit ? (route ? journeyDuration(route.durationSeconds) : "Mezzi pubblici · MATO") : navigation.supported ? "Anteprima" : "Navigazione su Android"; return ( - - {originPending || (routing && !route) ? "Calcolo del percorso…" : pickingOrigin ? "Tocca la partenza" : route ? `${formatDuration(route.durationSeconds)} · ${formatDistance(route.distanceMeters)}` : error ? "Percorso non disponibile" : "Anteprima del percorso"} - {routing && route ? "Aggiornamento…" : error && route ? "Aggiornamento non riuscito · percorso precedente" : planner.savedJourneyVisible ? "Viaggio salvato · da aggiornare" : retainedSelection ? "Selezione da aggiornare" : navigation.supported ? "Anteprima" : "Navigazione su Android"} + + {summary} + {status} {pickingOrigin ? : } - {navigation.supported ? : null} + {action.kind === "search" ? ( + + ) : action.kind === "follow" ? ( + + ) : action.kind === "start" ? ( + + ) : null} ); } diff --git a/src/features/planner/TransitJourney.tsx b/src/features/planner/TransitJourney.tsx new file mode 100644 index 0000000..691f269 --- /dev/null +++ b/src/features/planner/TransitJourney.tsx @@ -0,0 +1,209 @@ +import { useMemo, useState } from 'react'; +import { StyleSheet, View } from 'react-native'; +import type { RoutePlan, Stop, TransitTime } from '../../domain/types'; +import { matchJourneyStop } from '../../services/transit-stop-matching'; +import { useThemeColors } from '../../theme'; +import type { ThemeColors } from '../../theme/palette'; +import { Button, Icon, IconButton, Notice, Num, Text, TransitLineBadge } from '../../ui'; +import { PressableSurface } from '../../ui/PressableSurface'; +import { journeyDate, journeyTime, savedJourneyTimeLabel, transitTimeLabel } from './journey-presentation'; +import { alternativeRow, journeyTimeline, PLAN_FRESH_MS, type AlternativeRow, type TimelineItem, type TimelineTime, type TimingTone } from './transit-journey'; + +export const TONE_CLASS: Record = { + neutral: 'text-primary', scheduled: 'text-scheduled', caution: 'text-caution', disruption: 'text-cancelled font-semibold', +}; + +/** + * Transit results: concise alternatives, then the selected journey's timeline at once. Times are + * Geist Mono; provenance is spelled out on every boarding and alighting. + */ +export function JourneyResults({ plans, selected, onSelect, onRefresh, loading, error, now, query, saved = false, retained = false, destination, onOpenStop }: { + plans: RoutePlan[]; selected: RoutePlan; onSelect: (id: string) => void; onRefresh: () => void; + loading: boolean; error: string; now: number; query: TransitTime; saved?: boolean; retained?: boolean; + destination?: string; onOpenStop?: (stop: Stop) => void; +}) { + const age = Math.max(0, Math.floor((now - selected.fetchedAt) / 60_000)); + const stale = saved || retained || now - selected.fetchedAt > PLAN_FRESH_MS; + // A retained selection is no longer among the fresh alternatives: list it first, marked. + const rows = useMemo(() => (retained && !plans.some(plan => plan.id === selected.id) ? [selected, ...plans] : plans) + .map((plan, index) => ({ plan, row: alternativeRow(plan, now, index) })), [plans, selected, retained, now]); + return ( + + + + {saved ? savedJourneyTimeLabel(query, selected.fetchedAt) : transitTimeLabel(query)} + + Consultato il {journeyDate(selected.fetchedAt)} alle {journeyTime(selected.fetchedAt)} + {age === 0 ? ' · meno di 1 min fa' : <> · {age} min fa}{stale ? ' · da aggiornare' : ''} + + + + + {error ? : null} + {retained ? : null} + + {rows.map(({ plan, row }) => onSelect(plan.id)} />)} + + + {selected.legs.some(leg => leg.timingStatus === 'prediction') ? : null} + {selected.warnings.map((warning, index) => )} + {selected.source} · © OpenStreetMap contributors. Ora italiana. + + ); +} + +function AlternativeRowView({ row, selected, outdated, onPress }: { row: AlternativeRow; selected: boolean; outdated: boolean; onPress: () => void }) { + const colors = useThemeColors(); + return ( + + {/* Selection is a bar plus a check mark, never fill alone. */} + + + + {row.departure} – {row.arrival} + {row.arrivalDay ? {row.arrivalDay} : null} + + {row.duration} + + + + {row.walking} · {row.changes} · {outdated ? 'Da aggiornare' : row.confidence.label} + + + {selected ? : null} + + ); +} + +function SegmentStrip({ row }: { row: AlternativeRow }) { + const colors = useThemeColors(); + if (!row.segments.length) return A piedi fino alla destinazione; + return + {row.segments.map(segment => segment.kind === 'line' + ? (segment.line ? : {segment.label}) + : segment.kind === 'stay' + ? = + : + + {segment.walk ? <> : null} + )} + ; +} + +/** The selected journey as one vertical rail: walks are thin, rides are the solid ink line. */ +export function JourneyTimeline({ plan, now, stale, destination, onOpenStop, currentKey }: { + plan: RoutePlan; now: number; stale: boolean; destination?: string; onOpenStop?: (stop: Stop) => void; + /** Key of the one step being followed (`walk:`, `board:` or `ride:` plus the leg ID). */ + currentKey?: string; +}) { + const items = useMemo(() => journeyTimeline(plan, { now, stale, destination, match: matchJourneyStop }), [plan, now, stale, destination]); + return + {items.map((item, index) => )} + ; +} + +type Rail = 'ride' | 'walk' | 'none'; +function railKind(next: TimelineItem | undefined): Rail { + if (!next) return 'none'; + return next.kind === 'ride' || next.kind === 'alight' ? 'ride' : 'walk'; +} + +function railColor(colors: ThemeColors, rail: Rail) { return rail === 'ride' ? colors.textPrimary : rail === 'walk' ? colors.divider : 'transparent'; } + +function TimelineRow({ item, last, rail, current, onOpenStop }: { item: TimelineItem; last: boolean; rail: Rail; current: boolean; onOpenStop?: (stop: Stop) => void }) { + const colors = useThemeColors(); + const node = item.kind === 'board' || item.kind === 'alight' || item.kind === 'arrive'; + const time = item.kind === 'board' || item.kind === 'alight' ? item.at : null; + return + + {time ? : item.kind === 'arrive' ? {item.time} : null} + + + {node + ? + : {item.kind === 'walk' ? : null}} + {!last ? : null} + + + + {current ? In corso : null} + + ; +} + +function TimeCell({ at }: { at: TimelineTime }) { + return + {at.time} + {at.scheduled ? {at.scheduled} : null} + ; +} + +function StopLine({ stop }: { stop: { name: string; code?: string; platform?: string } }) { + return {stop.name} + {stop.code ? · fermata {stop.code} : null} + {stop.platform ? · banchina {stop.platform} : null} + ; +} + +function TimelineContent({ item, onOpenStop }: { item: TimelineItem; onOpenStop?: (stop: Stop) => void }) { + switch (item.kind) { + case 'walk': return <> + {item.title} + {item.detail} + ; + case 'wait': return {item.title}; + case 'board': return <> + + {item.line ? : {item.lineLabel}} + {item.direction} + + {item.title} + + + {item.stop.board && onOpenStop ? : null} + ; + case 'ride': return ; + case 'alight': return <> + {item.title} + + + {item.stop.board && onOpenStop ? : null} + ; + case 'arrive': return Arrivo · {item.name}; + } +} + +function ProvenanceLine({ at }: { at: TimelineTime }) { + return {at.provenance}{at.scheduled ? <> · programmato {at.scheduled} : null}; +} + +function RideStops({ item }: { item: Extract }) { + const [open, setOpen] = useState(false); + const stops = item.stops ?? []; + const collapsible = stops.length > 3; + const visible = !collapsible || open; + return + {item.duration} · {item.summary} + {visible && stops.length ? + {stops.map((stop, index) => + {stop.arrivalAt ? {journeyTime(stop.arrivalAt)} : null}{stop.name}{stop.code ? · {stop.code} : null} + )} + : null} + {collapsible ? : null} + ; +} + +function StopBoardButton({ stop, onOpen }: { stop: Stop; onOpen: (stop: Stop) => void }) { + return + + ; +} + diff --git a/src/features/planner/transit-journey.test.ts b/src/features/planner/transit-journey.test.ts new file mode 100644 index 0000000..0a4536b --- /dev/null +++ b/src/features/planner/transit-journey.test.ts @@ -0,0 +1,154 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { RouteLeg, RoutePlan, RouteStop, Stop } from '../../domain/types'; +import { alternativeConfidence, alternativeRow, alternativeSegments, followableJourney, journeyTimeline, legProvenance, plannerPrimaryAction, rideSummary, walkRole, type PrimaryActionInput } from './transit-journey'; + +const T = Date.parse('2026-11-02T11:00:00Z'); // 12:00 in Rome +const min = (value: number) => T + value * 60_000; +function walk(id: string, from: number, to: number, meters = 300): RouteLeg { + return { id, mode: 'walk', from: 'A', to: 'B', transitLeg: false, interlineWithPreviousLeg: false, timingStatus: 'unknown', realTime: false, + durationSeconds: (to - from) * 60, distanceMeters: meters, departureAt: min(from), arrivalAt: min(to), geometry: [], steps: [] }; +} +const stop = (name: string, code: string, platformCode?: string): RouteStop => ({ id: `mato:gtt:${code}`, name, code, coordinate: { latitude: 45.05, longitude: 7.66 }, ...(platformCode ? { platformCode } : {}) }); +function ride(id: string, line: string, from: number, to: number, extra: Partial = {}): RouteLeg { + return { id, mode: 'bus', line, headsign: 'NICHELINO', from: 'STAZIONE LINGOTTO', to: 'GARRONE', fromStop: stop('STAZIONE LINGOTTO', '2603'), toStop: stop('GARRONE', '488'), + transitLeg: true, interlineWithPreviousLeg: false, timingStatus: 'scheduled', realTime: false, + durationSeconds: (to - from) * 60, distanceMeters: 2000, departureAt: min(from), arrivalAt: min(to), geometry: [], steps: [], ...extra }; +} +function plan(legs: RouteLeg[], extra: Partial = {}): RoutePlan { + const boardings = legs.filter(leg => leg.transitLeg && !leg.interlineWithPreviousLeg).length; + const walks = legs.filter(leg => leg.mode === 'walk'); + return { id: legs.map(leg => leg.id).join('|'), mode: 'transit', distanceMeters: 5000, durationSeconds: (legs.at(-1)!.arrivalAt! - legs[0]!.departureAt!) / 1000, + departureAt: legs[0]!.departureAt, arrivalAt: legs.at(-1)!.arrivalAt, + walkingDurationSeconds: walks.reduce((sum, leg) => sum + leg.durationSeconds, 0), walkingDistanceMeters: walks.reduce((sum, leg) => sum + leg.distanceMeters, 0), + waitingDurationSeconds: 0, transferCount: Math.max(0, boardings - 1), geometry: [], legs, source: 'MATO / 5T', warnings: [], fetchedAt: T, ...extra }; +} +const twoLines = () => plan([walk('w1', 0, 4), ride('r1', '14', 6, 16), walk('w2', 16, 19, 220), ride('r2', '4', 22, 34, { mode: 'tram', timingStatus: 'prediction', realTime: true }), walk('w3', 34, 38)]); + +test('an alternative row reads departure–arrival, line badges with a walked change, walking and changes', () => { + const row = alternativeRow(twoLines(), T, 0); + assert.equal(row.departure, '12:00'); + assert.equal(row.arrival, '12:38'); + assert.equal(row.duration, '38 min'); + assert.deepEqual(row.segments.map(item => item.kind === 'line' ? `${item.line}:${item.mode}` : item.kind === 'change' ? `change:${item.walk}` : 'stay'), ['14:bus', 'change:true', '4:tram']); + assert.equal(row.walking, 'A piedi 11 min · 820 m'); + assert.equal(row.changes, '1 cambio'); + assert.deepEqual(row.confidence, { tone: 'scheduled', label: 'In parte programmato' }); + assert.match(row.accessibilityLabel, /^Alternativa 1: partenza 12:00, arrivo 12:38, 38 min, Linea 14, poi Linea 4, 1 cambio/); + assert.equal(row.arrivalDay, undefined); +}); + +test('a same-vehicle continuation is a stay marker, not a change, and a change without walking says so', () => { + const interline = plan([ride('a', '10', 0, 10), ride('b', '10N', 10, 20, { interlineWithPreviousLeg: true })]); + assert.deepEqual(alternativeSegments(interline).map(item => item.kind), ['line', 'stay', 'line']); + assert.equal(alternativeRow(interline, T).changes, 'Nessun cambio'); + const sameStop = plan([ride('a', '10', 0, 10), ride('b', '15', 12, 20)]); + const change = alternativeSegments(sameStop)[1]!; + assert.equal(change.kind === 'change' && change.walk, false); + assert.equal(alternativeRow(sameStop, T).walking, 'Senza tratti a piedi'); +}); + +test('confidence is the most severe word-labelled state: cancellation, passed departure, unknown, then timing mix', () => { + assert.deepEqual(alternativeConfidence(plan([ride('a', '1', 0, 5, { timingStatus: 'cancelled' }), ride('b', '2', 5, 9, { timingStatus: 'unknown' })]), T), { tone: 'disruption', label: 'Corsa cancellata' }); + assert.deepEqual(alternativeConfidence(plan([ride('a', '1', 0, 5)]), min(3)), { tone: 'caution', label: 'Partenza già passata' }); + assert.deepEqual(alternativeConfidence(plan([ride('a', '1', 0, 5)]), min(0.9)), { tone: 'scheduled', label: 'Orari programmati' }); + assert.deepEqual(alternativeConfidence(plan([ride('a', '1', 0, 5, { timingStatus: 'unknown' })]), T), { tone: 'caution', label: 'Orario non confermato' }); + // MATO predictions carry no source timestamp: never the live tone. + assert.deepEqual(alternativeConfidence(plan([ride('a', '1', 0, 5, { timingStatus: 'prediction', realTime: true })]), T), { tone: 'neutral', label: 'Previsione MATO' }); + assert.deepEqual(alternativeConfidence(plan([walk('w', 0, 20)]), T), { tone: 'neutral', label: 'Solo a piedi' }); +}); + +test('an overnight journey names its arrival day', () => { + const late = plan([ride('a', 'N4', 0, 90)], {}); + const shifted = { ...late, departureAt: Date.parse('2026-11-02T22:30:00Z'), arrivalAt: Date.parse('2026-11-03T00:00:00Z') }; + assert.equal(alternativeRow(shifted, T).arrivalDay, 'del 3 nov 2026'); +}); + +const lingotto: Stop = { id: '1765', code: '2603', name: 'STAZIONE LINGOTTO', coordinate: { latitude: 45.05, longitude: 7.66 }, lines: ['14'] }; +const matchLingotto = (routeStop: RouteStop | undefined) => routeStop?.code === '2603' ? lingotto : null; + +test('the timeline runs access walk → board → ride → alight → transfer walk → … → arrive', () => { + const items = journeyTimeline(twoLines(), { now: T, match: matchLingotto, destination: 'Gran Madre' }); + assert.deepEqual(items.map(item => item.kind === 'walk' ? `walk:${item.role}` : item.kind), [ + 'walk:access', 'wait', 'board', 'ride', 'alight', 'walk:transfer', 'wait', 'board', 'ride', 'alight', 'walk:egress', 'arrive', + ]); + const board = items.find(item => item.kind === 'board')!; + assert.ok(board.kind === 'board'); + assert.equal(board.stop.name, 'STAZIONE LINGOTTO'); + assert.equal(board.stop.code, '2603'); + assert.equal(board.direction, 'Direzione NICHELINO'); + assert.equal(board.at.time, '12:06'); + assert.equal(board.at.provenance, 'Orario programmato'); + assert.equal(board.stop.board?.id, '1765', 'validated endpoint links to its board'); + const alight = items.find(item => item.kind === 'alight')!; + assert.ok(alight.kind === 'alight' && alight.stop.board === null, 'unvalidated endpoint has no board link'); + const arrive = items.at(-1)!; + assert.ok(arrive.kind === 'arrive' && arrive.name === 'Gran Madre' && arrive.time === '12:38'); +}); + +test('boarding shows platform and scheduled vs predicted time with MATO provenance', () => { + const predicted = ride('r', '14', 8, 18, { timingStatus: 'prediction', realTime: true, scheduledDepartureAt: min(6), fromStop: stop('STAZIONE LINGOTTO', '2603', 'B') }); + const items = journeyTimeline(plan([predicted]), { now: T, match: () => null }); + const board = items.find(item => item.kind === 'board')!; + assert.ok(board.kind === 'board'); + assert.deepEqual(board.at, { time: '12:08', scheduled: '12:06', provenance: 'Previsione MATO', tone: 'neutral' }); + assert.equal(board.stop.platform, 'B'); + // The same prediction becomes a refresh advisory once the plan is old. + const old = journeyTimeline(plan([predicted]), { now: T + 5 * 60_000, match: () => null }).find(item => item.kind === 'board')!; + assert.ok(old.kind === 'board' && old.at.provenance === 'Previsione MATO da aggiornare' && old.at.tone === 'caution'); + assert.deepEqual(legProvenance(ride('c', '1', 0, 1, { timingStatus: 'cancelled' }), false), { label: 'Corsa cancellata', tone: 'disruption' }); +}); + +test('intermediate stops are listed when supplied and never guessed otherwise', () => { + assert.equal(rideSummary(ride('a', '14', 0, 10)), 'Fermate intermedie non disponibili'); + assert.equal(rideSummary(ride('a', '14', 0, 10, { intermediateStops: [] })), 'Nessuna fermata intermedia indicata'); + const stops = [{ id: 'mato:gtt:2605', name: 'MONTE CORNO', code: '2605', arrivalAt: min(2) }, { id: 'mato:gtt:508', name: 'PASSO BUOLE', code: '508' }]; + const leg = ride('a', '14', 0, 10, { intermediateStops: stops }); + assert.equal(rideSummary(leg), '2 fermate intermedie'); + const item = journeyTimeline(plan([leg]), { now: T, match: () => null }).find(entry => entry.kind === 'ride')!; + assert.ok(item.kind === 'ride' && item.stops?.length === 2 && item.duration === '10 min'); +}); + +test('walk roles distinguish access, transfer, egress and walking-only plans', () => { + const value = twoLines(); + assert.deepEqual([0, 2, 4].map(index => walkRole(value, index)), ['access', 'transfer', 'egress']); + assert.equal(walkRole(plan([walk('w', 0, 10)]), 0), 'only'); +}); + +const base: PrimaryActionInput = { + mode: 'transit', route: null, loading: false, retained: false, picking: false, originPending: false, originReady: true, + supported: true, navigationReady: true, navigationBusy: false, +}; + +test('Mezzi before any search offers Cerca percorsi, never a road Avvia', () => { + assert.deepEqual(plannerPrimaryAction(base), { kind: 'search', label: 'Cerca percorsi', enabled: true, loading: false }); + assert.deepEqual(plannerPrimaryAction({ ...base, loading: true }), { kind: 'search', label: 'Cerca percorsi', enabled: false, loading: true }); + assert.equal(plannerPrimaryAction({ ...base, originReady: false }).reason, 'Scegli la partenza'); + // A road preview still in memory never makes Mezzi start walking guidance. + const road = { ...plan([walk('w', 0, 10)]), mode: 'walk' as const }; + assert.equal(plannerPrimaryAction({ ...base, route: road }).kind, 'search'); +}); + +test('Segui viaggio is enabled only for a selected followable transit alternative', () => { + const route = twoLines(); + assert.deepEqual(plannerPrimaryAction({ ...base, route }), { kind: 'follow', label: 'Segui viaggio', enabled: true, loading: false }); + // Following needs no fix: a pending origin fix or a background refresh never disables it. + assert.equal(plannerPrimaryAction({ ...base, route, originPending: true, loading: true }).enabled, true); + assert.equal(plannerPrimaryAction({ ...base, route, retained: true }).reason, 'Scegli un’alternativa aggiornata'); + assert.equal(plannerPrimaryAction({ ...base, route: plan([ride('a', '1', 0, 5, { timingStatus: 'cancelled' })]) }).reason, 'Include una corsa cancellata'); + assert.equal(plannerPrimaryAction({ ...base, route: plan([walk('w', 0, 9)]) }).reason, 'Alternativa solo a piedi'); + assert.equal(plannerPrimaryAction({ ...base, route, navigationReady: false }).reason, 'Navigazione non pronta'); + assert.deepEqual(plannerPrimaryAction({ ...base, route, navigationBusy: true }), { kind: 'follow', label: 'Segui viaggio', enabled: false, loading: true }); + assert.equal(plannerPrimaryAction({ ...base, route, supported: false }).kind, 'none'); + assert.equal(followableJourney(route), true); + assert.equal(followableJourney({ ...route, mode: 'walk' }), false); +}); + +test('road modes keep Avvia with their existing guards', () => { + const road = { ...plan([walk('w', 0, 10)]), mode: 'walk' as const }; + const input = { ...base, mode: 'walk' as const, route: road }; + assert.deepEqual(plannerPrimaryAction(input), { kind: 'start', label: 'Avvia', enabled: true, loading: false }); + assert.equal(plannerPrimaryAction({ ...input, originPending: true }).enabled, false); + assert.equal(plannerPrimaryAction({ ...input, loading: true }).enabled, false); + assert.equal(plannerPrimaryAction({ ...input, route: twoLines() }).enabled, false, 'a transit plan cannot start road guidance'); +}); diff --git a/src/features/planner/transit-journey.ts b/src/features/planner/transit-journey.ts new file mode 100644 index 0000000..913e665 --- /dev/null +++ b/src/features/planner/transit-journey.ts @@ -0,0 +1,282 @@ +import type { NavigationStart, RoadMode, TransitNavigationStart } from '../../domain/navigation'; +import type { Coordinate, RouteIntermediateStop, RouteLeg, RoutePlan, RouteStop, Stop, TravelMode } from '../../domain/types'; +import { transitModeFromLeg, type TransitMode } from '../../ui/transit-line'; +import { journeyDate, journeyDistance, journeyDuration, journeyTime, waitBefore } from './journey-presentation'; + +/** + * Transit alternatives and the selected journey's timeline, derived from the MATO plan alone so the + * wording is unit-testable. Colour tones follow the brand: `live` is reserved for realtime with a + * source timestamp (MATO supplies none, so planner rows never use it), `caution` for unconfirmed or + * passed times and `disruption` for cancellations. Every tone also has its words. + */ +export type TimingTone = 'neutral' | 'scheduled' | 'caution' | 'disruption'; +/** Planner times older than this are labelled for refresh. */ +export const PLAN_FRESH_MS = 120_000; +/** Provider times are minute-granular: a time counts as passed one minute after it. */ +const PASSED_GRACE_MS = 60_000; + +export type AlternativeSegment = + | { kind: 'line'; key: string; line?: string; mode?: TransitMode; label: string } + /** Between two boardings: a change, on foot when the plan walks between them. */ + | { kind: 'change'; key: string; walk: boolean } + /** The provider's same-vehicle flag: the line continues without a change. */ + | { kind: 'stay'; key: string }; + +export interface AlternativeRow { + id: string; + departure: string; + arrival: string; + /** "del 3 nov 2026" when the journey ends on another day. */ + arrivalDay?: string; + duration: string; + segments: AlternativeSegment[]; + walking: string; + changes: string; + confidence: { tone: TimingTone; label: string }; + accessibilityLabel: string; +} + +export function legLabel(leg: RouteLeg): string { + return leg.transitLeg ? (leg.line ? `Linea ${leg.line}` : 'Mezzo pubblico') : leg.mode === 'walk' ? 'A piedi' : leg.mode === 'bicycle' ? 'In bici' : leg.mode === 'car' ? 'In auto' : 'Tratta'; +} +const transitLegs = (plan: RoutePlan) => plan.legs.filter(leg => leg.transitLeg); + +export function changesLabel(plan: RoutePlan): string { + if (!transitLegs(plan).length) return plan.legs.every(leg => leg.mode === 'walk') ? 'Solo a piedi' : 'Senza mezzi pubblici'; + return plan.transferCount === 0 ? 'Nessun cambio' : `${plan.transferCount} ${plan.transferCount === 1 ? 'cambio' : 'cambi'}`; +} + +export function walkingLabel(plan: RoutePlan): string { + if (plan.walkingDurationSeconds <= 0 && plan.walkingDistanceMeters <= 0) return 'Senza tratti a piedi'; + return `A piedi ${journeyDuration(plan.walkingDurationSeconds)} · ${journeyDistance(plan.walkingDistanceMeters)}`; +} + +/** Line badges in boarding order, with change and same-vehicle markers between them. */ +export function alternativeSegments(plan: RoutePlan): AlternativeSegment[] { + const segments: AlternativeSegment[] = []; + let walkedSinceAlighting = false; + let seenTransit = false; + for (const leg of plan.legs) { + if (!leg.transitLeg) { if (seenTransit) walkedSinceAlighting ||= leg.mode === 'walk' && leg.distanceMeters > 0; continue; } + if (seenTransit) segments.push(leg.interlineWithPreviousLeg ? { kind: 'stay', key: `stay:${leg.id}` } : { kind: 'change', key: `change:${leg.id}`, walk: walkedSinceAlighting }); + segments.push({ kind: 'line', key: leg.id, line: leg.line, mode: transitModeFromLeg(leg.mode), label: legLabel(leg) }); + seenTransit = true; + walkedSinceAlighting = false; + } + return segments; +} + +/** + * One word-labelled confidence per alternative, most severe first: a cancellation, a first boarding + * already passed, an unknown timing state, then the timetable/prediction mix. + */ +export function alternativeConfidence(plan: RoutePlan, now: number): AlternativeRow['confidence'] { + const legs = transitLegs(plan); + if (!legs.length) return { tone: 'neutral', label: 'Solo a piedi' }; + if (legs.some(leg => leg.timingStatus === 'cancelled')) return { tone: 'disruption', label: 'Corsa cancellata' }; + const first = legs[0]!; + if (first.departureAt != null && first.departureAt < now - PASSED_GRACE_MS) return { tone: 'caution', label: 'Partenza già passata' }; + if (legs.some(leg => leg.timingStatus === 'unknown')) return { tone: 'caution', label: 'Orario non confermato' }; + const predicted = legs.filter(leg => leg.timingStatus === 'prediction').length; + if (predicted === legs.length) return { tone: 'neutral', label: 'Previsione MATO' }; + if (predicted > 0) return { tone: 'scheduled', label: 'In parte programmato' }; + return { tone: 'scheduled', label: 'Orari programmati' }; +} + +export function alternativeRow(plan: RoutePlan, now: number, index = 0): AlternativeRow { + const departure = journeyTime(plan.departureAt); + const arrival = journeyTime(plan.arrivalAt); + const overnight = plan.departureAt != null && plan.arrivalAt != null && journeyDate(plan.departureAt) !== journeyDate(plan.arrivalAt); + const segments = alternativeSegments(plan); + const confidence = alternativeConfidence(plan, now); + const duration = journeyDuration(plan.durationSeconds); + const walking = walkingLabel(plan); + const changes = changesLabel(plan); + const lines = segments.filter((item): item is Extract => item.kind === 'line').map(item => item.label); + return { + id: plan.id, departure, arrival, ...(overnight ? { arrivalDay: `del ${journeyDate(plan.arrivalAt!)}` } : {}), duration, segments, walking, changes, confidence, + accessibilityLabel: `Alternativa ${index + 1}: partenza ${departure}, arrivo ${arrival}${overnight ? ` del ${journeyDate(plan.arrivalAt!)}` : ''}, ${duration}, ${lines.length ? lines.join(', poi ') : 'a piedi'}, ${changes}, ${walking}, ${confidence.label}`, + }; +} + +// --------------------------------------------------------------------------------------------- +// Selected journey timeline + +export interface TimelineTime { + /** The time the plan expects (a prediction when MATO supplies one). */ + time: string; + /** Timetable time, only when a supplied delay moves the expected time by a minute or more. */ + scheduled?: string; + provenance: string; + tone: TimingTone; +} +export interface TimelineStop { + name: string; + code?: string; + platform?: string; + /** A GTT stop validated by the strict journey-stop matcher; opens its board. */ + board: Stop | null; +} +export type WalkRole = 'access' | 'transfer' | 'egress' | 'only'; +export type TimelineItem = + | { kind: 'walk'; key: string; role: WalkRole; title: string; detail: string; legIndex: number } + | { kind: 'wait'; key: string; title: string; legIndex: number } + | { kind: 'board'; key: string; legIndex: number; line?: string; mode?: TransitMode; lineLabel: string; direction: string; stop: TimelineStop; at: TimelineTime; title: string; cancelled: boolean } + | { kind: 'ride'; key: string; legIndex: number; duration: string; stops: RouteIntermediateStop[] | null; summary: string } + | { kind: 'alight'; key: string; legIndex: number; stop: TimelineStop; at: TimelineTime; title: string } + | { kind: 'arrive'; key: string; name: string; time: string }; + +/** Planner provenance for one leg: predictions keep the missing source update explicit. */ +export function legProvenance(leg: RouteLeg, stale: boolean): { label: string; tone: TimingTone } { + if (leg.timingStatus === 'cancelled') return { label: 'Corsa cancellata', tone: 'disruption' }; + if (leg.timingStatus === 'scheduled') return { label: 'Orario programmato', tone: 'scheduled' }; + if (leg.timingStatus === 'unknown') return { label: 'Stato dell’orario non disponibile', tone: 'caution' }; + return stale ? { label: 'Previsione MATO da aggiornare', tone: 'caution' } : { label: 'Previsione MATO', tone: 'neutral' }; +} + +function timelineTime(expected: number | undefined, scheduled: number | undefined, leg: RouteLeg, stale: boolean): TimelineTime { + const provenance = legProvenance(leg, stale); + const moved = scheduled != null && expected != null && Math.abs(expected - scheduled) >= 60_000 && journeyTime(expected) !== journeyTime(scheduled); + return { time: journeyTime(expected), ...(moved ? { scheduled: journeyTime(scheduled) } : {}), provenance: provenance.label, tone: provenance.tone }; +} + +function timelineStop(stop: RouteStop | undefined, fallback: string, match: (stop: RouteStop | undefined) => Stop | null): TimelineStop { + return { + name: stop?.name ?? fallback, + ...(stop?.code ? { code: stop.code } : {}), + ...(stop?.platformCode ? { platform: stop.platformCode } : {}), + board: match(stop), + }; +} + +export function walkRole(plan: RoutePlan, index: number): WalkRole { + const before = plan.legs.slice(0, index).some(leg => leg.transitLeg); + const after = plan.legs.slice(index + 1).some(leg => leg.transitLeg); + return before && after ? 'transfer' : after ? 'access' : before ? 'egress' : 'only'; +} + +const walkTitles: Record = { + access: 'A piedi fino alla fermata', transfer: 'Cambio a piedi', egress: 'A piedi fino alla destinazione', only: 'A piedi fino alla destinazione', +}; + +/** Intermediate stops as supplied; a leg without them says so instead of guessing a count. */ +export function rideSummary(leg: RouteLeg): string { + const stops = leg.intermediateStops; + if (!stops) return 'Fermate intermedie non disponibili'; + if (!stops.length) return 'Nessuna fermata intermedia indicata'; + return `${stops.length} ${stops.length === 1 ? 'fermata intermedia' : 'fermate intermedie'}`; +} + +/** + * Access walk → board → ride → alight → transfer walk … → arrive. `match` is the strict GTT stop + * matcher, so only validated stop endpoints link to their boards. + */ +export function journeyTimeline(plan: RoutePlan, options: { now: number; stale?: boolean; destination?: string; match: (stop: RouteStop | undefined) => Stop | null }): TimelineItem[] { + const stale = options.stale || options.now - plan.fetchedAt > PLAN_FRESH_MS; + const items: TimelineItem[] = []; + plan.legs.forEach((leg, index) => { + const previous = plan.legs[index - 1]; + const next = plan.legs[index + 1]; + const wait = waitBefore(leg, previous); + if (wait >= 60 && leg.transitLeg) { + items.push({ kind: 'wait', key: `wait:${leg.id}`, legIndex: index, title: `${leg.interlineWithPreviousLeg ? 'Sosta a bordo' : 'Attesa'} ${journeyDuration(wait)}` }); + } + if (!leg.transitLeg) { + const role = walkRole(plan, index); + const mode = leg.mode === 'walk' ? walkTitles[role] : legLabel(leg); + items.push({ kind: 'walk', key: `walk:${leg.id}`, legIndex: index, role, title: mode, detail: `${journeyDuration(leg.durationSeconds)} · ${journeyDistance(leg.distanceMeters)}` }); + return; + } + const cancelled = leg.timingStatus === 'cancelled'; + if (!leg.interlineWithPreviousLeg) { + items.push({ + kind: 'board', key: `board:${leg.id}`, legIndex: index, line: leg.line, mode: transitModeFromLeg(leg.mode), lineLabel: legLabel(leg), + direction: leg.headsign ? `Direzione ${leg.headsign}` : 'Direzione non fornita dal servizio', + stop: timelineStop(leg.fromStop, leg.from, options.match), at: timelineTime(leg.departureAt, leg.scheduledDepartureAt, leg, stale), + title: cancelled ? 'Partenza cancellata' : 'Sali', cancelled, + }); + } + items.push({ kind: 'ride', key: `ride:${leg.id}`, legIndex: index, duration: journeyDuration(leg.durationSeconds), stops: leg.intermediateStops ?? null, summary: rideSummary(leg) }); + if (!next?.interlineWithPreviousLeg) { + items.push({ + kind: 'alight', key: `alight:${leg.id}`, legIndex: index, stop: timelineStop(leg.toStop, leg.to, options.match), + at: timelineTime(leg.arrivalAt, leg.scheduledArrivalAt, leg, stale), title: cancelled ? 'Arrivo programmato' : 'Scendi', + }); + } + }); + const last = plan.legs.at(-1); + items.push({ kind: 'arrive', key: 'arrive', name: options.destination ?? (last?.to && last.to !== 'Destinazione' ? last.to : 'Destinazione'), time: journeyTime(plan.arrivalAt ?? last?.arrivalAt) }); + return items; +} + +// --------------------------------------------------------------------------------------------- +// The planner's anchored primary action + +export interface PrimaryActionInput { + mode: TravelMode; + route: RoutePlan | null; + loading: boolean; + retained: boolean; + picking: boolean; + /** The origin is awaiting a fresh fix: relevant to road guidance only. */ + originPending: boolean; + originReady: boolean; + supported: boolean; + navigationReady: boolean; + navigationBusy: boolean; +} +export interface PrimaryAction { + kind: 'search' | 'follow' | 'start' | 'none'; + label: string; + enabled: boolean; + loading: boolean; + /** Why the action is unavailable, shown beside it. */ + reason?: string; +} + +export function followableJourney(plan: RoutePlan | null): plan is RoutePlan { + return !!plan && plan.mode === 'transit' && plan.legs.some(leg => leg.transitLeg) && !plan.legs.some(leg => leg.timingStatus === 'cancelled'); +} + +/** + * Mode-correct primary action. In Mezzi it searches until transit alternatives exist and then + * follows the selected one ("Segui viaggio"); it never starts road guidance. Following needs no + * position, so origin locating and background refreshes never disable it. + */ +export function plannerPrimaryAction(input: PrimaryActionInput): PrimaryAction { + const { mode, route } = input; + if (mode === 'transit') { + const transitRoute = route?.mode === 'transit' ? route : null; + if (!transitRoute) { + return { + kind: 'search', label: 'Cerca percorsi', loading: input.loading, + enabled: input.originReady && !input.picking && !input.loading, + ...(!input.originReady || input.picking ? { reason: 'Scegli la partenza' } : {}), + }; + } + if (!input.supported) return { kind: 'none', label: 'Segui viaggio', enabled: false, loading: false, reason: 'Segui il viaggio dall’app Android' }; + const reason = input.retained ? 'Scegli un’alternativa aggiornata' + : transitRoute.legs.some(leg => leg.timingStatus === 'cancelled') ? 'Include una corsa cancellata' + : !transitRoute.legs.some(leg => leg.transitLeg) ? 'Alternativa solo a piedi' + : input.picking ? 'Scegli la partenza' + : !input.navigationReady ? 'Navigazione non pronta' : undefined; + return { kind: 'follow', label: 'Segui viaggio', enabled: !reason && !input.navigationBusy, loading: input.navigationBusy, ...(reason ? { reason } : {}) }; + } + if (!input.supported) return { kind: 'none', label: 'Avvia', enabled: false, loading: false }; + const roadRoute = route?.mode === mode ? route : null; + return { + kind: 'start', label: 'Avvia', loading: false, + enabled: !!roadRoute && input.navigationReady && !input.loading && !input.retained && !input.picking && !input.originPending && !input.navigationBusy, + }; +} + +/** + * The Start request for the plan on screen, or null when it does not belong to the selected mode: + * Mezzi follows a transit journey and never starts road guidance. + */ +export function guidanceStart(mode: TravelMode, route: RoutePlan | null, retained: boolean, endpoints: { origin: Coordinate; destination: Coordinate } | null): + | { kind: 'transit'; options: TransitNavigationStart } | { kind: 'road'; options: NavigationStart } | null { + if (!route || retained || !endpoints) return null; + if (mode === 'transit') return followableJourney(route) ? { kind: 'transit', options: { plan: route, origin: endpoints.origin, destination: endpoints.destination } } : null; + return route.mode === mode ? { kind: 'road', options: { destination: endpoints.destination, mode: mode as RoadMode } } : null; +} diff --git a/src/features/planner/usePlanner.ts b/src/features/planner/usePlanner.ts index fd3212f..b6a5f0f 100644 --- a/src/features/planner/usePlanner.ts +++ b/src/features/planner/usePlanner.ts @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState, useSyncExternalStore } from 'react'; import { Keyboard } from 'react-native'; import type { Coordinate, Place, TransitTime, TravelMode } from '../../domain/types'; import { navigationLocationForReplan } from '../../domain/navigation'; +import { diagnostics } from '../../services/diagnostics'; import { savedTravel, type SavedJourney, type SavedTravelSnapshot } from '../../services/saved-travel'; import { createFeatureContext } from '../app/feature-context'; import type { SheetState } from '../app/sheet'; @@ -14,6 +15,7 @@ import type { NavigationModel } from '../navigation/useNavigation'; import type { Places } from '../places/usePlaces'; import { savedTravelFailureMessage } from '../transit/SavedTravelPanel'; import { routeQueryKey } from './route-state'; +import { guidanceStart } from './transit-journey'; import { useRoutePlans } from './useRoutePlans'; export interface Planner { @@ -190,10 +192,12 @@ export function usePlanner({ tasks, camera, location, places, navigation, sheet, restore(journey); }, [location, camera, sheet, restore, dispatch]); const startGuidance = useCallback(() => { - if (!route || routes.retainedSelection || !task) return; + const start = guidanceStart(mode, route, routes.retainedSelection, task ? { origin: task.origin.coordinate, destination: task.destination.coordinate } : null); + if (!start) { diagnostics.record({ type: 'navigation', state: 'start-ignored' }); return; } + // Transit following needs no position: a pending origin fix is simply cancelled, never awaited. location.cancel(); suspend(); suspendBoard(); camera.follow(); - if (mode === 'transit') void navigation.startTransit({ plan: route, origin: task.origin.coordinate, destination: task.destination.coordinate }); - else void navigation.start({ destination: task.destination.coordinate, mode }); + if (start.kind === 'transit') void navigation.startTransit(start.options); + else void navigation.start(start.options); }, [route, routes.retainedSelection, task, location, suspend, suspendBoard, camera, mode, navigation]); const replanFromNavigation = useCallback(async () => { const current = navigation.snapshot; diff --git a/src/features/transit/NearbyStops.tsx b/src/features/transit/NearbyStops.tsx index 15ad4eb..1f42590 100644 --- a/src/features/transit/NearbyStops.tsx +++ b/src/features/transit/NearbyStops.tsx @@ -1,30 +1,49 @@ import { useMemo } from "react"; import { View } from "react-native"; import { useThemeColors } from "../../theme"; -import { EmptyState, Icon, ListRow, SheetFlatList } from "../../ui"; +import { EmptyState, Icon, ListRow, SectionHeader, SheetFlatList } from "../../ui"; import { distanceFrom } from "../map/distance-reference"; import { useDistanceReference } from "../map/useDistanceReference"; +import { nearbyStopSubtitle } from "./stop-labels"; import { useTransitContext } from "./useTransit"; -/** Trasporti: stops around the explicit search area. */ +/** Trasporti: pilot rail stations and GTT stops around the explicit search area. */ export function NearbyStops() { const colors = useThemeColors(); - const { nearbyStops, openStop } = useTransitContext(); + const { nearbyStops, nearbyStations, openStop, openStation } = useTransitContext(); const reference = useDistanceReference(); // The column shows distances from the device (or the map centre); list the stops in that order. const rows = useMemo(() => nearbyStops.map(stop => ({ stop, distance: distanceFrom(reference, stop.coordinate) })) .sort((a, b) => a.distance.meters - b.distance.meters), [nearbyStops, reference]); + const stations = useMemo(() => nearbyStations.map(station => ({ station, distance: distanceFrom(reference, station.coordinate) })) + .sort((a, b) => a.distance.meters - b.distance.meters), [nearbyStations, reference]); + const header = stations.length ? + + {stations.map(({ station, distance }) => } + onPress={() => openStation(station)} + />)} + + : null; return ( row.stop.id} + ListHeaderComponent={header} renderItem={({ item: { stop: item, distance } }) => { + const subtitle = nearbyStopSubtitle(item); return } onPress={() => openStop(item)} />; diff --git a/src/features/transit/ProviderBoard.tsx b/src/features/transit/ProviderBoard.tsx new file mode 100644 index 0000000..d067218 --- /dev/null +++ b/src/features/transit/ProviderBoard.tsx @@ -0,0 +1,71 @@ +import { ActivityIndicator, View } from 'react-native'; +import { TRANSITOUS_PRIVACY_URL, TRANSITOUS_SOURCES_URL } from '../../services/transitous'; +import { useThemeColors } from '../../theme'; +import { Button, EmptyState, IconButton, Notice, Num, Text, TransitLineBadge, useHairlines } from '../../ui'; +import { journeyTime } from '../planner/journey-presentation'; +import { providerRowView, type ProviderTone } from './provider-board'; +import type { ProviderBoardState } from './useProviderBoard'; + +const TONE: Record = { + declared: 'text-primary', scheduled: 'text-scheduled', caution: 'text-caution', disruption: 'text-cancelled font-semibold', +}; + +/** Shown before the first Transitous request: what is sent, to whom, and for how long it is kept. */ +export function TransitousDisclosure({ text, onAccept, onCancel, onLink }: { text: string; onAccept: () => void; onCancel?: () => void; onLink: (url: string) => void }) { + const hairlines = useHairlines(); + return + Richiesta a Transitous + {text} + + + {onCancel ? : null} + + + ; +} + +/** + * A Transitous board: its own source line, rows with written realtime state and platform, warnings, + * attribution and the sources link. Rows are never combined with GTT rows. + */ +export function ProviderBoardView({ state, now, onLink, emptyTitle }: { state: ProviderBoardState; now: number; onLink: (url: string) => void; emptyTitle: string }) { + const colors = useThemeColors(); + const { board, loading, error, refresh } = state; + const fresh = board ? now < board.nextRefreshAt : false; + return + + + Fonte online: Transitous{board ? <> · consultato alle {journeyTime(board.retrievedAt)} : null} + {board && now - board.retrievedAt > 120_000 ? ' · da aggiornare' : ''} + + + + {loading && !board ? Chiedo gli orari a Transitous… : null} + {error ? : null} + {board ? <> + {board.warnings.map((warning, index) => )} + {board.rows.length ? {board.rows.map(row => )} + : } + + {board.attributions.map(attribution => {attribution})} + + + : null} + ; +} + +function ProviderRow({ row }: { row: ReturnType }) { + const hairlines = useHairlines(); + return + {row.line ? : } + + {row.headsign} + {row.status} + {row.platform || row.operator ? {[row.platform, row.operator].filter(Boolean).join(' · ')} : null} + + + {row.time} + {row.scheduled ? {row.scheduled} : null} + + ; +} diff --git a/src/features/transit/RailStationSheet.tsx b/src/features/transit/RailStationSheet.tsx new file mode 100644 index 0000000..83e92c5 --- /dev/null +++ b/src/features/transit/RailStationSheet.tsx @@ -0,0 +1,32 @@ +import { View } from 'react-native'; +import { TRANSITOUS_PRIVACY_NOTES } from '../../services/transitous'; +import type { RailPilotStation } from '../../services/transitous-stations'; +import { Num, SegmentedControl, Text } from '../../ui'; +import { useFeedback } from '../app/feedback'; +import { detailDistance } from '../map/distance-reference'; +import { useDistanceReference } from '../map/useDistanceReference'; +import { ProviderBoardView, TransitousDisclosure } from './ProviderBoard'; +import { useTransitContext } from './useTransit'; + +const EVENTS = [{ value: 'departure' as const, label: 'Partenze' }, { value: 'arrival' as const, label: 'Arrivi' }]; + +/** A pilot rail station: departures or arrivals from Transitous, after its disclosure. */ +export function RailStationSheet({ station, now }: { station: RailPilotStation; now: number }) { + const transit = useTransitContext(); + const { openLink } = useFeedback(); + const reference = useDistanceReference(); + const distance = detailDistance(reference, station.coordinate); + const { rail, consent } = transit; + return + + + Stazione ferroviaria{distance ? <> · {distance.label} : null} + + + + {!consent.ready ? null : !consent.accepted + ? + : } + Treni e bus Trenitalia della stazione. Gli orari “dichiarati in tempo reale” non indicano quando la fonte li ha aggiornati. Verifica sempre i monitor in stazione. + ; +} diff --git a/src/features/transit/StopBoardPanel.tsx b/src/features/transit/StopBoardPanel.tsx index 95941d9..4c5ab16 100644 --- a/src/features/transit/StopBoardPanel.tsx +++ b/src/features/transit/StopBoardPanel.tsx @@ -1,4 +1,9 @@ -import type { ReactNode } from 'react'; +import { useState, type ReactNode } from 'react'; +import { TRANSITOUS_PRIVACY_NOTES } from '../../services/transitous'; +import type { TransitousConsentSnapshot } from '../../services/transitous-consent'; +import { ProviderBoardView, TransitousDisclosure } from './ProviderBoard'; +import { transitousFallbackOffered } from './provider-board'; +import type { ProviderBoardState } from './useProviderBoard'; import { ActivityIndicator, Switch, View } from 'react-native'; import { Text } from '../../ui/Text'; import type { Stop } from '../../domain/types'; @@ -14,23 +19,51 @@ import { rowPresentation, rowStatusLines, visibleRows } from './departure-status import type { useStopBoard } from './useStopBoard'; type BoardState = ReturnType; -export function StopBoardPanel({ stop, state, now, onLink, onDirections, actions }: { +export interface TransitousFallback { + /** The board's online source is currently Transitous. */ + shown: boolean; + consent: TransitousConsentSnapshot; + board: ProviderBoardState; + open(): void; + close(): void; + accept(): void; +} +export function StopBoardPanel({ stop, state, now, onLink, onDirections, actions, transitous }: { stop: Stop; state: BoardState; now: number; onLink: (url: string) => void; onDirections: () => void; /** Secondary stop actions shown as icons beside refresh, such as saving the stop. */ actions?: ReactNode; + /** Explicit "Cerca su Transitous" replacement of the online source. */ + transitous?: TransitousFallback; }) { + const [asking, setAsking] = useState(false); const reference = useDistanceReference(); const distance = detailDistance(reference, stop.coordinate); const { board, alerts, arrivalsLoading, alertsLoading, arrivalsError, alertsError, refreshArrivals, refreshAlerts, schedules, updateSchedules, setSchedulesWifiOnly, setStopLive } = state; return Fermata {stop.code}{distance ? <> · {distance.label} : null} - + {transitous?.shown ? null : } {actions} + {transitous?.shown ? <> + + + + {!transitous.consent.accepted + ? + : } + : <> {schedules.phase === 'preparing' ? : null} {arrivalsLoading ? : null} {arrivalsError ? : null} + {transitous && transitousFallbackOffered(board, arrivalsError) ? + {asking && !transitous.consent.accepted + ? { setAsking(false); transitous.accept(); transitous.open(); }} onCancel={() => setAsking(false)} onLink={onLink} /> + : <> + Tempo reale GTT non disponibile per questa fermata. Puoi cercare le partenze su Transitous, un servizio esterno: le sue corse sostituiscono quelle GTT in questa bacheca. + + } + : null} {board ? <> Orari programmati GTT {board.schedule.feedVersion}{board.schedule.sourceUpdatedAt ? ` · fonte aggiornata il ${journeyDate(board.schedule.sourceUpdatedAt)}` : ''} @@ -44,6 +77,7 @@ export function StopBoardPanel({ stop, state, now, onLink, onDirections, actions : } {board.attributions.map(attribution => {attribution})} : null} + } {schedules.updateSupported ? diff --git a/src/features/transit/StopSheet.tsx b/src/features/transit/StopSheet.tsx index 3349c39..98bc4fe 100644 --- a/src/features/transit/StopSheet.tsx +++ b/src/features/transit/StopSheet.tsx @@ -34,9 +34,10 @@ export function StopSheet({ stop, now }: { stop: Stop; now: number }) { {saveError ? : null} } + transitous={{ shown: transit.fallback.stopId === stop.id, consent: transit.consent, board: transit.fallback.board, open: transit.fallback.open, close: transit.fallback.close, accept: transit.acceptTransitous }} onDirections={() => { void beginRoute({ - id: `stop:${stop.id}`, name: `Fermata ${stop.name}`, coordinate: stop.coordinate, + id: `stop:${stop.id}`, name: /^fermata\b/i.test(stop.name) ? stop.name : `Fermata ${stop.name}`, coordinate: stop.coordinate, category: "Fermata GTT", source: "GTT", attributions: ["Dati GTT"], }, "walk"); }} diff --git a/src/features/transit/provider-board.test.ts b/src/features/transit/provider-board.test.ts new file mode 100644 index 0000000..c73adf4 --- /dev/null +++ b/src/features/transit/provider-board.test.ts @@ -0,0 +1,73 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import type { TransitBoardRow } from '../../domain/types'; +import type { StopBoard } from '../../transit-data/board-model'; +import { boardModeBadge, providerRowView, transitousFallbackOffered } from './provider-board'; +import { metroOnlyStop, nearbyStopSubtitle } from './stop-labels'; + +const T = Date.parse('2026-11-02T11:00:00Z'); +const min = (value: number) => T + value * 60_000; +function row(extra: Partial = {}): TransitBoardRow { + return { + id: 'r', provider: 'transitous', upstream: { operator: 'TRENITALIA', dataset: 'it_trenitalia.gtfs.zip' }, event: 'departure', mode: 'rail-suburban', + line: 'SFM2', tripNumber: '26442', headsign: 'Chivasso', stop: { id: 'it-trenitalia_00222', name: 'TORINO PORTA SUSA' }, + scheduledAt: min(10), timeBasis: 'scheduled', realtimeState: 'scheduled', tripCancelled: false, retrievedAt: T, ...extra, + }; +} + +test('declared realtime is labelled without a source update and with its delay, never as live', () => { + const view = providerRowView(row({ realtimeState: 'declared-realtime-no-source-time', timeBasis: 'predicted', predictedAt: min(14), providerTimeAt: min(14), platform: { current: '5', changed: false } })); + assert.equal(view.time, '12:14'); + assert.equal(view.scheduled, '12:10'); + assert.equal(view.status, 'Partenza · ritardo 4 min · Dichiarato in tempo reale · aggiornamento origine non disponibile'); + assert.equal(view.tone, 'declared'); + assert.equal(view.platform, 'Binario 5'); + assert.equal(view.line, 'SFM2 26442'); + assert.equal(view.mode, 'rail'); + const onTime = providerRowView(row({ realtimeState: 'declared-realtime-no-source-time', predictedAt: min(10) })); + assert.equal(onTime.scheduled, undefined); + assert.match(onTime.status, /^Partenza · in orario · Dichiarato/); +}); + +test('scheduled, unknown and cancelled rows keep their written state and timetable time', () => { + assert.equal(providerRowView(row()).status, 'Orario programmato · nessun dato in tempo reale'); + assert.equal(providerRowView(row()).tone, 'scheduled'); + const unknown = providerRowView(row({ realtimeState: 'unknown', timeBasis: 'inconsistent', providerTimeAt: min(12) })); + assert.equal(unknown.time, '12:10'); + assert.equal(unknown.tone, 'caution'); + assert.equal(unknown.status, 'Dati in tempo reale incoerenti · orario non confermato'); + assert.equal(providerRowView(row({ realtimeState: 'unknown', timeBasis: 'unknown' })).status, 'Stato in tempo reale non determinabile · orario non confermato'); + const cancelled = providerRowView(row({ realtimeState: 'cancelled', tripCancelled: true })); + assert.equal(cancelled.status, 'Corsa cancellata'); + assert.equal(cancelled.tone, 'disruption'); + assert.match(cancelled.accessibilityLabel, /cancellato/); + assert.equal(providerRowView(row({ realtimeState: 'cancelled', tripCancelled: false })).status, 'Fermata soppressa per questa corsa'); +}); + +test('platforms: a changed track names the timetable one; a published track is shown as supplied', () => { + assert.equal(providerRowView(row({ platform: { scheduled: '3', current: '7', changed: true } })).platform, 'Binario 7 · cambiato da 3'); + assert.equal(providerRowView(row({ platform: { scheduled: '3', changed: false } })).platform, 'Binario 3'); + assert.equal(providerRowView(row()).platform, undefined); + assert.equal(providerRowView(row({ displayName: 'FR 9541', line: undefined })).line, 'FR 9541'); + assert.equal(providerRowView(row({ line: undefined, tripNumber: undefined, headsign: undefined, destination: 'Milano Centrale' })).headsign, 'Milano Centrale'); + assert.deepEqual(['bus', 'coach', 'tram', 'metro', 'rail-high-speed', 'ferry'].map(mode => boardModeBadge(mode as TransitBoardRow['mode'])), ['bus', 'bus', 'tram', 'metro', 'rail', undefined]); +}); + +test('Cerca su Transitous is offered only when GTT realtime is unavailable or unjoinable', () => { + const board = (state: StopBoard['realtime']['state']) => ({ realtime: { state, tripUpdates: 0, matchedTrips: 0, unmatchedTrips: 0 } }) as StopBoard; + assert.equal(transitousFallbackOffered(board('ok'), ''), false); + assert.equal(transitousFallbackOffered(board('unavailable'), ''), true); + assert.equal(transitousFallbackOffered(board('unmatched'), ''), true); + assert.equal(transitousFallbackOffered(board('not-requested'), ''), false); + assert.equal(transitousFallbackOffered(board('not-requested'), 'Rete assente'), true); + assert.equal(transitousFallbackOffered(null, ''), false); + assert.equal(transitousFallbackOffered(null, 'Rete assente'), true); +}); + +test('metro-only stops say they have timetable times only', () => { + assert.equal(metroOnlyStop({ lines: ['M1'] }), true); + assert.equal(metroOnlyStop({ lines: ['M1', '4'] }), false); + assert.equal(metroOnlyStop({ lines: [] }), false); + assert.equal(nearbyStopSubtitle({ code: '8221', lines: ['M1'] }), 'Fermata 8221 · M1 · Solo orari programmati — tempo reale non disponibile'); + assert.equal(nearbyStopSubtitle({ code: '472', lines: ['4', '15'] }), 'Fermata 472 · 4, 15'); +}); diff --git a/src/features/transit/provider-board.ts b/src/features/transit/provider-board.ts new file mode 100644 index 0000000..4894fa3 --- /dev/null +++ b/src/features/transit/provider-board.ts @@ -0,0 +1,95 @@ +import { delayMinutes, realtimeStateLabel } from '../../domain/transit-board'; +import type { TransitBoardMode, TransitBoardRow } from '../../domain/types'; +import type { StopBoard } from '../../transit-data/board-model'; +import type { TransitMode } from '../../ui/transit-line'; +import { journeyTime } from '../planner/journey-presentation'; + +/** + * Rows from an online provider other than the GTT feed (Transitous). They are rendered on their own + * board and never merged with GTT rows. Transitous publishes no source timestamp, so a realtime row + * is "declared" and never shown in the live colour. + */ +export type ProviderTone = 'declared' | 'scheduled' | 'caution' | 'disruption'; +export interface ProviderRowView { + id: string; + line: string; + mode?: TransitMode; + headsign: string; + /** The time to read: declared realtime when present, else the timetable. */ + time: string; + /** Timetable time beside a declared realtime time that differs by a minute or more. */ + scheduled?: string; + status: string; + tone: ProviderTone; + platform?: string; + /** Upstream operator, kept for provenance. */ + operator?: string; + accessibilityLabel: string; +} + +export function boardModeBadge(mode: TransitBoardMode): TransitMode | undefined { + if (mode.startsWith('rail')) return 'rail'; + if (mode === 'bus' || mode === 'coach') return 'bus'; + if (mode === 'tram') return 'tram'; + if (mode === 'metro') return 'metro'; + return undefined; +} + +function platformText(row: TransitBoardRow): string | undefined { + const platform = row.platform; + if (!platform?.current && !platform?.scheduled) return undefined; + if (platform.changed) return `Binario ${platform.current} · cambiato da ${platform.scheduled}`; + // A track without a separate timetable track is shown as published, not as a confirmed change. + return `Binario ${platform.current ?? platform.scheduled}`; +} + +export function providerRowView(row: TransitBoardRow): ProviderRowView { + const line = row.displayName ?? [row.line, row.tripNumber].filter(Boolean).join(' '); + const headsign = row.headsign ?? row.destination ?? 'Destinazione non indicata'; + const event = row.event === 'arrival' ? 'Arrivo' : 'Partenza'; + let time: string; + let scheduled: string | undefined; + let status: string; + let tone: ProviderTone; + switch (row.realtimeState) { + case 'cancelled': + time = journeyTime(row.scheduledAt ?? row.providerTimeAt); + status = realtimeStateLabel(row); + tone = 'disruption'; + break; + case 'declared-realtime-no-source-time': + case 'realtime-with-source-time': { + time = journeyTime(row.predictedAt ?? row.providerTimeAt); + const delay = delayMinutes(row); + if (delay && row.scheduledAt !== undefined) scheduled = journeyTime(row.scheduledAt); + const delayText = delay === undefined ? '' : delay === 0 ? ' · in orario' : delay > 0 ? ` · ritardo ${delay} min` : ` · anticipo ${-delay} min`; + status = `${event}${delayText} · ${realtimeStateLabel(row)}`; + tone = 'declared'; + break; + } + case 'scheduled': + time = journeyTime(row.scheduledAt ?? row.providerTimeAt); + status = realtimeStateLabel(row); + tone = 'scheduled'; + break; + default: + // An unknown state shows the timetable time and says it is unconfirmed. + time = journeyTime(row.scheduledAt ?? row.providerTimeAt); + status = realtimeStateLabel(row); + if (!status.includes('non confermato')) status += ' · orario non confermato'; + tone = 'caution'; + } + const platform = platformText(row); + const spokenLine = line || 'Linea non indicata'; + return { + id: row.id, line, mode: boardModeBadge(row.mode), headsign, time, ...(scheduled ? { scheduled } : {}), status, tone, + ...(platform ? { platform } : {}), ...(row.upstream.operator ? { operator: row.upstream.operator } : {}), + accessibilityLabel: `${spokenLine}, ${headsign}, ${row.realtimeState === 'cancelled' ? 'cancellato' : `alle ${time}`}${scheduled ? `, programmato ${scheduled}` : ''}, ${status}${platform ? `, ${platform}` : ''}`, + }; +} + +/** "Cerca su Transitous" is offered only when GTT realtime could not be retrieved or joined to the installed timetable. */ +export function transitousFallbackOffered(board: StopBoard | null, arrivalsError: string): boolean { + if (!board) return !!arrivalsError; + return board.realtime.state === 'unavailable' || board.realtime.state === 'unmatched' || (!!arrivalsError && board.realtime.state !== 'ok'); +} diff --git a/src/features/transit/stop-labels.ts b/src/features/transit/stop-labels.ts new file mode 100644 index 0000000..1d4567e --- /dev/null +++ b/src/features/transit/stop-labels.ts @@ -0,0 +1,14 @@ +import type { Stop } from '../../domain/types'; +import { LABELS } from '../../transit-data/board-model'; +import { transitModeFromLineName } from '../../ui/transit-line'; + +/** A stop served only by the metro: GTT publishes no metro realtime, so its board is timetable-only. */ +export function metroOnlyStop(stop: Pick): boolean { + return stop.lines.length > 0 && stop.lines.every(line => transitModeFromLineName(line) === 'metro'); +} + +/** Trasporti row subtitle: public code, lines, and the metro's missing realtime in words. */ +export function nearbyStopSubtitle(stop: Pick): string { + const lines = stop.lines.slice(0, 6).join(', ') || 'GTT'; + return `Fermata ${stop.code} · ${lines}${metroOnlyStop(stop) ? ` · ${LABELS.metroScheduledOnly}` : ''}`; +} diff --git a/src/features/transit/useProviderBoard.ts b/src/features/transit/useProviderBoard.ts new file mode 100644 index 0000000..0ad911c --- /dev/null +++ b/src/features/transit/useProviderBoard.ts @@ -0,0 +1,54 @@ +import { useCallback, useLayoutEffect, useReducer, useRef } from 'react'; +import type { TransitBoardSnapshot } from '../../domain/types'; +import { createActiveRefresh, type ActiveRefresh } from '../app/active-refresh'; +import { emptyResource, retainedResourceReducer, visibleResource } from './useStopBoard'; + +export interface ProviderBoardState { + board: TransitBoardSnapshot | null; + loading: boolean; + error: string; + refresh(): void; +} + +/** + * An explicitly requested online board (Transitous). It never polls: the first request follows the + * user's action once `enabled`, later ones only the refresh control. The client's cache answers + * refreshes inside its minimum interval with the same snapshot. + */ +export function useProviderBoard({ identity, enabled, active, load }: { + /** Stop/station and event; a change discards the shown board. */ + identity: string; + enabled: boolean; + active: boolean; + load: (signal: AbortSignal) => Promise; +}): ProviderBoardState { + const [state, update] = useReducer(retainedResourceReducer, emptyResource()); + const controller = useRef(null); + const latestLoad = useRef(load); + latestLoad.current = load; + const activity = useRef(active); + activity.current = active; + const key = enabled ? identity : ''; + useLayoutEffect(() => { + update({ type: 'identity', identity: key }); + if (!key) return; + const next = createActiveRefresh({ + intervalMs: null, + load: async signal => { const board = await latestLoad.current(signal); return { value: board, fetchedAt: board.retrievedAt }; }, + onSuccess: board => update({ type: 'success', identity: key, data: board }), + onError: error => update({ type: 'failure', identity: key, error: error instanceof Error ? error.message : 'Orari non disponibili.' }), + onLoadingChange: loading => update({ type: 'loading', identity: key, loading }), + }); + controller.current = next; + next.setActive(activity.current); + next.refresh(); + return () => { next.dispose(); if (controller.current === next) controller.current = null; }; + }, [key]); + useLayoutEffect(() => { controller.current?.setActive(active); }, [active, key]); + // A request interrupted by leaving the app is repeated on return, once; later ones stay manual. + const hasData = !!visibleResource(state, key).data; + useLayoutEffect(() => { if (active && key && !hasData) controller.current?.refresh(); }, [active, key, hasData]); + const refresh = useCallback(() => { controller.current?.refresh(); }, []); + const visible = visibleResource(state, key); + return { board: key ? visible.data : null, loading: !!key && visible.loading, error: key ? visible.error : '', refresh }; +} diff --git a/src/features/transit/useStopBoard.ts b/src/features/transit/useStopBoard.ts index f5d4830..b26f7e5 100644 --- a/src/features/transit/useStopBoard.ts +++ b/src/features/transit/useStopBoard.ts @@ -34,12 +34,17 @@ export function visibleResource(state: RetainedResource, identity: string) return state.identity === identity ? state : emptyResource(identity); } -export function useStopBoard({ stopId, active }: { stopId?: string; active: boolean }) { +/** + * A stop's board: local scheduled rows first, then the shared citywide realtime feed at the arrivals + * cadence while `active`. `alerts: false` skips service alerts (the transit following screen needs + * only the next departure). + */ +export function useStopBoard({ stopId, active, alerts: withAlerts = true }: { stopId?: string; active: boolean; alerts?: boolean }) { const identity = stopId ?? ''; const [arrivals, updateArrivals] = useReducer(retainedResourceReducer, emptyResource()); const [alerts, updateAlerts] = useReducer(retainedResourceReducer, emptyResource()); const schedules = useSyncExternalStore(timetableService.subscribe, timetableService.status, timetableService.status); - const controllers = useRef<{ arrivals: ActiveRefresh; alerts: ActiveRefresh } | null>(null); + const controllers = useRef<{ arrivals: ActiveRefresh; alerts?: ActiveRefresh } | null>(null); const activity = useRef(active); activity.current = active; // A newly activated package restarts the board's requests (aborting any in flight for the old @@ -78,7 +83,7 @@ export function useStopBoard({ stopId, active }: { stopId?: string; active: bool }, onLoadingChange: loading => updateArrivals({ type: 'loading', identity: boardKey, loading }), }), - alerts: createActiveRefresh({ + alerts: !withAlerts ? undefined : createActiveRefresh({ intervalMs: REFRESH_INTERVALS.alerts, load: async signal => { const snapshot = await getTransitAlerts(identity, { signal }); @@ -90,26 +95,29 @@ export function useStopBoard({ stopId, active }: { stopId?: string; active: bool }), }; controllers.current = next; - for (const controller of Object.values(next)) { + const all = [next.arrivals, ...(next.alerts ? [next.alerts] : [])]; + for (const controller of all) { controller.setActive(activity.current); controller.refresh(); } return () => { scheduled.abort(); - for (const controller of Object.values(next)) controller.dispose(); + for (const controller of all) controller.dispose(); if (controllers.current === next) controllers.current = null; }; - }, [identity, boardKey]); + }, [identity, boardKey, withAlerts]); useLayoutEffect(() => { - if (controllers.current) for (const controller of Object.values(controllers.current)) controller.setActive(active); + const current = controllers.current; + if (current) { current.arrivals.setActive(active); current.alerts?.setActive(active); } }, [active, identity]); // Opening or resuming a board checks the schedule manifest when the last success is over 6 h old. useEffect(() => { if (active && identity) void timetableService.check('open'); }, [active, identity]); const suspend = useCallback(() => { - if (controllers.current) for (const controller of Object.values(controllers.current)) controller.setActive(false); + const current = controllers.current; + if (current) { current.arrivals.setActive(false); current.alerts?.setActive(false); } }, []); const refreshArrivals = useCallback(() => { controllers.current?.arrivals.refresh(); }, []); - const refreshAlerts = useCallback(() => { controllers.current?.alerts.refresh(); }, []); + const refreshAlerts = useCallback(() => { controllers.current?.alerts?.refresh(); }, []); const updateSchedules = useCallback(() => { updateSchedulesNow(); }, []); const setSchedulesWifiOnly = useCallback((value: boolean) => { void timetableService.setWifiOnly(value); }, []); const setStopLive = useCallback((value: boolean) => { diff --git a/src/features/transit/useTransit.ts b/src/features/transit/useTransit.ts index eec7dda..172c40c 100644 --- a/src/features/transit/useTransit.ts +++ b/src/features/transit/useTransit.ts @@ -1,14 +1,21 @@ import { useCallback, useMemo, useState, useSyncExternalStore } from 'react'; -import type { Stop } from '../../domain/types'; +import { transitous } from '../../services/transitous-runtime'; +import { transitousConsent, type TransitousConsentSnapshot } from '../../services/transitous-consent'; +import { nearestRailPilotStations, type RailPilotStation } from '../../services/transitous-stations'; +import type { RouteLeg, Stop } from '../../domain/types'; +import { matchJourneyStop } from '../../services/transit-stop-matching'; import { getNearbyStops } from '../../services'; import { catalogVersion, subscribeCatalog } from '../../transit-data/stop-catalog'; import { savedTravel, type SavedTravelSnapshot } from '../../services/saved-travel'; import { createFeatureContext } from '../app/feature-context'; import type { SheetState } from '../app/sheet'; -import { boardInFront, boardStop, type TaskState } from '../app/task-model'; +import { boardInFront, boardStop, selectedStation, type TaskState } from '../app/task-model'; import { useTaskTransitions, type TaskModel } from '../app/useTaskModel'; import type { DeviceLocation } from '../map/useDeviceLocation'; import type { MapCamera } from '../map/useMapCamera'; +import type { NavigationModel } from '../navigation/useNavigation'; +import { followBoarding } from '../navigation/transit-follow'; +import { useProviderBoard, type ProviderBoardState } from './useProviderBoard'; import { useStopBoard } from './useStopBoard'; export interface Transit { @@ -17,6 +24,23 @@ export interface Transit { /** The stop whose board is open, if any. */ stop: Stop | null; board: ReturnType; + /** + * The next boarding of a followed transit journey: its plan leg, the GTT stop it validates to + * (strict matcher) and that stop's board, polled only while following is on screen. + */ + follow: { leg: RouteLeg | null; stop: Stop | null; board: ReturnType }; + /** Pilot rail stations near the search area, from the bundled mapping, computed on the device. */ + nearbyStations: (RailPilotStation & { distanceMeters: number })[]; + /** The open rail station board (Transitous), departures or arrivals. */ + rail: { station: RailPilotStation | null; event: 'departure' | 'arrival'; setEvent(event: 'departure' | 'arrival'): void; board: ProviderBoardState }; + /** + * "Cerca su Transitous" for the open GTT stop: an explicit replacement of the board's online + * source, never merged with GTT rows. While shown, GTT realtime requests for that board pause. + */ + fallback: { stopId: string | null; open(): void; close(): void; board: ProviderBoardState }; + consent: TransitousConsentSnapshot; + acceptTransitous(): void; + openStation(station: RailPilotStation): void; savedTravel: SavedTravelSnapshot; stopsBusy: boolean; isStopSaved(id: string): boolean; @@ -36,20 +60,46 @@ function boardIdentity(state: TaskState): string | null { const catalogPackageHash = () => catalogVersion().packageHash; -export function useTransit({ tasks, camera, location, sheet, appActive, navigationVisible }: { - tasks: TaskModel; camera: MapCamera; location: DeviceLocation; sheet: SheetState; appActive: boolean; navigationVisible: boolean; +export function useTransit({ tasks, camera, location, sheet, appActive, navigation }: { + tasks: TaskModel; camera: MapCamera; location: DeviceLocation; sheet: SheetState; appActive: boolean; navigation: NavigationModel; }): Transit { + const navigationVisible = navigation.visible; const searchCenter = camera.searchCenter; // Recomputed when the active timetable package (and so its stop catalog) changes. const catalogHash = useSyncExternalStore(subscribeCatalog, catalogPackageHash, catalogPackageHash); const nearbyStops = useMemo(() => { void catalogHash; return getNearbyStops(searchCenter, { limit: 15, radiusMeters: 1800 }); }, [searchCenter, catalogHash]); + const nearbyStations = useMemo(() => nearestRailPilotStations(searchCenter, { radiusMeters: 3000, limit: 3 }), [searchCenter]); const stop = boardStop(tasks.state); - const board = useStopBoard({ stopId: stop?.id, active: !!stop && appActive && !navigationVisible && boardInFront(tasks.state) }); - const { suspend } = board; + const consent = useSyncExternalStore(transitousConsent.subscribe, transitousConsent.getSnapshot, transitousConsent.getSnapshot); + const [fallbackFor, setFallbackFor] = useState(null); + const fallbackStopId = stop && fallbackFor === stop.id ? stop.id : null; + const board = useStopBoard({ stopId: stop?.id, active: !!stop && appActive && !navigationVisible && boardInFront(tasks.state) && !fallbackStopId }); + const fallbackBoard = useProviderBoard({ + identity: fallbackStopId ?? '', enabled: !!fallbackStopId && consent.accepted, + active: !!fallbackStopId && appActive && !navigationVisible && boardInFront(tasks.state), + load: signal => transitous.getGttStopFallbackBoard(stop!, { signal }), + }); + const station = selectedStation(tasks.state); + const [railEvent, setRailEvent] = useState<'departure' | 'arrival'>('departure'); + const railBoard = useProviderBoard({ + identity: station ? `${station.key}:${railEvent}` : '', enabled: !!station && consent.accepted, + active: !!station && appActive && !navigationVisible, + load: signal => transitous.getRailStationBoard(station!, { event: railEvent, signal }), + }); + const following = followBoarding(navigation.snapshot, navigation.transitPlan); + const followLeg = following?.leg ?? null; + const followStop = useMemo(() => { void catalogHash; return followLeg ? matchJourneyStop(followLeg.fromStop) : null; }, [followLeg, catalogHash]); + const followBoard = useStopBoard({ stopId: followStop?.id, active: !!followStop && appActive && navigationVisible && navigation.snapshot.mode === 'transit', alerts: false }); + const { suspend: suspendStopBoard } = board; + const { suspend: suspendFollowBoard } = followBoard; + // Lifecycle suspension stops both; task changes concern only the sheet's board. + const suspend = useCallback(() => { suspendStopBoard(); suspendFollowBoard(); }, [suspendStopBoard, suspendFollowBoard]); // A board stops before React renders a different stop or a task in front of it. useTaskTransitions(tasks, (previous, next) => { const before = boardIdentity(previous); - if (before && (before !== boardIdentity(next) || (boardInFront(previous) && !boardInFront(next)))) suspend(); + if (before && (before !== boardIdentity(next) || (boardInFront(previous) && !boardInFront(next)))) suspendStopBoard(); + // Another stop (or none) closes the Transitous replacement: each stop starts from GTT again. + if (before && before !== boardIdentity(next)) setFallbackFor(null); }); const snapshot = useSyncExternalStore(savedTravel.subscribe, savedTravel.getSnapshot, savedTravel.getSnapshot); const [stopsBusy, setStopsBusy] = useState(false); @@ -67,13 +117,29 @@ export function useTransit({ tasks, camera, location, sheet, appActive, navigati sheet.collapse(); dispatch({ type: 'openStop', stop: next }); }, [camera, location, sheet, dispatch]); + const openStation = useCallback((next: RailPilotStation) => { + location.cancel(); + camera.focus(next.coordinate); + sheet.collapse(); + setRailEvent('departure'); + dispatch({ type: 'openStation', station: next }); + }, [camera, location, sheet, dispatch]); + const fallback = useMemo(() => ({ + stopId: fallbackStopId, board: fallbackBoard, + open: () => { if (stop) setFallbackFor(stop.id); }, + close: () => setFallbackFor(null), + }), [fallbackStopId, fallbackBoard, stop]); + const acceptTransitous = useCallback(() => { void transitousConsent.accept(); }, []); const openJourneyStop = useCallback((next: Stop) => { location.cancel(); dispatch({ type: 'openJourneyStop', stop: next }); camera.focus(next.coordinate); sheet.collapse(); }, [camera, location, sheet, dispatch]); - return { nearbyStops, stop, board, savedTravel: snapshot, stopsBusy, isStopSaved, mutateSavedStops, openStop, openJourneyStop, suspend }; + return { + nearbyStops, stop, board, follow: { leg: followLeg, stop: followStop, board: followBoard }, + nearbyStations, rail: { station, event: railEvent, setEvent: setRailEvent, board: railBoard }, fallback, consent, acceptTransitous, openStation, + savedTravel: snapshot, stopsBusy, isStopSaved, mutateSavedStops, openStop, openJourneyStop, suspend }; } export const [TransitProvider, useTransitContext] = createFeatureContext('Transit'); diff --git a/src/platform/navigation.ts b/src/platform/navigation.ts index e710940..db29d99 100644 --- a/src/platform/navigation.ts +++ b/src/platform/navigation.ts @@ -2,10 +2,11 @@ import { requireOptionalNativeModule } from 'expo'; import { PermissionsAndroid, Platform } from 'react-native'; import type { NavigationPlatform, NavigationSnapshot, NavigationStart, TransitConfirmation, TransitNavigationStart } from '../domain/navigation'; import { idleNavigation } from '../domain/navigation'; +import { nativeRoadStart, nativeTransitStart } from '../domain/navigation-payload'; interface NativeNavigation { - startNavigation(options: NavigationStart): Promise; - startTransitNavigation(options: TransitNavigationStart): Promise; + startNavigation(options: ReturnType): Promise; + startTransitNavigation(options: ReturnType): Promise; confirmTransitStep(sessionId: string, action: TransitConfirmation): Promise; stopNavigation(sessionId: string | null): Promise; retryNavigation(sessionId: string): Promise; @@ -26,8 +27,9 @@ export const navigationPlatform: NavigationPlatform = { if (result[PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION] !== PermissionsAndroid.RESULTS.GRANTED) throw new Error('location-permission'); if (Number(Platform.Version) >= 33) await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS); }, - startNavigation: options => native?.startNavigation(options) ?? unavailable(), - startTransitNavigation: options => native?.startTransitNavigation(options) ?? unavailable(), + // Explicit, bridge-safe payloads: the native bridge rejects nested undefined/null before Kotlin runs. + startNavigation: async (options: NavigationStart) => native ? native.startNavigation(nativeRoadStart(options)) : unavailable(), + startTransitNavigation: async (options: TransitNavigationStart) => native ? native.startTransitNavigation(nativeTransitStart(options)) : unavailable(), confirmTransitStep: (sessionId, action) => native?.confirmTransitStep(sessionId, action) ?? unavailable(), stopNavigation: sessionId => native?.stopNavigation(sessionId) ?? Promise.resolve(idleNavigation), retryNavigation: sessionId => native?.retryNavigation(sessionId) ?? unavailable(), diff --git a/src/platform/road-routing.native.ts b/src/platform/road-routing.native.ts index 9628835..61324d0 100644 --- a/src/platform/road-routing.native.ts +++ b/src/platform/road-routing.native.ts @@ -1,11 +1,12 @@ import { requireOptionalNativeModule } from 'expo'; import { Platform } from 'react-native'; +import { bridgePoint } from '../domain/navigation-payload'; import type { RoadRoutingTransport } from './road-routing.types'; const native = Platform.OS === 'android' ? requireOptionalNativeModule('AvoidNavigation') : null; // An Android build without the module must not bypass the shared native provider queue. export const nativeRoadRouting: RoadRoutingTransport | null = Platform.OS === 'android' ? { - requestRoadRoute: (requestId, from, to, mode) => native?.requestRoadRoute(requestId, from, to, mode) + requestRoadRoute: (requestId, from, to, mode) => native?.requestRoadRoute(requestId, bridgePoint(from), bridgePoint(to), mode) ?? Promise.reject(Object.assign(new Error('Road routing unavailable'), { code: 'unavailable' })), cancelRoadRoute: requestId => native?.cancelRoadRoute(requestId), } : null; diff --git a/src/services/diagnostics.ts b/src/services/diagnostics.ts index 8346bc1..a897227 100644 --- a/src/services/diagnostics.ts +++ b/src/services/diagnostics.ts @@ -7,7 +7,7 @@ const states = { app: ['launch', 'active', 'background', 'inactive', 'unknown', 'runtime-error'], map: ['loaded', 'failed'], location: ['requested', 'approximate', 'precise', 'granted', 'denied', 'fix', 'timeout', 'unavailable', 'services-disabled', 'providers-gps-network', 'providers-gps', 'providers-network', 'providers-other', 'providers-none'], - navigation: ['start-requested', 'start-ignored', 'waiting-for-fix', 'routing', 'active', 'degraded', 'location-inaccurate', 'location-stale', 'location-unavailable', 'start-timeout', 'off-route', 'rerouting', 'arrived', 'stopped', 'interrupted', 'denied', 'location-disabled', 'invalid', 'foreground-required', 'engine-unavailable', 'service-unavailable', 'route-unavailable', 'route-invalid', 'route-network', 'route-timeout', 'route-not-started', 'rate-limit', 'reroute-limit', 'transit-replan-needed', 'native-error'], + navigation: ['start-requested', 'start-ignored', 'waiting-for-fix', 'routing', 'active', 'degraded', 'location-inaccurate', 'location-stale', 'location-unavailable', 'start-timeout', 'off-route', 'rerouting', 'arrived', 'stopped', 'interrupted', 'denied', 'location-disabled', 'invalid', 'foreground-required', 'engine-unavailable', 'service-unavailable', 'route-unavailable', 'route-invalid', 'route-network', 'route-timeout', 'route-not-started', 'rate-limit', 'reroute-limit', 'transit-replan-needed', 'native-error', 'bridge-error'], favorites: ['read-failed', 'write-failed'], 'saved-travel': ['read-failed', 'write-failed', 'remove-failed', 'invalid'], clipboard: ['copied', 'failed'], diff --git a/src/services/notices.ts b/src/services/notices.ts index ff990d8..0dc7aba 100644 --- a/src/services/notices.ts +++ b/src/services/notices.ts @@ -11,8 +11,9 @@ export const PROVIDER_NOTICES = [ { name: 'Ricerca online', text: 'Photon / OpenStreetMap: se la ricerca online è abilitata, nomi e indirizzi cercati e il centro della mappa vengono inviati al servizio. Se Photon non trova una ricerca che nomina un quartiere (per esempio «Eataly Lingotto»), una seconda richiesta invia le altre parole con il punto pubblico OpenStreetMap di quel quartiere al posto del centro mappa. Categorie, fermate e linee sono cercate solo sul dispositivo. Nessuna disponibilità garantita.', url: 'https://photon.komoot.io' }, { name: 'Quartieri', text: `${localities.localities.length} nomi di quartiere con il loro punto OpenStreetMap (© OpenStreetMap contributors · ODbL), estratti il ${localities.retrievedAt}: servono a leggere ricerche come «bar San Salvario». Aree approssimate, non confini.`, url: 'https://www.openstreetmap.org/copyright' }, { name: 'Percorsi stradali', text: 'FOSSGIS / OpenStreetMap: partenza e destinazione inviate al servizio e registrate nei log. Massimo una richiesta al secondo; servizio pubblico per uso moderato.', url: 'https://www.openstreetmap.org/fixthemap' }, - { name: 'Fermate e previsioni', text: `Data source: GTT S.p.A. – Gruppo Torinese Trasporti. Dati per uso non commerciale. Orari programmati GTT ${manifest.gtt.version} inclusi nell’app; versioni più recenti verificate tramite hash vengono scaricate da ${mirrorHosts().join(', ')} (il server vede indirizzo IP e ora della richiesta, non la fermata né la posizione). Il feed tempo reale è scaricato per l’intera città: non contiene la tua posizione né la fermata scelta.`, url: 'https://www.gtt.to.it' }, + { name: 'Fermate e previsioni', text: `Data source: GTT S.p.A. – Gruppo Torinese Trasporti. Dati per uso non commerciale. Orari programmati GTT ${manifest.gtt.version} inclusi nell’app; ${mirrorHosts().length ? `versioni più recenti verificate tramite hash vengono scaricate da ${mirrorHosts().join(', ')} (il server vede indirizzo IP e ora della richiesta, non la fermata né la posizione).` : 'gli aggiornamenti arrivano con le nuove versioni dell’app; quando GTT cambia i codici delle corse l’app legge da gtt.to.it solo l’elenco corse e i calendari (non la fermata né la posizione).'} Il feed tempo reale è scaricato per l’intera città: non contiene la tua posizione né la fermata scelta.`, url: 'https://www.gtt.to.it' }, { name: STOP_LIVE_SETTING, text: STOP_LIVE_DISCLOSURE, url: 'https://www.gtt.to.it' }, + { name: 'Treni e Transitous', text: 'Transitous (api.transitous.org): solo su richiesta esplicita (bacheca di una stazione, «Cerca su Transitous» su una fermata senza tempo reale GTT) riceve il codice della stazione o fermata scelta, mai la posizione. Conserva indirizzo IP, ora e nome dell’app fino a 2 giorni. Dati BusOne, Trenitalia e GTT per uso non commerciale; orari “dichiarati in tempo reale” senza ora di aggiornamento della fonte.', url: 'https://transitous.org/sources/' }, { name: 'Orari GTT: identità delle corse', text: 'Quando GTT riassegna gli identificativi delle corse, l’app legge direttamente dall’archivio orari ufficiale GTT (www.gtt.to.it) solo l’elenco corse e i calendari, con richieste parziali condizionali al massimo una volta al giorno (con «Aggiorna orari», al massimo ogni 10 minuti) e solo con una bacheca aperta. Non invia fermata né posizione; GTT vede indirizzo IP e ora della richiesta.', url: 'https://www.gtt.to.it/open_data/gtt_gtfs.zip' }, { name: 'Treni e ricerca su Transitous', text: 'Transitous (servizio comunitario, uso non commerciale) riceve solo su tua richiesta: il codice della stazione o fermata quando apri una bacheca treni o scegli «Cerca su Transitous», il codice della corsa quando ne apri le fermate, il testo digitato quando cerchi una fermata per nome. Mai la tua posizione. Transitous registra indirizzo IP, ora, URL della richiesta e User-Agent (nome e versione dell’app) e conserva i log fino a 2 giorni. Dati da BusOne (https://busone.app) and Trenitalia; BusOne (https://busone.app) and GTT. Fonti complete al link.', url: 'https://transitous.org/sources/' }, { name: 'Viaggi pubblici', text: 'MATO / 5T: partenza e destinazione inviate al servizio. Integrazione sperimentale; licenza di riuso API, quote e continuità non verificate.', url: 'https://mato.muoversiatorino.it/' }, diff --git a/src/services/routing.test.ts b/src/services/routing.test.ts index ab28188..0fd0646 100644 --- a/src/services/routing.test.ts +++ b/src/services/routing.test.ts @@ -383,3 +383,45 @@ test('route requests send validated depart/arrive time and reject invalid or abo assert.match(queries[0]!, /stop \{ gtfsId name code platformCode \}/); } finally { global.fetch = original; } }); + +test('supplied intermediate stops and realtime delays are kept; malformed stops are dropped, not repaired', async () => { + const value = gttStopLinkLeg(); + value.realTime = true; value.realtimeState = 'UPDATED'; value.departureDelay = 120; value.arrivalDelay = 60; + value.intermediatePlaces = [ + // Captured from a public MATO line 14 response; times are synthetic. + { name: 'MONTE CORNO', arrivalTime: value.startTime + 120_000, lat: 45.02574, lon: 7.65476, stop: { gtfsId: 'gtt:2605', name: 'MONTE CORNO', code: '2605', lat: 45.02574, lon: 7.65476 } }, + { name: 'PASSO BUOLE', arrivalTime: value.endTime + 3_600_000, stop: { gtfsId: 'gtt:508', name: 'PASSO BUOLE', code: '508' } }, + { name: 'senza fermata', arrivalTime: value.startTime + 60_000, stop: null }, + null as never, + ]; + const parsed = parseTransitRoute(response({ duration: 600, legs: [value] }), fetchedAt).legs[0]!; + assert.equal(parsed.timingStatus, 'prediction'); + assert.equal(parsed.scheduledDepartureAt, value.startTime - 120_000); + assert.equal(parsed.scheduledArrivalAt, value.endTime - 60_000); + assert.deepEqual(parsed.intermediateStops, [ + { id: 'mato:gtt:2605', name: 'MONTE CORNO', code: '2605', coordinate: { latitude: 45.02574, longitude: 7.65476 }, arrivalAt: value.startTime + 120_000 }, + // An arrival outside the leg is not a time for this stop. + { id: 'mato:gtt:508', name: 'PASSO BUOLE', code: '508' }, + ]); + const scheduled = gttStopLinkLeg(); + scheduled.departureDelay = 0; + const plain = parseTransitRoute(response({ duration: 600, legs: [scheduled] }), fetchedAt).legs[0]!; + assert.equal(plain.scheduledDepartureAt, undefined, 'a timetable leg has no separate scheduled time'); + const onTime = gttStopLinkLeg(); + onTime.realTime = true; onTime.realtimeState = 'UPDATED'; onTime.departureDelay = 0; + assert.equal(parseTransitRoute(response({ duration: 600, legs: [onTime] }), fetchedAt).legs[0]!.scheduledDepartureAt, onTime.startTime, 'a zero delay states the timetable time'); + const unknownDelay = gttStopLinkLeg(); + unknownDelay.realTime = true; unknownDelay.realtimeState = 'UPDATED'; unknownDelay.departureDelay = null; + assert.equal(parseTransitRoute(response({ duration: 600, legs: [unknownDelay] }), fetchedAt).legs[0]!.scheduledDepartureAt, undefined, 'no delay: timetable time unknown'); + assert.equal(plain.intermediateStops, undefined, 'not requested is not "none"'); + const storage = new Map(); + const store = createSavedTravel({ now: () => fetchedAt + 1000 }); + await store.initialize({ getItem: async key => storage.get(key) ?? null, setItem: async (key, item) => { storage.set(key, item); }, removeItem: async key => { storage.delete(key); } }); + const plan = parseTransitRoute(response({ duration: 600, legs: [value] }), fetchedAt); + assert.equal(await store.saveJourney({ query: { from, to, mode: 'transit', transitTime: { kind: 'now' } }, originLabel: 'A', destinationLabel: 'B', plan }), true); + const reloaded = createSavedTravel(); + await reloaded.initialize({ getItem: async key => storage.get(key) ?? null, setItem: async (key, item) => { storage.set(key, item); }, removeItem: async key => { storage.delete(key); } }); + const restored = reloaded.getSnapshot().journey!.plan.legs[0]!; + assert.deepEqual(restored.intermediateStops, parsed.intermediateStops); + assert.equal(restored.scheduledDepartureAt, parsed.scheduledDepartureAt); +}); diff --git a/src/services/routing.ts b/src/services/routing.ts index ea893df..d18baf4 100644 --- a/src/services/routing.ts +++ b/src/services/routing.ts @@ -160,6 +160,8 @@ export interface MatoLeg { mode: string; duration: number; distance: number; realTime?: boolean | null; realtimeState?: string | null; transitLeg?: boolean | null; interlineWithPreviousLeg?: boolean | null; startTime: number; endTime: number; serviceDate?: string | null; + departureDelay?: number | null; arrivalDelay?: number | null; + intermediatePlaces?: { name?: string | null; arrivalTime?: number | null; lat?: number | null; lon?: number | null; stop?: MatoStop | null }[] | null; route?: { shortName?: string | null; longName?: string | null } | null; trip?: { gtfsId?: string | null; tripHeadsign?: string | null } | null; from: MatoPoint; to: MatoPoint; legGeometry?: { points?: string | null } | null; @@ -195,6 +197,25 @@ function routeStop(point: MatoPoint): RouteStop | undefined { coordinate: pointCoordinate(point.stop) ?? pointCoordinate(point), }; } +/** Supplied intermediate stops; malformed entries are dropped, never repaired. */ +function intermediateStops(leg: MatoLeg): RouteLeg['intermediateStops'] { + if (!Array.isArray(leg.intermediatePlaces)) return undefined; + return leg.intermediatePlaces.slice(0, 200).flatMap(place => { + if (!place || typeof place !== 'object') return []; + const stop = routeStop({ name: text(place.name) ?? '', lat: place.lat, lon: place.lon, stop: place.stop }); + if (!stop) return []; + const arrivalAt = timestamp(place.arrivalTime) && place.arrivalTime! >= leg.startTime && place.arrivalTime! <= leg.endTime ? place.arrivalTime! : undefined; + return [{ id: stop.id, name: stop.name, ...(stop.code ? { code: stop.code } : {}), ...(stop.coordinate ? { coordinate: stop.coordinate } : {}), ...(arrivalAt ? { arrivalAt } : {}) }]; + }); +} +/** + * Timetable time behind a predicted leg time, only when MATO supplies a plausible delay (zero + * included: the prediction then equals the timetable). Without one the timetable time is unknown. + */ +function scheduledTime(time: number, delaySeconds: unknown, status: RouteLeg['timingStatus']): number | undefined { + if (status !== 'prediction' || typeof delaySeconds !== 'number' || !Number.isFinite(delaySeconds) || Math.abs(delaySeconds) > 3 * 3600) return undefined; + return time - delaySeconds * 1000; +} function timingStatus(leg: MatoLeg, transitLeg: boolean): RouteLeg['timingStatus'] { if (!transitLeg) return 'unknown'; const state = text(leg.realtimeState)?.toUpperCase(); @@ -225,6 +246,9 @@ function parseItinerary(itinerary: MatoItinerary, fetchedAt: number): RoutePlan if (!geometry.every(validCoordinate)) invalidTransitData(); } const status = timingStatus(leg, transitLeg); + const scheduledDepartureAt = scheduledTime(leg.startTime, leg.departureDelay, status); + const scheduledArrivalAt = scheduledTime(leg.endTime, leg.arrivalDelay, status); + const stops = transitLeg ? intermediateStops(leg) : undefined; // Known trips retain identity across prediction changes, even without a stop ID. // Only unidentified trips need timing hints to avoid merging unrelated services. const identity = transitLeg && tripId && serviceDate @@ -235,6 +259,8 @@ function parseItinerary(itinerary: MatoItinerary, fetchedAt: number): RoutePlan headsign: text(leg.trip?.tripHeadsign), from: leg.from.name === 'Origin' ? 'Partenza' : leg.from.name, to: leg.to.name === 'Destination' ? 'Destinazione' : leg.to.name, fromStop, toStop, tripId: tripId ? `mato:${tripId}` : undefined, serviceDate, + ...(stops ? { intermediateStops: stops } : {}), + ...(scheduledDepartureAt !== undefined ? { scheduledDepartureAt } : {}), ...(scheduledArrivalAt !== undefined ? { scheduledArrivalAt } : {}), transitLeg, interlineWithPreviousLeg: transitLeg && !!previousIsTransit && leg.interlineWithPreviousLeg === true, timingStatus: status, realTime: status === 'prediction', durationSeconds: leg.duration, distanceMeters: leg.distance, departureAt: leg.startTime, arrivalAt: leg.endTime, @@ -294,7 +320,7 @@ export async function planRoutes(options: PlanRouteOptions): Promise fetchJSON(MATO_ENDPOINT, { method: 'POST', signal, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query }) }, 'mato'), signal); return parseServiceData('mato', () => parseTransitRoutes(response)); } diff --git a/src/services/saved-travel.ts b/src/services/saved-travel.ts index 5bdc34c..1fb538d 100644 --- a/src/services/saved-travel.ts +++ b/src/services/saved-travel.ts @@ -1,4 +1,4 @@ -import type { Coordinate, RouteLeg, RoutePlan, RouteStep, RouteStop, Stop, TransitTime, TravelMode } from '../domain/types'; +import type { Coordinate, RouteIntermediateStop, RouteLeg, RoutePlan, RouteStep, RouteStop, Stop, TransitTime, TravelMode } from '../domain/types'; import { catalogStop, catalogVersion, subscribeCatalog } from '../transit-data/stop-catalog'; import { diagnostics } from './diagnostics'; import { resolveTransitTime } from './transit-time'; @@ -154,6 +154,17 @@ function journeyInput(value: unknown): SavedJourneyInput { coordinate: optional(item.coordinate, point), }; } + function intermediateStop(value: unknown): RouteIntermediateStop { + const item = record(value); + const result: RouteIntermediateStop = { id: string(item.id, 4096), name: string(item.name) }; + const code = optional(item.code, value => string(value, 128)); + const coordinate = optional(item.coordinate, point); + const arrivalAt = optional(item.arrivalAt, timestamp); + if (code !== undefined) result.code = code; + if (coordinate) result.coordinate = coordinate; + if (arrivalAt !== undefined) result.arrivalAt = arrivalAt; + return result; + } function step(value: unknown): RouteStep { if (--remainingSteps < 0) invalid('too-large'); const item = record(value); @@ -172,6 +183,12 @@ function journeyInput(value: unknown): SavedJourneyInput { departureAt: optional(item.departureAt, timestamp), arrivalAt: optional(item.arrivalAt, timestamp), geometry: geometry(item.geometry), steps: list(item.steps, 2_000).map(step), }; + const intermediate = optional(item.intermediateStops, value => list(value, 200).map(intermediateStop)); + if (intermediate) result.intermediateStops = intermediate; + const scheduledDepartureAt = optional(item.scheduledDepartureAt, timestamp); + const scheduledArrivalAt = optional(item.scheduledArrivalAt, timestamp); + if (scheduledDepartureAt !== undefined) result.scheduledDepartureAt = scheduledDepartureAt; + if (scheduledArrivalAt !== undefined) result.scheduledArrivalAt = scheduledArrivalAt; if (result.serviceDate) { const date = result.serviceDate; const iso = `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`; diff --git a/src/services/transitous-consent.test.ts b/src/services/transitous-consent.test.ts new file mode 100644 index 0000000..3d937c8 --- /dev/null +++ b/src/services/transitous-consent.test.ts @@ -0,0 +1,43 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createTransitousConsent, TRANSITOUS_CONSENT_KEY } from './transitous-consent'; + +function memory(initial: Record = {}, failing = false) { + const values = new Map(Object.entries(initial)); + return { + values, + getItem: async (key: string) => { if (failing) throw new Error('unavailable'); return values.get(key) ?? null; }, + setItem: async (key: string, value: string) => { if (failing) throw new Error('unavailable'); values.set(key, value); }, + removeItem: async (key: string) => { values.delete(key); }, + }; +} + +test('no request is consented until the disclosure is acknowledged, and the acknowledgement persists', async () => { + const consent = createTransitousConsent(); + assert.deepEqual(consent.getSnapshot(), { ready: false, accepted: false }); + const storage = memory(); + await consent.initialize(storage); + assert.deepEqual(consent.getSnapshot(), { ready: true, accepted: false }); + await consent.accept(); + assert.equal(consent.getSnapshot().accepted, true); + assert.equal(storage.values.get(TRANSITOUS_CONSENT_KEY), JSON.stringify({ version: 1, accepted: true })); + const later = createTransitousConsent(); + await later.initialize(storage); + assert.equal(later.getSnapshot().accepted, true); + await later.revoke(); + assert.equal(later.getSnapshot().accepted, false); + assert.equal(storage.values.has(TRANSITOUS_CONSENT_KEY), false); +}); + +test('an unreadable or foreign record shows the disclosure again; failed storage keeps a session-only choice', async () => { + for (const raw of ['{', JSON.stringify({ version: 2, accepted: true }), JSON.stringify({ version: 1, accepted: 'yes' }), 'x'.repeat(300)]) { + const consent = createTransitousConsent(); + await consent.initialize(memory({ [TRANSITOUS_CONSENT_KEY]: raw })); + assert.deepEqual(consent.getSnapshot(), { ready: true, accepted: false }, raw.slice(0, 20)); + } + const consent = createTransitousConsent(); + await consent.initialize(memory({}, true)); + assert.deepEqual(consent.getSnapshot(), { ready: true, accepted: false }); + await consent.accept(); + assert.equal(consent.getSnapshot().accepted, true); +}); diff --git a/src/services/transitous-consent.ts b/src/services/transitous-consent.ts new file mode 100644 index 0000000..7e0b8f7 --- /dev/null +++ b/src/services/transitous-consent.ts @@ -0,0 +1,53 @@ +export const TRANSITOUS_CONSENT_KEY = '@avoid-maps/transitous-consent-v1'; +export interface ConsentStorage { + getItem(key: string): Promise; + setItem(key: string, value: string): Promise; + removeItem?(key: string): Promise; +} +export interface TransitousConsentSnapshot { + /** The stored choice has been read (or found unreadable). */ + ready: boolean; + /** The disclosure was acknowledged; until then no Transitous request is issued. */ + accepted: boolean; +} + +/** + * The Transitous disclosure is shown before the first request. Acknowledging it is stored on the + * device only; an unreadable record counts as not acknowledged, so the disclosure is shown again. + */ +export function createTransitousConsent() { + let snapshot: TransitousConsentSnapshot = { ready: false, accepted: false }; + let storage: ConsentStorage | undefined; + let initialization: Promise | undefined; + const listeners = new Set<() => void>(); + const update = (next: TransitousConsentSnapshot) => { snapshot = next; listeners.forEach(listener => listener()); }; + return { + getSnapshot: () => snapshot, + subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; }, + initialize(target: ConsentStorage): Promise { + if (initialization) return initialization; + storage = target; + initialization = (async () => { + try { + const raw = await target.getItem(TRANSITOUS_CONSENT_KEY); + const value: unknown = raw === null || raw.length > 256 ? null : JSON.parse(raw); + const accepted = !!value && typeof value === 'object' && 'version' in value && value.version === 1 && 'accepted' in value && value.accepted === true; + // A choice made before storage finished loading stands. + update({ ready: true, accepted: snapshot.accepted || accepted }); + } catch { update({ ready: true, accepted: snapshot.accepted }); } + })(); + return initialization; + }, + /** Applies at once for this session; persistence failure only means the disclosure returns next launch. */ + async accept(): Promise { + update({ ready: true, accepted: true }); + try { await storage?.setItem(TRANSITOUS_CONSENT_KEY, JSON.stringify({ version: 1, accepted: true })); } catch { /* Session-only acknowledgement. */ } + }, + async revoke(): Promise { + update({ ready: snapshot.ready, accepted: false }); + try { await storage?.removeItem?.(TRANSITOUS_CONSENT_KEY); } catch { /* Next launch still reads a stale record; acceptance is re-shown only then. */ } + }, + }; +} + +export const transitousConsent = createTransitousConsent(); diff --git a/src/transit-data/config.ts b/src/transit-data/config.ts index 0c56cee..877bd81 100644 --- a/src/transit-data/config.ts +++ b/src/transit-data/config.ts @@ -13,12 +13,14 @@ export interface TimetableMirror { /** Hosts that also receive the request through redirects (for privacy notices). */ redirectHosts?: readonly string[]; } -export const TIMETABLE_MIRRORS: readonly TimetableMirror[] = [ - { base: 'https://avoid-quest.github.io/maps/gtt/', layout: 'tree' }, - // Assets of the rolling `gtt-timetable` prerelease (never marked "latest"). - // Release downloads redirect to GitHub's asset CDN, which also sees the request. - { base: 'https://github.com/avoid-quest/maps/releases/download/gtt-timetable/', layout: 'flat', redirectHosts: ['release-assets.githubusercontent.com', 'objects.githubusercontent.com'] }, -]; +/** + * No mirror is configured: GTT's static-export host refuses connections from GitHub-hosted + * runners, so the CI pipeline cannot build packages (the workflow is disabled). Phones reach GTT + * directly, so boards rely on the bundled package plus the identity remap read from GTT. To + * re-enable, publish packages from a host that can reach GTT and list the mirrors here, e.g. + * `{ base: 'https://avoid-quest.github.io/maps/gtt/', layout: 'tree' }`. + */ +export const TIMETABLE_MIRRORS: readonly TimetableMirror[] = []; export const manifestUrl = (mirror: TimetableMirror) => `${mirror.base}manifest.json`; /** `packagePath` is validated as `packages/gtt-.json` before this is called. */ diff --git a/src/ui/PressableSurface.tsx b/src/ui/PressableSurface.tsx index 32cbe82..01c594e 100644 --- a/src/ui/PressableSurface.tsx +++ b/src/ui/PressableSurface.tsx @@ -27,9 +27,11 @@ export function PressableSurface({ surfaceStyle, className, contentClassName, ri children: ReactNode; }) { return ( - - {/* grow: when a row stretches the surface (a taller sibling), the content and its touch area fill it. */} - + // justify-center keeps the content centred when a row stretches the surface (a taller sibling). + // The content must not grow: inside a scroll view a growable child absorbs the scroll content's + // spare height during the sheet's first layout pass (an outlined button became screen-tall). + + {children} diff --git a/src/ui/Sheet.tsx b/src/ui/Sheet.tsx index 565efe4..916b8eb 100644 --- a/src/ui/Sheet.tsx +++ b/src/ui/Sheet.tsx @@ -77,7 +77,7 @@ export function AppSheet({ snap, heights, onSnapChange, header, footer, footerHe accessibilityLabel="" accessibilityRole="none" > - + {header} {children} @@ -119,10 +119,20 @@ function SheetFooter(props: BottomSheetFooterProps) { return {footer}; } -/** Scrolling content that cooperates with sheet dragging. */ +/** + * Fills the space left in the sheet and may shrink below its content. The library sizes the sheet's + * content box with an animated height that arrives after the first layout pass, while that box is + * still sized by its children. React Native's `flex: 1` grows but does not shrink, so a wrapper with + * plain `flex: 1` kept its content height: the ScrollView's viewport equalled its content (nothing + * to scroll) and the end of the content sat below the visible sheet. Every wrapper between the sheet + * and a scroller uses this style. + */ +export const SHRINKING_FILL = { flexGrow: 1, flexShrink: 1, flexBasis: 0, minHeight: 0 } as const; + +/** Scrolling content that cooperates with sheet dragging; fills and scrolls the space left in the sheet. */ export function SheetScrollView({ children }: { children: ReactNode }) { - return {children}; + return {children}; } /** A virtualized list inside the sheet; use for results, stops and saved items. Taps work with the keyboard open. */ -export const SheetFlatList = ((props: Parameters[0]) => ) as typeof BottomSheetFlatList; +export const SheetFlatList = ((props: Parameters[0]) => ) as typeof BottomSheetFlatList; diff --git a/src/ui/index.ts b/src/ui/index.ts index cf3a15f..fb0324f 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -9,7 +9,7 @@ export { SectionHeader } from "./SectionHeader"; export { SheetHeader } from "./SheetHeader"; export { TransitLineBadge } from "./TransitLineBadge"; export { lineBadgeColors, transitModeFromLeg, transitModeFromLineName, type TransitMode } from "./transit-line"; -export { AppSheet, SheetFlatList, SheetScrollView } from "./Sheet"; +export { AppSheet, SheetFlatList, SheetScrollView, SHRINKING_FILL } from "./Sheet"; export { SHEET_SNAPS, type SheetHeights, type SheetSnap } from "./sheet-snaps"; export { Divider, useHairlines } from "./Divider"; export { switchColors } from "./control-styles"; diff --git a/src/ui/sheet-layout.test.ts b/src/ui/sheet-layout.test.ts new file mode 100644 index 0000000..3968778 --- /dev/null +++ b/src/ui/sheet-layout.test.ts @@ -0,0 +1,27 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const read = (path: string) => readFileSync(new URL(`../${path}`, import.meta.url), 'utf8'); + +test('every wrapper between the sheet and its scrollers can shrink (scroll regression)', () => { + // The library sizes its content box after the first layout pass; a plain flex: 1 wrapper keeps its + // content height, so the scroller's viewport equals its content and nothing can scroll. + const sheet = read('ui/Sheet.tsx'); + assert.match(sheet, /export const SHRINKING_FILL = \{ flexGrow: 1, flexShrink: 1, flexBasis: 0, minHeight: 0 \}/); + assert.match(sheet, //, 'the task content wrapper'); + for (const [name, text] of [['Sheet.tsx', sheet], ['TaskSheet.tsx', taskSheet]] as const) { + assert.doesNotMatch(text, /style=\{\{ flex: 1/, `${name} has no non-shrinking flex: 1 wrapper`); + } +}); + +test('pressable content never grows inside scroll content', () => { + // A growable child absorbed the scroll content's spare height during the sheet's first layout pass. + const surface = read('ui/PressableSurface.tsx'); + const pressable = /]*>/.exec(surface)?.[0] ?? ''; + assert.doesNotMatch(pressable, /\bgrow\b|flex-1|flexGrow/); +}); diff --git a/src/ui/sheet-snaps.ts b/src/ui/sheet-snaps.ts index d1ade5b..0a17ec3 100644 --- a/src/ui/sheet-snaps.ts +++ b/src/ui/sheet-snaps.ts @@ -1,6 +1,6 @@ /** * The task sheet rests at one of three heights. `peek` shows the title and the first row of content, - * `half` shares the screen with the map, `full` leaves only the search bar and a strip of map. + * `half` shares the screen with the map, `full` sits just under the search bar. */ export const SHEET_SNAPS = ['peek', 'half', 'full'] as const; export type SheetSnap = typeof SHEET_SNAPS[number];