@motionstudies/core 0.1.0-alpha.0 → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,8 +4,8 @@ Shared packages for the Motion Studies transport instrument. The source workspac
4
4
 
5
5
  - `@motionstudies/core`: transport contracts, indexing, interpolation and visual theme contracts; no browser or Node dependencies.
6
6
  - `@motionstudies/three`: `NationalNetworkScene`, `HubPulseScene`, `StationFlowScene`, camera framing and label-mode contracts. React, React Three Fiber and Three.js are peers; rendering internals are not public subpaths.
7
- - `@motionstudies/web`: picker, theme application, mounting, progressive loaders, observed operations and recording. Import `tokens.css` and `mobile-picker.css` for isolated widgets. `shell.css` is an optional full-page study shell scoped to `.motion-study`; `mountMotionStudy` applies that class. Fonts and edition layouts belong to consumers.
8
- - `@motionstudies/data`: Node-only GTFS readers, network chunking, merging and station ranking. ZIP reading requires `unzip` on the host. Source selection, provenance overrides and compilation commands belong to each edition.
7
+ - `@motionstudies/web`: picker, button tooltips, theme application, mounting, progressive loaders, observed operations and recording. Import `tokens.css` and `mobile-picker.css` for isolated widgets. `shell.css` is an optional full-page study shell scoped to `.motion-study`; `mountMotionStudy` applies that class. Fonts and edition layouts belong to consumers.
8
+ - `@motionstudies/data`: Node-only GTFS readers, ADS-B heatmap compilation, air endpoint enrichment, network chunking, merging and station ranking. ZIP reading requires `unzip` on the host. Source selection, provenance overrides and compilation commands belong to each edition.
9
9
 
10
10
  ```tsx
11
11
  import { MobilePicker } from '@motionstudies/web/components/MobilePicker'
@@ -24,3 +24,172 @@ Keep the resolver stable across renders. Manifest paths and their chunk paths ar
24
24
  Build release candidates with `npm run build:packages`. Distribution manifests and compiled ESM/declarations are written to `.package-dist/`; workspace manifests continue to point at source for fast local iteration. `npm run check:packed` packs and installs those distributions into a separate consumer, builds the lab and validates the public exports. No source aliases or workspace links are used in that consumer.
25
25
 
26
26
  Source workspace manifests always stay private. `npm run check:release` builds public candidates, tests their packed consumer and records the tested tarball hashes; `npm run release:dry-run` inspects the publication without writing to npm. The manual main-branch `release.yml` workflow publishes those same tarballs with public access and provenance. See [release instructions](https://github.com/emmettl/motionstudies/blob/main/docs/RELEASING.md) for bootstrap-token and trusted-publisher setup. All four shared packages are MIT-licensed; each distribution includes `LICENSE`.
27
+
28
+ ## Now and browser location
29
+
30
+ `useNowClock` from `@motionstudies/web/use-now-clock` follows the wall clock on each animation frame, so returning from a suspended tab catches up immediately. Call `start()` from a Now button, set the consumer's playback rate to 1, and render its `time` while `active`. With `NationalNetworkScene`, pass `isPlaying={false}` while this external clock owns time. Call `stop()` before pausing, seeking or changing speed, and retain the last clock time for ordinary playback. Clear moving vehicle selections on entry to keep the camera still; panning and zooming remain available.
31
+
32
+ Supply a resolver `(instant: Date) => number | null` that maps the instant into the edition's service-time coordinates. The edition owns timezone, service date, daylight-saving rules and source coverage. Now is appropriate when the data gives a meaningful sense of this place at this time; exact live vehicle positions are not required. An edition may explicitly map the current local clock onto a suitable representative weekday or seasonal timetable, with a quiet label such as “Typical weekday · realtime pace”. Historical or modelled sources need that same meaningful relationship to the present; merely having timestamps is insufficient. Return null outside the chosen data's coverage: the hook stops, retains the last valid time and exposes `unavailable`. Do not silently relabel a recording as live or wrap a partial study window. Timetable and observed-data labels remain the consumer's responsibility; 1× playback does not imply a live vehicle feed.
33
+
34
+ `useBrowserLocation` from `@motionstudies/web/use-browser-location` requests a single position only when `locate()` is called. It exposes `location`, `status` and `clear()`; it neither stores nor sends coordinates. Render localized messages for denied, timeout and unavailable states. Clearing or unmounting discards late responses. A secure browser context and user permission are required.
35
+
36
+ Pass an in-coverage position as `NationalNetworkScene`'s `userLocation` for a steady glowing dot. Use the existing `focus-location` camera command once after locating, with `[longitude, latitude]` and a suitable `distanceScale`. Validate coverage in the consumer and preserve the view when the user is outside it. Show the reported `accuracy` in accessible text; the dot is an approximate position. The marker hides in diagram layouts. The lab's **Now** specimen uses a clearly labelled synthetic UTC timetable and covers clock, permission and out-of-coverage behavior. Public editions still require independent adoption and releases.
37
+
38
+ ## Selection labels
39
+
40
+ `NationalNetworkScene` gives the selected station first label priority, followed by the selected route's terminal stops (including branches), then intermediate stops. Selected services use their own endpoints. Priority precedes retained labels and ordinary rank/tier admission; clearing selection restores edition ranking. This is built in for every consumer, including geographic and diagram layouts. Supply complete enabled infrastructure as `referenceSnapshot` to preserve endpoints through timetable gaps; its stop indexes need not match the active snapshot. See the [edition behaviour contract](https://github.com/emmettl/motionstudies/blob/main/docs/EDITIONS.md#selection-and-station-labels).
41
+
42
+ ## Button help
43
+
44
+ `mountMotionStudy` installs one shared tooltip surface. Independent consumers such as the lab can render `ButtonTooltips` from `@motionstudies/web/components/ButtonTooltips` once instead. Put concise, action-oriented help in each button’s `data-tooltip`; icon buttons fall back to their `aria-label`. An empty `data-tooltip` opts out. Avoid native `title` attributes on these buttons, which can also appear during touch interaction.
45
+
46
+ Help appears after a short mouse hover or on keyboard focus when the primary pointer is fine and supports hover. Touch input suppresses it, including on hybrid devices. Escape, activation, scrolling and blur dismiss it. The tooltip stays inside the viewport, can itself be hovered, and temporarily extends `aria-describedby` without replacing existing descriptions. Copy and translations stay in the edition; rendering and input handling stay in this package. The Controls specimen and packed-consumer tests exercise this contract.
47
+
48
+ ## Airport heroes and split-flap boards
49
+
50
+ `AirportHeroCard` provides an airport identity header and switchable departure/arrival boards. `SplitFlapBoard` is the underlying transport-neutral widget, also suitable for rail stations. Both use scoped package styles, semantic tables, full accessible cell values, keyboard-operable selection, contained horizontal scrolling and reduced-motion support. Only changed characters remount for the flap animation.
51
+
52
+ ```tsx
53
+ import { AirportHeroCard } from '@motionstudies/web/components/AirportHeroCard'
54
+ import '@motionstudies/web/airport-hero-card.css'
55
+
56
+ <AirportHeroCard
57
+ key={airport.id}
58
+ airport={airport}
59
+ departures={departures}
60
+ arrivals={arrivals}
61
+ study={{ time, windowStart: metadata.windowStart, windowEnd: metadata.windowEnd }}
62
+ dateLabel={metadata.serviceDate}
63
+ note="Observed study · inferred directions; times are observations."
64
+ onSelectFlight={selectAirTrack}
65
+ selectedFlightId={selectedAirTrackId}
66
+ />
67
+ ```
68
+
69
+ Entries have a stable `id`, a `service` label, and optional numeric `time`, `place`, `stand`, `status` and `tone` (`neutral`, `accent` or `warning`). Movement times and `study.time`, `windowStart`, and `windowEnd` must use the same study-relative seconds and service date. Do not parse display strings or normalize numeric times at midnight: an event after 24:00 retains its value above 86,400. `formatTime` optionally controls display formatting; the default uses the study's `formatServiceTime` helper. The header clock is derived directly from `study.time`, with no independent wall clock.
70
+
71
+ The card sorts movements chronologically and shows up to eight rows per direction inside the intersection of the study bounds and a rolling window: ten minutes behind the playback clock and sixty minutes ahead, with inclusive endpoints. Override this with `horizon={{ lookBehindSeconds: 600, lookAheadSeconds: 3600 }}` and `maxRows`. Playback, backward seeking, changed study bounds and updated movement times all recalculate the rows. An out-of-study or invalid clock shows no movements; rows with missing or non-finite times are excluded because they cannot be placed in the window. Other unknown fields render as a dash. Labels include `studyTime`, `boardWindow` and `outsideWindow` for localization. Filtering does not infer operational statuses or clear the consumer's map selection when a row leaves the window.
72
+
73
+ Consumers still own time coordinates, source interpretation and data loading. Supply movements for the displayed horizon, not just aircraft active at the current second, and use the selected study's bounds rather than an individual progressive chunk's bounds. Do not turn an approach-envelope association into a confirmed departure/arrival: unclassified tracks should remain outside these direction lists. Current `AirTrack` data does not supply scheduled times, routes or gates; leave those fields absent, use observation times only when clearly labelled, and explain any inference in the required `note`.
74
+
75
+ Pass `labels` for edition translations, `loading`, or a localized `error` and `onRetry` for data states. The selected direction is local to each card; key the card by airport ID to reset it on selection changes. The Airports lab specimen exercises synthetic timetables, playback, scrubbing, study-window changes, incomplete observations, French labels, long destinations, updates and recovery. Edition adoption happens through their independently pinned package releases; adding this export does not update deployed studies.
76
+
77
+ For a custom rail or transport board, import `SplitFlapBoard` from `@motionstudies/web/components/SplitFlapBoard` and `@motionstudies/web/split-flap-board.css`. Supply `columns` (`key`, `label`, `characters`) and `rows` (`id`, `cells`, optional `tone`). Cell text longer than its flap count is visually ellipsized, with the full value retained for assistive technology and hover. `onSelectRow`, `selectedRowId` and `selectionColumn` optionally make one cell per row selectable.
78
+
79
+ For bus stops and local transport, `DotMatrixBoard` accepts the same rows, selection callbacks, loading state and empty/loading messages. It uses an amber 5 × 7 LED alphabet and its own scoped stylesheet; the flip-board stylesheet is not required. Consumers can switch components without remapping their data.
80
+
81
+ ```tsx
82
+ import { DotMatrixBoard } from '@motionstudies/web/components/DotMatrixBoard'
83
+ import '@motionstudies/web/dot-matrix-board.css'
84
+
85
+ <DotMatrixBoard
86
+ label="Bus departures"
87
+ columns={[
88
+ { key: 'route', label: 'Route', characters: 4, minCharacters: 4 },
89
+ { key: 'destination', label: 'Destination', characters: 24 },
90
+ { key: 'time', label: 'Due', characters: 6, minCharacters: 6, align: 'right' },
91
+ ]}
92
+ rows={[{ id: 'bus-71', cells: { route: '71', destination: 'City Centre', time: '2 min' } }]}
93
+ lineCount="auto"
94
+ style={{ height: 360 }}
95
+ />
96
+ ```
97
+
98
+ `lineCount` defaults to six display slots and accepts 1–30 (values outside that range are clamped; non-finite values use six). Fixed counts keep all slots and scale their contents to the available height, so dense boards need taller containers to remain readable. `"auto"` observes the actual container and fits 1–30 rows at a target `minRowHeight` of 34px. The default board height is 320px; use `style`, `className`, or `height: '100%'` inside a parent with a defined height. Unused slots stay blank; rows beyond the visible slots are omitted, without pagination or changes to consumer selection.
99
+
100
+ For dot-matrix columns, `characters` is a width weight, while `minCharacters` reserves space before the remaining width is distributed. At very narrow widths all columns scale down. Long cell values are visually ellipsized, with their full original text available to assistive technology and on hover. Characters outside the bitmap alphabet (including accented names and non-Latin scripts) use SVG text as a visual fallback. `--matrix-ink` and `--matrix-unlit` customize the LEDs. Updates are immediate, with no flashing or scrolling animation. The **Bus boards** lab specimen exercises both presentations, height/width resizing, row counts, selection, long names, loading and empty states using synthetic timetable data.
101
+
102
+ `variant="uk-rail"` gives the matrix a square black enclosure, mixed-case amber lettering, matrix column headings and horizontal display bands. Optional `heading` and `headingColumnSpan` replace the visual labels across the leading columns while preserving the individual accessible column headers. `footerLabel` and `clockLabel` add a matrix footer; the consumer owns clock formatting and updates. No live clock or pagination is inferred. `DotMatrixRow.note` adds a detail line and an accessible description on the selection button. Details consume one display slot and stay with their departure: if only one slot remains, the next departure with a detail waits until there is room for both. A one-line board still shows its first departure, retaining its full note for assistive technology.
103
+
104
+ ## Rail, bus and airport hero cards
105
+
106
+ Hero cards have separate transport-specific APIs and visual identities, with shared display components underneath:
107
+
108
+ | Card | Identity | Departure fields | Default display |
109
+ | --- | --- | --- | --- |
110
+ | `RailStationHeroCard` | Station name, optional code and locality | Scheduled time, destination, platform, expected time/status, via/service note | UK rail matrix |
111
+ | `BusStopHeroCard` | Stop name, optional stop code and locality | Route, destination, due estimate, optional via | Bus dot matrix |
112
+ | `AirportHeroCard` | IATA code, airport name and city | Flight, time, destination/origin, gate, remarks, direction tabs | Split flap |
113
+
114
+ Import the new cards from `@motionstudies/web/components/RailStationHeroCard` or `@motionstudies/web/components/BusStopHeroCard`, plus `@motionstudies/web/transport-hero-cards.css` (which includes both board styles). Airport imports and study-window behavior remain as documented above.
115
+
116
+ ```tsx
117
+ <RailStationHeroCard
118
+ station={{ name: 'Bristol Temple Meads', code: 'BRI', locality: 'Bristol' }}
119
+ departures={[{
120
+ id: 'train-1', time: '17:15', destination: 'Portsmouth Harbour',
121
+ platform: '9', expected: '17:22', via: 'Eastleigh',
122
+ }]}
123
+ lineCount="auto"
124
+ boardHeight={400}
125
+ clockLabel="16:49:26"
126
+ footerLabel="Study timetable"
127
+ note="Synthetic timetable. Example times, not a live service."
128
+ />
129
+
130
+ <BusStopHeroCard
131
+ stop={{ name: 'Anchor Road', code: 'A1', locality: 'Bristol' }}
132
+ departures={[{ id: 'bus-1', route: '71', destination: 'City Centre', due: '2 min' }]}
133
+ lineCount={6}
134
+ note="Synthetic timetable. Example estimates, not a live service."
135
+ />
136
+ ```
137
+
138
+ Rail and bus consumers supply already ordered and formatted departures, including their own filtering, timezones and freshness. Missing times, platforms and statuses stay unknown rather than becoming “On time”. Both cards accept `presentation` (`'uk-rail'`, `'dot-matrix'`, `'split-flap'`), `lineCount`, `boardHeight` in pixels, `minRowHeight`, `loading`, `error`, `onRetry`, localized `labels`, and controlled `onSelectDeparture`/`selectedDepartureId`. A required `note` explains the source. The matrix fits its container; the split-flap alternative contains scrolling and places any service details in an Information column. Fixed line counts represent physical matrix lines; in split-flap mode they limit departure rows. The **Transport heroes** lab compares all three cards, switches the new cards' presentations, and exercises details, row fitting, updates, long names and failure states.
139
+
140
+ The rail card additionally accepts `presentation="sbb"`: a blue-and-white typographic departure board with service badges, scheduled time, destination/via information and prominent track numbers. This layout follows the information hierarchy in [SBB's general display guide](https://www.sbb.ch/en/travel-information/stations/services-station/station-customer-information/general-display-board.html). It uses ordinary text, including accented and non-Latin names. `RailDeparture.service` supplies a train label such as `IC 1`; optional `serviceCategory` (`'intercity'`, `'international'`, `'regional'`, `'suburban'`) selects the badge treatment. `platformSector` supplies a separate sector label when known. Expected times or disruption messages appear below the scheduled time; absence of a message does not manufacture an “On time” assertion.
141
+
142
+ For this layout, `lineCount` counts departures with their inline detail, and `"auto"` fits rows using a default target height of 64px. Dense fixed counts reduce type size; long values remain in the accessible text and hover titles. Labels stay consumer-owned, including the added `service` column label. The lab's **SBB departure board** option selects a synthetic Zürich HB example with German, French, Italian and English labels. Both new board styles are included in `transport-hero-cards.css`.
143
+
144
+ At compact widths the SBB layout stacks the service badge under the time, preserving destination space and the separate track column. Rail and bus hero padding follows the card width rather than the viewport. The lab includes a 240–980px width slider and Compact/Mobile/Panel/Wide presets, plus a 180–640px board-height control. The size regression suite covers seven card widths, four board heights, fixed and automatic line counts, long destinations, selection during updates, mobile viewports and loading/error states in Chromium and WebKit. Prefer `lineCount="auto"` for small panels; high fixed line counts deliberately trade text size for density.
145
+
146
+ ```tsx
147
+ <RailStationHeroCard
148
+ presentation="sbb"
149
+ station={{ name: 'Zürich HB' }}
150
+ labels={{ station: 'Bahnhof', departures: 'Abfahrt', service: 'Zug', time: 'Zeit', destination: 'Nach', platform: 'Gleis' }}
151
+ departures={[{ id: 'example-1', service: 'IC 1', serviceCategory: 'intercity',
152
+ time: '09:02', destination: 'Genève-Aéroport', via: 'Bern · Lausanne', platform: '32', platformSector: 'ABCD' }]}
153
+ lineCount="auto"
154
+ boardHeight={430}
155
+ note="Synthetic timetable · Example data."
156
+ />
157
+ ```
158
+
159
+ The shared board also accepts `loading`, a localized `loadingMessage`, and `loadingRows` (default five). While loading, its decorative rows cycle through staggered letters and digits; they are hidden from assistive technology and cannot be selected. A single status message announces loading. When data arrives, characters flip through a short sequence and settle into their actual values; later changes animate only the changed characters. These CSS animations have no JavaScript timers and stop looping when loading ends or the board is removed. Reduced-motion users get static blank loading flaps and immediate final text. `AirportHeroCard` uses this shared loading treatment automatically. Use **Reload board** in the Airports lab to preview the complete loading-to-ready transition.
160
+
161
+ Empty messages also appear on the flaps, in the widest column (the destination/origin column in airport cards), with the other columns blank. Longer localized messages wrap across display rows instead of being truncated. They settle with the same animation as flight details, and one hidden status announces the complete message to assistive technology. This also applies when the study clock moves into a window with no movements.
162
+
163
+ Rail and other transport consumers can share the same time filtering through `movementBoardWindow(study, horizon)` and `movementsForBoard(entries, window, maxRows)` from `@motionstudies/core/domain/movement-board`. Format the returned numeric times when mapping them into `SplitFlapBoard` cells. The lab's rail board follows the same study clock and horizon as its airport card.
164
+
165
+ `@motionstudies/data/air-endpoints` provides offline `enrichAirEndpoints` for existing air manifests, chunks and opening snapshots. Supply cached same-date global ADSB.lol heatmaps, an OurAirports CSV and the service date's local UTC offset. It associates only unambiguous low-altitude endpoints near a reference airport; cruise-only traces and uncertain routes stay unknown. Optional `AirEndpoint` origin/destination fields carry airport identity, observed boundary time and `observed-endpoint` evidence. `airportBoardMovements` maps full manifest entries to board rows without confusing playback chunk boundaries with flight endpoints. Input hashes and source/licence attribution are recorded in fixture metadata. These fields describe inferred observations, never flight schedules, gates or live status.
166
+
167
+ ## Optional live airport feed
168
+
169
+ `AirportBoard` from `@motionstudies/web/components/AirportBoard` adds Study/Now controls around an existing `AirportHeroCard` configuration. Pass `studyCard` with the usual card props and `live={{ baseUrl, edition, airport }}` for the shared service. Import `airport-hero-card.css`. `labels` localizes the wrapper's control and availability messages. The lower-level `useAirportFeed` hook and core `domain/live-airport` contract are also public exports.
170
+
171
+ Live timestamps are Unix seconds and use the airport's timezone for display, independently of recorded service time. The wrapper does not pass live flight IDs to the recorded scene's selection callback. The recorded card remains mounted while hidden; the edition still owns playback and can pause its study when appropriate. Only Now mode fetches flight boards; checking capabilities does not query the paid provider. Stale results carry their retrieval time and disappear when expired. Source data never falls back to synthetic or recorded flights under a live label.
172
+
173
+ See [service architecture and operations](../docs/LIVE-AIRPORTS.md). The Worker is deployed separately; npm publication and edition adoption remain explicit release steps.
174
+
175
+ ## Shared recorded air compilation
176
+
177
+ `@motionstudies/data/adsb-heatmap` consolidates the offline heatmap pipeline previously copied between editions. `ingestAdsbHeatmaps` reads cached gzip slices, decodes observations, filters transport-scale tracks, splits flights, and writes either an opening snapshot or an indexed day with overlapping chunks. Source hashes, chunk hashes and ODbL attribution accompany the output. It makes no network requests.
178
+
179
+ The same `decodeAdsbHeatmap` now powers `enrichAirEndpoints`; endpoint inference retains full coordinate precision, while playback compilation retains the existing five-decimal coordinates. `transportAirTracks` and `chunkAirSnapshot` are also available for consumers that assemble their own pipeline. All functions have public TypeScript declarations and work in the packed Node package.
180
+
181
+ Editions supply geographic bounds, service date, explicit UTC offset, optional timezone, input files and output paths. Flight IDs and chunk overlap retain the existing contracts. The default splits known callsign changes and gaps over 30 minutes. Set `splitTracks: false` only when reproducing a legacy opening snapshot with one ID per aircraft. See [adoption and compatibility](../docs/AIR-DATA.md).
182
+
183
+ ## Shared edition controllers and performance
184
+
185
+ `positionForTrain` now indexes chronological stop times with binary search and retains sequential behavior for unordered observations. Stop arrays are immutable: replace the array when a timetable changes. Arrival/departure boundaries, dwell, cancellation and backward seeking retain the existing contract.
186
+
187
+ `countableVehicleTrains(network, stations, selection)` and `createActiveTimetableVehicleCounter(trains, options)` from `@motionstudies/core/domain/vehicle-counts` separate station/route/category membership from clock updates. Build the selector and counter with `useMemo` when data or selection changes, then call the counter at the displayed time. It includes both interval endpoints and excludes cancellations and inverted intervals. Missing stations yield no matches. By default it counts timetable intervals even if a journey lacks enough stops to position; `{ requirePositionable: true }` excludes journeys with fewer than two stops. This distinction is explicit so an edition can retain its established metric.
188
+
189
+ The renderer now shares active GPU upload ranges, paused frame reuse, label and trail frame budgets, cached text comparators and batched hub lines. Custom layers can import the low-level helpers from `@motionstudies/three/render-performance`. Recreate frame trackers when their geometry/data/selection inputs change; `batchHubLines` takes ownership of two-vertex source line resources. Edition-specific worker transfer, picking and cartographic adapters remain consumer-owned.
190
+
191
+ `useJsonAsset<T>(url, enabled, parse?, optional?)` from `@motionstudies/web/use-json-asset` loads a single asset lazily and exposes `data`, `loading`, `error`, `unavailable`, and `retry`. Keep the parser stable and perform edition-specific schema/source compatibility checks there. Successful data remains cached while disabled; consumers decide whether to display it. Changing the URL or parser immediately discards prior-source state, and disabling/unmounting cancels requests. `retry()` discards cached state and requests again when enabled. Optional HTTP 404 responses are unavailable; other failures are errors. No source fallback or freshness policy is inferred.
192
+
193
+ `useTransitionValue(target, { durationMs, easing, steps })` from `@motionstudies/web/use-transition-value` animates a numeric value, returning `value` and `transitioning`. It reverses from the current frame, cancels on teardown, and settles immediately when reduced motion becomes active. `smoothTransition` is the default easing; `cosineTransition` and stepped progress support existing edition rhythms. Keep custom easing functions stable. Camera actions and lazy layout loading stay in the edition.
194
+
195
+ Edition chunk scripts can call `runNetworkChunkCli()` from `@motionstudies/data/network-chunk-cli`. It accepts the existing `--input`, `--manifest`, `--opening`, `--chunk-hours`, `--opening-start`, `--opening-end`, and `--focus` arguments. Source acquisition, provenance, output paths and command invocation remain edition-owned.
package/air-search.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AirEndpoint } from './domain/air.ts';
1
2
  export interface AirSearchTrack {
2
3
  readonly id: string;
3
4
  readonly icaoAddress?: string;
@@ -5,6 +6,8 @@ export interface AirSearchTrack {
5
6
  readonly start: number;
6
7
  readonly end: number;
7
8
  readonly airportIds?: readonly string[];
9
+ readonly origin?: AirEndpoint;
10
+ readonly destination?: AirEndpoint;
8
11
  }
9
12
  export declare function airTrackSearchText(track: AirSearchTrack): string;
10
13
  export declare function airTrackSearchValue(track: AirSearchTrack): string;
@@ -1,4 +1,4 @@
1
- import type { AirSnapshot, AirTrack } from './air.ts';
1
+ import type { AirEndpoint, AirSnapshot, AirTrack } from './air.ts';
2
2
  export interface AirDayAircraft {
3
3
  readonly id: string;
4
4
  readonly icaoAddress: string;
@@ -6,6 +6,8 @@ export interface AirDayAircraft {
6
6
  readonly start: number;
7
7
  readonly end: number;
8
8
  readonly airportIds?: readonly string[];
9
+ readonly origin?: AirEndpoint;
10
+ readonly destination?: AirEndpoint;
9
11
  readonly chunkIds: readonly string[];
10
12
  }
11
13
  export interface AirDayChunkDescriptor {
package/domain/air.d.ts CHANGED
@@ -5,6 +5,15 @@ export type AirSample = readonly [
5
5
  altitudeFeet: number,
6
6
  groundSpeedKnots: number
7
7
  ];
8
+ export interface AirEndpoint {
9
+ readonly icao: string;
10
+ readonly iata: string;
11
+ readonly name: string;
12
+ readonly city: string;
13
+ /** Study-local seconds at the observed approach/departure boundary; not a scheduled time. */
14
+ readonly time: number;
15
+ readonly evidence: 'observed-endpoint';
16
+ }
8
17
  export interface AirTrack {
9
18
  readonly id: string;
10
19
  readonly icaoAddress?: string;
@@ -12,6 +21,8 @@ export interface AirTrack {
12
21
  readonly start: number;
13
22
  readonly end: number;
14
23
  readonly airportIds?: readonly string[];
24
+ readonly origin?: AirEndpoint;
25
+ readonly destination?: AirEndpoint;
15
26
  readonly samples: readonly AirSample[];
16
27
  }
17
28
  export interface AirSnapshot {
@@ -1,4 +1,5 @@
1
1
  import type { AirTrack } from './air.ts';
2
+ import type { AirSearchTrack } from '../air-search.ts';
2
3
  export interface StudyAirport {
3
4
  readonly id: string;
4
5
  readonly name: string;
@@ -15,3 +16,18 @@ export declare function airportSearchText(airport: StudyAirport): string;
15
16
  export declare function searchAirports(airports: readonly StudyAirport[], searchQuery: string, limit?: number): readonly StudyAirport[];
16
17
  export declare function airTrackServesAirport(track: AirTrack, airport: StudyAirport): boolean;
17
18
  export declare function airportAirTrackIds(tracks: readonly AirTrack[], airport: StudyAirport): ReadonlySet<string>;
19
+ /** Board events come from full-flight endpoint evidence, not truncated playback chunks. */
20
+ export declare function airportBoardMovements(aircraft: readonly AirSearchTrack[], airport: StudyAirport): {
21
+ departures: {
22
+ id: string;
23
+ time: number;
24
+ service: string;
25
+ place?: string;
26
+ }[];
27
+ arrivals: {
28
+ id: string;
29
+ time: number;
30
+ service: string;
31
+ place?: string;
32
+ }[];
33
+ };
package/domain/airport.js CHANGED
@@ -39,3 +39,26 @@ export function airportAirTrackIds(tracks, airport) {
39
39
  .filter((track) => airTrackServesAirport(track, airport))
40
40
  .map((track) => track.id));
41
41
  }
42
+ /** Board events come from full-flight endpoint evidence, not truncated playback chunks. */
43
+ export function airportBoardMovements(aircraft, airport) {
44
+ const departures = [];
45
+ const arrivals = [];
46
+ const seen = new Set();
47
+ for (const track of aircraft) {
48
+ for (const direction of ['origin', 'destination']) {
49
+ const endpoint = track[direction];
50
+ if (!endpoint || endpoint.icao !== airport.icao || !Number.isFinite(endpoint.time))
51
+ continue;
52
+ const key = `${track.icaoAddress ?? track.id}:${direction}:${endpoint.time}`;
53
+ if (seen.has(key))
54
+ continue;
55
+ seen.add(key);
56
+ const other = direction === 'origin' ? track.destination : track.origin;
57
+ const row = { id: track.id, time: endpoint.time, service: track.callsign,
58
+ place: other ? `${other.city || other.name} ${other.iata || other.icao}` : undefined };
59
+ const rows = direction === 'origin' ? departures : arrivals;
60
+ rows.push(row);
61
+ }
62
+ }
63
+ return { departures, arrivals };
64
+ }
@@ -0,0 +1,42 @@
1
+ /** Live boards use Unix seconds throughout, independent of an edition's recorded service day. */
2
+ export interface LiveAirportMovement {
3
+ readonly id: string;
4
+ readonly service: string;
5
+ readonly scheduledTime?: number;
6
+ /** Provider revision: may be estimated or actual; do not relabel as confirmed. */
7
+ readonly revisedTime?: number;
8
+ readonly place?: string;
9
+ readonly gate?: string;
10
+ readonly status?: string;
11
+ readonly tone?: 'neutral' | 'accent' | 'warning';
12
+ }
13
+ export interface LiveAirportSnapshot {
14
+ readonly airport: {
15
+ readonly iata: string;
16
+ readonly name: string;
17
+ readonly city: string;
18
+ readonly timeZone: string;
19
+ };
20
+ readonly fetchedAt: number;
21
+ readonly freshUntil: number;
22
+ readonly expiresAt: number;
23
+ readonly windowStart: number;
24
+ readonly windowEnd: number;
25
+ readonly departures: readonly LiveAirportMovement[];
26
+ readonly arrivals: readonly LiveAirportMovement[];
27
+ }
28
+ export type AirportFeedReason = 'disabled' | 'not-configured' | 'subscription' | 'budget' | 'provider' | 'rate-limit';
29
+ export interface AirportFeedResponse {
30
+ readonly version: 1;
31
+ readonly status: 'fresh' | 'stale' | 'unavailable' | 'disabled';
32
+ readonly reason?: AirportFeedReason;
33
+ readonly retryAfterSeconds: number;
34
+ readonly snapshot?: LiveAirportSnapshot;
35
+ }
36
+ export interface AirportFeedCapabilities {
37
+ readonly version: 1;
38
+ readonly enabled: boolean;
39
+ readonly airports: readonly string[];
40
+ }
41
+ /** Validate the network boundary before publishing data to a card. */
42
+ export declare function isAirportFeedResponse(value: unknown): value is AirportFeedResponse;
@@ -0,0 +1,32 @@
1
+ const record = (value) => !!value && typeof value === 'object';
2
+ const finite = (value) => typeof value === 'number' && Number.isFinite(value);
3
+ function movement(value) {
4
+ return record(value) && typeof value.id === 'string' && typeof value.service === 'string'
5
+ && ['scheduledTime', 'revisedTime'].every((key) => value[key] === undefined || finite(value[key]))
6
+ && ['place', 'gate', 'status'].every((key) => value[key] === undefined || typeof value[key] === 'string')
7
+ && (value.tone === undefined || ['neutral', 'accent', 'warning'].includes(String(value.tone)));
8
+ }
9
+ /** Validate the network boundary before publishing data to a card. */
10
+ export function isAirportFeedResponse(value) {
11
+ if (!record(value) || value.version !== 1 || !['fresh', 'stale', 'unavailable', 'disabled'].includes(String(value.status))
12
+ || !finite(value.retryAfterSeconds) || value.retryAfterSeconds < 0)
13
+ return false;
14
+ if (value.status === 'disabled' || value.status === 'unavailable')
15
+ return value.snapshot === undefined;
16
+ const s = value.snapshot;
17
+ try {
18
+ if (!record(s) || !record(s.airport) || typeof s.airport.timeZone !== 'string')
19
+ return false;
20
+ new Intl.DateTimeFormat('en', { timeZone: s.airport.timeZone }).format(0);
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ return record(s) && record(s.airport)
26
+ && ['iata', 'name', 'city', 'timeZone'].every((key) => typeof s.airport[key] === 'string')
27
+ && ['fetchedAt', 'freshUntil', 'expiresAt', 'windowStart', 'windowEnd'].every((key) => finite(s[key]))
28
+ && Number(s.fetchedAt) <= Number(s.freshUntil) && Number(s.freshUntil) <= Number(s.expiresAt)
29
+ && Number(s.windowStart) < Number(s.windowEnd)
30
+ && Array.isArray(s.departures) && s.departures.every(movement)
31
+ && Array.isArray(s.arrivals) && s.arrivals.every(movement);
32
+ }
@@ -0,0 +1,21 @@
1
+ /** All values use the study's time coordinate, in seconds (including times beyond midnight). */
2
+ export interface MovementBoardStudy {
3
+ readonly time: number;
4
+ readonly windowStart: number;
5
+ readonly windowEnd: number;
6
+ }
7
+ export interface MovementBoardHorizon {
8
+ readonly lookBehindSeconds?: number;
9
+ readonly lookAheadSeconds?: number;
10
+ }
11
+ export interface MovementBoardWindow {
12
+ readonly start: number;
13
+ readonly end: number;
14
+ }
15
+ /** Keep recent movements briefly, then show the next hour, clipped to the selected study. */
16
+ export declare function movementBoardWindow(study: MovementBoardStudy, { lookBehindSeconds, lookAheadSeconds }?: MovementBoardHorizon): MovementBoardWindow | undefined;
17
+ /** Unknown times cannot be placed in a time-windowed board. Never mutate the caller's rows. */
18
+ export declare function movementsForBoard<T extends {
19
+ readonly id: string;
20
+ readonly time?: number;
21
+ }>(movements: readonly T[], window: MovementBoardWindow | undefined, maxRows?: number): readonly T[];
@@ -0,0 +1,23 @@
1
+ /** Keep recent movements briefly, then show the next hour, clipped to the selected study. */
2
+ export function movementBoardWindow(study, { lookBehindSeconds = 600, lookAheadSeconds = 3600 } = {}) {
3
+ const { time, windowStart, windowEnd } = study;
4
+ if (![time, windowStart, windowEnd, lookBehindSeconds, lookAheadSeconds].every(Number.isFinite)
5
+ || windowStart > windowEnd || time < windowStart || time > windowEnd
6
+ || lookBehindSeconds < 0 || lookAheadSeconds < 0)
7
+ return undefined;
8
+ return {
9
+ start: Math.max(windowStart, time - lookBehindSeconds),
10
+ end: Math.min(windowEnd, time + lookAheadSeconds),
11
+ };
12
+ }
13
+ /** Unknown times cannot be placed in a time-windowed board. Never mutate the caller's rows. */
14
+ export function movementsForBoard(movements, window, maxRows = 8) {
15
+ if (!window || ![window.start, window.end, maxRows].every(Number.isFinite)
16
+ || window.start > window.end || maxRows < 1)
17
+ return [];
18
+ return movements
19
+ .filter((entry) => entry.time !== undefined && Number.isFinite(entry.time)
20
+ && entry.time >= window.start && entry.time <= window.end)
21
+ .sort((first, second) => first.time - second.time || (first.id < second.id ? -1 : first.id > second.id ? 1 : 0))
22
+ .slice(0, Math.floor(maxRows));
23
+ }
package/domain/network.js CHANGED
@@ -69,7 +69,7 @@ export function buildStationIndex(snapshot) {
69
69
  routes: [...record.routes.values()].sort((first, second) => first.name.localeCompare(second.name, 'de-CH')),
70
70
  }));
71
71
  }
72
- export function positionForTrain(train, time) {
72
+ function linearPositionForTrain(train, time) {
73
73
  if (train.realtime?.status === 'cancelled' ||
74
74
  time < train.start ||
75
75
  time > train.end ||
@@ -98,6 +98,42 @@ export function positionForTrain(train, time) {
98
98
  const last = train.stops.at(-1);
99
99
  return { fromStop: last[0], toStop: last[0], progress: 0 };
100
100
  }
101
+ // Timetables are immutable. A replacement stop array (including realtime edits)
102
+ // gets its own validation; old schedules can be garbage collected.
103
+ const chronologicalSchedules = new WeakMap();
104
+ export function positionForTrain(train, time) {
105
+ if (train.realtime?.status === 'cancelled' || time < train.start || time > train.end || train.stops.length < 2)
106
+ return;
107
+ const stops = train.stops;
108
+ let chronological = chronologicalSchedules.get(stops);
109
+ if (chronological === undefined) {
110
+ chronological = stops.every((stop, index) => Number.isFinite(stop[1]) && Number.isFinite(stop[2]) &&
111
+ stop[2] >= stop[1] && (index === 0 || stop[1] >= stops[index - 1][2]));
112
+ chronologicalSchedules.set(stops, chronological);
113
+ }
114
+ // Preserve sequential semantics for unordered observations and non-finite clocks.
115
+ if (!chronological || !Number.isFinite(time))
116
+ return linearPositionForTrain(train, time);
117
+ let lower = 0;
118
+ let upper = stops.length;
119
+ while (lower < upper) {
120
+ const middle = (lower + upper) >>> 1;
121
+ if (stops[middle][2] < time)
122
+ lower = middle + 1;
123
+ else
124
+ upper = middle;
125
+ }
126
+ const next = stops[Math.min(lower, stops.length - 1)];
127
+ if (lower === 0 || lower === stops.length || time > next[1]) {
128
+ return { fromStop: next[0], toStop: next[0], progress: 0 };
129
+ }
130
+ const previous = stops[lower - 1];
131
+ return {
132
+ fromStop: previous[0], toStop: next[0],
133
+ progress: Math.min(1, Math.max(0, (time - previous[2]) / Math.max(1, next[1] - previous[2]))),
134
+ segmentIndex: lower - 1,
135
+ };
136
+ }
101
137
  export function formatServiceTime(totalSeconds) {
102
138
  const normalized = ((Math.round(totalSeconds) % 86400) + 86400) % 86400;
103
139
  const hours = Math.floor(normalized / 3600);
@@ -0,0 +1,15 @@
1
+ import type { NetworkSnapshot, ServiceCategory } from './network.ts';
2
+ export interface StationDeparture {
3
+ readonly id: string;
4
+ readonly trainId: string;
5
+ /** Time from the supplied snapshot: realtime-adjusted snapshots contain adjusted times. */
6
+ readonly time: number;
7
+ readonly service: string;
8
+ readonly category: ServiceCategory;
9
+ readonly destination: string;
10
+ readonly platform?: string;
11
+ readonly via: readonly string[];
12
+ readonly status: 'scheduled' | 'adjusted' | 'cancelled';
13
+ }
14
+ /** Resolve the station against this snapshot, retaining repeat calls but excluding terminators. */
15
+ export declare function stationDepartures(snapshot: NetworkSnapshot, stationName: string): readonly StationDeparture[];
@@ -0,0 +1,25 @@
1
+ /** Resolve the station against this snapshot, retaining repeat calls but excluding terminators. */
2
+ export function stationDepartures(snapshot, stationName) {
3
+ const stopIndexes = new Set();
4
+ snapshot.stops.forEach((stop, index) => { if (stop[2] === stationName)
5
+ stopIndexes.add(index); });
6
+ if (!stopIndexes.size)
7
+ return [];
8
+ const departures = [];
9
+ for (const train of snapshot.trains) {
10
+ train.stops.forEach(([stopIndex, , departure], callIndex) => {
11
+ if (!stopIndexes.has(stopIndex) || !Number.isFinite(departure) || callIndex === train.stops.length - 1)
12
+ return;
13
+ const onward = train.stops.slice(callIndex + 1).map(([index]) => snapshot.stops[index]?.[2]).filter((name) => Boolean(name));
14
+ if (!onward.length)
15
+ return;
16
+ const destination = train.headsign.trim() || onward.at(-1);
17
+ departures.push({ id: `${train.id}:${callIndex}`, trainId: train.id, time: departure,
18
+ service: train.route || train.shortName, category: train.category, destination,
19
+ platform: snapshot.stops[stopIndex]?.[3]?.trim() || undefined,
20
+ via: [...new Set(onward.slice(0, -1).filter((name) => name !== stationName && name !== destination))].slice(0, 3),
21
+ status: train.realtime?.status ?? 'scheduled' });
22
+ });
23
+ }
24
+ return departures.sort((a, b) => a.time - b.time || a.id.localeCompare(b.id));
25
+ }
@@ -0,0 +1,13 @@
1
+ import type { NetworkSnapshot, NetworkTrain, ServiceCategory, StationIndexEntry } from './network.ts';
2
+ export declare function countableVehicleTrains(network: NetworkSnapshot | undefined, stations: readonly StationIndexEntry[], selection: {
3
+ category?: ServiceCategory;
4
+ station?: Pick<StationIndexEntry, 'name'>;
5
+ route?: {
6
+ name: string;
7
+ category: ServiceCategory;
8
+ };
9
+ }): readonly NetworkTrain[];
10
+ /** Build once per immutable selection; clock updates need only two binary searches. */
11
+ export declare function createActiveTimetableVehicleCounter(trains: readonly NetworkTrain[], options?: {
12
+ readonly requirePositionable?: boolean;
13
+ }): (time: number) => number;
@@ -0,0 +1,33 @@
1
+ export function countableVehicleTrains(network, stations, selection) {
2
+ const stationTrainIds = selection.station
3
+ ? new Set(stations.find(station => station.name === selection.station?.name)?.trainIds ?? [])
4
+ : undefined;
5
+ return network?.trains.filter(train => (!selection.category || train.category === selection.category) &&
6
+ (!stationTrainIds || stationTrainIds.has(train.id)) &&
7
+ (!selection.route || (train.route === selection.route.name && train.category === selection.route.category))) ?? [];
8
+ }
9
+ /** Build once per immutable selection; clock updates need only two binary searches. */
10
+ export function createActiveTimetableVehicleCounter(trains, options = {}) {
11
+ const starts = [], ends = [];
12
+ for (const train of trains) {
13
+ if (train.realtime?.status === 'cancelled' || (options.requirePositionable && train.stops.length < 2) || !(train.start <= train.end))
14
+ continue;
15
+ starts.push(train.start);
16
+ ends.push(train.end);
17
+ }
18
+ starts.sort((a, b) => a - b);
19
+ ends.sort((a, b) => a - b);
20
+ const before = (values, time, inclusive) => {
21
+ let low = 0, high = values.length;
22
+ while (low < high) {
23
+ const middle = (low + high) >>> 1;
24
+ if (values[middle] < time || inclusive && values[middle] === time)
25
+ low = middle + 1;
26
+ else
27
+ high = middle;
28
+ }
29
+ return low;
30
+ };
31
+ // Include both departure and arrival instants, including zero-length trips.
32
+ return time => Number.isNaN(time) ? 0 : before(starts, time, true) - before(ends, time, false);
33
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionstudies/core",
3
- "version": "0.1.0-alpha.0",
3
+ "version": "0.1.0-alpha.10",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Transport contracts and motion primitives for Motion Studies.",
@@ -65,6 +65,11 @@
65
65
  "import": "./domain/airport.js",
66
66
  "default": "./domain/airport.js"
67
67
  },
68
+ "./domain/movement-board": {
69
+ "types": "./domain/movement-board.d.ts",
70
+ "import": "./domain/movement-board.js",
71
+ "default": "./domain/movement-board.js"
72
+ },
68
73
  "./domain/boundary": {
69
74
  "types": "./domain/boundary.d.ts",
70
75
  "import": "./domain/boundary.js",
@@ -139,6 +144,21 @@
139
144
  "types": "./domain/train-time-index.d.ts",
140
145
  "import": "./domain/train-time-index.js",
141
146
  "default": "./domain/train-time-index.js"
147
+ },
148
+ "./domain/live-airport": {
149
+ "types": "./domain/live-airport.d.ts",
150
+ "import": "./domain/live-airport.js",
151
+ "default": "./domain/live-airport.js"
152
+ },
153
+ "./domain/station-departures": {
154
+ "types": "./domain/station-departures.d.ts",
155
+ "import": "./domain/station-departures.js",
156
+ "default": "./domain/station-departures.js"
157
+ },
158
+ "./domain/vehicle-counts": {
159
+ "types": "./domain/vehicle-counts.d.ts",
160
+ "import": "./domain/vehicle-counts.js",
161
+ "default": "./domain/vehicle-counts.js"
142
162
  }
143
163
  },
144
164
  "files": [