Compare commits

...
Author SHA1 Message Date
Said Turksever 48ef645d65 Merge #689 (adsbdb rate limit and cache ceiling) onto current main 2026-11-23 01:20:39 +00:00
Sameh Khamis d9d79ebc4d A line can be drawn as several runs (breaks) (#1895)
* A line can be drawn as several runs (`breaks`)

LineItem.breaks (capability lineBreaks) lists the positions that start a new
run of a line: the segment into each is not drawn nor picked, and the line
does not join across it, each run having ends of its own. Many lines in one
style, such as many moving objects' trails, can then be sent as one item.
Segment colours and shows stay one a pair of positions, age times one a
position, and the reveal runs along the runs in order. The Cesium port draws
a line in runs a piece a run, draped or not, and lists the capability; the
stub picks the runs only; the conformance check draw.lines.breaks pins it.

* A line in runs is cut by time run by run, whatever their order

The conformance check draw.lines.breaks.timeWindow draws a line in runs,
draped and not, whose first run is later than its second, and reads each
run drawn and cut by its own times as the scene clock moves.

It found that a plain line drawn in a polyline collection after an aged one
was the page's first of its style's type stopped the frame: Cesium keeps a
material type's uniform names from the first material of it, and a part of
a composite material has them renumbered. A part's type is now made on its
own first.

* Changelog for line breaks (#1895)
2026-11-21 13:04:19 -08:00
Sameh Khamis e4caf5d3af A line can show only the part of it within a time span of the scene clock (#1894)
* A line can show only the part of it within a time span of the scene clock

LineAgeFade.showMs (capability lineTimeWindow) draws only the part of an aged
line whose time, interpolated along it, lies between showMs before the scene
clock and the clock itself, cut as the clock moves without the line being sent
again. A moving trail can then be sent once as its whole track. The Cesium
port discards by time in its aged line material, draped or not, and the
conformance check draw.lines.timeWindow pins it. Without showMs the fade is
unchanged.

* Changelog for line time window (#1894)
2026-11-21 07:45:43 -08:00
Sameh Khamis 561f5885c2 Opening the phone Context tab no longer switches Contacts on (#1893)
* Opening the phone Context tab no longer switches Contacts on

With an aircraft tracked, the tab now only presents the Context panel, which
shows that aircraft's card as on desktop. The tab bar's open callback had no
other use and is removed.

* Add changelog fragment for #1893
2026-11-21 06:44:57 -08:00
Sameh Khamis 7ff536299a Lines can fade with the age of their points, drawn by the renderer on the GPU (#1892)
* Lines can fade with the age of their points, drawn by the renderer on the GPU

A LineItem's ageFade gives each position a time, a window and floors; the
renderer fades the line's alpha (and optionally its width) by each point's
recency on the scene clock, so a moving trail is not re-sent each frame.
Capability lineAgeFade; the Cesium port draws it in its line materials from a
small float texture of the points' times and a per-frame uniform, and the
conformance check draw.lines.ageFade pins it.

* Changelog for line age fade (#1892)
2026-11-21 06:29:57 -08:00
Sameh Khamis 918435ddc7 A voice or chat selection shows its card in the Context panel (#1890)
* fix(voice): a selection steps a docked assistant panel down so Context shows; the panel keeps the last reply

A voice or chat action that selects an entity (select_nearest_aircraft,
track_entity) now minimizes a voice or chat panel docked in the right rail's
lane, so the rail and its Context panel show as after a click. The voice
card inside the panel no longer hides 14 s after its last update: the reply
stays until the next turn, Stop or a dismissal. The floating card keeps its
idle deadline.

* fix(voice): a voice or chat selection opens its card in the Context panel

A successful select_nearest_aircraft or track_entity now selects the entity
in the Context panel's entity card store the same way a click does, so the
panel opens on its details; the docked assistant panel then steps down so it
shows. track_entity reports the id it tracked. Nothing opens in Cockpit,
where Context is hidden.

* fix(voice): a slow selection never replaces a card picked since; Cockpit is read from its own state

The entity card store counts selections and clears. A voice or chat
selection notes that count when it is asked and opens its card only if no
other card was picked or cleared before it finished. Whether Cockpit is
running is read from the style manager's Cockpit state when it has one.

* Add the changelog entry

* fix(voice): the app hands voice its Context card opener

The voice package no longer imports the entity card store. The app builds
the opener (createContextCardOpener) and passes it to the voice commands as
contextCard, which keeps the voice package inside its own boundary.
2026-11-20 22:19:16 -08:00
Sameh Khamis fbbe6cd91f Voice Cockpit entry no longer switches Contacts on (#1889)
* fix(voice): voice Cockpit entry no longer turns Contacts on

Voice entry now changes no Context mode or detection setting, as the COCKPIT
button does not. An entry that names a layer or class searches that layer's
own aircraft, nearest first from the followed aircraft or the ground under
the camera, and follows the nearest match before entering; the followed
aircraft counts when it matches. A military request while Military Flights
is off switches that layer on as a plain layer. The class filter is shared
with Contacts navigation.

* fix(voice): a military Cockpit entry waits for the layer's first data and leaves no layer behind

A military entry that switched Military Flights on waits for that layer to
report its first data before searching it, bounded by that update, the
layer failing or going off, and the request's cancellation. If entry then
fails, the layer is switched off again; a layer that was already on stays
on. The search covers only the aircraft the person's filters show.

* Add the changelog entry
2026-11-20 22:01:03 -08:00
Sameh Khamis 5608b12a25 Show JTWC cyclones: western Pacific, Indian Ocean and Southern Hemisphere (#1891)
* Show JTWC warnings in Cyclone advisories

Cyclone advisories now also read the Joint Typhoon Warning Center (keyless,
public domain) for the western North Pacific, North Indian Ocean and Southern
Hemisphere, beside NHC and CPHC.

- server/providers/jtwc.js reads JTWC's warnings feed, each storm's JMV 3.0
  warning (.tcw) and its overlay (.kmz). /api/cyclones merges them with NHC's:
  one storm per id, NHC's advisory where NHC lists the storm. A failed JTWC
  read keeps its last storms, marked stale, and never hides NHC's.
- Storms carry an agency. A JTWC warning has no cone; its 34-knot wind danger
  area is drawn as its own dashed area and named for the selected storm.
- A JTWC storm's card notes that the regional centre's warning is official
  and that JTWC winds are 1-minute averages. Source and coverage wording names
  both agencies.
- Each storm is served while its own advisory is usable (12 hours for NHC,
  13 for JTWC).

* Keep one JTWC failure from affecting other storms or NHC

- A storm whose JTWC warning cannot be read or parsed is left out and the
  others are shown; the read fails only when every listed storm's does.
- JTWC is read under its own 8-second deadline. A failed or slow JTWC read
  keeps JTWC's last good storms and never delays, fails or stales the NHC
  answer.
- Danger-swath longitudes past ±180 (a ring crossing the antimeridian) are
  wrapped into -180..180 instead of dropping the ring.

* Add the changelog entry for JTWC cyclones
2026-11-20 21:48:15 -08:00
Bilawal Sidhu ae212e5b63 Place trademark attribution below the README install links (#1888) 2026-11-20 22:42:21 -06:00
Sameh Khamis deff042265 fix(satellites): releasing a tracked satellite clears its focus dimming (#1887)
_clearTracking cleared the focus rectangle, then told the camera to stop
following before marking the satellite released. A follow listener that read
the tracked position in between (the Cockpit entry button does) published the
rectangle again, and nothing cleared it: every icon inside a centred screen
rectangle stayed at 25% opacity once the camera was farther than the old
follow distance.

The satellite is now marked released before the camera hears of it.
2026-11-20 20:05:40 -08:00
Sameh Khamis aac6be7773 test(scenes): drop the resumed-flight timing test (#1885)
It timed a 0.2 s camera flight against real timers with a few milliseconds of slack, so slow runners failed it at random. The resumed-hold tests next to it still cover resuming a run partway through a scene.
2026-11-20 18:43:35 -08:00
Sameh Khamis 84324ea678 Put the globe actions back on the title row, with the loading line under them (#1884)
The desktop search layout had moved the round globe actions down to the
HUD's top rows, where the loading line (top: 74px) was drawn over them.
They now sit on the title row again (top: 32px), level with the title,
and the loading line stays under them. Narrower than 1180px, where the
centred row would reach the title, the actions keep their lower place and
the loading line moves 42px under them.
2026-11-20 18:30:17 -08:00
daika 28c9c4d730 test(adsbdb): give the Flights retry case the services enrichment now reads 2026-11-10 15:51:42 +07:00
daika ec90e98d61 Merge branch 'main' into fix/adsbdb-cache-and-rate-limit
# Conflicts:
#	src/layers/flights/enrichment.js
2026-11-10 15:46:59 +07:00
daika 94e3d01d75 Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit 2026-11-09 17:55:51 +07:00
daikaginza 9aa71cdfeb Merge upstream main 9d3548c27 into fix/adsbdb-cache-and-rate-limit
# Conflicts:
#	scripts/format-scope.json
2026-10-24 13:19:58 +07:00
daikaginza 80b2ead154 fix(adsbdb): 720/min by default, configurable, and a 429 is not an answer
The cap becomes GEV_RATELIMIT_ADSBDB_PER_MIN with a 720 default, read
through resolvePerMinuteCap like the other cost limiters (0 disables, an
unreadable value takes the default). On a 429 both enrichment queues make
the key askable again after the error's retry-after, so the next request
for that aircraft is dispatched instead of dropped.
2026-10-23 12:39:32 +07:00
daikaginza b83e1a2c98 test(adsbdb): size the limiter for two client queues and retry a 429
Review on #689: one tab runs two enrichment queues (Flights and Local
ADS-B) at 200 ms each, so a real session reaches 600/min, not 300; and a
429 left the aircraft's metadata empty for the session, because both
queues mark a key seen before dispatch and swallow the error. The cases
pin 600/min fitting, the GEV_RATELIMIT_ADSBDB_PER_MIN override (0 off),
and both queues asking again after the refusal. Four fail on the branch
as it stands.
2026-10-23 12:39:32 +07:00
daikaginza ed1e2771a0 Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit 2026-10-23 12:35:03 +07:00
daikaginza 7fa3e5e7bf docs(changelog): move the entry into a changelog.d fragment
Main now takes pending entries as changelog.d/<pr>-<slug>.md
files (#787), so the entry leaves CHANGELOG.md for changelog.d/689-adsbdb-cache-and-rate-limit.md.
2026-10-18 13:36:07 +07:00
daikaginza fbd99dad7c Merge upstream/main 93ea088f4 2026-10-18 13:36:07 +07:00
daikaginza c20af07adb Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit
main now reads adsbdb bodies through readResponseJsonCapped. That capped
payload feeds this branch's bounded store via remember(), so both the size cap
and the entry cap apply.
2026-10-16 09:26:47 +07:00
daikaginza 0bd8e9a62c Merge remote-tracking branch 'upstream/main' into q689
# Conflicts:
#	CHANGELOG.md
#	scripts/format-scope.json
2026-10-05 17:31:29 +07:00
daikaginza 0d5a0cdf49 Merge remote-tracking branch 'upstream/main' into fix/adsbdb-cache-and-rate-limit 2026-09-28 08:50:12 +07:00
daikaginza 03814d8c47 fix(adsbdb): rate-limit /api/adsbdb and cap its enrichment caches
Both keys this route accepts come from the caller — a callsign is 2-8 of
[A-Z0-9], a hex is six of [0-9a-f] — and every distinct key that reached
upstream was cached, 404s included, with nothing ever removing one. A caller
walking the keyspace could therefore drive unlimited live requests at the free
community API and grow `.gev-cache/adsbdb.json` without end.

Admit 360 requests/minute per client address, global backstop 3x, refusing the
rest with 429 and `Retry-After` before any cache, disk or upstream work. The
browser cannot exceed 300/min by construction: ENRICH_DISPATCH_GAP_MS is
200 ms, so the enrichment queue drips at most five lookups a second.

Hold each store to 20,000 entries, dropping least-recently-written first, and
discard entries past the existing 24-hour TTL when the file is read back. A
cache file above 16 MB is skipped rather than parsed. Sized from a real
session's own file: 397 aircraft entries (~100 B) and 3 route entries
(~231 B), so the ceiling is about fifty times an ordinary working set and
bounds the file at roughly 7 MB.

The two stores become Maps: `size` is O(1), so the ceiling can be enforced on
every write, and iteration is true insertion order — an all-digit callsign
like "1234" sorts ahead of everything else as an object key. The on-disk JSON
shape is unchanged.

Refs #261
2026-09-27 22:23:55 +07:00
83 changed files with 5388 additions and 944 deletions

No files matched your search

+6
View File
@@ -51,6 +51,12 @@ GOOGLE_MAPS_SERVER_API_KEY=
# Quotas).
# GEV_RATELIMIT_GOOGLE_PER_MIN=60 # uncomment to tighten from the default 120
# Optional: per-IP requests/minute for the keyless adsbdb aircraft-enrichment
# proxy (/api/adsbdb). DEFAULTS TO 720: one tab's two enrichment queues
# (Flights and Local ADS-B) top out at 600. Same rules as above: 0 disables,
# an unreadable value takes the default.
# GEV_RATELIMIT_ADSBDB_PER_MIN=720
# Optional: Google Photorealistic 3D Tiles through Cesium ion, Bing world
# imagery, and Cesium World Terrain. The free Community plan is for eligible
# personal/non-commercial use and has quotas; check current Cesium terms. A
+21
View File
@@ -20,6 +20,7 @@ How to read this:
| **NOAA nowCOAST observed weather** (`nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite}/ows`, WMS 1.1.1) | Rain radar (MRMS base reflectivity, contiguous US, about 4-minute updates) and Satellite clouds (GOES-19/18 Band 14 regional infrared, about 5-minute updates; global infrared mosaic, hourly). Keyless; layer metadata refreshed every 2 minutes, exact-time images cached for up to 24 hours | [NOAA disclaimer](https://oceanservice.noaa.gov/disclaimer.html) | "NOAA nowCOAST · NWS/OAR MRMS radar; NESDIS GOES and global satellite partners" |
| **NOAA nowCOAST lightning density** (`nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows`) | Lightning density: 15-minute accumulated strike density on an approximately 8 km grid, Americas and Pacific. Keyless; layer metadata refreshed every 10 minutes, exact-time images cached for up to 24 hours | NOAA Level-5 derived product from Vaisala NLDN/GLD360; the [product description](https://ocean.weather.gov/lightning/lightning_pdd.php) permits public distribution of this density product, not of raw Vaisala detections | "NOAA/NWS nowCOAST; derived from Vaisala NLDN/GLD360" |
| **NOAA NHC / CPHC advisories** (`www.nhc.noaa.gov/CurrentStorms.json` + the `mapservices.weather.noaa.gov` tropical weather summary MapServer) | Cyclone advisories: storm positions, forecast tracks, points and cones for the Atlantic and eastern/central North Pacific. Keyless through `/api/cyclones`; cached for 5 minutes | [NWS public-data terms](https://www.weather.gov/disclaimer); no endorsement implied | "NOAA/NWS NHC / CPHC" |
| **Joint Typhoon Warning Center (JTWC) warnings** (`www.metoc.navy.mil/jtwc/rss/jtwc.rss`, each storm's `.tcw` and `.kmz`) | Cyclone advisories for the western North Pacific, North Indian Ocean and Southern Hemisphere: positions, forecast tracks and 34-knot wind danger areas. Keyless through `/api/cyclones`, read beside NHC | US government work (U.S. Navy / U.S. Air Force); not the official regional warning; no endorsement implied | "Joint Typhoon Warning Center" |
| **Mapillary** (vector tiles, Graph API, MapillaryJS) | Street Level: coverage lines, image cones and the embedded viewer. Coverage tiles kept in server memory for 24 h | Imagery [CC BY-SA 4.0](https://www.mapillary.com/terms); API under the Mapillary terms with a client token | "© Mapillary contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
| **Google Street View** (Maps JavaScript API) | Street Level, on the Google 3D map only (Google's terms): Google's panorama viewer and nearest-panorama lookups; panorama dates and addresses kept for the session only | Google Maps Platform ToS (your own key + billing; every panorama load is billed) | "Street View imagery © Google" on the globe while the provider is on, and Google's logo and terms in the viewer |
| **KartaView** (`api.kartaview.org` coverage tiles and photo API, `cdn.kartaview.org` image proxy, `storage*.openstreetcam.org` photos) | Street Level: coverage lines (z13–14 JSON tiles; with the imagery filter on, KartaView's filtered PNG tiles as a mask), nearest-photo lookups, the photo's sequence and the photo itself, fetched by the browser. Keyless; nothing cached beyond the session | Imagery [CC BY-SA 4.0](https://kartaview.org/terms) (KartaView terms §4); the public API needs no token | "© KartaView contributors, CC BY-SA 4.0", shown on the globe while the provider is on |
@@ -709,6 +710,26 @@ This implementation is original; those contributions have not been merged here.
fixed upstream endpoints, bounded bodies/geometry/deadline, explicit unavailable/stale states.
Direct status fetching is unsuitable in browsers because NHC does not advertise CORS.
### Weather: JTWC cyclone warnings
- **Sources:** the [JTWC warnings feed](https://www.metoc.navy.mil/jtwc/rss/jtwc.rss), and for each
storm it lists, the warning's JMV 3.0 data (`products/<storm>.tcw`) and Google Earth overlay
(`products/<storm>.kmz`).
- **Rights/credit:** Joint Typhoon Warning Center (U.S. Navy / U.S. Air Force), a US government
work. JTWC warns for US government interests; the official warning for each basin is its
regional centre's (for example JMA, IMD, RSMC Nadi, BoM, Météo-France La Réunion). No bundled
archive and no endorsement implied.
- **Coverage/meaning:** western North Pacific, North Indian Ocean and Southern Hemisphere. Where
NHC or CPHC lists the same storm, theirs is shown. Winds are 1-minute averages. The 34-knot wind
danger area is the swath of 34-knot winds widened by forecast track error, drawn as its own
area and never as a cone; it comes only from the overlay of the same warning number, and the
geometry waits for it.
- **Delivery:** read in `/api/cyclones` beside NHC under its own 8-second deadline, bounded
bodies, no redirects. A warning is usable for 13 hours after issuance (some storms are on
12-hourly warnings). A storm whose warning cannot be read is left out and the others shown; a
failed or slow JTWC read keeps JTWC's last good storms and never delays or stales NHC's. Swath
longitudes past ±180 (a ring crossing the antimeridian) are wrapped, not dropped.
### Weather: observed lightning density
- **Source:** [NOAA nowCOAST lightning detection WMS](https://nowcoast.noaa.gov/geoserver/observations/lightning_detection/ows),
+5 -3
View File
@@ -16,6 +16,8 @@ Click any satellite, plane, ship or public camera and you can track it. Turn on
**[One-click install with Pinokio](https://pinokio.co/apps/github-com-bilawalsidhu-gods-eye-view)** · **[Run it from the terminal](#-quick-start)** · **[Hosted version waitlist](https://godseyeview.ai/online/)**
God’s Eye View™ is a trademark of Metaversity LLC, used under license by Halfpixel, Inc. [Official download page](https://godseyeview.ai/download/).
🏆 **#1 on GitHub Trending**, daily and weekly · **[#8 Product of the Day](https://www.producthunt.com/products/god-s-eye-view?launch=god-s-eye-view)**, hunted by Chris Messina · _“pretty cool”_ — [Brendan Eich](https://x.com/BrendanEich/status/2094592096401490266), creator of JavaScript · Featured on **[Pinokio](https://pinokio.co/posts/01m1m4p9xxm3qw7dnnpj2wr93g)**
▶️ **From the project behind the God's Eye View series** _(formerly WorldView)_ — [25M+ views on YouTube](https://youtube.com/playlist?list=PL6qSg2I-7_koPbDnSMo0QeeHX_RknA2uv&si=nBGYMoHWQw41v93Q)
@@ -94,7 +96,7 @@ We've got a plurality of sensor systems watching the planet right now. Satellite
- **🎥 Scene director:** Capture cinematic camera tours for clips and demos.
- **🔗 Share Links:** Camera, style, layers, and even one tracked target serialize into a URL — a live target is a handoff, not a bookmark.
- **🏠 Reset Globe:** One control — or one sentence — back to the full Earth.
- **🌦️ Weather:** Animate GFS or ECMWF forecast wind, replay observed radar, satellite clouds and lightning on one timeline, and follow NHC/CPHC cyclone tracks. No key needed.
- **🌦️ Weather:** Animate GFS or ECMWF forecast wind, replay observed radar, satellite clouds and lightning on one timeline, and follow NHC/CPHC and JTWC cyclone tracks. No key needed.
- **📷 Mapped ALPR cameras:** License-plate-reader camera locations tagged in OpenStreetMap, one city at a time. Locations and tags only; no key needed.
- **🔭 Satellite passes:** Ask by voice when any loaded satellite next rises over you: rise, peak and set times, and whether you can see it.
- **🔎 Analyst answers:** Count, filter and rank satellites, datacenters and dams by voice, alongside flights, ships, fires and quakes; answers say when a feed is stale or on a fallback.
@@ -464,11 +466,11 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
| 🦉 **Wildlife Sightings** | Wildlife observed within 48 h (whales 7 d): density glow, taxon badges and anchored photo cards with creator/licence credit. Salish Sea marine mammals via Acartia; sensitive locations shown as 0.2° cells. Not a census | iNaturalist, Acartia | 🟢 |
| 🌬️ **Wind** | Animated 10 m forecast wind with an optional speed, temperature or pressure color field and a reading at map center | NOAA GFS / ECMWF IFS | 🟢 |
| 🌦️ **Observed Weather** | Rain radar (contiguous US), Satellite clouds (GOES regional or global infrared, Clouds only or Full image) and Lightning density (Americas and Pacific) on one history timeline | NOAA nowCOAST | 🟢 |
| 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones for the Atlantic and eastern/central North Pacific | NOAA NHC / CPHC | 🟢 |
| 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones (Atlantic, eastern/central North Pacific); warnings with 34-knot wind danger areas elsewhere | NOAA NHC / CPHC · JTWC | 🟢 |
</details>
**Weather, keyless.** **Wind** animates 10 m forecast flow from NOAA GFS or ECMWF IFS, with an optional color field and a reading at map center. **Rain radar**, **Satellite clouds** and **Lightning density** are observations on one history timeline in the **WEATHER** panel (step back, **Play**, **Latest**); **Cyclone advisories** draw NHC and CPHC positions, forecast tracks and cones. On Google 3D Tiles the observed layers float above the city as translucent shells, sharpened around your view.
**Weather, keyless.** **Wind** animates 10 m forecast flow from NOAA GFS or ECMWF IFS, with an optional color field and a reading at map center. **Rain radar**, **Satellite clouds** and **Lightning density** are observations on one history timeline in the **WEATHER** panel (step back, **Play**, **Latest**); **Cyclone advisories** draw NHC and CPHC positions, forecast tracks and cones, and JTWC warnings with their 34-knot wind danger areas for the other basins. On Google 3D Tiles the observed layers float above the city as translucent shells, sharpened around your view.
In the app, **Data Layers** groups them as Movement, Cameras, Infrastructure, Events, Weather and Audio; Directions and OSM Places sit in the separate **Utilities** panel with Draw and Import.
@@ -0,0 +1,3 @@
- Voice Cockpit entry no longer switches Contacts on; a request for a class
such as a military helicopter finds the nearest matching aircraft itself
and switches on only the layer it needs (samehkhamis, #1889).
@@ -0,0 +1,3 @@
- A voice or chat selection opens its card in the Context panel, as a click
does, and a docked assistant panel steps down so the card shows; the reply
stays until the next one (samehkhamis, #1890).
+5
View File
@@ -0,0 +1,5 @@
- Cyclone advisories show the Joint Typhoon Warning Center's storms beside
NHC's: the western Pacific, the Indian Ocean and the Southern Hemisphere.
JTWC's 34-knot wind danger area is drawn where it publishes no cone, its
cards say the regional centre's warning is the official one, and each storm
now ages out on its own (samehkhamis, #1891).
+4
View File
@@ -0,0 +1,4 @@
- Lines can fade with the age of their points (`LineItem.ageFade`, capability
`lineAgeFade`), drawn by the renderer on the GPU on the scene clock, so a
moving trail is not re-sent each frame; the Cesium renderer draws it, draped
or not (samehkhamis, #1892).
@@ -0,0 +1,2 @@
- Opening the phone Context tab with an aircraft tracked shows its card and no
longer switches Contacts on (samehkhamis, #1893).
+5
View File
@@ -0,0 +1,5 @@
- A line can show only the part of it within a span of the scene clock
(`LineAgeFade.showMs`, capability `lineTimeWindow`): the renderer cuts it by
time on the GPU as the clock moves, so a moving trail can be sent once as
its whole track; the Cesium renderer draws it, draped or not (samehkhamis,
#1894).
+5
View File
@@ -0,0 +1,5 @@
- A line can be drawn as several runs (`LineItem.breaks`, capability
`lineBreaks`): the segments across its breaks are not drawn nor picked,
and each run has ends of its own, so many lines in one style, such as
many moving objects' trails, can be sent as one item; the Cesium renderer
draws it, draped or not (samehkhamis, #1895).
@@ -0,0 +1,13 @@
- Bound the adsbdb enrichment proxy. `/api/adsbdb` had no request limit and no
cache eviction, so a caller cycling through the callsign or hex keyspace
could drive unlimited live requests at the free community API and grow
`.gev-cache/adsbdb.json` without end — every distinct key, 404s included, was
remembered forever. The route now admits 720 requests/minute per client
address (`GEV_RATELIMIT_ADSBDB_PER_MIN`; one tab's two enrichment queues top
out at 600), refusing the rest with 429 and `Retry-After` before any cache,
disk or upstream work. A refused lookup is asked for again once the refusal
has passed instead of leaving that aircraft without metadata for the
session. Each cache holds at most 20,000 entries, dropping the
least-recently-written first, and entries past the existing 24-hour TTL are
discarded when the file is read back. Cached answers and response shapes are
unchanged (daikaginza, #689).
+41 -6
View File
@@ -1627,7 +1627,7 @@ warning, capped and unknown cost states also appear in the dock heading when
Settings is closed. The existing hard cost cap still stops the session and
announces the reason.
Automatic Voice Preview uses output from the active mounted provider, including late replies that may answer an older request. Manual panel choices remain until genuine local input rearms automatic presentation. Preview stays off when disabled, remains hidden in Cockpit, and retires on Stop or provider replacement. Display events do not grant command authority.
Automatic Voice Preview uses output from the active mounted provider, including late replies that may answer an older request. Manual panel choices remain until genuine local input rearms automatic presentation. Preview stays off when disabled, remains hidden in Cockpit, and retires on Stop or provider replacement. In the panel, the last reply stays until the next turn replaces it; only the voice card floating on a control without the panel hides 14 s after its last update. Display events do not grant command authority.
Typed chat sits beside voice in the dock. Chat replies are silent and never
request microphone access. The first message connects with the selected
@@ -1657,6 +1657,12 @@ and the chat shows a matching message.
Chat and the voice panel sit above the dock or dock into the right rail's lane,
which hides the rail until the panel minimizes or closes, or a rail panel opens.
A voice or chat action that selects something (`select_nearest_aircraft`,
`track_entity`) opens its card in the Context panel as a click on it does
(`createContextCardOpener` in `src/ui/stores/entityCard.js`, handed to voice by the app), except in
Cockpit (as Cockpit's own state reports it) or when another card was picked
while the action ran, which then stays, and steps a panel docked in the lane down to its bar so the rail
shows it; a panel above the dock leaves the rail in view and stays as it is.
Minimized panels always sit as a bar centred above the dock; restoring returns a
docked panel to the lane. A centred panel steps down to its bar when the pointer
reaches the Location or Visual Presets button and rests above an open tray,
@@ -3746,9 +3752,10 @@ that misses onto the map surface, it searches at most eight hits in a 14px squar
and accepts the first registered layer hit, stopping at non-map objects. Civil
and military aircraft and vessels share this rule; fine pointers stay exact.
Manually opening Context with a tracked civilian or military aircraft enters
the existing Contacts mode when Context is off. Contacts adopts that aircraft
without restarting its tracking. Programmatic sheet changes and closing the tab do not activate a mode.
Opening the Context tab only presents the Context panel, as on desktop: with
an aircraft tracked it shows that aircraft's card (a click on it opened the card
whether or not the panel was open). It never switches Contacts or any other
Context mode on, and changes no layer or detection.
Sheets borrow panels. Opening one expands its panels without persisting them or
claiming a user choice, and share links keep reporting each borrowed panel's
@@ -4343,6 +4350,25 @@ The existing aircraft normalizer is separately available through the portable
`gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache
policy, fallback behavior, response shapes and rendering remain unchanged.
### ADSBDB enrichment bounds
`/api/adsbdb` admits 720 requests/minute per client address
(`GEV_RATELIMIT_ADSBDB_PER_MIN`; `0` disables), with a global backstop of three
times that; a refused request answers 429 with `Retry-After` and reaches
neither the cache nor api.adsbdb.com. Each browser enrichment queue drips at
most 300/minute and one tab runs two (Flights and Local ADS-B), so an ordinary
session never meets the limit. When a lookup is refused anyway, both queues
make that key askable again after the refusal's retry-after rather than
treating the 429 as an answer.
Both enrichment caches hold at most 20,000 entries each, dropping the
least-recently-written first, and entries past their 24-hour TTL are discarded
when `.gev-cache/adsbdb.json` is read back. A cache file above 16 MB is skipped
rather than parsed. An evicted key costs one upstream request the next time it
is asked for; cached answers are otherwise unchanged.
Updated: October 23, 2026
## Control names for assistive technology
Scope, Bloom, Sharpen and location search have explicit accessible names.
@@ -9093,8 +9119,17 @@ apply to `public/` assets or built-preview serving.
ending, by its own switch or one of its layers going off, restores the
pre-Contacts layers but keeps the ridden one and the view; Live Signals then
drops the rows Contacts built and shows `CONTEXT STANDBY`. The visible
Cockpit actions, double-click and voice use the same gate; voice entry still
opens Contacts first, as its layer-targeted entry navigates through Contacts.
Cockpit actions, double-click and voice use the same gate. Voice entry, like
the COCKPIT button, never turns Contacts or detection on. A
voice entry that names a layer or class ("a military helicopter") searches
the aircraft that layer shows under the person's filters, nearest first,
from the followed aircraft or the ground under the camera, and follows the
nearest match (the followed aircraft counts when it matches) before it
enters (`_retargetCockpitEntryLayer` in `src/ui/cockpitCoordinator.js`). A
military request while Military Flights is off switches that layer on as a
plain layer the person can switch off, waits for its first data before
searching, and switches it off again if entry then fails; a layer that was
already on stays on. Contacts stays as it is.
The ship bridge and the orbital view have their own own-layer gates
(`bridgeEntryAllowed`, `orbitEntryAllowed`; see
[Ship bridge view](#ship-bridge-view) and [Orbital view](#orbital-view)).
+7 -3
View File
@@ -105,9 +105,13 @@ Status: Open (source limits, by design)
15-minute density product derived from Vaisala NLDN/GLD360 on an approximately
8 km grid, for the Americas and Pacific only (110°E across the dateline to 0°,
25°S–80°N). It is not a live strike counter or an all-clear.
- **Cyclone advisories cover NOAA's basins only:** the Atlantic and the
eastern/central North Pacific (NHC and CPHC). Storms elsewhere do not appear.
The cone is forecast-center uncertainty, not storm size.
- **Cyclone advisories come from two agencies:** NHC and CPHC for the Atlantic
and the eastern/central North Pacific, and the Joint Typhoon Warning Center
(JTWC) for the western North Pacific, North Indian Ocean and Southern
Hemisphere. JTWC is not the official warning centre for those basins, and its
winds are 1-minute averages, higher than the 10-minute winds regional centres
quote. The NHC cone is forecast-center uncertainty, not storm size; JTWC's
34-knot wind danger area is not a cone.
- **Satellite clouds:** global infrared is hourly with typically 2–3 hours of
source latency. Clouds only is a brightness filter, not a cloud mask.
- **Wind is a forecast.** The animation flows through one forecast on an
+52
View File
@@ -122,6 +122,58 @@ optional:
- A line item's `depthFail` style, solid or dashed, draws the parts behind
the surface (the Draw tool's rubber band is dashed there too); without one
they are hidden.
- `LineItem.ageFade` (capability `lineAgeFade`, `LineAgeFade`) fades a
line with the age of its points on the scene clock (`frame.setTime`):
each position has a time, a point's recency is
`1 - clamp((now - time) / windowMs, 0, 1)`, running evenly between
positions, and the line's colour (its style's or a segment's) draws at its
alpha times `mix(alphaFloor, 1, smoothstep(0, 1, recency))`, times
`mix(squaredAlphaFloor, 1, recency²)` with `squaredAlphaFloor`, and
`widthPx` times `mix(widthFloor, 1, recency)` wide with `widthFloor`. Time
passing changes the drawing, not the line, so a trail whose points stay
put is never sent again; new times with new positions are an ordinary
update. A renderer without the capability draws the line unfaded. The
Cesium port lists it where its context has floating-point textures: an
aged line's material reads its points' times from a small texture and the
scene's time from a uniform set each frame, per fragment (draped lines
along their length, others per vertex), and an undraped one moves and
recolours in place in its polyline collection. The check
`draw.lines.ageFade` covers it, draped and not, narrowed too.
- `LineAgeFade.showMs` (capability `lineTimeWindow`) draws only the part of
an aged line within `showMs` of the scene clock: where its time, running
evenly between positions as the fade's does, is after now or before
`now - showMs`, it is not drawn (nor picked), cut there along the line,
not at a position. The cut follows `frame.setTime` as the fade does, so a
moving object's trail can be its whole track, sent once and drawn from
`showMs` ago up to where the object is now; `Infinity` cuts at now alone.
A renderer without the capability draws the whole line. The Cesium port
lists it with `lineAgeFade` and discards by time in the same material;
the check `draw.lines.timeWindow` covers it, draped and not.
- `LineItem.breaks` (capability `lineBreaks`, `LineBreaks`) draws one line
as several runs, so many lines that share one style can be sent as one
item: thousands of moving objects' trails as one line, say, which the
renderer then handles as one item instead of thousands. Each break is the
index `i` of a position that starts a new run, sorted, with
`0 < i < positions.length`; the segment from position `i - 1` to `i` is
not drawn nor picked, and the line does not join across it: each run has
two ends of its own, capped and joined as a line of its own would be.
`segmentColors` and `segmentShow` stay one a pair of neighbouring
positions (`j`, from position `j` to `j + 1`), so the entry of a pair
across a break is ignored; `ageFade.times` stays one a position; and
`revealFraction` runs along all the runs, in order, as one length (the
gaps have none). It is an optimisation: a renderer without it is never
sent `breaks`, and is sent the same lines as an item a run instead,
drawing the same picture. The Cesium port lists it and draws a line
in runs a piece a run (a polyline each in the set's collection, undraped;
a ground polyline each, draped; a primitive each with a depth-fail style
or in the sky's frame), each taking its own points' times, share of the
reveal and segment colours, and picked as the line. A draped solid line
with segment colours stays one ground instance a segment, none across a
break. Colours and shows change in place; new positions, times, reveal or
breaks draw the line anew. The check `draw.lines.breaks` covers it,
draped and not, with segment colours and without, and
`draw.lines.breaks.timeWindow` a line in runs cut by time whose first
run is later than its second, each run cut by its own times.
- A solid line's `outline.widthPx` is the outline's whole width, half on
each side, inside the line's own width: an 8 px line with a 4 px outline
is 2 px of outline, 4 px of colour and 2 px of outline, as Cesium draws
+5 -1
View File
@@ -80,6 +80,8 @@
"src/render/cesium/tileRequests.test.mjs",
"src/queries/heights.test.mjs",
"src/render/cesium/heights.test.mjs",
"src/render/cesium/drawLineAges.test.mjs",
"src/render/cesium/drawLineBreaks.test.mjs",
"docs/CODE-BOUNDARIES.md",
"src/main.js",
"docs/APPLICATION.md",
@@ -1701,5 +1703,7 @@
"src/ui/livePanel.test.mjs",
"src/ui/stationPanel.test.mjs",
"src/ui/styles/live.css",
"src/ui/styles/station.css"
"src/ui/styles/station.css",
"src/adsbdbCacheGovernor.test.mjs",
"src/layers/enrichmentRateLimitRetry.test.mjs"
]
+2
View File
@@ -392,6 +392,8 @@
"server/providers/common/compress.js",
"server/providers/common/http.js",
"server/providers/common/query.js",
"server/providers/common/rate-limit.js",
"src/sources/rateLimit.js",
"server/providers/aircraft/opensky.js",
"server/providers/aircraft/adsb-lol.js",
"server/providers/aircraft/enrichment.js",
+133 -17
View File
@@ -1,5 +1,10 @@
import path from 'node:path';
import { promises as fsp } from 'node:fs';
import {
makeRateLimiter,
clientKey,
resolvePerMinuteCap,
} from '../common/rate-limit.js';
import { readResponseJsonCapped } from '../common/http.js';
/** Route and aircraft lookups are a few hundred bytes; 1 MiB is a hard bound. */
@@ -12,29 +17,126 @@ const ADSBDB_MAX_RESPONSE_BYTES = 1024 * 1024;
* cached. Adapted from skylight
* (MIT) server/src/enrich/routes.ts.
*/
export function adsbdbProxy() {
export function adsbdbProxy(options = {}) {
// Destructured in the body, not the signature: `proxyErrorResponses.test.mjs`
// extracts these proxies by slicing to the first closing brace in column zero.
const {
cacheMaxEntries = 20_000,
cacheMaxDiskBytes = 16 * 1024 * 1024,
cachePath,
} = options;
const TTL_MS = 24 * 3600_000;
const CACHE_PATH = path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
let cache = { routes: {}, aircraft: {} };
const CACHE_PATH =
cachePath || path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
/**
* Entry ceiling per store.
*
* Both keyspaces are enumerable by the caller — a callsign is 2-8 of
* `[A-Z0-9]`, a hex is six of `[0-9a-f]` — and every distinct key that
* reaches upstream is cached, 404s included. Without a ceiling the maps, and
* the file they are written to, grow for as long as a caller keeps asking.
* Sized from a real session's own file: `.gev-cache/adsbdb.json` held 397
* aircraft entries (~100 B each) and 3 route entries (~231 B each), so
* 20,000 per store is roughly fifty times an ordinary working set and still
* bounds the file at about 7 MB.
*/
const CACHE_MAX_ENTRIES = cacheMaxEntries;
const CACHE_MAX_DISK_BYTES = cacheMaxDiskBytes;
/**
* Requests/minute/IP (`GEV_RATELIMIT_ADSBDB_PER_MIN`; unset takes the
* default, `0` disables). Each browser queue drips at most five lookups a
* second (`ENRICH_DISPATCH_GAP_MS`, 200 ms), and one tab can run two — the
* Flights layer's and Local ADS-B's — so a real session tops out at 600.
* The assistant's aviation tools look up through the same source, unqueued
* but one at a time per tool call. 720 leaves all of that untouched while
* still capping an enumerating caller. The global backstop is the usual
* generous multiple.
*/
const RATE_PER_MIN = resolvePerMinuteCap(
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN,
720,
);
const allow =
RATE_PER_MIN > 0
? makeRateLimiter({
windowMs: 60_000,
max: RATE_PER_MIN,
globalMax: RATE_PER_MIN * 3,
})
: () => true;
// Maps, not plain objects: `size` is O(1), so the ceiling can be enforced on
// every write, and iteration is true insertion order (an all-digit callsign
// like "1234" would sort ahead of everything else as an object key).
let cache = { routes: new Map(), aircraft: new Map() };
let dirty = false;
let loaded = false;
const inflight = new Map();
/** Rehydrate one store, dropping entries that expired while we were down. */
function toStore(raw) {
const store = new Map();
const now = Date.now();
for (const [key, entry] of Object.entries(raw ?? {})) {
const at = Number(entry?.at);
if (!Number.isFinite(at) || now - at >= TTL_MS) continue;
store.set(key, entry);
}
prune(store);
return store;
}
/** Hold the store at its ceiling, dropping least-recently-written first. */
function prune(store) {
while (store.size > CACHE_MAX_ENTRIES) {
const oldest = store.keys().next().value;
if (oldest === undefined) break;
store.delete(oldest);
}
}
/** Write `key` as the newest entry, then restore the ceiling. */
function remember(store, key, entry) {
store.delete(key); // re-insert so insertion order tracks last write
store.set(key, entry);
prune(store);
dirty = true;
}
async function loadOnce() {
if (loaded) return;
loaded = true;
let sizeBytes = null;
try {
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
cache = { routes: parsed.routes ?? {}, aircraft: parsed.aircraft ?? {} };
sizeBytes = (await fsp.stat(CACHE_PATH)).size;
} catch {
/* first run */
sizeBytes = null; // cannot measure it — let the read below decide
}
if (sizeBytes !== null && sizeBytes > CACHE_MAX_DISK_BYTES) {
console.warn('[adsbdb-proxy] cache file above ceiling — starting empty');
} else {
try {
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
cache = {
routes: toStore(parsed.routes),
aircraft: toStore(parsed.aircraft),
};
} catch {
/* first run */
}
}
setInterval(async () => {
if (!dirty) return;
dirty = false;
try {
await fsp.mkdir(path.dirname(CACHE_PATH), { recursive: true });
await fsp.writeFile(CACHE_PATH, JSON.stringify(cache), 'utf8');
await fsp.writeFile(
CACHE_PATH,
JSON.stringify({
routes: Object.fromEntries(cache.routes),
aircraft: Object.fromEntries(cache.aircraft),
}),
'utf8',
);
} catch {
dirty = true;
} // retry next tick
@@ -74,7 +176,7 @@ export function adsbdbProxy() {
function lookup(kind, key) {
const store = kind === 'route' ? cache.routes : cache.aircraft;
if (fresh(store[key])) return Promise.resolve(store[key].data);
if (fresh(store.get(key))) return Promise.resolve(store.get(key).data);
const ik = `${kind}:${key}`;
if (!inflight.has(ik)) {
inflight.set(
@@ -95,18 +197,19 @@ export function adsbdbProxy() {
);
const data =
kind === 'route' ? parseRoute(payload) : parseAircraft(payload);
store[key] = { at: Date.now(), data }; // data may be null — negative cache
dirty = true;
// data may be null — negative cache
remember(store, key, { at: Date.now(), data });
return data;
}
if (res.status === 404) {
store[key] = { at: Date.now(), data: null }; // known-missing — cache the miss
dirty = true;
// known-missing — cache the miss
remember(store, key, { at: Date.now(), data: null });
}
// other statuses: leave uncached so we retry later
return fresh(store[key]) ? store[key].data : null;
return fresh(store.get(key)) ? store.get(key).data : null;
} catch {
return fresh(store[key]) ? store[key].data : null; // network error → stale if any
// network error → stale if any
return fresh(store.get(key)) ? store.get(key).data : null;
} finally {
inflight.delete(ik);
}
@@ -118,11 +221,24 @@ export function adsbdbProxy() {
const installMiddleware = (server) => {
server.middlewares.use('/api/adsbdb', async (req, res) => {
await loadOnce();
const send = (status, obj) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
const send = (status, obj, headers = {}) => {
res.writeHead(status, {
'Content-Type': 'application/json',
...headers,
});
res.end(JSON.stringify(obj));
};
// Before any work: a refused request must not touch the cache, the disk,
// or api.adsbdb.com.
if (!allow(clientKey(req)))
return send(
429,
{ error: 'Rate limit exceeded' },
{
'Retry-After': '10',
},
);
await loadOnce();
try {
const [, kind, rawKey] = String(req.url || '')
.split('?')[0]
+97 -12
View File
@@ -1,4 +1,8 @@
import { readResponseTextCapped } from './common/http.js';
import {
readResponseBytesCapped,
readResponseTextCapped,
} from './common/http.js';
import { JTWC_USABLE_MS, readJtwcStorms } from './jtwc.js';
const STATUS_URL = 'https://www.nhc.noaa.gov/CurrentStorms.json';
const GIS =
@@ -7,7 +11,14 @@ const HOUR = 3600_000;
// Data, not UI copy: src/layers/cyclones/index.js keeps the same English in
// msg() and translates it when shown (likewise 'Cyclone data unavailable').
const COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
const SOURCE = 'NOAA NHC / CPHC · JTWC';
const ATTRIBUTION =
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center; Joint Typhoon Warning Center (U.S. Navy / U.S. Air Force)';
/** How long a storm's advisory stays usable after issuance, by agency. */
export function cycloneUsableMs(storm) {
return storm?.agency === 'jtwc' ? JTWC_USABLE_MS : 12 * HOUR;
}
const LAYERS = [
{ id: 5, cap: 512 * 1024, count: 500, kind: 'points' },
{ id: 6, cap: 512 * 1024, count: 32, kind: 'track' },
@@ -114,6 +125,7 @@ export function parseCycloneStatus(payload, now = Date.now()) {
const positionAt = iso(raw.lastUpdate, now);
return {
id: raw.id,
agency: 'nhc',
name: text(raw.name),
classification: text(raw.classification, 16),
basin: raw.id.slice(0, 2).toUpperCase(),
@@ -138,6 +150,7 @@ export function parseCycloneStatus(payload, now = Date.now()) {
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
});
}
@@ -262,8 +275,13 @@ export function cycloneProxy({
fetchImpl = fetch,
now = () => Date.now(),
timeoutMs = 12_000,
// JTWC's own deadline, inside NHC's: a slow JTWC never holds NHC's answer.
jtwcTimeoutMs = 8_000,
readJtwc = readJtwcStorms,
} = {}) {
let cache = null;
// JTWC's storms from its last good read, reused while a read fails.
let jtwcCache = null;
let operation = null;
let attemptedAt = -Infinity;
async function upstream(url, cap, signal) {
@@ -286,7 +304,64 @@ export function cycloneProxy({
signal.throwIfAborted();
return result;
}
// A JTWC product: text or bytes; null when JTWC has none posted (403/404).
async function jtwcRead(url, kind, signal) {
signal.throwIfAborted();
const response = await fetchImpl(url, {
signal,
redirect: 'error',
headers: { 'User-Agent': 'Gods Eye View (public JTWC warning context)' },
});
if (
kind === 'bytes' &&
(response.status === 403 || response.status === 404)
) {
await response.body?.cancel();
return null;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error('cyclone_upstream_unavailable');
}
return kind === 'bytes'
? readResponseBytesCapped(response, 4 * 1024 * 1024, signal)
: readResponseTextCapped(response, 256 * 1024, signal);
}
/**
* JTWC's storms, read under their own deadline. A read that fails or runs
* out of time gives JTWC's last good storms still usable, so it never fails,
* delays past its deadline or stales NHC's answer.
*/
async function jtwc(signal) {
const controller = new AbortController();
const abort = () => controller.abort();
signal.addEventListener('abort', abort, { once: true });
const timer = setTimeout(abort, jtwcTimeoutMs);
try {
const storms = await Promise.race([
readJtwc((url, kind) => jtwcRead(url, kind, controller.signal), now()),
new Promise((_, reject) =>
controller.signal.addEventListener(
'abort',
() => reject(new Error('jtwc_timeout')),
{ once: true },
),
),
]);
jtwcCache = storms;
return storms;
} catch {
return (jtwcCache || []).filter(
(storm) => now() - Date.parse(storm.issuedAt) <= JTWC_USABLE_MS,
);
} finally {
clearTimeout(timer);
signal.removeEventListener('abort', abort);
}
}
async function refresh(signal) {
// JTWC is read beside NHC and never rejects.
const pendingJtwc = jtwc(signal);
let storms = parseCycloneStatus(
await upstream(STATUS_URL, 128 * 1024, signal),
now(),
@@ -323,6 +398,14 @@ export function cycloneProxy({
}));
}
}
// One storm per id: NHC's advisory where NHC lists the storm (a storm
// crossing 180° keeps its id), JTWC's elsewhere.
const fromJtwc = await pendingJtwc;
const listed = new Set(storms.map((storm) => storm.id));
storms = [
...storms,
...fromJtwc.filter((storm) => !listed.has(storm.id)),
].slice(0, 32);
signal.throwIfAborted();
cache = { storms, fetchedAt: now() };
return cache;
@@ -365,9 +448,8 @@ export function cycloneProxy({
function describe(value, stale = false) {
return {
schemaVersion: 1,
source: 'NOAA NHC / CPHC',
attribution:
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center',
source: SOURCE,
attribution: ATTRIBUTION,
coverage: COVERAGE,
fetchedAt: value?.fetchedAt ?? null,
stale: stale || !value,
@@ -402,13 +484,16 @@ export function cycloneProxy({
json(200, describe(await acquire(controller.signal)));
} catch (error) {
if (error.status === 429) return json(429, { error: 'cyclone_busy' });
const usable =
cache &&
now() - cache.fetchedAt <= 12 * HOUR &&
cache.storms.every(
(storm) => now() - Date.parse(storm.issuedAt) <= 12 * HOUR,
);
json(200, describe(usable ? cache : null, true));
// Each storm is served while its own advisory is usable.
const usable = cache &&
now() - cache.fetchedAt <= 12 * HOUR && {
...cache,
storms: cache.storms.filter(
(storm) =>
now() - Date.parse(storm.issuedAt) <= cycloneUsableMs(storm),
),
};
json(200, describe(usable || null, true));
}
} finally {
res.removeListener?.('close', close);
+459
View File
@@ -0,0 +1,459 @@
import { inflateRawSync } from 'node:zlib';
/**
* Joint Typhoon Warning Center (JTWC) warnings for the cyclone layer: the
* western North Pacific, North Indian Ocean and Southern Hemisphere, where
* NHC and CPHC issue none. Keyless; US government work.
*
* rss/jtwc.rss current warnings, product links in each item
* products/<prefix>.tcw JMV 3.0 warning data (position, forecast, text)
* products/<prefix>.kmz Google Earth overlay: the 34-knot danger swath
*
* JTWC publishes no schema for any of these. Each reader takes only what it
* recognises and throws on a product that lacks it. The danger swath is the
* swath of 34-knot winds widened by forecast track error; it is drawn as its
* own area (`dangerArea`), never as a cone of centre-track uncertainty.
*/
export const JTWC_ORIGIN = 'https://www.metoc.navy.mil';
export const JTWC_RSS_URL = `${JTWC_ORIGIN}/jtwc/rss/jtwc.rss`;
export const JTWC_PRODUCTS_URL = `${JTWC_ORIGIN}/jtwc/products`;
const WARNING_ITEMS = [
'NWPAC-NIO-WARNINGS',
'EPAC-CPAC-WARNINGS',
'SH-WARNINGS',
];
const NO_WARNINGS = 'No Current Tropical Cyclone Warnings';
const PREFIX = /^(?:wp|io|sh|ep|cp)\d{4}$/;
const HOUR = 3600_000;
/**
* A JTWC warning is usable for 13 hours after issuance: some storms are on
* 12-hourly warnings, and the next one posts shortly before its time.
*/
export const JTWC_USABLE_MS = 13 * HOUR;
const KML_MAX_BYTES = 4 * 1024 * 1024;
function invalid(what) {
return new Error(`invalid_jtwc_data: ${what}`);
}
/** Storm product prefixes (`sh0427`) the feed lists, in feed order. */
export function parseJtwcFeed(feed) {
if (typeof feed !== 'string' || !feed.includes('<rss')) throw invalid('feed');
const prefixes = [];
for (const guid of WARNING_ITEMS) {
const item = feed
.split('<item>')
.slice(1)
.map((part) => part.split('</item>')[0])
.find((part) => part.includes(`<guid>${guid}</guid>`));
if (!item) throw invalid(`feed item ${guid}`);
const found = [
...item.matchAll(
/\/jtwc\/products\/([a-z]{2}\d{4})(?:web\.txt|\.tcw|\.kmz)/g,
),
]
.map((match) => match[1])
.filter((prefix) => PREFIX.test(prefix));
if (!found.length && !item.includes(NO_WARNINGS))
throw invalid(`feed item ${guid}`);
for (const prefix of found)
if (!prefixes.includes(prefix)) prefixes.push(prefix);
}
return prefixes;
}
/** `sh0427` is ATCF `sh042027` (the season year). */
export function jtwcStormId(prefix) {
if (!PREFIX.test(prefix)) throw invalid('prefix');
return `${prefix.slice(0, 4)}20${prefix.slice(4)}`;
}
// JTWC's words for a storm, longest first, and their codes.
const KINDS = [
['SUPER TYPHOON', 'STY'],
['SUBTROPICAL STORM', 'SS'],
['SUBTROPICAL DEPRESSION', 'SD'],
['TROPICAL CYCLONE', 'TC'],
['TROPICAL STORM', 'TS'],
['TROPICAL DEPRESSION', 'TD'],
['TYPHOON', 'TY'],
['HURRICANE', 'HU'],
];
/** `115S` / `1642W` (tenths) or `11.6S` (degrees); south and west negative. */
function coordinate(word, tenths) {
const match = /^(\d+(?:\.\d+)?)([NSEW])$/.exec(word || '');
if (!match || (tenths && match[1].includes('.'))) return null;
const value = Number(match[1]) / (tenths ? 10 : 1);
const limit = 'NS'.includes(match[2]) ? 90 : 180;
if (!(value <= limit)) return null;
return 'SW'.includes(match[2]) ? -value : value;
}
function utc(year, month, day, hour, minute = 0) {
const at = Date.UTC(year, month - 1, day, hour, minute);
const date = new Date(at);
return date.getUTCDate() === day && date.getUTCHours() === hour ? at : NaN;
}
/** `ddhhmm` (optionally `Z`-suffixed) as the time nearest `near`. */
function nearest(dtg, near) {
const match = /^(\d\d)(\d\d)(\d\d)Z?[.,]?$/.exec(dtg || '');
if (!match) return NaN;
const base = new Date(near);
let best = NaN;
for (const offset of [-1, 0, 1]) {
const month = new Date(
Date.UTC(base.getUTCFullYear(), base.getUTCMonth() + offset, 1),
);
const at = utc(
month.getUTCFullYear(),
month.getUTCMonth() + 1,
Number(match[1]),
Number(match[2]),
Number(match[3]),
);
if (
Number.isFinite(at) &&
(!Number.isFinite(best) || Math.abs(at - near) < Math.abs(best - near))
)
best = at;
}
return best;
}
const iso = (ms) => new Date(ms).toISOString();
function titleCase(name) {
return name
.toLowerCase()
.replace(
/(^|[\s-])([a-z])/g,
(_, gap, letter) => gap + letter.toUpperCase(),
);
}
/**
* One storm's warning (`.tcw`) as a cyclone-snapshot storm, its geometry
* pending until `withJtwcDangerArea` gives it the warning's danger swath.
* Throws on a warning without its header, hour 0 or subject.
*/
export function parseJtwcWarning(prefix, text) {
const id = jtwcStormId(prefix);
if (typeof text !== 'string') throw invalid('tcw');
const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, ''));
const dtg = lines[0]?.split(/\s+/)[2];
const headerAt = lines.findIndex((line) => /^\d{10}\s/.test(line));
if (headerAt < 0 || !dtg) throw invalid('tcw header');
const header = lines[headerAt].split(/\s+/);
const synopticAt = utc(
Number(header[0].slice(0, 4)),
Number(header[0].slice(4, 6)),
Number(header[0].slice(6, 8)),
Number(header[0].slice(8, 10)),
);
if (!Number.isFinite(synopticAt)) throw invalid('tcw synoptic time');
const number = header[1];
let at = 2;
const nameWords = [];
while (at < header.length && !/^\d+$/.test(header[at]))
nameWords.push(header[at++]);
const numbers = header.slice(at);
const warningMatch = /^0*(\d{1,3})$/.exec(numbers[0] || '');
if (!warningMatch || !number) throw invalid('tcw warning number');
const advisoryNumber = String(Number(warningMatch[1]));
const issuedAt = nearest(dtg, synopticAt);
if (!Number.isFinite(issuedAt)) throw invalid('tcw message time');
const direction = Number(numbers[2]);
const speed = Number(numbers[3]);
const forecast = [];
for (const line of lines.slice(headerAt + 1)) {
const words = line.trim().split(/\s+/);
const tau = /^T(\d{3})$/.exec(words[0]);
if (!tau) break;
const latitude = coordinate(words[1], true);
const longitude = coordinate(words[2], true);
const windKt = Number(words[3]);
if (latitude === null || longitude === null || !/^\d+$/.test(words[3]))
throw invalid('tcw forecast line');
forecast.push({
position: { longitude, latitude },
tauHours: Number(tau[1]),
windKt,
gustKt: null,
});
}
if (forecast[0]?.tauHours !== 0) throw invalid('tcw hour 0');
const subjectAt = lines.findIndex((line) => /^\s*SUBJ/.test(line));
if (subjectAt < 0) throw invalid('tcw subject');
const subject = lines[subjectAt]
.replace(/^\s*SUBJ[:/]?/, '')
.replace(/\/+$/, '')
.trim();
let end = lines.findIndex((line, i) => i > subjectAt && line.trim() === '//');
if (end < 0) end = lines.length;
const body = lines.slice(subjectAt, end);
let tau = null;
for (const line of body) {
const trimmed = line.trim();
const hours = /^(\d+) HRS, VALID AT:$/.exec(trimmed);
if (trimmed.startsWith('WARNING POSITION')) tau = 0;
else if (hours) tau = Number(hours[1]);
else {
const gust = /GUSTS (\d+) KT/.exec(trimmed);
const point = gust && forecast.find((p) => p.tauHours === tau);
if (point && point.gustKt === null) point.gustKt = Number(gust[1]);
}
}
const remarksAt = body.findIndex((line) => /^\s*REMARKS/.test(line));
const remarks = (remarksAt < 0 ? [] : body.slice(remarksAt))
.join(' ')
.replace(/\s+/g, ' ');
const issue = /(\d{6})Z POSITION NEAR (\d+\.\d)([NS]) (\d+\.\d)([EW])/.exec(
remarks,
);
const issueAt = issue ? nearest(issue[1], synopticAt) : NaN;
const pressure = /CENTRAL PRESSURE AT \d{6}Z IS (\d{3,4}) MB/.exec(remarks);
const kind = KINDS.find(([words]) => subject.includes(words));
const first = forecast[0];
const position =
issue && Number.isFinite(issueAt)
? {
longitude: coordinate(`${issue[4]}${issue[5]}`, false),
latitude: coordinate(`${issue[2]}${issue[3]}`, false),
}
: first.position;
if (position.longitude === null || position.latitude === null)
throw invalid('tcw position');
const basin = id.slice(0, 2);
const longitude = position.longitude;
const outlook =
basin === 'io' || (basin === 'sh' && longitude >= 0 && longitude < 135)
? 'abioweb.txt'
: basin === 'wp' || basin === 'sh'
? 'abpwweb.txt'
: null;
const pressureHpa = pressure ? Number(pressure[1]) : null;
const storm = {
id,
agency: 'jtwc',
name: nameWords.length ? titleCase(nameWords.join(' ')) : number,
classification: kind ? kind[1] : 'TC',
basin: basin.toUpperCase(),
position,
positionAt: iso(Number.isFinite(issueAt) ? issueAt : synopticAt),
advisoryNumber,
issuedAt: iso(issuedAt),
windKt: first.windKt <= 300 ? first.windKt : null,
pressureHpa:
pressureHpa !== null && pressureHpa >= 800 && pressureHpa <= 1100
? pressureHpa
: null,
movement: {
directionDegrees:
Number.isInteger(direction) && direction <= 360 ? direction : null,
speedKt: Number.isInteger(speed) && speed <= 200 ? speed : null,
},
advisoryUrl: `${JTWC_PRODUCTS_URL}/${prefix}web.txt`,
outlookUrl: outlook ? `${JTWC_PRODUCTS_URL}/${outlook}` : null,
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
return { storm, forecast };
}
/**
* The storm with its forecast geometry, current only with the danger swath
* of its own warning number (JTWC posts the overlay before the text).
*/
export function withJtwcDangerArea({ storm, forecast }, overlay) {
if (
!overlay ||
overlay.advisoryNumber !== storm.advisoryNumber ||
!overlay.dangerArea ||
forecast.length < 2
)
return storm;
return {
...storm,
geometryStatus: 'current',
geometryAdvisoryNumber: storm.advisoryNumber,
forecastPoints: forecast.map((point) => ({
position: { ...point.position },
tauHours: point.tauHours,
windKt: point.windKt,
gustKt: point.gustKt,
})),
track: {
type: 'LineString',
coordinates: forecast.map((point) => [
point.position.longitude,
point.position.latitude,
]),
},
dangerArea: overlay.dangerArea,
};
}
/** The warning number and 34-knot danger swath of a warning's KML. */
export function parseJtwcKml(kml) {
if (typeof kml !== 'string') throw invalid('kml');
const number = /WARNING NR\s+0*(\d{1,3})\b/.exec(kml);
if (!number) throw invalid('kml warning number');
const polygons = [];
for (const part of kml.split('<Placemark').slice(1)) {
const placemark = part.split('</Placemark>')[0];
const name = /<name>([^<]*)<\/name>/.exec(placemark)?.[1] || '';
if (!/^\s*34 knot Danger Swath/i.test(name)) continue;
for (const polygonPart of placemark.split('<Polygon').slice(1)) {
const polygon = polygonPart.split('</Polygon>')[0];
const rings = [
...polygon.matchAll(/<coordinates>([\s\S]*?)<\/coordinates>/g),
]
.map((match) => ring(match[1]))
.filter(Boolean);
if (rings.length) polygons.push(rings);
}
}
return {
advisoryNumber: String(Number(number[1])),
dangerArea: !polygons.length
? null
: polygons.length === 1
? { type: 'Polygon', coordinates: polygons[0] }
: { type: 'MultiPolygon', coordinates: polygons },
};
}
/**
* `longitude` in -180..180 (180 stays 180). JTWC writes a ring crossing the
* antimeridian with longitudes past ±180 (`181.5`); wrapped, the ring crosses
* 180° as NHC's cones that cross it do.
*/
export function wrapJtwcLongitude(longitude) {
if (Math.abs(longitude) <= 180) return longitude;
const wrapped = ((((longitude + 180) % 360) + 360) % 360) - 180;
// JTWC writes two decimals; this drops the float noise of the wrap.
return Math.round(wrapped * 1e6) / 1e6;
}
function ring(text) {
const points = [];
for (const tuple of text.trim().split(/\s+/)) {
const [lon, lat] = tuple.split(',').map(Number);
if (
!Number.isFinite(lon) ||
!Number.isFinite(lat) ||
Math.abs(lon) > 540 ||
Math.abs(lat) > 90
)
return null;
points.push([wrapJtwcLongitude(lon), lat]);
}
if (!points.length) return null;
const [a, b] = [points[0], points.at(-1)];
if (a[0] !== b[0] || a[1] !== b[1]) points.push([...a]);
return points.length >= 4 ? points : null;
}
/**
* The first `.kml` entry of a KMZ (a zip), from its central directory.
* Stored and deflated entries only.
*/
export function kmlFromKmz(bytes) {
const data = Buffer.from(bytes);
let end = -1;
for (let i = data.length - 22; i >= Math.max(0, data.length - 65_557); i--)
if (data.readUInt32LE(i) === 0x06054b50) {
end = i;
break;
}
if (end < 0) throw invalid('kmz');
const entries = data.readUInt16LE(end + 10);
let at = data.readUInt32LE(end + 16);
for (let n = 0; n < entries; n++) {
if (at + 46 > data.length || data.readUInt32LE(at) !== 0x02014b50)
throw invalid('kmz directory');
const method = data.readUInt16LE(at + 10);
const compressed = data.readUInt32LE(at + 20);
const size = data.readUInt32LE(at + 24);
const nameLength = data.readUInt16LE(at + 28);
const extra = data.readUInt16LE(at + 30);
const comment = data.readUInt16LE(at + 32);
const local = data.readUInt32LE(at + 42);
const name = data.toString('utf8', at + 46, at + 46 + nameLength);
at += 46 + nameLength + extra + comment;
if (!name.toLowerCase().endsWith('.kml')) continue;
if (size > KML_MAX_BYTES || data.readUInt32LE(local) !== 0x04034b50)
throw invalid('kmz entry');
const start =
local +
30 +
data.readUInt16LE(local + 26) +
data.readUInt16LE(local + 28);
const raw = data.subarray(start, start + compressed);
if (method === 0) return raw.toString('utf8');
if (method === 8)
return inflateRawSync(raw, { maxOutputLength: KML_MAX_BYTES }).toString(
'utf8',
);
throw invalid('kmz compression');
}
throw invalid('kmz holds no kml');
}
/**
* Every storm JTWC lists, through `read(url, kind)` (kind `text` or
* `bytes`). A feed that cannot be read throws. One storm never stops the
* others: a warning that cannot be read or parsed leaves that storm out,
* and only when every listed storm's fails does the read throw. An overlay
* that cannot be read leaves its storm's geometry `unavailable`, and one
* JTWC has not posted yet (`read` resolving null), or posted for another
* warning, leaves it `pending`.
*/
export async function readJtwcStorms(read, now = Date.now()) {
const prefixes = parseJtwcFeed(await read(JTWC_RSS_URL, 'text'));
// Each storm's warning and overlay are read at once, every storm alike.
const readStorm = async (prefix) => {
const [text, overlay] = await Promise.all([
read(`${JTWC_PRODUCTS_URL}/${prefix}.tcw`, 'text'),
read(`${JTWC_PRODUCTS_URL}/${prefix}.kmz`, 'bytes')
.then((bytes) =>
bytes === null ? null : parseJtwcKml(kmlFromKmz(bytes)),
)
.catch((error) => {
if (error?.name === 'AbortError') throw error;
return undefined;
}),
]);
if (text === null) throw invalid(`${prefix}.tcw missing`);
const warning = parseJtwcWarning(prefix, text);
const issued = Date.parse(warning.storm.issuedAt);
// A warning past its use, or dated far ahead of this clock, is left out.
if (now - issued > JTWC_USABLE_MS || issued - now > 90 * 60_000)
return null;
// An overlay that could not be read: the geometry is unavailable.
return overlay === undefined
? { ...warning.storm, geometryStatus: 'unavailable' }
: withJtwcDangerArea(warning, overlay);
};
const results = await Promise.allSettled(prefixes.map(readStorm));
const failed = results.filter((result) => result.status === 'rejected');
const aborted = failed.find((result) => result.reason?.name === 'AbortError');
if (aborted) throw aborted.reason;
if (failed.length && failed.length === results.length) throw failed[0].reason;
const storms = [];
for (const result of results) {
const storm = result.status === 'fulfilled' ? result.value : null;
if (storm && !storms.some((held) => held.id === storm.id))
storms.push(storm);
}
return storms;
}
+332
View File
@@ -0,0 +1,332 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { deflateRawSync } from 'node:zlib';
import {
wrapJtwcLongitude,
JTWC_PRODUCTS_URL,
JTWC_RSS_URL,
jtwcStormId,
kmlFromKmz,
parseJtwcFeed,
parseJtwcKml,
parseJtwcWarning,
readJtwcStorms,
withJtwcDangerArea,
} from './jtwc.js';
// Tropical Cyclone 04P (Xavier), warning 15, as JTWC published it on
// 2026-11-21 (past fixes shortened).
const TCW = `WTPS51 PGTW 210300
WARNING ATCG MIL 04P SWP 261121015248
2026112100 04P XAVIER 015 01 245 04 SATL 020
T000 115S 1642W 045 R034 075 NE QD 105 SE QD 090 SW QD 050 NW QD
T012 120S 1652W 045 R034 075 NE QD 105 SE QD 090 SW QD 035 NW QD
T024 125S 1665W 040 R034 070 NE QD 100 SE QD 070 SW QD 020 NW QD
T072 130S 1708W 030
AMP
072HR DISSIPATED AS A SIGNIFICANT TROPICAL CYCLONE OVER WATER
SUBJ: TROPICAL CYCLONE 04P (XAVIER) WARNING NR 015
1. TROPICAL CYCLONE 04P (XAVIER) WARNING NR 015
01 ACTIVE TROPICAL CYCLONE IN SOUTHPAC
---
WARNING POSITION:
210000Z --- NEAR 11.5S 164.2W
MAX SUSTAINED WINDS - 045 KT, GUSTS 055 KT
---
FORECASTS:
12 HRS, VALID AT:
211200Z --- 12.0S 165.2W
MAX SUSTAINED WINDS - 045 KT, GUSTS 055 KT
---
24 HRS, VALID AT:
220000Z --- 12.5S 166.5W
MAX SUSTAINED WINDS - 040 KT, GUSTS 050 KT
---
72 HRS, VALID AT:
240000Z --- 13.0S 170.8W
MAX SUSTAINED WINDS - 030 KT, GUSTS 040 KT
---
REMARKS:
210300Z POSITION NEAR 11.6S 164.5W.
21NOV26. TROPICAL CYCLONE 04P (XAVIER), LOCATED APPROXIMATELY 416
NM EAST-NORTHEAST OF PAGO PAGO, HAS TRACKED WEST-SOUTHWESTWARD AT
04 KNOTS OVER THE PAST SIX HOURS.
MINIMUM CENTRAL PRESSURE AT 210000Z IS 995 MB. MAXIMUM
SIGNIFICANT WAVE HEIGHT AT 210000Z IS 19 FEET. NEXT WARNINGS AT
210900Z, 211500Z, 212100Z AND 220300Z.
//
0426112018 113S1638W 55
0426112100 115S1642W 45
NNNN
`;
const item = (guid, body) =>
`<item><title>${guid}</title><description><![CDATA[${body}]]></description><guid>${guid}</guid></item>`;
const NONE =
"<ul><li><font color='red'>No Current Tropical Cyclone Warnings.</font></li></ul>";
function feed(prefixes = ['sh0427']) {
const links = prefixes
.map(
(prefix) =>
`<li><a href='${JTWC_PRODUCTS_URL}/${prefix}web.txt'>TC Warning Text</a></li><li><a href='${JTWC_PRODUCTS_URL}/${prefix}.tcw'>JMV 3.0 Data</a></li>`,
)
.join('');
return `<?xml version="1.0"?><rss version="2.0"><channel>${item('NWPAC-NIO-WARNINGS', NONE)}${item('EPAC-CPAC-WARNINGS', NONE)}${item('SH-WARNINGS', prefixes.length ? links : NONE)}${item('TROPICAL-ADVISORIES', `<a href="${JTWC_PRODUCTS_URL}/abpwweb.txt">ABPW10</a>`)}</channel></rss>`;
}
const SWATH = [
[-164.02, -9.5],
[-163.0, -12.0],
[-171.0, -14.5],
[-170.0, -11.0],
];
function kml(number = 15) {
return `<kml><Document><Folder>
<Placemark><name>21/00Z (TROPICAL CYCLONE 04P (XAVIER) WARNING NR ${number} - 45 knots)</name>
<Point><coordinates>-164.2,-11.5,0</coordinates></Point></Placemark>
<Placemark><name>RADIUS OF 34 KT WINDS</name><Polygon><outerBoundaryIs><LinearRing><coordinates>-164.2,-10.25,0 -163,-11,0 -164.2,-12.5,0 -164.2,-10.25,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
<Placemark><name>34 knot Danger Swath</name><Polygon><outerBoundaryIs><LinearRing><coordinates>
${SWATH.map(([lon, lat]) => `${lon},${lat},0`).join(' ')}
</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
</Folder></Document></kml>`;
}
/** A zip holding `files` ({name: text}), deflated. */
function zip(files) {
const locals = [],
central = [];
let offset = 0;
for (const [name, text] of Object.entries(files)) {
const data = Buffer.from(text);
const packed = deflateRawSync(data);
const nameBytes = Buffer.from(name);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(8, 8);
local.writeUInt32LE(packed.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(nameBytes.length, 26);
const entry = Buffer.alloc(46);
entry.writeUInt32LE(0x02014b50, 0);
entry.writeUInt16LE(8, 10);
entry.writeUInt32LE(packed.length, 20);
entry.writeUInt32LE(data.length, 24);
entry.writeUInt16LE(nameBytes.length, 28);
entry.writeUInt32LE(offset, 42);
locals.push(local, nameBytes, packed);
central.push(entry, nameBytes);
offset += 30 + nameBytes.length + packed.length;
}
const directory = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(Object.keys(files).length, 8);
end.writeUInt16LE(Object.keys(files).length, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
return new Uint8Array(Buffer.concat([...locals, directory, end]));
}
const NOW = Date.UTC(2026, 10, 21, 3, 20);
test('the feed lists the storms of the warning items and refuses anything else', () => {
assert.deepEqual(parseJtwcFeed(feed()), ['sh0427']);
assert.deepEqual(parseJtwcFeed(feed([])), []);
assert.deepEqual(parseJtwcFeed(feed(['wp3026', 'sh0427', 'wp3026'])), [
'wp3026',
'sh0427',
]);
assert.throws(() => parseJtwcFeed('<html>blocked</html>'));
assert.throws(() =>
parseJtwcFeed(feed().replace('<guid>SH-WARNINGS', '<guid>OTHER')),
);
assert.throws(() => parseJtwcFeed(feed([]).replaceAll(NONE, '<ul></ul>')));
});
test('product prefixes are season-year ATCF ids', () => {
assert.equal(jtwcStormId('sh0427'), 'sh042027');
assert.equal(jtwcStormId('wp3026'), 'wp302026');
assert.throws(() => jtwcStormId('al0126'));
});
test('a warning reads as a pending JTWC storm with its forecast', () => {
const { storm, forecast } = parseJtwcWarning('sh0427', TCW);
assert.deepEqual(
{ ...storm },
{
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
// Where the storm was at issuance, from the remarks.
position: { longitude: -164.5, latitude: -11.6 },
positionAt: '2026-11-21T03:00:00.000Z',
advisoryNumber: '15',
issuedAt: '2026-11-21T03:00:00.000Z',
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
},
);
assert.deepEqual(
forecast.map((point) => [point.tauHours, point.windKt, point.gustKt]),
[
[0, 45, 55],
[12, 45, 55],
[24, 40, 50],
[72, 30, 40],
],
);
assert.deepEqual(forecast[0].position, { longitude: -164.2, latitude: -11.5 });
});
test('classes come from the subject; broken warnings throw', () => {
const typhoon = TCW.replace(
'SUBJ: TROPICAL CYCLONE 04P',
'SUBJ: SUPER TYPHOON 04P',
);
assert.equal(parseJtwcWarning('sh0427', typhoon).storm.classification, 'STY');
for (const broken of [
'',
'<html>Access Denied</html>',
TCW.replace(/^T000.*$/m, ''),
TCW.replace('SUBJ:', 'XXXX:'),
TCW.replace('T000 115S', 'T000 115X'),
])
assert.throws(() => parseJtwcWarning('sh0427', broken), /invalid_jtwc/);
});
test('the danger swath makes the geometry current only for its own warning', () => {
const warning = parseJtwcWarning('sh0427', TCW);
const overlay = parseJtwcKml(kml(15));
assert.equal(overlay.advisoryNumber, '15');
assert.deepEqual(overlay.dangerArea, {
type: 'Polygon',
coordinates: [[...SWATH, SWATH[0]]],
});
const storm = withJtwcDangerArea(warning, overlay);
assert.equal(storm.geometryStatus, 'current');
assert.equal(storm.geometryAdvisoryNumber, '15');
assert.equal(storm.cone, null);
assert.deepEqual(storm.track.coordinates[0], [-164.2, -11.5]);
assert.equal(storm.forecastPoints.length, 4);
assert.equal(
withJtwcDangerArea(warning, parseJtwcKml(kml(14))).geometryStatus,
'pending',
);
assert.equal(withJtwcDangerArea(warning, null).geometryStatus, 'pending');
assert.throws(() => parseJtwcKml('<kml></kml>'));
});
test('the KML is read out of the KMZ', () => {
assert.equal(
kmlFromKmz(zip({ 'images/logo.png': 'png', 'doc.kml': kml() })),
kml(),
);
assert.throws(() => kmlFromKmz(new Uint8Array([1, 2, 3])));
assert.throws(() => kmlFromKmz(zip({ 'logo.png': 'png' })));
});
function reader(answers) {
const calls = [];
const read = async (url, kind) => {
calls.push(url);
const answer = answers[url];
if (answer instanceof Error) throw answer;
if (answer === undefined) return null;
return kind === 'bytes' ? answer : String(answer);
};
return { read, calls };
}
test('every listed storm is read with its overlay; an unreadable overlay leaves its geometry unavailable', async () => {
const products = (prefix, kmz) => ({
[`${JTWC_PRODUCTS_URL}/${prefix}.tcw`]: TCW,
[`${JTWC_PRODUCTS_URL}/${prefix}.kmz`]: kmz,
});
const good = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', zip({ 'doc.kml': kml() })),
});
const [storm] = await readJtwcStorms(good.read, NOW);
assert.equal(storm.geometryStatus, 'current');
assert.deepEqual(good.calls.sort(), [
`${JTWC_PRODUCTS_URL}/sh0427.kmz`,
`${JTWC_PRODUCTS_URL}/sh0427.tcw`,
JTWC_RSS_URL,
]);
const notPosted = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', undefined),
});
assert.equal(
(await readJtwcStorms(notPosted.read, NOW))[0].geometryStatus,
'pending',
);
const broken = reader({
[JTWC_RSS_URL]: feed(),
...products('sh0427', new Uint8Array([1, 2, 3])),
});
assert.equal(
(await readJtwcStorms(broken.read, NOW))[0].geometryStatus,
'unavailable',
);
// A warning past 13 hours is left out; with every listed warning missing,
// the read fails.
assert.deepEqual(
await readJtwcStorms(good.read, NOW + 13 * 3600_000),
[],
);
const missing = reader({ [JTWC_RSS_URL]: feed() });
await assert.rejects(readJtwcStorms(missing.read, NOW), /invalid_jtwc/);
const down = reader({ [JTWC_RSS_URL]: new Error('down') });
await assert.rejects(readJtwcStorms(down.read, NOW), /down/);
});
test('one storm whose warning cannot be read or parsed never stops the others', async () => {
const { read } = reader({
[JTWC_RSS_URL]: feed(['wp3026', 'sh0427', 'io0126']),
[`${JTWC_PRODUCTS_URL}/wp3026.tcw`]: new Error('HTTP 500'),
[`${JTWC_PRODUCTS_URL}/io0126.tcw`]: '<html>Access Denied</html>',
[`${JTWC_PRODUCTS_URL}/sh0427.tcw`]: TCW,
[`${JTWC_PRODUCTS_URL}/sh0427.kmz`]: zip({ 'doc.kml': kml() }),
});
const storms = await readJtwcStorms(read, NOW);
assert.deepEqual(
storms.map((storm) => [storm.id, storm.geometryStatus]),
[['sh042027', 'current']],
);
});
test('a danger swath crossing the antimeridian is kept, its longitudes wrapped', () => {
const crossing = kml().replace(
/<coordinates>\n[^<]*<\/coordinates>/,
'<coordinates>179.5,-15,0 181,-16,0 180.5,-18,0 179.5,-17,0</coordinates>',
);
assert.deepEqual(parseJtwcKml(crossing).dangerArea, {
type: 'Polygon',
coordinates: [
[
[179.5, -15],
[-179, -16],
[-179.5, -18],
[179.5, -17],
[179.5, -15],
],
],
});
assert.equal(wrapJtwcLongitude(-181.5), 178.5);
assert.equal(wrapJtwcLongitude(180), 180);
assert.equal(wrapJtwcLongitude(-164.2), -164.2);
});
+238
View File
@@ -0,0 +1,238 @@
// ADSBDB ENRICHMENT — the keyspace the cache used to remember forever.
//
// `/api/adsbdb` answers `route/<callsign>` and `type/<hex>`. Both keys come
// from the caller: a callsign is 2-8 of [A-Z0-9], a hex is six of [0-9a-f].
// Every distinct key that reached upstream was cached — 404s included — and
// nothing ever removed one, so a caller walking the keyspace grew both the
// in-memory maps and `.gev-cache/adsbdb.json` without bound, at one live
// request to the free community API per new key.
//
// These cases drive the real exported route handler. No network: `fetch` is
// stubbed per test and restored afterwards, so a case that reaches upstream
// fails loudly rather than making a request.
//
// Run with: npm test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import path from 'node:path';
import os from 'node:os';
import { adsbdbProxy } from '../server/providers/aircraft/enrichment.js';
/** Collect a plugin's routes into a path → handler map. */
function install(plugin) {
const routes = new Map();
plugin.configureServer({
middlewares: {
use(routePath, handler) {
routes.set(routePath, handler);
},
},
});
return routes;
}
function request(handler, { url = '/', remoteAddress = '127.0.0.1' } = {}) {
return new Promise((resolve, reject) => {
const headers = new Map();
const req = { method: 'GET', url, headers: {}, socket: { remoteAddress } };
const res = {
statusCode: 200,
writeHead(status, hdrs = {}) {
this.statusCode = status;
for (const [name, value] of Object.entries(hdrs))
headers.set(String(name).toLowerCase(), String(value));
},
end(body = '') {
let parsed = null;
try {
parsed = body ? JSON.parse(String(body)) : null;
} catch {
parsed = String(body);
}
resolve({
statusCode: this.statusCode,
headers: Object.fromEntries(headers),
body: parsed,
});
},
};
Promise.resolve(handler(req, res)).catch(reject);
});
}
/**
* Replace global fetch for the duration of one test, counting the calls the
* cache failed to absorb. Every hex answers with the same aircraft, so a
* second live call for a key we already asked about is a cache miss, nothing
* else.
*/
function stubUpstream(t) {
const asked = [];
const original = globalThis.fetch;
globalThis.fetch = async (url) => {
asked.push(String(url));
return new Response(
JSON.stringify({
response: {
aircraft: {
icao_type: 'B738',
manufacturer: 'Boeing',
type: '737-800',
registration: 'N-FIXTURE',
},
},
}),
{ status: 200 },
);
};
t.after(() => {
globalThis.fetch = original;
});
return asked;
}
/** A cache path inside the OS temp dir: these cases never load or write it. */
const scratchCachePath = () =>
path.join(os.tmpdir(), `gev-adsbdb-fixture-${process.pid}-absent.json`);
const hex = (i) => i.toString(16).padStart(6, '0');
test('an enrichment lookup still answers, and is cached', async (t) => {
const asked = stubUpstream(t);
const routes = install(
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 10 }),
);
const handler = routes.get('/api/adsbdb');
const first = await request(handler, { url: '/type/abc123' });
assert.equal(first.statusCode, 200);
assert.equal(first.body.found, true);
assert.equal(first.body.typeCode, 'B738');
assert.equal(asked.length, 1);
const second = await request(handler, { url: '/type/abc123' });
assert.equal(second.body.typeCode, 'B738');
assert.equal(asked.length, 1, 'a warm key costs no upstream request');
});
test('the cache stops growing, and an evicted key is simply re-fetched', async (t) => {
const asked = stubUpstream(t);
// A ceiling of 3 exercises the same path 20,000 does, in four keys.
const routes = install(
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 3 }),
);
const handler = routes.get('/api/adsbdb');
for (let i = 1; i <= 4; i += 1)
await request(handler, { url: `/type/${hex(i)}` });
assert.equal(asked.length, 4, 'four distinct keys, four upstream requests');
// The newest is still warm...
await request(handler, { url: `/type/${hex(4)}` });
assert.equal(asked.length, 4);
// ...and the oldest was evicted, so it costs exactly one re-fetch, and
// still answers correctly.
const again = await request(handler, { url: `/type/${hex(1)}` });
assert.equal(asked.length, 5);
assert.match(asked[4], new RegExp(`/aircraft/${hex(1)}$`));
assert.equal(again.body.typeCode, 'B738');
});
test('route and aircraft keys are held to the ceiling independently', async (t) => {
const asked = stubUpstream(t);
const routes = install(
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 2 }),
);
const handler = routes.get('/api/adsbdb');
await request(handler, { url: '/type/aaaaaa' });
await request(handler, { url: '/type/bbbbbb' });
// Two callsigns must not push the two hexes out — they are separate stores.
await request(handler, { url: '/route/BAW1' });
await request(handler, { url: '/route/DLH2' });
assert.equal(asked.length, 4);
await request(handler, { url: '/type/aaaaaa' });
assert.equal(asked.length, 4, 'the aircraft store kept its own two keys');
});
test('a caller enumerating the keyspace is refused, and refusal costs nothing', async (t) => {
const asked = stubUpstream(t);
const routes = install(adsbdbProxy({ cachePath: scratchCachePath() }));
const handler = routes.get('/api/adsbdb');
let refused = null;
let served = 0;
// Each client queue drips one lookup per ENRICH_DISPATCH_GAP_MS (200 ms),
// and one tab runs two (Flights and Local ADS-B): 600/min must fit.
for (let i = 0; i < 1000 && !refused; i += 1) {
const res = await request(handler, { url: `/type/${hex(i)}` });
if (res.statusCode === 429) refused = res;
else served += 1;
}
assert.ok(refused, 'an unbounded sweep is eventually refused');
assert.equal(refused.body.error, 'Rate limit exceeded');
assert.equal(refused.headers['retry-after'], '10');
assert.ok(
served >= 600,
`both client queues together (600/min) must fit; served ${served}`,
);
assert.equal(
asked.length,
served,
'a refused request never reaches api.adsbdb.com',
);
});
test('a different client keeps its own budget', async (t) => {
stubUpstream(t);
const routes = install(adsbdbProxy({ cachePath: scratchCachePath() }));
const handler = routes.get('/api/adsbdb');
let noisy = 0;
for (let i = 0; i < 1000; i += 1) {
const res = await request(handler, {
url: `/type/${hex(i)}`,
remoteAddress: '10.0.0.1',
});
if (res.statusCode === 200) noisy += 1;
}
assert.ok(noisy > 0 && noisy < 1000, 'the noisy client was throttled');
const quiet = await request(handler, {
url: '/type/ffffff',
remoteAddress: '10.0.0.2',
});
assert.equal(quiet.statusCode, 200, 'a quiet client is not collateral');
});
test('GEV_RATELIMIT_ADSBDB_PER_MIN sets the cap, and 0 turns it off', async (t) => {
stubUpstream(t);
const original = process.env.GEV_RATELIMIT_ADSBDB_PER_MIN;
t.after(() => {
if (original === undefined) delete process.env.GEV_RATELIMIT_ADSBDB_PER_MIN;
else process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = original;
});
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '5';
const tight = install(adsbdbProxy({ cachePath: scratchCachePath() })).get(
'/api/adsbdb',
);
const statuses = [];
for (let i = 0; i < 6; i += 1)
statuses.push(
(await request(tight, { url: `/type/${hex(i)}` })).statusCode,
);
assert.deepEqual(statuses, [200, 200, 200, 200, 200, 429]);
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '0';
const open = install(adsbdbProxy({ cachePath: scratchCachePath() })).get(
'/api/adsbdb',
);
for (let i = 0; i < 1500; i += 1) {
const res = await request(open, { url: `/type/${hex(i)}` });
assert.equal(res.statusCode, 200, `request ${i} with the limiter off`);
}
});
+3
View File
@@ -17,6 +17,7 @@ import {
import { initGeoFileImport } from '../ui/geoFileImport.js';
import { useDisplayStore } from '../ui/stores/display.js';
import { applicationPinia } from '../ui/vueRuntime.js';
import { createContextCardOpener } from '../ui/stores/entityCard.js';
import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
import { createRecentImageryPanel } from '../ui/recentImagery.js';
import { createDataLibrary } from '../library/controller.js';
@@ -349,6 +350,8 @@ export function createApplicationTools({
dataManager,
sceneDirector,
annotations,
// A voice or chat selection opens its card in Context, as a click does.
contextCard: createContextCardOpener(applicationPinia()),
});
defer(() => {
voiceCommands.stop({ removeUi: true });
+20 -6
View File
@@ -1165,7 +1165,10 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
mobileCockpit[1],
/@media \(min-width: 390px\) and \(min-height: 240px\),\s*\(min-height: 450px\) \{\s*body\.cockpit-mode\.mobile-shell/,
);
assert.match(css, /\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/);
assert.match(
css,
/\.cockpit-visor-shell \{[^}]*?inset:\s*var\(--cockpit-visor-top\)/,
);
assert.match(
mobileCockpit[1],
/body\.cockpit-mode \.cockpit-utility-control\.is-expanded[\s\S]*?top:\s*96px;/,
@@ -1185,8 +1188,14 @@ test('mobile Cockpit prioritizes flight instruments and collision-safe controls'
});
test('the unread Stories announcement waits until Cockpit closes', () => {
assert.match(css, /body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/);
const storiesView = fs.readFileSync(path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'), 'utf8');
assert.match(
css,
/body\.cockpit-mode #gev-stories #hPop \{\s*display:\s*none;\s*\}/,
);
const storiesView = fs.readFileSync(
path.join(ROOT, 'src', 'ui', 'views', 'StoriesView.vue'),
'utf8',
);
assert.match(
storiesView,
/async function openExplore\(\) \{[^}]*?if \(await store\.controller\.open\(\)\) markPopSeen\(\);/,
@@ -1374,12 +1383,17 @@ test('voice Cockpit entry honours a requested contact layer before it enters', (
const retarget = ui.slice(
ui.indexOf(' _retargetCockpitEntryLayer({'),
ui.indexOf(' * Controls cockpit entry/exit and context navigation.'),
ui.indexOf(' controlCockpit(\n'),
);
assert.match(
retarget,
/militaryAwarenessLayer\.navigateNext\(\{\s*targetLayer,\s*aircraftClass,\s*origin: 'voice',\s*\}\)/,
'retargeting reuses filtered navigation with durable voice selection authority',
/layer\.trackById\?\.\(match\.icao24, \{ origin: 'voice' \}\)/,
'retargeting follows the match with durable voice selection authority',
);
assert.doesNotMatch(
retarget,
/militaryAwarenessLayer/,
'retargeting needs nothing from Contacts',
);
assert.match(
retarget,
+161 -2
View File
@@ -74,7 +74,12 @@ function collections(adv = '10') {
}
function install(options = {}, preview = false) {
let handler;
const plugin = cycloneProxy({ now: () => NOW, ...options });
// JTWC has its own tests below; these cover NHC alone.
const plugin = cycloneProxy({
now: () => NOW,
readJtwc: async () => [],
...options,
});
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: {
use(path, callback) {
@@ -297,7 +302,7 @@ test('dev and preview serve only fixed bounded NOAA queries, caching a complete
const snapshot = body(await request());
assert.equal(snapshot.unavailable, false);
assert.equal(snapshot.stale, false);
assert.match(snapshot.coverage, /not worldwide/);
assert.match(snapshot.coverage, /JTWC: western North Pacific/);
assert.equal(snapshot.storms[0].geometryStatus, 'current');
assert.equal(snapshot.fetchedAt, NOW);
assert.equal(calls.length, 4);
@@ -491,3 +496,157 @@ test('shared refresh caps waiting consumers and rejects redirects without exposi
});
assert.equal(body(await redirected.request()).unavailable, true);
});
function jtwcStorm(overrides = {}) {
return {
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
position: { longitude: -164.5, latitude: -11.6 },
positionAt: TIME,
advisoryNumber: '15',
issuedAt: TIME,
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
...overrides,
};
}
test('JTWC storms join NHC’s, and NHC’s advisory wins for a storm both list', async () => {
const crossing = jtwcStorm({
id: 'ep152026',
basin: 'EP',
name: 'JTWC copy',
});
const { request } = install({
fetchImpl: fetcher(),
readJtwc: async () => [jtwcStorm(), crossing],
});
const snapshot = body(await request());
assert.deepEqual(
snapshot.storms.map((storm) => [storm.id, storm.agency, storm.name]),
[
['ep152026', 'nhc', 'Fifteen-E'],
['sh042027', 'jtwc', 'Xavier'],
],
);
assert.equal(snapshot.stale, false);
assert.match(snapshot.source, /JTWC/);
assert.match(snapshot.attribution, /Joint Typhoon Warning Center/);
});
test('JTWC reads go through the bounded fetch with no redirects', async () => {
const calls = [];
const { request } = install({
fetchImpl: async (url, options) => {
calls.push({ url, options });
if (url.includes('jtwc.rss'))
return new Response(
'<rss><item><guid>NWPAC-NIO-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>EPAC-CPAC-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>SH-WARNINGS</guid>No Current Tropical Cyclone Warnings</item></rss>',
);
return fetcher()(url, options);
},
readJtwc: undefined,
});
const snapshot = body(await request());
assert.equal(snapshot.stale, false);
const jtwc = calls.filter(({ url }) => url.includes('metoc.navy.mil'));
assert.deepEqual(
jtwc.map(({ url }) => url),
['https://www.metoc.navy.mil/jtwc/rss/jtwc.rss'],
);
assert.equal(jtwc[0].options.redirect, 'error');
});
test('a failed JTWC read keeps its last storms and leaves NHC’s answer fresh', async () => {
let fail = false;
let clock = NOW;
const { request } = install({
fetchImpl: fetcher(),
now: () => clock,
readJtwc: async () => {
if (fail) throw new Error('jtwc down');
return [jtwcStorm()];
},
});
assert.equal(body(await request()).storms.length, 2);
fail = true;
clock += 6 * 60_000;
const kept = body(await request());
assert.equal(kept.stale, false);
assert.equal(kept.reason, null);
assert.deepEqual(
kept.storms.map((storm) => storm.id),
['ep152026', 'sh042027'],
);
// Past their use, both advisories leave the cached answer.
clock = Date.parse(TIME) + 13 * 3600_000 + 60_000;
const later = body(await request());
assert.deepEqual(
later.storms.map((storm) => storm.id),
[],
);
});
test('a cached answer drops each storm whose own advisory is past use, not all of them', async () => {
let up = true;
let clock = NOW;
const { request } = install({
fetchImpl: async (url, options) => {
if (!up) throw new Error('down');
return fetcher()(url, options);
},
now: () => clock,
readJtwc: async () => [
jtwcStorm({ issuedAt: new Date(NOW - 30 * 60_000).toISOString() }),
],
});
assert.equal(body(await request()).storms.length, 2);
up = false;
// 12 h 10 min after the NHC advisory: NHC's is past use, JTWC's is not.
clock = Date.parse(TIME) + 12 * 3600_000 + 10 * 60_000;
const cached = body(await request());
assert.equal(cached.stale, true);
assert.deepEqual(
cached.storms.map((storm) => storm.id),
['sh042027'],
);
});
test('a JTWC that hangs or answers 500 leaves NHC’s answer unchanged', async (t) => {
const nhcOnly = body(await install({ fetchImpl: fetcher() }).request());
assert.equal(nhcOnly.stale, false);
const jtwcCalls = [];
for (const mode of ['500', 'hang']) {
const { request } = install({
readJtwc: undefined,
jtwcTimeoutMs: 20,
fetchImpl: async (url, options) => {
if (!String(url).includes('metoc.navy.mil'))
return fetcher()(url, options);
jtwcCalls.push(mode);
if (mode === '500') return new Response('down', { status: 500 });
// Hangs until its own deadline aborts it.
return new Promise((_, reject) =>
options.signal.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
),
);
},
});
const answer = body(await request());
assert.deepEqual(answer, nhcOnly, `JTWC ${mode}`);
}
assert.deepEqual(jtwcCalls, ['500', 'hang']);
});
+1 -1
View File
@@ -563,7 +563,7 @@ export const DATA_CREDITS = [
},
{
key: 'weather-cyclones',
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific. Forecast center uncertainty, not storm size.',
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific; <a href="https://www.metoc.navy.mil/jtwc/jtwc.html" target="_blank" rel="noopener">Joint Typhoon Warning Center</a> · western North Pacific, North Indian Ocean, Southern Hemisphere. The NHC cone is forecast center uncertainty, not storm size.',
},
{
key: 'weather-lightning',
+29
View File
@@ -14,6 +14,35 @@ export const AWARENESS_RELATIONSHIP = Object.freeze({
UNKNOWN: 'UNKNOWN',
});
/**
* Whether an aircraft matches a spoken class filter ("helicopter", "tanker"),
* on its class or type fields. No filter matches everything; an aircraft
* with no class or type matches no filter.
* @param {object} item Aircraft summary (`getNearby` row or cohort item).
* @param {string|null} aircraftClass Requested class.
* @returns {boolean}
*/
export function aircraftClassMatches(item, aircraftClass) {
const normalize = (value) =>
String(value || '')
.trim()
.toLowerCase();
const requested = normalize(aircraftClass);
if (!requested) return true;
return [
item?.aircraftClass,
item?.klass,
item?.type,
item?.typeCode,
item?.typeName,
]
.map(normalize)
.filter(Boolean)
.some(
(candidate) => candidate === requested || candidate.includes(requested),
);
}
/**
* Search an expanding area synchronously, doubling the radius after each miss.
* The maximum covers the farthest possible Earth-surface chord while keeping
+14 -7
View File
@@ -1521,7 +1521,6 @@
"FOV {value}° (DATASHEET)": "FOV {value}° (ورقة البيانات)",
"SPEC FOV {span}° (CAPABILITY)": "FOV حسب المواصفات {span}° (القدرة)",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · المواصفات: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "الأطلسي وشرق/وسط شمال المحيط الهادئ؛ ليست تغطية عالمية للأعاصير.",
"Cyclone advisories unavailable": "نشرات الأعاصير غير متاحة",
"Cyclone data unavailable": "بيانات الأعاصير غير متاحة",
"Potential tropical cyclone": "إعصار مداري محتمل",
@@ -1549,17 +1548,12 @@
"Maximum sustained wind: {wind}": "أقصى سرعة للرياح المستمرة: {wind}",
"Pressure: {pressure}": "الضغط: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · النشرة رقم {number} · صدرت {time}",
"No active NHC/CPHC systems": "لا توجد أنظمة مدارية نشطة لدى NHC/CPHC",
"Advisories unavailable": "النشرات غير متاحة",
"Cyclones · NHC / CPHC": "الأعاصير · NHC / CPHC",
"Atlantic · E/C Pacific": "الأطلسي · شرق/وسط الهادئ",
"{storms} · {name} selected": "{storms} · المحدد: {name}",
"Official advisory ↗": "النشرة الرسمية ↗",
"Active NHC and CPHC cyclone advisories": "نشرات الأعاصير النشطة من NHC وCPHC",
"Wind unavailable": "الرياح غير متاحة",
"Advisory center / forecast track": "المركز حسب النشرة / المسار المتوقع",
"Center-track uncertainty cone": "مخروط عدم اليقين لمسار المركز",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "حدّد عاصفة على الخريطة، أو اخترها من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مساحة فارغة من الخريطة لإلغاء التحديد. سياق نشرات NOAA NHC/CPHC. يصف المخروط عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا كامل منطقة الخطر. تشير تسميات نقاط التوقع إلى مدة التوقع بالساعات كما يوردها المصدر، لا إلى أوقات محسوبة من وقت صدور النشرة. تتبع الأشكال الهندسية السطح؛ والارتفاع لا يمثل ارتفاع الظواهر الجوية. راجع النشرة الرسمية.",
"DRIVE": "قيادة",
"Drive": "بالسيارة",
"WALK": "مشي",
@@ -4849,5 +4843,18 @@
"Telemetry reads while the model is on screen": "تُقرأ القياسات أثناء ظهور النموذج على الشاشة",
"Connecting to telemetry…": "جارٍ الاتصال بالقياسات…",
"{seconds} s": "{seconds} ث",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: المحيط الأطلسي وشرق ووسط شمال المحيط الهادئ. JTWC: غرب شمال المحيط الهادئ وشمال المحيط الهندي ونصف الكرة الجنوبي.",
"34-knot wind danger area": "منطقة خطر رياح 34 عقدة",
"Track and 34-knot wind danger area match this warning": "المسار ومنطقة خطر رياح 34 عقدة مطابقان لهذا التحذير",
"Track/danger area awaiting warning {number}": "المسار/منطقة الخطر بانتظار التحذير رقم {number}",
"Track/danger area unavailable": "المسار/منطقة الخطر غير متاحين",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "تحذير JTWC: التحذير الرسمي هو تحذير المركز الإقليمي. رياح JTWC متوسطات دقيقة واحدة.",
"No active tropical cyclone warnings": "لا توجد تحذيرات نشطة من الأعاصير المدارية",
"Cyclones · NHC / CPHC · JTWC": "الأعاصير · NHC / CPHC · JTWC",
"All tropical basins": "كل الأحواض المدارية",
"JTWC warning ↗": "تحذير JTWC ↗",
"Active cyclone advisories and warnings": "نشرات وتحذيرات الأعاصير النشطة",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "اختر عاصفة على الخريطة، أو اختر عاصفة من القائمة لتحديدها وتحريك الكاميرا إليها. انقر على مكان فارغ من الخريطة لإلغاء التحديد. نشرات NOAA NHC/CPHC وتحذيرات JTWC. يصف مخروط NHC عدم اليقين في المسار المتوقع للمركز، لا حجم العاصفة ولا منطقة الخطر كاملة. منطقة خطر رياح 34 عقدة لدى JTWC هي حيث قد تصل رياح بسرعة 34 عقدة، موسّعةً بخطأ توقع المسار؛ وهي ليست مخروطًا. تسميات نقاط التوقع هي ساعات المهلة لدى المصدر، لا أوقات محسوبة من وقت الإصدار. تتبع الأشكال سطح الأرض؛ والارتفاع ليس ارتفاعًا جويًا. ارجع إلى النشرة الرسمية أو إلى مركز الإنذار الإقليمي.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · التحذير {number} · صدر {time}"
}
+14 -7
View File
@@ -1436,7 +1436,6 @@
"FOV {value}° (DATASHEET)": "FOV {value}° (DATENBLATT)",
"SPEC FOV {span}° (CAPABILITY)": "SPEZ. FOV {span}° (BEREICH)",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPEZ.: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantik und östlicher/zentraler Nordpazifik; keine weltweite Abdeckung von Wirbelstürmen.",
"Cyclone advisories unavailable": "Wirbelsturm-Lageberichte nicht verfügbar",
"Cyclone data unavailable": "Wirbelsturmdaten nicht verfügbar",
"Potential tropical cyclone": "Potenzieller tropischer Wirbelsturm",
@@ -1460,17 +1459,12 @@
"Maximum sustained wind: {wind}": "Maximaler Dauerwind: {wind}",
"Pressure: {pressure}": "Luftdruck: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Lagebericht {number} · ausgegeben {time}",
"No active NHC/CPHC systems": "Keine aktiven NHC/CPHC-Systeme",
"Advisories unavailable": "Lageberichte nicht verfügbar",
"Cyclones · NHC / CPHC": "Wirbelstürme · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlantik · östl./zentr. Pazifik",
"{storms} · {name} selected": "{storms} · {name} ausgewählt",
"Official advisory ↗": "Offizieller Lagebericht ↗",
"Active NHC and CPHC cyclone advisories": "Aktive Wirbelsturm-Lageberichte von NHC und CPHC",
"Wind unavailable": "Wind nicht verfügbar",
"Advisory center / forecast track": "Zentrum laut Lagebericht / Vorhersagebahn",
"Center-track uncertainty cone": "Unsicherheitskegel der Zentrumsbahn",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Einen Sturm auf der Karte auswählen oder in der Liste wählen, um ihn auszuwählen und die Kamera dorthin zu bewegen. Auf eine leere Kartenstelle klicken, um die Auswahl aufzuheben. Kontext aus Lageberichten von NOAA NHC/CPHC. Der Kegel beschreibt die Unsicherheit der vorhergesagten Zentrumsbahn, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Die Beschriftungen der Vorhersagepunkte sind Vorlaufstunden der Quelle, keine aus dem Ausgabezeitpunkt berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Darstellungshöhe hat keine meteorologische Bedeutung. Den offiziellen Lagebericht beachten.",
"DRIVE": "AUTO",
"Drive": "Auto",
"WALK": "ZU FUSS",
@@ -4425,5 +4419,18 @@
"Telemetry reads while the model is on screen": "Telemetrie wird gelesen, solange das Modell zu sehen ist",
"Connecting to telemetry…": "Verbindung zur Telemetrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Solarflügel, Radiatoren und eine Antenne folgen der Live-Telemetrie der NASA. Die andere Antenne steht still und die Arme bewegen sich zur Veranschaulichung.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlantik und östlicher/zentraler Nordpazifik. JTWC: westlicher Nordpazifik, nördlicher Indischer Ozean und Südhalbkugel.",
"34-knot wind danger area": "Gefahrenbereich für 34-Knoten-Wind",
"Track and 34-knot wind danger area match this warning": "Zugbahn und 34-Knoten-Gefahrenbereich passen zu dieser Warnung",
"Track/danger area awaiting warning {number}": "Zugbahn/Gefahrenbereich warten auf Warnung {number}",
"Track/danger area unavailable": "Zugbahn/Gefahrenbereich nicht verfügbar",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC-Warnung: Maßgeblich ist die Warnung des regionalen Zentrums. JTWC-Winde sind 1-Minuten-Mittel.",
"No active tropical cyclone warnings": "Keine aktiven Warnungen vor tropischen Wirbelstürmen",
"Cyclones · NHC / CPHC · JTWC": "Wirbelstürme · NHC / CPHC · JTWC",
"All tropical basins": "Alle tropischen Becken",
"JTWC warning ↗": "JTWC-Warnung ↗",
"Active cyclone advisories and warnings": "Aktive Wirbelsturm-Lageberichte und -Warnungen",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Wähle einen Sturm auf der Karte oder in der Liste, um ihn auszuwählen und die Kamera hinzubewegen. Ein Klick auf eine leere Kartenstelle hebt die Auswahl auf. Lageberichte von NOAA NHC/CPHC und Warnungen des JTWC. Der NHC-Kegel beschreibt die Unsicherheit der vorhergesagten Zugbahn des Zentrums, nicht die Sturmgröße oder das gesamte Gefahrengebiet. Der 34-Knoten-Gefahrenbereich des JTWC ist das Gebiet, das Winde von 34 Knoten erreichen können, erweitert um den Fehler der Zugbahnvorhersage; er ist kein Kegel. Die Beschriftungen der Vorhersagepunkte sind die Vorlaufstunden der Quelle, keine aus der Ausgabe berechneten Zeiten. Die Geometrie folgt der Oberfläche; die Höhe ist keine Wetterhöhe. Maßgeblich sind der offizielle Lagebericht oder das regionale Warnzentrum.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Warnung {number} · ausgegeben {time}"
}
+14 -7
View File
@@ -1342,7 +1342,6 @@
"None on screen — nearby cameras are outside the view": "Ninguna en pantalla — las cámaras cercanas están fuera de la vista",
"ALPR camera": "Cámara ALPR",
"OpenStreetMap · community mapped": "OpenStreetMap · mapeado por la comunidad",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlántico y Pacífico Norte oriental/central; no es una cobertura mundial de ciclones.",
"Potential tropical cyclone": "Posible ciclón tropical",
"Post-tropical cyclone": "Ciclón postropical",
"Hurricane": "Huracán",
@@ -1365,17 +1364,12 @@
"Maximum sustained wind: {wind}": "Viento máximo sostenido: {wind}",
"Pressure: {pressure}": "Presión: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
"No active NHC/CPHC systems": "Sin sistemas activos del NHC/CPHC",
"Advisories unavailable": "Avisos no disponibles",
"Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlántico · Pacífico E/C",
"{storms} · {name} selected": "{storms} · {name} seleccionado",
"Official advisory ↗": "Aviso oficial ↗",
"Active NHC and CPHC cyclone advisories": "Avisos de ciclones activos del NHC y el CPHC",
"Wind unavailable": "Viento no disponible",
"Advisory center / forecast track": "Centro del ciclón según el aviso / trayectoria pronosticada",
"Center-track uncertainty cone": "Cono de incertidumbre de la trayectoria del centro",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecciona un ciclón en el mapa, o elige uno en la lista para seleccionarlo y mover la cámara. Haz clic en un espacio vacío del mapa para borrar la selección. Contexto de avisos NOAA NHC/CPHC. El cono describe la incertidumbre de la trayectoria pronosticada del centro, no el tamaño del ciclón ni toda el área de peligro. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas a partir de la emisión del aviso. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial.",
"Directions": "Indicaciones",
"{mode} — reroute for {modeLower}": "{mode} — recalcular la ruta {modeLower}",
"CLICK MAP": "CLIC EN EL MAPA",
@@ -4531,5 +4525,18 @@
"Telemetry reads while the model is on screen": "La telemetría se lee mientras el modelo está en pantalla",
"Connecting to telemetry…": "Conectando con la telemetría…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Los paneles, los radiadores y una antena siguen la telemetría en vivo de la NASA. La otra antena permanece quieta y los brazos se mueven a modo de ilustración.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlántico y Pacífico Norte oriental/central. JTWC: Pacífico Norte occidental, océano Índico Norte y hemisferio sur.",
"34-knot wind danger area": "Zona de peligro de vientos de 34 nudos",
"Track and 34-knot wind danger area match this warning": "La trayectoria y la zona de peligro de 34 nudos coinciden con este aviso",
"Track/danger area awaiting warning {number}": "Trayectoria/zona de peligro a la espera del aviso {number}",
"Track/danger area unavailable": "Trayectoria/zona de peligro no disponibles",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Aviso del JTWC: el aviso oficial es el del centro regional. Los vientos del JTWC son promedios de 1 minuto.",
"No active tropical cyclone warnings": "Sin avisos activos de ciclones tropicales",
"Cyclones · NHC / CPHC · JTWC": "Ciclones · NHC / CPHC · JTWC",
"All tropical basins": "Todas las cuencas tropicales",
"JTWC warning ↗": "Aviso del JTWC ↗",
"Active cyclone advisories and warnings": "Avisos activos de ciclones",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecciona una tormenta en el mapa o elige una en la lista para seleccionarla y mover la cámara. Haz clic en una zona vacía del mapa para quitar la selección. Avisos de NOAA NHC/CPHC y del JTWC. El cono del NHC describe la incertidumbre de la trayectoria prevista del centro, no el tamaño de la tormenta ni toda la zona de peligro. La zona de peligro de 34 nudos del JTWC es donde pueden llegar vientos de 34 nudos, ampliada por el error de la trayectoria prevista; no es un cono. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas desde la emisión. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial o el centro de avisos regional.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
}
+14 -7
View File
@@ -644,7 +644,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "CONTEXTE {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · CARACT. : CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantique et Pacifique Nord oriental/central ; pas une couverture mondiale des cyclones.",
"Cyclone advisories unavailable": "Bulletins cycloniques indisponibles",
"Cyclone data unavailable": "Données cycloniques indisponibles",
"Potential tropical cyclone": "Cyclone tropical potentiel",
@@ -669,17 +668,12 @@
"Maximum sustained wind: {wind}": "Vent maximal soutenu : {wind}",
"Pressure: {pressure}": "Pression : {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bulletin {number} · émis le {time}",
"No active NHC/CPHC systems": "Aucun système actif NHC/CPHC",
"Advisories unavailable": "Bulletins indisponibles",
"Cyclones · NHC / CPHC": "Cyclones · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlantique · Pacifique E/C",
"{storms} · {name} selected": "{storms} · {name} sélectionné",
"Official advisory ↗": "Bulletin officiel ↗",
"Active NHC and CPHC cyclone advisories": "Bulletins cycloniques actifs du NHC et du CPHC",
"Wind unavailable": "Vent indisponible",
"Advisory center / forecast track": "Centre selon le bulletin / trajectoire prévue",
"Center-track uncertainty cone": "Cône d'incertitude de la trajectoire du centre",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Sélectionnez un cyclone sur la carte, ou choisissez-en un dans la liste pour le sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Contexte des bulletins NOAA NHC/CPHC. Le cône décrit l'incertitude de la trajectoire prévue du centre, pas la taille du cyclone ni toute la zone de danger. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l'émission du bulletin. La géométrie suit la surface ; la hauteur n'est pas une altitude météorologique. Consultez le bulletin officiel.",
"DRIVE": "VOITURE",
"Drive": "En voiture",
"WALK": "À PIED",
@@ -4531,5 +4525,18 @@
"Telemetry reads while the model is on screen": "La télémétrie est lue tant que le modèle est à l'écran",
"Connecting to telemetry…": "Connexion à la télémétrie…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Les panneaux, les radiateurs et une antenne suivent la télémétrie en direct de la NASA. L'autre antenne reste immobile et les bras bougent à titre d'illustration.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC : Atlantique et Pacifique Nord oriental/central. JTWC : Pacifique Nord occidental, nord de l’océan Indien et hémisphère Sud.",
"34-knot wind danger area": "Zone de danger des vents de 34 nœuds",
"Track and 34-knot wind danger area match this warning": "La trajectoire et la zone de danger de 34 nœuds correspondent à cet avertissement",
"Track/danger area awaiting warning {number}": "Trajectoire/zone de danger en attente de l’avertissement {number}",
"Track/danger area unavailable": "Trajectoire/zone de danger indisponibles",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Avertissement du JTWC : l’avertissement officiel est celui du centre régional. Les vents du JTWC sont des moyennes sur 1 minute.",
"No active tropical cyclone warnings": "Aucun avertissement de cyclone tropical en cours",
"Cyclones · NHC / CPHC · JTWC": "Cyclones · NHC / CPHC · JTWC",
"All tropical basins": "Tous les bassins tropicaux",
"JTWC warning ↗": "Avertissement du JTWC ↗",
"Active cyclone advisories and warnings": "Bulletins et avertissements cycloniques en cours",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Sélectionnez une tempête sur la carte, ou choisissez-en une dans la liste pour la sélectionner et déplacer la caméra. Cliquez sur une zone vide de la carte pour effacer la sélection. Bulletins NOAA NHC/CPHC et avertissements du JTWC. Le cône du NHC décrit l’incertitude de la trajectoire prévue du centre, pas la taille de la tempête ni toute la zone de danger. La zone de danger de 34 nœuds du JTWC est l’endroit que peuvent atteindre des vents de 34 nœuds, élargi de l’erreur de prévision de trajectoire ; ce n’est pas un cône. Les étiquettes des points de prévision sont les échéances de la source, pas des heures calculées depuis l’émission. La géométrie suit la surface ; la hauteur n’est pas une altitude météorologique. Consultez le bulletin officiel ou le centre d’avertissement régional.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avertissement {number} · émis {time}"
}
+14 -7
View File
@@ -532,7 +532,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "הקשר {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · מפרט: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "האטלנטי והפסיפיק הצפוני המזרחי/מרכזי; אין כיסוי ציקלונים עולמי.",
"Cyclone advisories unavailable": "עדכוני ציקלונים אינם זמינים",
"Cyclone data unavailable": "נתוני ציקלונים אינם זמינים",
"Potential tropical cyclone": "ציקלון טרופי פוטנציאלי",
@@ -557,17 +556,12 @@
"Maximum sustained wind: {wind}": "רוח מתמשכת מרבית: {wind}",
"Pressure: {pressure}": "לחץ: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · עדכון {number} · פורסם {time}",
"No active NHC/CPHC systems": "אין מערכות NHC/CPHC פעילות",
"Advisories unavailable": "עדכונים אינם זמינים",
"Cyclones · NHC / CPHC": "ציקלונים · NHC / CPHC",
"Atlantic · E/C Pacific": "האטלנטי · מזרח ומרכז הפסיפיק",
"{storms} · {name} selected": "{storms} · {name} נבחר",
"Official advisory ↗": "עדכון רשמי ↗",
"Active NHC and CPHC cyclone advisories": "עדכוני ציקלונים פעילים של NHC ו-CPHC",
"Wind unavailable": "רוח אינה זמינה",
"Advisory center / forecast track": "מרכז הסערה לפי העדכון / מסלול התחזית",
"Center-track uncertainty cone": "חרוט אי-הוודאות של מסלול המרכז",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "בחר סערה במפה, או בחר סערה ברשימה כדי לבחור אותה ולהזיז את המצלמה. לחץ בשטח ריק במפה כדי לבטל את הבחירה. הקשר עדכונים של NOAA NHC/CPHC. החרוט מתאר אי-ודאות של מסלול המרכז בתחזית, לא את גודל הסערה ולא את מלוא אזור הסכנה. תוויות נקודות התחזית הן שעות חיזוי של המקור, לא זמנים שחושבו מפרסום העדכון. הגאומטריה נצמדת לפני הקרקע; הגובה אינו גובה מטאורולוגי. עיין בעדכון הרשמי.",
"Malformed cyclone snapshot": "תמונת מצב של ציקלון פגומה",
"Cyclone request timed out": "בקשת הציקלון חרגה מהזמן הקצוב",
"DRIVE": "נסיעה",
@@ -4531,5 +4525,18 @@
"Telemetry reads while the model is on screen": "הטלמטריה נקראת כל עוד הדגם מוצג על המסך",
"Connecting to telemetry…": "מתחבר לטלמטריה…",
"{seconds} s": "{seconds} שנ׳",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: האוקיינוס האטלנטי ומזרח ומרכז צפון האוקיינוס השקט. JTWC: מערב צפון האוקיינוס השקט, צפון האוקיינוס ההודי וחצי הכדור הדרומי.",
"34-knot wind danger area": "אזור סכנה של רוחות 34 קשר",
"Track and 34-knot wind danger area match this warning": "המסלול ואזור הסכנה של 34 קשר תואמים לאזהרה הזו",
"Track/danger area awaiting warning {number}": "מסלול/אזור סכנה ממתינים לאזהרה {number}",
"Track/danger area unavailable": "מסלול/אזור סכנה אינם זמינים",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "אזהרת JTWC: האזהרה הרשמית היא של המרכז האזורי. רוחות JTWC הן ממוצעים של דקה אחת.",
"No active tropical cyclone warnings": "אין אזהרות פעילות מפני ציקלונים טרופיים",
"Cyclones · NHC / CPHC · JTWC": "ציקלונים · NHC / CPHC · JTWC",
"All tropical basins": "כל האגנים הטרופיים",
"JTWC warning ↗": "אזהרת JTWC ↗",
"Active cyclone advisories and warnings": "עדכוני ציקלונים ואזהרות פעילים",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "בחרו סופה במפה, או בחרו סופה ברשימה כדי לסמן אותה ולהזיז אליה את המצלמה. לחיצה על מקום ריק במפה מבטלת את הבחירה. עדכוני NOAA NHC/CPHC ואזהרות JTWC. החרוט של NHC מתאר את אי-הוודאות במסלול החזוי של המרכז, לא את גודל הסופה ולא את כל אזור הסכנה. אזור הסכנה של 34 קשר של JTWC הוא המקום שאליו עשויות להגיע רוחות של 34 קשר, מורחב בשגיאת תחזית המסלול; הוא אינו חרוט. התוויות של נקודות התחזית הן שעות התחזית של המקור, לא זמנים שחושבו ממועד הפרסום. הצורות עוקבות אחר פני השטח; הגובה אינו גובה מטאורולוגי. עיינו בעדכון הרשמי או במרכז ההתרעות האזורי.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · אזהרה {number} · פורסמה {time}"
}
+14 -7
View File
@@ -644,7 +644,6 @@
"SRC {value}": "FONTE {value}",
"{value} CONTEXT": "CONTESTO {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPECIFICHE: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlantico e Pacifico settentrionale orientale/centrale; non è una copertura mondiale dei cicloni.",
"Cyclone advisories unavailable": "Bollettini sui cicloni non disponibili",
"Cyclone data unavailable": "Dati sui cicloni non disponibili",
"Potential tropical cyclone": "Potenziale ciclone tropicale",
@@ -669,17 +668,12 @@
"Maximum sustained wind: {wind}": "Vento massimo sostenuto: {wind}",
"Pressure: {pressure}": "Pressione: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bollettino {number} · emesso {time}",
"No active NHC/CPHC systems": "Nessun sistema NHC/CPHC attivo",
"Advisories unavailable": "Bollettini non disponibili",
"Cyclones · NHC / CPHC": "Cicloni · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlantico · Pacifico E/C",
"{storms} · {name} selected": "{storms} · selezione: {name}",
"Official advisory ↗": "Bollettino ufficiale ↗",
"Active NHC and CPHC cyclone advisories": "Bollettini attivi sui cicloni di NHC e CPHC",
"Wind unavailable": "Vento non disponibile",
"Advisory center / forecast track": "Centro del ciclone da bollettino / traccia prevista",
"Center-track uncertainty cone": "Cono di incertezza della traccia del centro",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Seleziona una tempesta sulla mappa, o scegline una nell'elenco per selezionarla e spostare la camera. Fai clic su un punto vuoto della mappa per annullare la selezione. Contesto dai bollettini NOAA NHC/CPHC. Il cono descrive l'incertezza sulla traccia prevista del centro, non le dimensioni della tempesta né l'intera area di pericolo. Le etichette dei punti di previsione indicano le scadenze di previsione in ore fornite dalla fonte, non orari calcolati dall'emissione del bollettino. La geometria segue la superficie; l'altezza non è la quota meteorologica. Consulta il bollettino ufficiale.",
"DRIVE": "AUTO",
"Drive": "In auto",
"WALK": "A PIEDI",
@@ -4531,5 +4525,18 @@
"Telemetry reads while the model is on screen": "La telemetria viene letta finché il modello è sullo schermo",
"Connecting to telemetry…": "Connessione alla telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Pannelli, radiatori e un'antenna seguono la telemetria in diretta della NASA. L'altra antenna resta ferma e i bracci si muovono a scopo illustrativo.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlantico e Pacifico settentrionale orientale/centrale. JTWC: Pacifico settentrionale occidentale, Oceano Indiano settentrionale ed emisfero australe.",
"34-knot wind danger area": "Area di pericolo per venti a 34 nodi",
"Track and 34-knot wind danger area match this warning": "Traccia e area di pericolo a 34 nodi corrispondono a questo avviso",
"Track/danger area awaiting warning {number}": "Traccia/area di pericolo in attesa dell’avviso {number}",
"Track/danger area unavailable": "Traccia/area di pericolo non disponibili",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Avviso JTWC: l’avviso ufficiale è quello del centro regionale. I venti JTWC sono medie su 1 minuto.",
"No active tropical cyclone warnings": "Nessun avviso attivo di ciclone tropicale",
"Cyclones · NHC / CPHC · JTWC": "Cicloni · NHC / CPHC · JTWC",
"All tropical basins": "Tutti i bacini tropicali",
"JTWC warning ↗": "Avviso JTWC ↗",
"Active cyclone advisories and warnings": "Bollettini e avvisi attivi sui cicloni",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Seleziona una tempesta sulla mappa o sceglila nell’elenco per selezionarla e spostare la telecamera. Fai clic su un punto vuoto della mappa per annullare la selezione. Bollettini NOAA NHC/CPHC e avvisi JTWC. Il cono NHC descrive l’incertezza della traccia prevista del centro, non le dimensioni della tempesta né l’intera area di pericolo. L’area di pericolo a 34 nodi del JTWC è dove possono arrivare venti a 34 nodi, ampliata dall’errore di previsione della traccia; non è un cono. Le etichette dei punti di previsione sono ore di anticipo della fonte, non orari calcolati dall’emissione. La geometria segue la superficie; l’altezza non è quota meteorologica. Consulta il bollettino ufficiale o il centro di allerta regionale.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Avviso {number} · emesso {time}"
}
+14 -7
View File
@@ -616,7 +616,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "{value}コンテキスト",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 仕様:CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "大西洋と北太平洋東部・中部のみです。全世界のサイクロンを網羅するものではありません。",
"Cyclone advisories unavailable": "サイクロン情報を取得できません",
"Cyclone data unavailable": "サイクロンデータを取得できません",
"Potential tropical cyclone": "サイクロン化のおそれがある擾乱",
@@ -639,17 +638,12 @@
"Maximum sustained wind: {wind}": "最大持続風速:{wind}",
"Pressure: {pressure}": "気圧:{pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第{number}報 · {time}発表",
"No active NHC/CPHC systems": "NHC/CPHCが監視中のサイクロンはありません",
"Advisories unavailable": "サイクロン情報を取得できません",
"Cyclones · NHC / CPHC": "サイクロン · NHC / CPHC",
"Atlantic · E/C Pacific": "大西洋 · 東部/中部太平洋",
"{storms} · {name} selected": "{storms} · {name}を選択中",
"Official advisory ↗": "公式情報 ↗",
"Active NHC and CPHC cyclone advisories": "発生中のNHCおよびCPHCサイクロン情報",
"Wind unavailable": "風のデータを取得できません",
"Advisory center / forecast track": "発表時の中心 / 予報進路",
"Center-track uncertainty cone": "中心進路の予報円",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "地図上でサイクロンを選択するか、リストから選ぶと、そのサイクロンが選択されてカメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報に基づく表示です。予報円は予報される中心進路の不確かさを示すもので、サイクロンの大きさや危険範囲全体ではありません。予報点のラベルはソースの予報時間で、発表時刻から計算した時刻ではありません。図形は地表に沿って表示され、高さは気象上の高度ではありません。公式情報を確認してください。",
"DRIVE": "車",
"Drive": "車",
"WALK": "徒歩",
@@ -4319,5 +4313,18 @@
"Telemetry reads while the model is on screen": "テレメトリはモデルが画面にある間に読み取られます",
"Connecting to telemetry…": "テレメトリに接続中…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋、北太平洋東部・中部。JTWC:北西太平洋、北インド洋、南半球。",
"34-knot wind danger area": "34ノット風の危険域",
"Track and 34-knot wind danger area match this warning": "進路と34ノット風の危険域はこの警報と一致しています",
"Track/danger area awaiting warning {number}": "進路/危険域は第{number}号警報待ち",
"Track/danger area unavailable": "進路/危険域は利用できません",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC警報:公式の警報は地域センターの警報です。JTWCの風速は1分間平均です。",
"No active tropical cyclone warnings": "発表中の熱帯低気圧警報はありません",
"Cyclones · NHC / CPHC · JTWC": "サイクロン · NHC / CPHC · JTWC",
"All tropical basins": "すべての熱帯海域",
"JTWC warning ↗": "JTWC警報 ↗",
"Active cyclone advisories and warnings": "発表中のサイクロン情報と警報",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "地図上の嵐を選ぶか、リストから嵐を選ぶと選択され、カメラが移動します。地図の何もない場所をクリックすると選択を解除します。NOAA NHC/CPHCの情報とJTWCの警報です。NHCの予報円は中心の予報進路の不確かさを表すもので、嵐の大きさや危険域全体ではありません。JTWCの34ノット風の危険域は、34ノットの風が及ぶおそれのある範囲を進路予報の誤差分だけ広げたもので、予報円ではありません。予報点のラベルは情報源の予報時間で、発表時刻から計算した時刻ではありません。形状は地表に沿って描かれ、高さは気象上の高度ではありません。公式の情報または地域の警報センターを確認してください。",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第{number}号警報 · {time} 発表"
}
+14 -7
View File
@@ -644,7 +644,6 @@
"SRC {value}": "FONTE {value}",
"{value} CONTEXT": "CONTEXTO {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ESPECIFICAÇÕES: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlântico e Pacífico Norte oriental/central; não é uma cobertura mundial de ciclones.",
"Cyclone advisories unavailable": "Boletins de ciclones indisponíveis",
"Cyclone data unavailable": "Dados de ciclones indisponíveis",
"Potential tropical cyclone": "Potencial ciclone tropical",
@@ -669,17 +668,12 @@
"Maximum sustained wind: {wind}": "Vento máximo sustentado: {wind}",
"Pressure: {pressure}": "Pressão: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Boletim {number} · emitido em {time}",
"No active NHC/CPHC systems": "Nenhum sistema ativo do NHC/CPHC",
"Advisories unavailable": "Boletins indisponíveis",
"Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlântico · Pacífico Leste/Central",
"{storms} · {name} selected": "{storms} · {name} selecionado",
"Official advisory ↗": "Boletim oficial ↗",
"Active NHC and CPHC cyclone advisories": "Boletins de ciclones ativos do NHC e do CPHC",
"Wind unavailable": "Vento indisponível",
"Advisory center / forecast track": "Centro do ciclone no boletim / trajetória prevista",
"Center-track uncertainty cone": "Cone de incerteza da trajetória do centro",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecione um ciclone no mapa ou escolha um na lista para selecioná-lo e mover a câmera. Clique em um espaço vazio do mapa para limpar a seleção. Contexto dos boletins NOAA NHC/CPHC. O cone descreve a incerteza da trajetória prevista do centro, não o tamanho do ciclone nem toda a área de risco. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão do boletim. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial.",
"DRIVE": "CARRO",
"Drive": "De carro",
"WALK": "A PÉ",
@@ -4531,5 +4525,18 @@
"Telemetry reads while the model is on screen": "A telemetria é lida enquanto o modelo está no ecrã",
"Connecting to telemetry…": "A ligar à telemetria…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Painéis, radiadores e uma antena seguem a telemetria ao vivo da NASA. A outra antena fica parada e os braços se movem de forma ilustrativa.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlântico e Pacífico Norte oriental/central. JTWC: Pacífico Norte ocidental, Oceano Índico Norte e Hemisfério Sul.",
"34-knot wind danger area": "Área de perigo de ventos de 34 nós",
"Track and 34-knot wind danger area match this warning": "A trajetória e a área de perigo de 34 nós correspondem a este aviso",
"Track/danger area awaiting warning {number}": "Trajetória/área de perigo aguardando o aviso {number}",
"Track/danger area unavailable": "Trajetória/área de perigo indisponíveis",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Aviso do JTWC: o aviso oficial é o do centro regional. Os ventos do JTWC são médias de 1 minuto.",
"No active tropical cyclone warnings": "Nenhum aviso ativo de ciclone tropical",
"Cyclones · NHC / CPHC · JTWC": "Ciclones · NHC / CPHC · JTWC",
"All tropical basins": "Todas as bacias tropicais",
"JTWC warning ↗": "Aviso do JTWC ↗",
"Active cyclone advisories and warnings": "Boletins e avisos de ciclones ativos",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Selecione uma tempestade no mapa ou escolha uma na lista para selecioná-la e mover a câmera. Clique em uma área vazia do mapa para limpar a seleção. Boletins da NOAA NHC/CPHC e avisos do JTWC. O cone do NHC descreve a incerteza da trajetória prevista do centro, não o tamanho da tempestade nem toda a área de perigo. A área de perigo de 34 nós do JTWC é onde ventos de 34 nós podem chegar, ampliada pelo erro da previsão de trajetória; não é um cone. Os rótulos dos pontos de previsão são horas de antecedência da fonte, não horários calculados a partir da emissão. A geometria acompanha a superfície; a altura não é altitude meteorológica. Consulte o boletim oficial ou o centro de alertas regional.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}"
}
+14 -7
View File
@@ -1369,7 +1369,6 @@
"None on screen — nearby cameras are outside the view": "На экране нет — ближайшие камеры вне поля зрения",
"ALPR camera": "Камера ALPR",
"OpenStreetMap · community mapped": "OpenStreetMap · данные сообщества",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика и восточная/центральная часть северного Тихого океана; покрытие циклонов не глобальное.",
"Potential tropical cyclone": "Потенциальный тропический циклон",
"Post-tropical cyclone": "Посттропический циклон",
"Hurricane": "Ураган",
@@ -1393,17 +1392,12 @@
"Maximum sustained wind: {wind}": "Макс. устойчивый ветер: {wind}",
"Pressure: {pressure}": "Давление: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Сводка № {number} · выпущена {time}",
"No active NHC/CPHC systems": "Нет активных систем NHC/CPHC",
"Advisories unavailable": "Сводки недоступны",
"Cyclones · NHC / CPHC": "Циклоны · NHC / CPHC",
"Atlantic · E/C Pacific": "Атлантика · вост./центр. Тихий океан",
"{storms} · {name} selected": "{storms} · выбран {name}",
"Official advisory ↗": "Официальная сводка ↗",
"Active NHC and CPHC cyclone advisories": "Действующие сводки NHC и CPHC о циклонах",
"Wind unavailable": "Ветер: нет данных",
"Advisory center / forecast track": "Центр циклона по сводке / прогнозный трек",
"Center-track uncertainty cone": "Конус неопределённости трека центра",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить к нему камеру. Щёлкните по пустому месту карты, чтобы снять выделение. Контекст сводок NOAA NHC/CPHC. Конус описывает неопределённость прогнозного трека центра, а не размер шторма или всю зону опасности. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска сводки. Геометрия следует поверхности; высота не отражает высоту погодных явлений. Сверяйтесь с официальной сводкой.",
"Directions": "Маршруты",
"{mode} — reroute for {modeLower}": "{mode} — перестроить маршрут: {modeLower}",
"CLICK MAP": "ЩЁЛКНИТЕ ПО КАРТЕ",
@@ -4637,5 +4631,18 @@
"Telemetry reads while the model is on screen": "Телеметрия читается, пока модель на экране",
"Connecting to telemetry…": "Подключение к телеметрии…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Атлантика и восточная/центральная часть северного Тихого океана. JTWC: западная часть северного Тихого океана, северная часть Индийского океана и Южное полушарие.",
"34-knot wind danger area": "Опасная зона ветра 34 узла",
"Track and 34-knot wind danger area match this warning": "Трек и опасная зона ветра 34 узла соответствуют этому предупреждению",
"Track/danger area awaiting warning {number}": "Трек и опасная зона появятся с предупреждением № {number}",
"Track/danger area unavailable": "Трек и опасная зона недоступны",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Предупреждение JTWC: официальным является предупреждение регионального центра. Ветер JTWC — средний за 1 минуту.",
"No active tropical cyclone warnings": "Нет действующих предупреждений о тропических циклонах",
"Cyclones · NHC / CPHC · JTWC": "Циклоны · NHC / CPHC · JTWC",
"All tropical basins": "Все тропические бассейны",
"JTWC warning ↗": "Предупреждение JTWC ↗",
"Active cyclone advisories and warnings": "Действующие сводки и предупреждения о циклонах",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить камеру. Щелчок по пустому месту карты снимает выделение. Сводки NOAA NHC/CPHC и предупреждения JTWC. Конус NHC показывает неопределённость прогнозного трека центра, а не размер шторма или всю опасную зону. Опасная зона ветра 34 узла JTWC — это область, куда может дойти ветер 34 узла, расширенная на ошибку прогноза трека; это не конус. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска. Геометрия следует поверхности; высота не является метеорологической высотой. Сверяйтесь с официальной сводкой или региональным центром предупреждений.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Предупреждение № {number} · выпущено {time}"
}
+14 -7
View File
@@ -1352,7 +1352,6 @@
"FOV {value}° (DATASHEET)": "FOV {value}° (DATABLAD)",
"SPEC FOV {span}° (CAPABILITY)": "SPEC. FOV {span}° (FÖRMÅGA)",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · SPEC.: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlanten och östra/centrala norra Stilla havet; ingen global täckning av cykloner.",
"Cyclone advisories unavailable": "Cyklonbulletiner otillgängliga",
"Cyclone data unavailable": "Cyklondata otillgängliga",
"Potential tropical cyclone": "Potentiell tropisk cyklon",
@@ -1376,17 +1375,12 @@
"Maximum sustained wind: {wind}": "Högsta medelvind: {wind}",
"Pressure: {pressure}": "Lufttryck: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Bulletin {number} · utfärdad {time}",
"No active NHC/CPHC systems": "Inga aktiva NHC/CPHC-system",
"Advisories unavailable": "Bulletiner otillgängliga",
"Cyclones · NHC / CPHC": "Cykloner · NHC / CPHC",
"Atlantic · E/C Pacific": "Atlanten · östra/centrala Stilla havet",
"{storms} · {name} selected": "{storms} · {name} vald",
"Official advisory ↗": "Officiell bulletin ↗",
"Active NHC and CPHC cyclone advisories": "Aktiva cyklonbulletiner från NHC och CPHC",
"Wind unavailable": "Vind otillgänglig",
"Advisory center / forecast track": "Centrum enligt bulletin / prognosbana",
"Center-track uncertainty cone": "Osäkerhetskon för centrumbanan",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran dit. Klicka på en tom yta på kartan för att avmarkera. Underlag: bulletiner från NOAA NHC/CPHC. Konen beskriver osäkerheten i den prognostiserade centrumbanan, inte stormens storlek eller hela riskområdet. Etiketterna vid prognospunkterna är källans prognostimmar, inte tider beräknade från bulletinens utfärdande. Geometrin följer ytan; höjden motsvarar ingen höjd i atmosfären. Läs den officiella bulletinen.",
"DRIVE": "BIL",
"Drive": "Bil",
"WALK": "GÅNG",
@@ -4425,5 +4419,18 @@
"Telemetry reads while the model is on screen": "Telemetri läses medan modellen syns på skärmen",
"Connecting to telemetry…": "Ansluter till telemetri…",
"{seconds} s": "{seconds} s",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Paneler, radiatorer och en antenn följer NASA:s telemetri i realtid. Den andra antennen står stilla och armarna rör sig som illustration.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Atlanten och östra/centrala norra Stilla havet. JTWC: västra norra Stilla havet, norra Indiska oceanen och södra halvklotet.",
"34-knot wind danger area": "Riskområde för vind på 34 knop",
"Track and 34-knot wind danger area match this warning": "Bana och riskområde för 34 knop stämmer med denna varning",
"Track/danger area awaiting warning {number}": "Bana/riskområde väntar på varning {number}",
"Track/danger area unavailable": "Bana/riskområde inte tillgängliga",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC-varning: den regionala centralens varning är den officiella. JTWC:s vindar är 1-minutsmedelvärden.",
"No active tropical cyclone warnings": "Inga aktiva varningar för tropiska cykloner",
"Cyclones · NHC / CPHC · JTWC": "Cykloner · NHC / CPHC · JTWC",
"All tropical basins": "Alla tropiska bassänger",
"JTWC warning ↗": "JTWC-varning ↗",
"Active cyclone advisories and warnings": "Aktiva cyklonbulletiner och varningar",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Välj en storm på kartan, eller välj en storm i listan för att markera den och flytta kameran. Klicka på en tom plats på kartan för att rensa markeringen. Bulletiner från NOAA NHC/CPHC och varningar från JTWC. NHC:s kon beskriver osäkerheten i centrums prognosbana, inte stormens storlek eller hela riskområdet. JTWC:s riskområde för 34 knop är där vindar på 34 knop kan nå, vidgat med felet i banprognosen; det är ingen kon. Etiketterna på prognospunkterna är källans prognostimmar, inte tider räknade från utgivningen. Geometrin följer ytan; höjden är inte väderhöjd. Läs den officiella bulletinen eller den regionala varningscentralen.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Varning {number} · utfärdad {time}"
}
+14 -7
View File
@@ -658,7 +658,6 @@
"SRC {value}": "ДЖЕР. {value}",
"{value} CONTEXT": "КОНТЕКСТ: {value}",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ХАРАКТЕРИСТИКИ: CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика та східна/центральна частина північного Тихого океану; покриття циклонів не глобальне.",
"Cyclone advisories unavailable": "Зведення про циклони недоступні",
"Cyclone data unavailable": "Дані про циклони недоступні",
"Potential tropical cyclone": "Потенційний тропічний циклон",
@@ -684,17 +683,12 @@
"Maximum sustained wind: {wind}": "Макс. середня швидкість вітру: {wind}",
"Pressure: {pressure}": "Тиск: {pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Зведення № {number} · випущено {time}",
"No active NHC/CPHC systems": "Немає активних систем NHC/CPHC",
"Advisories unavailable": "Зведення недоступні",
"Cyclones · NHC / CPHC": "Циклони · NHC / CPHC",
"Atlantic · E/C Pacific": "Атлантика · сх./центр. Тихий океан",
"{storms} · {name} selected": "{storms} · вибрано {name}",
"Official advisory ↗": "Офіційне зведення ↗",
"Active NHC and CPHC cyclone advisories": "Чинні зведення NHC і CPHC про циклони",
"Wind unavailable": "Вітер: немає даних",
"Advisory center / forecast track": "Центр циклону за зведенням / прогнозний трек",
"Center-track uncertainty cone": "Конус невизначеності треку центру",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Виберіть шторм на карті або в списку, щоб виділити його й перемістити до нього камеру. Клацніть на порожньому місці карти, щоб зняти виділення. Контекст зведень NOAA NHC/CPHC. Конус описує невизначеність прогнозного треку центру, а не розмір шторму чи всю зону небезпеки. Підписи прогнозних точок показують завчасність прогнозу в годинах за даними джерела, а не час, розрахований від випуску зведення. Геометрія повторює поверхню; висота не відображає висоту погодних явищ. Звіряйтеся з офіційним зведенням.",
"DRIVE": "АВТО",
"Drive": "Автомобілем",
"WALK": "ПІШКИ",
@@ -4637,5 +4631,18 @@
"Telemetry reads while the model is on screen": "Телеметрія читається, поки модель на екрані",
"Connecting to telemetry…": "Підключення до телеметрії…",
"{seconds} s": "{seconds} с",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації.",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC: Атлантика та східна/центральна частина північного Тихого океану. JTWC: західна частина північного Тихого океану, північна частина Індійського океану та Південна півкуля.",
"34-knot wind danger area": "Небезпечна зона вітру 34 вузли",
"Track and 34-knot wind danger area match this warning": "Трек і небезпечна зона вітру 34 вузли відповідають цьому попередженню",
"Track/danger area awaiting warning {number}": "Очікуються трек і небезпечна зона для попередження № {number}",
"Track/danger area unavailable": "Трек і небезпечна зона недоступні",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "Попередження JTWC: офіційним є попередження регіонального центру. Вітер JTWC — середній за 1 хвилину.",
"No active tropical cyclone warnings": "Немає чинних попереджень про тропічні циклони",
"Cyclones · NHC / CPHC · JTWC": "Циклони · NHC / CPHC · JTWC",
"All tropical basins": "Усі тропічні басейни",
"JTWC warning ↗": "Попередження JTWC ↗",
"Active cyclone advisories and warnings": "Чинні зведення та попередження про циклони",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "Виберіть шторм на карті або у списку, щоб виділити його й перемістити камеру. Клацання по порожньому місцю карти знімає виділення. Зведення NOAA NHC/CPHC та попередження JTWC. Конус NHC показує невизначеність прогнозного треку центру, а не розмір шторму чи всю небезпечну зону. Небезпечна зона вітру 34 вузли JTWC — це область, куди може дійти вітер 34 вузли, розширена на похибку прогнозу треку; це не конус. Підписи прогнозних точок — завчасність джерела в годинах, а не час, обчислений від випуску. Геометрія повторює поверхню; висота не є метеорологічною висотою. Звіряйтеся з офіційним зведенням або регіональним центром попереджень.",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · Попередження № {number} · випущено {time}"
}
+14 -7
View File
@@ -615,7 +615,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "{value} 态势",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 规格:CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "仅覆盖大西洋及北太平洋东部和中部,并非全球气旋覆盖。",
"Cyclone advisories unavailable": "气旋公告不可用",
"Cyclone data unavailable": "气旋数据不可用",
"Potential tropical cyclone": "潜在热带气旋",
@@ -638,17 +637,12 @@
"Maximum sustained wind: {wind}": "最大持续风速:{wind}",
"Pressure: {pressure}": "气压:{pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第 {number} 号公告 · 发布于 {time}",
"No active NHC/CPHC systems": "当前没有活跃的 NHC/CPHC 气旋",
"Advisories unavailable": "公告不可用",
"Cyclones · NHC / CPHC": "气旋 · NHC / CPHC",
"Atlantic · E/C Pacific": "大西洋 · 东/中太平洋",
"{storms} · {name} selected": "{storms} · 已选择 {name}",
"Official advisory ↗": "官方公告 ↗",
"Active NHC and CPHC cyclone advisories": "活跃的 NHC 与 CPHC 气旋公告",
"Wind unavailable": "风场数据不可用",
"Advisory center / forecast track": "公告中的气旋中心 / 预报路径",
"Center-track uncertainty cone": "中心路径预报不确定范围",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "在地图上点选气旋,或在列表中点选气旋,即可选中并移动相机。点击空白地图区域可清除选择。内容来自 NOAA NHC/CPHC 公告。该区域表示气旋中心路径预报的不确定范围,不代表气旋大小或全部灾害影响范围。预报点标注的是数据源的预报时效(小时),不是按公告发布时刻推算的时间。几何图形贴地显示;显示高度并非气象高度。请以官方公告为准。",
"DRIVE": "驾车",
"Drive": "驾车",
"WALK": "步行",
@@ -4319,5 +4313,18 @@
"Telemetry reads while the model is on screen": "模型显示在屏幕上时读取遥测",
"Connecting to telemetry…": "正在连接遥测…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋及北太平洋东部/中部。JTWC:北太平洋西部、北印度洋及南半球。",
"34-knot wind danger area": "34 节风危险区",
"Track and 34-knot wind danger area match this warning": "路径和 34 节风危险区与本期警报一致",
"Track/danger area awaiting warning {number}": "路径/危险区等待第 {number} 号警报",
"Track/danger area unavailable": "路径/危险区不可用",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC 警报:以区域中心的警报为准。JTWC 风速为 1 分钟平均值。",
"No active tropical cyclone warnings": "当前没有生效的热带气旋警报",
"Cyclones · NHC / CPHC · JTWC": "气旋 · NHC / CPHC · JTWC",
"All tropical basins": "所有热带海域",
"JTWC warning ↗": "JTWC 警报 ↗",
"Active cyclone advisories and warnings": "生效的气旋公告和警报",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地图上选择风暴,或在列表中选择风暴以选中它并移动镜头。点击地图空白处可取消选择。NOAA NHC/CPHC 公告和 JTWC 警报。NHC 的预报不确定范围表示中心预报路径的不确定性,而不是风暴大小或整个危险区域。JTWC 的 34 节风危险区是 34 节风可能到达的范围,并按路径预报误差加宽;它不是预报不确定范围。预报点标签是数据源的预报时效(小时),不是根据发布时间计算的时刻。几何形状贴合地表;高度不是气象高度。请以官方公告或区域警报中心为准。",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 号警报 · 发布于 {time}"
}
+14 -7
View File
@@ -615,7 +615,6 @@
"SRC {value}": "SRC {value}",
"{value} CONTEXT": "{value} 態勢",
"{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · 規格:CCTV-DATABASE.COM",
"Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "僅覆蓋大西洋及北太平洋東部和中部,並非全球氣旋覆蓋。",
"Cyclone advisories unavailable": "氣旋公告不可用",
"Cyclone data unavailable": "氣旋數據不可用",
"Potential tropical cyclone": "潛在熱帶氣旋",
@@ -638,17 +637,12 @@
"Maximum sustained wind: {wind}": "最大持續風速:{wind}",
"Pressure: {pressure}": "氣壓:{pressure}",
"{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · 第 {number} 號公告 · 發布於 {time}",
"No active NHC/CPHC systems": "當前沒有活躍的 NHC/CPHC 氣旋",
"Advisories unavailable": "公告不可用",
"Cyclones · NHC / CPHC": "氣旋 · NHC / CPHC",
"Atlantic · E/C Pacific": "大西洋 · 東/中太平洋",
"{storms} · {name} selected": "{storms} · 已選擇 {name}",
"Official advisory ↗": "官方公告 ↗",
"Active NHC and CPHC cyclone advisories": "活躍的 NHC 與 CPHC 氣旋公告",
"Wind unavailable": "風場數據不可用",
"Advisory center / forecast track": "公告中的氣旋中心 / 預報路徑",
"Center-track uncertainty cone": "中心路徑預報不確定範圍",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "在地圖上點選氣旋,或在列表中點選氣旋,即可選中並移動相機。點擊空白地圖區域可清除選擇。內容來自 NOAA NHC/CPHC 公告。該區域表示氣旋中心路徑預報的不確定範圍,不代表氣旋大小或全部災害影響範圍。預報點標註的是數據源的預報時效(小時),不是按公告發布時刻推算的時間。幾何圖形貼地顯示;顯示高度並非氣象高度。請以官方公告為準。",
"DRIVE": "駕車",
"Drive": "駕車",
"WALK": "步行",
@@ -4319,5 +4313,18 @@
"Telemetry reads while the model is on screen": "模型顯示在屏幕上時讀取遙測",
"Connecting to telemetry…": "正在連接遙測…",
"{seconds} s": "{seconds} 秒",
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。",
"NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.": "NHC/CPHC:大西洋及北太平洋東部/中部。JTWC:北太平洋西部、北印度洋及南半球。",
"34-knot wind danger area": "34 節風危險區",
"Track and 34-knot wind danger area match this warning": "路徑和 34 節風危險區與本期警報一致",
"Track/danger area awaiting warning {number}": "路徑/危險區等待第 {number} 號警報",
"Track/danger area unavailable": "路徑/危險區不可用",
"JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.": "JTWC 警報:以區域中心的警報為準。JTWC 風速為 1 分鐘平均值。",
"No active tropical cyclone warnings": "當前沒有生效的熱帶氣旋警報",
"Cyclones · NHC / CPHC · JTWC": "氣旋 · NHC / CPHC · JTWC",
"All tropical basins": "所有熱帶海域",
"JTWC warning ↗": "JTWC 警報 ↗",
"Active cyclone advisories and warnings": "生效的氣旋公告和警報",
"Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.": "在地圖上選擇風暴,或在列表中選擇風暴以選中它並移動鏡頭。點擊地圖空白處可取消選擇。NOAA NHC/CPHC 公告和 JTWC 警報。NHC 的預報不確定範圍表示中心預報路徑的不確定性,而不是風暴大小或整個危險區域。JTWC 的 34 節風危險區是 34 節風可能到達的範圍,並按路徑預報誤差加寬;它不是預報不確定範圍。預報點標籤是數據源的預報時效(小時),不是根據發布時間計算的時刻。幾何形狀貼合地表;高度不是氣象高度。請以官方公告或區域警報中心為準。",
"{name} · {classification} · Warning {number} · issued {time}": "{name} · {classification} · 第 {number} 號警報 · 發布於 {time}"
}
+1 -1
View File
@@ -541,7 +541,7 @@
"Conversation",
"Country",
"Cyan",
"Cyclones · NHC / CPHC",
"Cyclones · NHC / CPHC · JTWC",
"DENSE",
"DEST ---°",
"DEST {bearing}",
+2 -24
View File
@@ -4,6 +4,7 @@ import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
findByDoublingRadius,
AWARENESS_RADIUS_M,
aircraftClassMatches,
} from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_EXAMPLES,
@@ -52,29 +53,7 @@ export function createNavigation({
return layerId === 'flights' || layerId === 'military';
}
function normalizeAircraftClass(value) {
return String(value || '')
.trim()
.toLowerCase();
}
function aircraftClassMatchesFilter(item, aircraftClass) {
const requested = normalizeAircraftClass(aircraftClass);
if (!requested) return true;
const candidates = [
item?.aircraftClass,
item?.klass,
item?.type,
item?.typeCode,
item?.typeName,
]
.map((value) => normalizeAircraftClass(value))
.filter(Boolean);
if (!candidates.length) return false;
return candidates.some(
(candidate) => candidate === requested || candidate.includes(requested),
);
}
const aircraftClassMatchesFilter = aircraftClassMatches;
function selectNavigationTargets(
sourceCohorts,
@@ -265,7 +244,6 @@ export function createNavigation({
summarizeAwarenessCohortForNavigation,
resetNavigationVisitedCycle,
isFlightLayer,
normalizeAircraftClass,
aircraftClassMatchesFilter,
selectNavigationTargets,
alternativeFlightAvailable,
+1 -1
View File
@@ -5,7 +5,7 @@ import { setLocale, t } from '../../i18n/index.js';
// The exact string the server sends (COVERAGE in server/providers/cyclones.js).
const SERVER_COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
const time = '2026-09-16T03:00:00.000Z';
const storm = {
id: 'ep152026',
+71 -30
View File
@@ -32,8 +32,14 @@ const utc = (value) =>
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${isolate(value.slice(11, 16))}\u00a0UTC`
: t('Unavailable');
const COVERAGE = msg(
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.',
);
// The layer's sources, and each storm's.
const SOURCE = 'NOAA NHC / CPHC · JTWC';
const AGENCY_SOURCES = Object.freeze({ nhc: 'NOAA NHC / CPHC', jtwc: 'JTWC' });
const sourceOf = (storm) => AGENCY_SOURCES[storm?.agency] || AGENCY_SOURCES.nhc;
const isJtwc = (storm) => storm?.agency === 'jtwc';
const DANGER_AREA = msg('34-knot wind danger area');
// The server sends the same English coverage (server/providers/cyclones.js);
// data stays English and is translated here, where it is shown.
const coverageText = (coverage) =>
@@ -44,7 +50,9 @@ const SERVER_REASONS = new Set([msg('Cyclone data unavailable')]);
const errorText = (error) =>
error && (SERVER_REASONS.has(error) ? t(error) : translateKnown(error));
// NHC's Tropical Cyclone Status JSON reference: PTC is post-tropical, PC is a
// potential tropical cyclone, and subtropical systems are STS and STD.
// potential tropical cyclone, and subtropical systems are STS and STD. JTWC
// warns of typhoons (TY), super typhoons (STY), tropical cyclones (TC) and
// subtropical storms and depressions (SS, SD).
const CLASSIFICATION_NAMES = Object.freeze({
PC: msg('Potential tropical cyclone'),
PTC: msg('Post-tropical cyclone'),
@@ -53,6 +61,11 @@ const CLASSIFICATION_NAMES = Object.freeze({
TD: msg('Tropical depression'),
STS: msg('Subtropical storm'),
STD: msg('Subtropical depression'),
TY: msg('Typhoon'),
STY: msg('Super typhoon'),
TC: msg('Tropical cyclone'),
SS: msg('Subtropical storm'),
SD: msg('Subtropical depression'),
});
const classificationName = (code) =>
Object.hasOwn(CLASSIFICATION_NAMES, code)
@@ -123,7 +136,7 @@ export function createCyclonesLayer({
id: contextId,
layerId: 'weather-cyclones',
layerName: 'Cyclone advisories',
source: 'NOAA NHC / CPHC',
source: sourceOf(storm),
label: storm.name,
latitude: storm.position.latitude,
longitude: storm.position.longitude,
@@ -137,6 +150,7 @@ export function createCyclonesLayer({
? CLASSIFICATION_NAMES[storm.classification]
: undefined,
basin: storm.basin,
agency: storm.agency,
advisoryNumber: storm.advisoryNumber,
issuedAt: storm.issuedAt,
positionAt: storm.positionAt,
@@ -146,7 +160,7 @@ export function createCyclonesLayer({
movementDirectionDegrees: storm.movement?.directionDegrees,
movementSpeedKt: storm.movement?.speedKt,
advisoryUrl: storm.advisoryUrl,
// Only while the proxy serves its cache because NHC is unreachable.
// Only while the proxy serves its cache because a source is unreachable.
staleCacheFetchedAt:
snapshot.stale && Number.isFinite(snapshot.fetchedAt)
? new Date(snapshot.fetchedAt).toISOString()
@@ -205,7 +219,7 @@ export function createCyclonesLayer({
id: 'weather-cyclones',
name: 'Cyclone advisories',
icon: '◉',
source: 'NOAA NHC / CPHC',
source: SOURCE,
updateInterval: 300_000,
init(nextViewer) {
viewer = nextViewer;
@@ -361,13 +375,28 @@ export function createCyclonesLayer({
snapshot && !snapshot.unavailable && snapshot.storms.length === 0;
const geometry =
storm &&
(coherentCycloneGeometry(storm)
? t('Track and cone match this advisory')
: storm.geometryStatus === 'pending'
? t('Track/cone awaiting advisory {number}', {
number: storm.advisoryNumber,
})
: t('Track/cone unavailable'));
(isJtwc(storm)
? coherentCycloneGeometry(storm)
? t('Track and 34-knot wind danger area match this warning')
: storm.geometryStatus === 'pending'
? t('Track/danger area awaiting warning {number}', {
number: storm.advisoryNumber,
})
: t('Track/danger area unavailable')
: coherentCycloneGeometry(storm)
? t('Track and cone match this advisory')
: storm.geometryStatus === 'pending'
? t('Track/cone awaiting advisory {number}', {
number: storm.advisoryNumber,
})
: t('Track/cone unavailable'));
// JTWC is not the regional warning centre for any basin.
const note =
storm && isJtwc(storm)
? t(
'JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.',
)
: '';
const status =
errorText(error) ||
(snapshot?.stale
@@ -388,14 +417,21 @@ export function createCyclonesLayer({
: '';
const intensity = storm ? intensityText(storm) : '';
const detail = storm
? t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
? isJtwc(storm)
? t('{name} · {classification} · Warning {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
: t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
: empty
? t('No active NHC/CPHC systems')
? t('No active tropical cyclone warnings')
: stormCount
? activeStorms
: loading
@@ -404,8 +440,8 @@ export function createCyclonesLayer({
const controls = {
readout: true,
summary: {
label: t('Cyclones · NHC / CPHC'),
coverage: t('Atlantic · E/C Pacific'),
label: t('Cyclones · NHC / CPHC · JTWC'),
coverage: t('All tropical basins'),
compact: stormCount
? storm
? t('{storms} · {name} selected', {
@@ -418,7 +454,9 @@ export function createCyclonesLayer({
? [
{
id: 'advisory',
label: t('Official advisory ↗'),
label: isJtwc(storm)
? t('JTWC warning ↗')
: t('Official advisory ↗'),
href: storm.advisoryUrl,
},
]
@@ -436,6 +474,7 @@ export function createCyclonesLayer({
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
{ id: 'note', text: note, muted: true },
].filter((line) => line.text)
: [],
detail,
@@ -443,7 +482,7 @@ export function createCyclonesLayer({
units: 'kt',
},
list: {
ariaLabel: t('Active NHC and CPHC cyclone advisories'),
ariaLabel: t('Active cyclone advisories and warnings'),
items: (snapshot?.storms || []).map((item, index) => ({
id: item.id,
ordinal: index + 1,
@@ -461,17 +500,19 @@ export function createCyclonesLayer({
label: t('Advisory center / forecast track'),
color: '#7fe6ed',
},
{
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
isJtwc(storm)
? { label: t(DANGER_AREA), color: '#ffb15c44' }
: {
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
]
: [],
info: storm
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}${note ? '\n' + note : ''}\n${coverageText(snapshot.coverage)}`
: `${detail}${status ? '\n' + status : ''}\n${coverageText(snapshot?.coverage)}`,
infoTitle: t(
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.',
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisories and JTWC warnings. The NHC cone describes forecast center-track uncertainty, not storm size or the full hazard area. The JTWC 34-knot wind danger area is where 34-knot winds may reach, widened by forecast track error; it is not a cone. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory or the regional warning centre.',
),
};
return controls;
@@ -518,7 +559,7 @@ export function createCyclonesLayer({
loading,
error,
stale: Boolean(snapshot?.stale),
source: 'NOAA NHC / CPHC',
source: storm ? sourceOf(storm) : SOURCE,
advisoryAt: storm?.issuedAt || null,
empty: Boolean(
snapshot && !snapshot.unavailable && !snapshot.storms.length,
+66 -3
View File
@@ -861,7 +861,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
const controls = h.layer.getRowControls();
assert.equal(controls.readout, true);
assert.deepEqual(controls.chips, []);
assert.equal(controls.summary.coverage, 'Atlantic · E/C Pacific');
assert.equal(controls.summary.coverage, 'All tropical basins');
assert.equal(controls.summary.actions[0].href, storm().advisoryUrl);
assert.equal(controls.summary.lines.length, 3);
assert.deepEqual(controls.summary.settings, []);
@@ -870,7 +870,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
]);
assert.match(controls.summary.compact, /2 active storms · .* selected/);
assert.equal(controls.summary.sections, undefined);
assert.match(controls.list.ariaLabel, /NHC/);
assert.match(controls.list.ariaLabel, /cyclone advisories and warnings/);
assert.equal(controls.list.items.length, 2);
assert.equal(controls.list.items[0].active, true);
assert.match(controls.info, /awaiting advisory 10/);
@@ -912,7 +912,10 @@ test('empty successful coverage, unavailable source and stale advisory are diffe
h.layer.enable();
await h.layer.update();
assert.equal(h.layer.getStats().empty, true);
assert.match(h.layer.getRowControls().summary.detail, /No active NHC\/CPHC/);
assert.match(
h.layer.getRowControls().summary.detail,
/No active tropical cyclone warnings/,
);
next = { ...snapshot(), stale: true };
await h.layer.update();
assert.match(h.layer.getRowControls().summary.status, /stale/);
@@ -987,3 +990,63 @@ test('external cancellation and acquisition failure cannot install or retain unl
assert.ok(h.cleared > 0);
h.layer.destroy();
});
test('a JTWC warning reads as a warning, notes the official regional centre and its danger area', async () => {
const jtwc = {
...storm('sh042027'),
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
advisoryNumber: '15',
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
dangerArea: null,
};
const h = harness({ getSnapshot: async () => snapshot([jtwc]) });
try {
h.layer.enable();
await h.layer.update();
const controls = h.layer.getRowControls();
assert.match(
plain(controls.summary.detail),
/^Xavier · Tropical cyclone · Warning 15 · issued/,
);
assert.deepEqual(controls.summary.actions, [
{ id: 'advisory', label: 'JTWC warning ↗', href: jtwc.advisoryUrl },
]);
const note = controls.summary.lines.find((line) => line.id === 'note');
assert.equal(
note.text,
'JTWC warning: the regional centre’s warning is official. JTWC winds are 1-minute averages.',
);
assert.match(controls.info, /awaiting warning 15/);
assert.match(controls.info, /regional centre’s warning is official/);
assert.deepEqual(
controls.legend.map((item) => item.label),
['Advisory center / forecast track', '34-knot wind danger area'],
);
assert.equal(h.layer.getStats().source, 'JTWC');
} finally {
h.layer.destroy();
}
});
test('an NHC advisory carries no JTWC note and keeps its cone legend', async () => {
const h = harness({ getSnapshot: async () => snapshot([storm()]) });
try {
h.layer.enable();
await h.layer.update();
const controls = h.layer.getRowControls();
assert.equal(
controls.summary.lines.find((line) => line.id === 'note'),
undefined,
);
assert.deepEqual(
controls.legend.map((item) => item.label),
['Advisory center / forecast track', 'Center-track uncertainty cone'],
);
assert.equal(h.layer.getStats().source, 'NOAA NHC / CPHC');
} finally {
h.layer.destroy();
}
});
+35 -3
View File
@@ -3,6 +3,7 @@ import {
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
import { t } from '../../i18n/index.js';
/**
* @module cyclones/labels
@@ -19,6 +20,8 @@ export const CYCLONE_LEAD_LABEL_MAX_DISTANCE_M = 4_000_000;
export const CYCLONE_OVERLAY_COHORT_LIMIT = 64;
/** Advisory centre and forecast track; single source for points and cards. */
export const CYCLONE_ACCENT = '#7fe6ed';
/** JTWC's 34-knot wind danger area: its fill, dashed edge and label. */
export const CYCLONE_DANGER_ACCENT = '#ffb15c';
/** Selected advisory centre. */
export const CYCLONE_SELECTED_ACCENT = '#ffe19a';
/** Point sizes the cards keep clear of. */
@@ -112,7 +115,32 @@ function cycloneLeadEntry(stormId, point) {
}
/**
* Storm cards for every storm and lead-hour labels for the selected one.
* The name of the selected storm's 34-knot wind danger area, on its edge.
* @param {string} stormId
* @param {object} position
* @returns {object}
*/
function cycloneDangerAreaEntry(stormId, position) {
return {
...SHARED_CARD,
...markerClearance(0),
id: `area:${stormId}`,
position,
variant: 'card',
title: t('34-knot wind danger area'),
details: [],
accent: CYCLONE_DANGER_ACCENT,
selected: false,
protected: false,
// Below every lead-hour label.
priority: LEAD_PRIORITY - 200,
maxDistance: Number.POSITIVE_INFINITY,
};
}
/**
* Storm cards for every storm, and lead-hour labels and the danger area's
* name for the selected one.
* @param {Array<object>} storms Renderer anchors with `forecasts`.
* @param {?string} selectedId
* @returns {Array<object>}
@@ -125,13 +153,17 @@ export function cycloneOverlayEntries(storms, selectedId) {
if (!selected) continue;
for (const point of storm.forecasts || [])
entries.push(cycloneLeadEntry(storm.id, point));
if (storm.dangerArea)
entries.push(cycloneDangerAreaEntry(storm.id, storm.dangerArea));
}
return entries;
}
/** Storm id behind a published card or lead-hour label id, else null. */
/** Storm id behind a published card, lead-hour or area label id, else null. */
export function cycloneStormIdFromEntryId(entryId) {
const match = /^(?:storm|lead):([^:]+)(?::|$)/.exec(String(entryId ?? ''));
const match = /^(?:storm|lead|area):([^:]+)(?::|$)/.exec(
String(entryId ?? ''),
);
return match ? match[1] : null;
}
+4
View File
@@ -198,3 +198,7 @@ test('storm identity resolves from card and lead-hour ids only', () => {
for (const value of ['vessel:123', 'storm:', 'lead:', '', null, undefined])
assert.equal(cycloneStormIdFromEntryId(value), null, String(value));
});
test('a danger area label names its storm', () => {
assert.equal(cycloneStormIdFromEntryId('area:sh042027'), 'sh042027');
});
+93 -33
View File
@@ -3,6 +3,7 @@ import { sphereFromPoints } from '../../geo/sphere.js';
import { drawOf } from '../../render/rendererOf.js';
import {
CYCLONE_ACCENT,
CYCLONE_DANGER_ACCENT,
CYCLONE_MARKER_PX,
CYCLONE_SELECTED_ACCENT,
createCycloneLabels,
@@ -24,6 +25,29 @@ export function coherentCycloneGeometry(storm) {
);
}
/**
* Where a danger area's label sits: the vertex of its outer ring nearest the
* forecast point halfway along the track (ECEF).
*/
function dangerAreaAnchor(ring, forecastPoints, ecef, lonLat) {
const middle = forecastPoints[Math.floor(forecastPoints.length / 2)];
if (!middle) return ring[0];
const target = ecef(lonLat(middle.position));
let best = ring[0],
bestDistance = Infinity;
for (const vertex of ring) {
const d =
(vertex.x - target.x) ** 2 +
(vertex.y - target.y) ** 2 +
(vertex.z - target.z) ** 2;
if (d < bestDistance) {
best = vertex;
bestDistance = d;
}
}
return best;
}
/** A `#rrggbb` colour at `alpha`, as CSS. */
function withAlpha(hex, alpha) {
const n = Number.parseInt(hex.slice(1), 16);
@@ -64,7 +88,14 @@ export function createCycloneRendering({ viewer, overlayHost }) {
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const emptyCounts = () => ({
storms: 0,
tracks: 0,
cones: 0,
dangerAreas: 0,
forecastPoints: 0,
});
let counts = emptyCounts();
let itemCount = 0;
function centerItem(storm) {
@@ -104,7 +135,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const nextCounts = emptyCounts();
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
@@ -130,6 +161,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
windKt: storm.windKt,
position: center,
forecasts: [],
dangerArea: null,
};
nextLabels.push(label);
nextCounts.storms++;
@@ -151,38 +183,66 @@ export function createCycloneRendering({ viewer, overlayHost }) {
});
nextCounts.tracks++;
});
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:cone:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(CYCLONE_ACCENT, 0.16),
height: 'clampGround',
});
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: 1,
mode: 'draped',
style: {
kind: 'solid',
color: withAlpha(CYCLONE_ACCENT, 0.55),
},
// NHC's cone of centre-track uncertainty, or JTWC's 34-knot wind
// danger area: drawn apart, never one as the other.
const areas = [
{ kind: 'cone', shape: storm.cone, color: CYCLONE_ACCENT },
{
kind: 'danger',
shape: storm.dangerArea,
color: CYCLONE_DANGER_ACCENT,
},
];
for (const { kind, shape, color } of areas) {
const polygons =
shape?.type === 'Polygon'
? [shape.coordinates]
: shape?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native
// geographic tessellation handles the antimeridian; never
// flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:${kind}:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(color, kind === 'cone' ? 0.16 : 0.12),
height: 'clampGround',
});
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:${kind}:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: kind === 'cone' ? 1 : 1.5,
mode: 'draped',
style:
kind === 'cone'
? { kind: 'solid', color: withAlpha(color, 0.55) }
: {
kind: 'dash',
color: withAlpha(color, 0.8),
length: 16,
},
});
});
if (kind === 'cone') nextCounts.cones++;
else {
nextCounts.dangerAreas++;
// The area's name sits on its edge nearest the middle of
// the forecast track.
label.dangerArea ??= dangerAreaAnchor(
ecefRings[0],
storm.forecastPoints,
ecef,
lonLat,
);
}
});
nextCounts.cones++;
});
}
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
@@ -252,7 +312,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
counts = emptyCounts();
},
destroy() {
if (destroyed) return;
+49
View File
@@ -210,6 +210,7 @@ test('advisory geometry keeps polygon parts, holes and geographic seam coordinat
storms: 1,
tracks: 1,
cones: 2,
dangerAreas: 0,
forecastPoints: 1,
dataSources: 1,
entities: 8,
@@ -375,6 +376,7 @@ test('clear empties the sets and a later advisory draws again', async () => {
storms: 0,
tracks: 0,
cones: 0,
dangerAreas: 0,
forecastPoints: 0,
dataSources: 0,
entities: 0,
@@ -451,3 +453,50 @@ test('labels publish committed anchors to the shared overlay and follow selectio
h.rendering.destroy();
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
});
test('a JTWC danger area is drawn apart from any cone, with a dashed edge and its name for the selected storm', async () => {
const h = harness();
const jtwc = {
...storm(),
id: 'sh042027',
cone: null,
dangerArea: {
type: 'Polygon',
coordinates: [
[
[178, 10],
[-178, 10],
[-178, 20],
[178, 10],
],
],
},
};
assert.equal(await h.rendering.setSnapshot({ storms: [jtwc] }), true);
const [area] = [...h.sets.cones.items.values()];
assert.equal(area.id, 'cyclone:sh042027:danger:0');
assert.equal(area.fill, 'rgba(255,177,92,0.12)');
const outline = [...h.sets.lines.items.values()].find(
(line) => line.id === 'cyclone:sh042027:danger:0:outline:0',
);
assert.deepEqual(outline.style, {
kind: 'dash',
color: 'rgba(255,177,92,0.8)',
length: 16,
});
const diagnostics = h.rendering.getDiagnostics();
assert.equal(diagnostics.cones, 0);
assert.equal(diagnostics.dangerAreas, 1);
// A click on the area names its storm.
assert.equal(
h.rendering.pickStorm(h.hit('cones', 'cyclone:sh042027:danger:0')),
'sh042027',
);
assert.equal(h.overlay.entry('area:sh042027'), null, 'unselected: no name');
h.rendering.setSelection('sh042027');
const name = h.overlay.entry('area:sh042027');
assert.equal(name.title, '34-knot wind danger area');
// On the area's edge, at the vertex nearest the middle forecast point.
assert.deepEqual(name.position, fromDegrees(-178, 20, 0));
h.rendering.destroy();
});
+42 -17
View File
@@ -45,22 +45,33 @@ const position = (value) => {
};
};
function officialLink(value, outlook = false) {
/** The agencies whose advisories the snapshot carries. */
export const CYCLONE_AGENCIES = Object.freeze(['nhc', 'jtwc']);
// Each agency's storm ids, advisory links and outlook links.
const AGENCY_RULES = Object.freeze({
nhc: {
id: /^(?:al|ep|cp)\d{6}$/,
origin: 'https://www.nhc.noaa.gov',
advisory: /^\/text\/[A-Z0-9]+\.shtml$/,
outlook: /^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/,
},
jtwc: {
id: /^(?:wp|io|sh|ep|cp)\d{6}$/,
origin: 'https://www.metoc.navy.mil',
advisory: /^\/jtwc\/products\/[a-z]{2}\d{4}web\.txt$/,
outlook: /^\/jtwc\/products\/(?:abpw|abio)web\.txt$/,
},
});
function officialLink(value, rules, outlook = false) {
if (value === null) return null;
const url = new URL(text(value, 256));
if (
url.origin !== 'https://www.nhc.noaa.gov' ||
url.username ||
url.password ||
url.hash
)
if (url.origin !== rules.origin || url.username || url.password || url.hash)
throw malformed();
if (
outlook
? !/^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/.test(
url.pathname + url.search,
)
: url.search || !/^\/text\/[A-Z0-9]+\.shtml$/.test(url.pathname)
? !rules.outlook.test(url.pathname + url.search)
: url.search || !rules.advisory.test(url.pathname)
)
throw malformed();
return url.href;
@@ -122,8 +133,14 @@ export function validateCycloneSnapshot(value) {
const seen = new Set(),
budget = { coordinates: 0, points: 0 };
const storms = value.storms.map((raw) => {
// A snapshot from before agencies carries NHC storms only.
const agency = raw?.agency === undefined ? 'nhc' : raw.agency;
const rules = Object.hasOwn(AGENCY_RULES, agency)
? AGENCY_RULES[agency]
: null;
if (
!/^(?:al|ep|cp)\d{6}$/.test(raw?.id) ||
!rules ||
!rules.id.test(raw?.id) ||
seen.has(raw.id) ||
!['current', 'pending', 'unavailable'].includes(raw.geometryStatus)
)
@@ -158,20 +175,27 @@ export function validateCycloneSnapshot(value) {
};
});
const track = geometry(raw.track, 'track', budget),
cone = geometry(raw.cone, 'cone', budget);
cone = geometry(raw.cone, 'cone', budget),
dangerArea = geometry(raw.dangerArea ?? null, 'cone', budget);
// NHC draws a cone of centre-track uncertainty; JTWC publishes none, but
// a 34-knot wind danger area, which is never a cone.
const area = agency === 'nhc' ? cone : dangerArea;
if ((agency === 'nhc' && dangerArea) || (agency === 'jtwc' && cone))
throw malformed();
if (
raw.geometryStatus !== 'current' &&
(track || cone || forecastPoints.length)
(track || area || forecastPoints.length)
)
throw malformed();
if (
raw.geometryStatus === 'current' &&
(!track || !cone || !forecastPoints.length)
(!track || !area || !forecastPoints.length)
)
throw malformed();
if (raw.basin !== raw.id.slice(0, 2).toUpperCase()) throw malformed();
return {
id: raw.id,
agency,
name: text(raw.name, 80),
classification: text(raw.classification, 16),
basin: raw.basin,
@@ -185,13 +209,14 @@ export function validateCycloneSnapshot(value) {
directionDegrees: number(raw.movement?.directionDegrees, 0, 360),
speedKt: number(raw.movement?.speedKt, 0, 200),
},
advisoryUrl: officialLink(raw.advisoryUrl),
outlookUrl: officialLink(raw.outlookUrl, true),
advisoryUrl: officialLink(raw.advisoryUrl, rules),
outlookUrl: officialLink(raw.outlookUrl, rules, true),
geometryStatus: raw.geometryStatus,
geometryAdvisoryNumber,
forecastPoints,
track,
cone,
dangerArea,
};
});
if (value.unavailable && storms.length) throw malformed();
+66
View File
@@ -230,3 +230,69 @@ test('source deadline cancels request and removes timer on completion', async (t
await rejected;
assert.equal(signal.aborted, true);
});
/** The current advisory as a JTWC warning with its 34-knot danger area. */
function jtwc() {
const value = current(),
storm = value.storms[0];
Object.assign(storm, {
id: 'sh042027',
agency: 'jtwc',
basin: 'SH',
classification: 'TC',
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
dangerArea: storm.cone,
cone: null,
});
return value;
}
test('a JTWC warning is accepted with its danger area and its own links, never with a cone', () => {
const [storm] = validateCycloneSnapshot(jtwc()).storms;
assert.equal(storm.agency, 'jtwc');
assert.equal(storm.cone, null);
assert.equal(storm.dangerArea.type, 'MultiPolygon');
assert.equal(
storm.advisoryUrl,
'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
);
// A snapshot from before agencies is NHC's.
assert.equal(validateCycloneSnapshot(current()).storms[0].agency, 'nhc');
for (const change of [
(s) => (s.cone = s.dangerArea),
(s) => (s.dangerArea = null),
(s) => (s.agency = 'jma'),
(s) => (s.id = 'al042027'),
(s) => (s.basin = 'WP'),
(s) => (s.advisoryUrl = 'https://www.nhc.noaa.gov/text/MIATCMEP5.shtml'),
(s) => (s.advisoryUrl = 'https://www.metoc.navy.mil/jtwc/other.txt'),
(s) =>
(s.outlookUrl = 'https://www.nhc.noaa.gov/gtwo.php?basin=epac&fdays=7'),
]) {
const value = jtwc();
change(value.storms[0]);
assert.throws(() => validateCycloneSnapshot(value), /Malformed/);
}
// NHC keeps its cone and never carries a danger area; its ids stay its own.
const nhc = current();
nhc.storms[0].dangerArea = nhc.storms[0].cone;
assert.throws(() => validateCycloneSnapshot(nhc), /Malformed/);
const western = current();
western.storms[0].id = 'wp012026';
western.storms[0].basin = 'WP';
assert.throws(() => validateCycloneSnapshot(western), /Malformed/);
// A pending JTWC warning carries no geometry.
const pending = jtwc();
Object.assign(pending.storms[0], {
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
dangerArea: null,
});
assert.equal(
validateCycloneSnapshot(pending).storms[0].geometryStatus,
'pending',
);
});
@@ -0,0 +1,120 @@
// A 429 from /api/adsbdb must not leave an aircraft's metadata empty for the
// rest of the session.
//
// Both enrichment queues (Flights and Local ADS-B) mark a key as seen before
// they dispatch it, so a second request for the same aircraft is dropped. That
// is right for an answer or a 404, and wrong for a refusal: the server said
// "later", not "no". These cases drive the real queues against a source that
// refuses once and then answers.
//
// Run with: npm test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { LiveSourceError } from '../sources/live/contract.js';
import { createLocalAdsbEnrichment } from './localAdsb/enrichment.js';
import { createFlightState } from './flights/state.js';
import { createEnrichment } from './flights/enrichment.js';
/** Short real delay, so the case needs no clock control. */
const RETRY_AFTER_MS = 20;
/** A source that refuses the first lookup with a 429, then answers. */
function refusingOnce() {
const calls = [];
return {
calls,
async getEnrichment(query) {
calls.push(query);
if (calls.length === 1)
throw new LiveSourceError('limited', 'Flights rate limited', {
status: 429,
retryAfterMs: RETRY_AFTER_MS,
});
return { found: true, typeCode: 'B738', typeName: 'Boeing 737-800' };
},
};
}
const settle = (ms) => new Promise((done) => setTimeout(done, ms));
/** The services Flights enrichment reads: neither military nor a TR-3B. */
const enrichServices = {
militaryRegistry: { isMilitaryIcao: () => false },
aircraftPresentation: { isTr3b: () => false },
};
test('Local ADS-B asks again after a 429 once the refusal has passed', async (t) => {
const source = refusingOnce();
const enrichment = createLocalAdsbEnrichment({ source, onChange() {} });
t.after(() => enrichment.destroy());
const record = { icao: 'abc123', category: 'A3' };
enrichment.request(record);
await settle(0);
assert.equal(source.calls.length, 1);
enrichment.request(record);
await settle(0);
assert.equal(source.calls.length, 1, 'no retry inside the refusal window');
await settle(RETRY_AFTER_MS + 250); // refusal window, then the 200 ms drip
enrichment.request(record);
await settle(250);
assert.equal(source.calls.length, 2, 'the aircraft is asked for again');
assert.equal(enrichment.get('abc123')?.typeCode, 'B738');
});
test('an answered lookup is still asked for only once', async (t) => {
const calls = [];
const enrichment = createLocalAdsbEnrichment({
source: {
async getEnrichment(query) {
calls.push(query);
return { found: false };
},
},
onChange() {},
});
t.after(() => enrichment.destroy());
enrichment.request({ icao: 'def456' });
await settle(RETRY_AFTER_MS + 250);
enrichment.request({ icao: 'def456' });
await settle(250);
assert.equal(calls.length, 1, 'a 404 is an answer, not a refusal');
});
test('Flights asks again after a 429 once the refusal has passed', async (t) => {
const source = refusingOnce();
const flightState = createFlightState({
source,
services: {
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
},
});
t.after(() => flightState.lifetime.abort());
const enrichment = createEnrichment({
flightState,
services: enrichServices,
parts: {},
});
let applied = null;
const ask = () =>
enrichment._enqueueEnrich(
't:abc123',
{ kind: 'type', id: 'abc123' },
(data) => {
applied = data;
},
);
ask();
await settle(0);
ask();
await settle(0);
assert.equal(source.calls.length, 1, 'no retry inside the refusal window');
await settle(RETRY_AFTER_MS + 250);
ask();
await settle(250);
assert.equal(source.calls.length, 2, 'the aircraft is asked for again');
assert.equal(applied?.typeCode, 'B738');
});
+17 -2
View File
@@ -63,10 +63,25 @@ export function createEnrichment({
);
}
/**
* How long a temporarily failed lookup stays unasked. A rate-limit refusal
* says itself when to ask again (`retryAfterMs`), so that wins; any other
* temporary failure waits ENRICH_RETRY_COOLDOWN_MS.
* @param {*} error The rejection, as `LiveSourceError` carries it.
* @returns {number} Milliseconds.
*/
function _enrichCooldownMs(error) {
const hinted = Number(error?.retryAfterMs);
return error?.code === 'limited' && Number.isFinite(hinted) && hinted > 0
? hinted
: ENRICH_RETRY_COOLDOWN_MS;
}
/**
* Ask each key at most once per session, except that a lookup whose source
* failed temporarily (rejected or threw) may be asked again after
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
* ENRICH_RETRY_COOLDOWN_MS, or after the refusal's own `retryAfterMs` for a
* rate limit (see _enrichCooldownMs); an answer, found or not, and a permanent
* refusal (see _enrichFailureIsFinal) are final.
* @param {string} key Session-unique lookup key.
* @param {object} query The source's enrichment query.
@@ -133,7 +148,7 @@ export function createEnrichment({
flightState._enrichSeen.delete(job.key);
flightState._enrichRetryAfter.set(
job.key,
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
Date.now() + _enrichCooldownMs(error),
);
},
)
+18 -4
View File
@@ -35,7 +35,8 @@ export function localAdsbClass(record, meta = null) {
* session, at most four requests are in flight and dispatches are dripped
* 200 ms apart. Only the selected aircraft (type + route) and aircraft that
* are about to render as 3D models (type) are ever looked up — never one
* request per contact per tick.
* request per contact per tick. A rate-limit refusal is not an answer: the key
* becomes askable again once the refusal's retry-after has passed.
* @param {object} options
* @param {{getEnrichment?: Function}|null} options.source Flights source.
* @param {() => void} options.onChange Called when metadata arrives.
@@ -53,6 +54,7 @@ export function createLocalAdsbEnrichment({
let active = 0;
let lastDispatchAt = -Infinity;
let dripTimer = null;
const retryTimers = new Set();
let lifetime = new AbortController();
function entry(icao) {
@@ -68,7 +70,7 @@ export function createLocalAdsbEnrichment({
function enqueue(key, query, apply, priority) {
if (typeof source?.getEnrichment !== 'function' || seen.has(key)) return;
seen.add(key);
const job = { query, apply };
const job = { key, query, apply };
if (priority) queue.unshift(job);
else queue.push(job);
drain();
@@ -97,8 +99,10 @@ export function createLocalAdsbEnrichment({
onChange?.();
}
})
.catch(() => {
/* enrichment never surfaces errors */
.catch((error) => {
// Enrichment never surfaces errors; a 429 only defers the key.
if (error?.code === 'limited')
forgetLater(job.key, error.retryAfterMs);
})
.finally(() => {
if (signal.aborted) return;
@@ -108,6 +112,14 @@ export function createLocalAdsbEnrichment({
}
}
function forgetLater(key, delayMs) {
const timer = setTimeout(() => {
retryTimers.delete(timer);
seen.delete(key);
}, delayMs);
retryTimers.add(timer);
}
return {
/** @param {string} icao @returns {object|null} */
get(icao) {
@@ -160,6 +172,8 @@ export function createLocalAdsbEnrichment({
lifetime = new AbortController();
clearTimeout(dripTimer);
dripTimer = null;
for (const timer of retryTimers) clearTimeout(timer);
retryTimers.clear();
queue.length = 0;
active = 0;
},
+51 -3
View File
@@ -21,6 +21,11 @@ import { ISS_NORAD, TRACKED_ORBIT_COLOR } from './policy.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import {
clearFocusTarget,
getFocusTarget,
publishFocusTargetAt,
} from '../../data/focusDeemphasis.js';
const COMPANION = 25545;
const GPS = 32711;
@@ -70,7 +75,14 @@ function fakeFollowCamera() {
camera.flightsCancelled += 1;
},
flyTo() {},
pose: () => ({ lon: 0, lat: 0, height: 2e7, heading: 0, pitch: -1.57 }),
pose: () => ({
lon: 0,
lat: 0,
height: 2e7,
heading: 0,
pitch: -1.57,
position: { x: 2.6378e7, y: 0, z: 0 },
}),
on(event, cb) {
if (event !== 'followChanged') return () => {};
listeners.add(cb);
@@ -135,7 +147,13 @@ const SENSORS = indexImagingSensors({
],
});
async function fixture(t) {
/**
* @param {object} t The test context.
* @param {{realFocus?: boolean}} [options] `realFocus` publishes through the
* shared focus rectangle, with a query port that projects every point to
* the screen centre.
*/
async function fixture(t, { realFocus = false } = {}) {
const source = {
async readGroup(group) {
const text = GROUP_TEXT[group] || '';
@@ -165,6 +183,9 @@ async function fixture(t) {
getFocusTarget: () => null,
focusNowMs: (now) => now,
focusPassIsNeeded: () => false,
...(realFocus
? { clearFocusTarget, getFocusTarget, publishFocusTargetAt }
: {}),
},
context: {
clearTrackedSubjectContext: noop,
@@ -203,7 +224,12 @@ async function fixture(t) {
const viewer = { canvas: new EventTarget(), scene: {} };
const camera = fakeFollowCamera();
const frame = fakeFrame();
const { draw, unbind } = bindFakeDraw(viewer, { camera, frame });
const query = { project: () => ({ x: 720, y: 450 }) };
const { draw, unbind } = bindFakeDraw(viewer, {
camera,
frame,
...(realFocus ? { query } : {}),
});
const input = fakeInput(viewer);
let frameNumber = 1;
const { log, warn } = console;
@@ -221,6 +247,7 @@ async function fixture(t) {
console.log = log;
input.destroy();
unbind();
if (realFocus) clearFocusTarget();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
@@ -412,6 +439,27 @@ test('holding the subject hides its dot, ring, docked companions and bracket', a
assert.ok(f.detected().includes(ISS_NORAD));
});
test('releasing a satellite leaves no focus rectangle, even when a follow listener reads it', async (t) => {
const f = await fixture(t, { realFocus: true });
// As the Cockpit entry button does: every follow change asks for the subject.
let readsOnRelease = 0;
f.camera.on('followChanged', (followed) => {
if (followed) return;
readsOnRelease += 1;
f.methods.getCockpitSubject();
});
assert.equal(f.track(GPS), true);
f.nextFrame();
f.methods.getCockpitSubject();
assert.equal(getFocusTarget()?.ownerLayer, 'satellites');
assert.equal(getFocusTarget()?.id, GPS);
f.methods.stopTracking();
assert.equal(readsOnRelease, 1, 'the listener ran during the release');
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(getFocusTarget(), null);
});
test('a subject that is not tracked holds nothing', async (t) => {
const f = await fixture(t);
f.track(GPS);
+11 -8
View File
@@ -90,18 +90,18 @@ export function createTracking({ state: layerState, services, parts, source }) {
return;
}
const clearedNorad = layerState._trackedNorad;
clearFocusTarget('satellites', layerState._trackedNorad);
clearFocusTarget('satellites', clearedNorad);
// Re-show the dot (hidden while the tracked dot drew it) and
// restore the original group palette from the shared style table (WS-D3)
parts.rendering._restorePoint(
layerState._trackedNorad,
clearedNorad,
parts.controls._pointStyleFor(
layerState._trackedNorad,
layerState._catalog.get(layerState._trackedNorad)?.group,
clearedNorad,
layerState._catalog.get(clearedNorad)?.group,
),
// Back to its class's visibility: a hidden class stays hidden.
parts.controls._classVisible(layerState._trackedNorad),
parts.controls._classVisible(clearedNorad),
);
// Invalidate the per-frame tracked-position cache (WS-D2)
@@ -109,9 +109,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedFrameGeo = null;
// Remove the tracked dot and orbit path (unless ISS — keep its path)
if (layerState._trackedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(layerState._trackedNorad);
if (clearedNorad !== ISS_NORAD) {
parts.rendering._hideOrbitPath(clearedNorad);
}
// Released before the camera hears of it: a follow listener that reads
// the tracked position mid-release must find nothing, or it would publish
// the focus rectangle again after it was cleared above.
layerState._trackedNorad = null;
if (layerState._viewer && !skipViewerUntrack)
stopFollowing(layerState._viewer);
layerState._followTarget = null;
@@ -119,7 +123,6 @@ export function createTracking({ state: layerState, services, parts, source }) {
parts.rendering._removeTrackedEntity(layerState._trackedEntity);
layerState._trackedEntity = null;
}
layerState._trackedNorad = null;
layerState._trackedDockedToStation = null;
layerState._trackedDockedToIss = false;
parts.controls._syncIssOrbit?.();
+2 -2
View File
@@ -5,7 +5,7 @@ import path from 'node:path';
import { providerCooldownMs } from '../server/providers/space/cooldown.js';
import { parseTerrainPoints } from './data/terrainHeightsProxy.js';
import { readResponseTextCapped, coalesceProxyRequest } from './sources/httpBody.js';
import { makeRateLimiter, clientKey } from '../server/providers/common/rate-limit.js';
import { makeRateLimiter, clientKey, resolvePerMinuteCap } from '../server/providers/common/rate-limit.js';
const source = ['local.js', 'common/http.js', 'aircraft/enrichment.js', 'terrain.js', 'space/celestrak.js', 'space/launch-library.js', '../../src/data/spaceProviderRequests.js']
.map(file => readFileSync(new URL(`../server/providers/${file}`, import.meta.url), 'utf8'))
@@ -27,7 +27,7 @@ function fixture(name, overrides = {}, preview = false) {
readResponseTextCapped, coalesceProxyRequest, providerCooldownMs,
// The rate-limited proxies reach for these; give them the real ones so a
// fixture request is throttled exactly as production would be.
makeRateLimiter, clientKey,
makeRateLimiter, clientKey, resolvePerMinuteCap,
// terrain.js gates cross-site requests first; fixture requests carry no
// browser headers, so admit them like a loopback tool.
admitSameSiteKeyless: () => false,
+672 -69
View File
File diff suppressed because it is too large. Load diff
+416
View File
@@ -0,0 +1,416 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test, { after } from 'node:test';
import { createCesiumDraw, lineAgeData } from './draw.js';
// Node has no WebGL context to report line-width limits.
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
// A material's texture uniform is told from the browser's image classes, which
// Node lacks.
const IMAGE_CLASSES = [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
];
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
after(() =>
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
);
/** A scene with what a line set touches: primitives, its events and its time. */
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
const added = [];
return {
added,
postRender: new Cesium.Event(),
preRender: new Cesium.Event(),
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
frameState: {
mode: Cesium.SceneMode.SCENE3D,
time: Cesium.JulianDate.fromDate(new Date(ms)),
},
updateHeight: () => () => {},
getHeight: () => undefined,
primitives: {
add: (primitive) => (added.push(primitive), primitive),
remove: (primitive) => {
const at = added.indexOf(primitive);
if (at >= 0) added.splice(at, 1);
return at >= 0;
},
length: 0,
},
requestRender() {},
isDestroyed: () => false,
};
}
const T0 = Date.UTC(2026, 0, 1);
/** A port that fades lines with age, over `scene`, and its frames at a scene time. */
function agedDraw(scene = fakeScene(), capabilities = ['lineAgeFade']) {
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
capabilities: new Set(capabilities),
});
return {
part,
scene,
frameAt(ms) {
scene.frameState.time = Cesium.JulianDate.fromDate(new Date(ms));
part.beforeRender();
part.afterRender();
},
};
}
const along = (n, lat = 10) =>
Array.from({ length: n }, (_, i) =>
Cesium.Cartesian3.fromDegrees(i * 0.01, lat, 100),
);
const trail = (positions, times, extra = {}) => ({
id: 'trail',
positions,
widthPx: 3,
mode: '3d',
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
ageFade: { times, windowMs: 60_000, alphaFloor: 0.06, ...extra },
pickable: false,
});
/** The polylines a line set's host draws in its collection. */
function collectionOf(scene) {
const host = scene.added.at(-1);
if (host instanceof Cesium.PolylineCollection) return host;
for (let i = 0; i < host.length; i++)
if (host.get(i) instanceof Cesium.PolylineCollection) return host.get(i);
return null;
}
test('a polyline’s age texels: a point at the place of the one before it is dropped, the rest even along it, times in seconds before the newest', () => {
const [a, b, c] = along(3);
const age = lineAgeData([a, a, b, c], [T0, T0 + 1000, T0 + 2000, T0 + 4000], {
times: [],
windowMs: 30_000,
alphaFloor: 0.06,
squaredAlphaFloor: 0.14,
});
assert.equal(age.count, 3);
assert.equal(age.base, T0 + 4000);
const texel = (i) => [age.data[i * 4], age.data[i * 4 + 1]];
assert.deepEqual(texel(0), [0, -4]);
assert.deepEqual(texel(1), [0.5, -2]);
assert.deepEqual(texel(2), [1, 0]);
assert.deepEqual(age.uniforms, {
ageCount: 3,
ageWidth: 3,
ageRows: 1,
ageByLength: 0,
ageWindow: 30,
ageAlphaFloor: 0.06,
ageSquaredFloor: 0.14,
ageWidthFloor: 1,
ageShow: 0,
});
});
test('a windowed line’s age texels carry its span, in seconds; an endless one cuts at now alone', () => {
const points = along(2);
const fade = (showMs) => ({
times: [],
windowMs: 30_000,
alphaFloor: 0.06,
showMs,
});
const at = (showMs, windowed = true) =>
lineAgeData(points, [T0, T0 + 1000], fade(showMs), false, windowed).uniforms
.ageShow;
assert.equal(at(45_000), 45);
assert.equal(at(Infinity), -1);
assert.equal(at(undefined), 0, 'no span, no cut');
assert.equal(at(45_000, false), 0, 'not cut where the port does not');
});
test('a draped line’s age texels lie along it by distance, and a long line takes more rows', () => {
const points = [
Cesium.Cartesian3.fromDegrees(0, 0),
Cesium.Cartesian3.fromDegrees(1, 0),
Cesium.Cartesian3.fromDegrees(4, 0),
];
const age = lineAgeData(
points,
[0, 1000, 2000],
{ times: [], windowMs: 1, alphaFloor: 0 },
true,
);
assert.equal(age.uniforms.ageByLength, 1);
assert.equal(age.data[0], 0);
assert.ok(
Math.abs(age.data[4] - 0.25) < 1e-6,
`a quarter along (${age.data[4]})`,
);
assert.equal(age.data[8], 1);
const long = along(2500);
const many = lineAgeData(
long,
long.map((_, i) => i),
{ times: [], windowMs: 1, alphaFloor: 0 },
);
assert.equal(many.width, 1024);
assert.equal(many.rows, 3);
assert.equal(many.data.length, 1024 * 3 * 4);
});
test('an aged line fades on the scene clock: time passing changes its material, never its line', () => {
const { part, scene, frameAt } = agedDraw();
const set = part.port.lines({ id: 'trails' });
const positions = along(4);
const times = [T0 - 30_000, T0 - 20_000, T0 - 10_000, T0];
set.set([
trail(positions, times, { squaredAlphaFloor: 0.14, widthFloor: 0.3 }),
]);
const polylines = collectionOf(scene);
const polyline = polylines.get(0);
const material = polyline.material;
assert.equal(material.type, 'DrawAgedLine_solid');
assert.ok(material.isTranslucent(), 'drawn in the translucent pass');
assert.equal(material.uniforms.ageWindow, 60);
assert.equal(material.uniforms.ageAlphaFloor, 0.06);
assert.equal(material.uniforms.ageSquaredFloor, 0.14);
assert.equal(material.uniforms.ageWidthFloor, 0.3);
assert.equal(material.uniforms.ageCount, 4);
assert.ok(
Cesium.Color.equals(
material.materials.aged.uniforms.color,
new Cesium.Color(0.2, 0.8, 1, 0.9),
),
'its style’s colour inside',
);
for (let k = 1; k <= 120; k++) {
frameAt(T0 + k * 1000);
assert.equal(
material.uniforms.ageNow,
k,
`seconds after its newest point, frame ${k}`,
);
}
assert.equal(collectionOf(scene), polylines, 'the same collection');
assert.equal(polylines.length, 1);
assert.equal(polylines.get(0), polyline, 'the same line');
assert.equal(polyline.material, material, 'the same material');
});
test('an aged line given new points and times moves in place and takes the new times', () => {
const { part, scene, frameAt } = agedDraw();
const set = part.port.lines({ id: 'trails' });
const positions = along(5);
const times = [0, 1, 2, 3, 4].map((i) => T0 + i * 10_000);
set.set([trail(positions.slice(0, 4), times.slice(0, 4))]);
const polyline = collectionOf(scene).get(0);
const material = polyline.material;
frameAt(T0 + 40_000);
assert.equal(material.uniforms.ageNow, 10);
set.upsert([trail(positions.slice(1), times.slice(1))]);
assert.equal(collectionOf(scene).get(0), polyline, 'moved in place');
assert.equal(polyline.material, material);
frameAt(T0 + 45_000);
assert.equal(material.uniforms.ageNow, 5, 'from its new newest point');
assert.ok(Cesium.Cartesian3.equals(polyline.positions[0], positions[1]));
// A new colour is taken in place too, inside the fade.
set.upsert([
{
...trail(positions.slice(1), times.slice(1)),
style: { kind: 'solid', color: '#ff0000' },
},
]);
assert.equal(collectionOf(scene).get(0), polyline, 'recoloured in place');
assert.ok(
Cesium.Color.equals(
material.materials.aged.uniforms.color,
Cesium.Color.RED,
),
);
});
test('segment colours fade with age too, each segment with its own two times', () => {
const { part, scene, frameAt } = agedDraw();
const set = part.port.lines({ id: 'trails' });
const times = [T0, T0 + 1000, T0 + 2000];
set.set([
{
...trail(along(3), times),
segmentColors: ['#ff0000', '#00ff00'],
},
]);
const pieces = [];
const visit = (primitive) => {
if (primitive instanceof Cesium.Primitive) pieces.push(primitive);
else if (primitive?.length !== undefined && primitive.get)
for (let i = 0; i < primitive.length; i++) visit(primitive.get(i));
};
visit(scene.added.at(-1));
assert.equal(pieces.length, 2);
frameAt(T0 + 3000);
const [first, second] = pieces.map((piece) => piece.appearance.material);
assert.equal(first.type, 'DrawAgedLine_solid');
assert.equal(
first.uniforms.ageNow,
2,
'its newer point a second after the first',
);
assert.equal(second.uniforms.ageNow, 1);
assert.ok(
Cesium.Color.equals(first.materials.aged.uniforms.color, Cesium.Color.RED),
);
assert.ok(
Cesium.Color.equals(
second.materials.aged.uniforms.color,
Cesium.Color.LIME,
),
);
});
test('a draped aged line draws by a ground primitive of its own, its times along its length', () => {
const { part, scene } = agedDraw();
const set = part.port.lines({ id: 'trails' });
const ground = [0, 1, 2].map((i) =>
Cesium.Cartesian3.fromDegrees(i * 0.01, 10),
);
set.set([{ ...trail(ground, [T0, T0 + 1, T0 + 2]), mode: 'draped' }]);
const host = scene.added.at(-1);
const primitives = [];
const visit = (primitive) => {
if (primitive instanceof Cesium.GroundPolylinePrimitive)
primitives.push(primitive);
else if (primitive?.length !== undefined && primitive.get)
for (let i = 0; i < primitive.length; i++) visit(primitive.get(i));
};
visit(host);
assert.equal(primitives.length, 1);
const material = primitives[0].appearance.material;
assert.equal(material.type, 'DrawAgedLine_solid');
assert.equal(material.uniforms.ageByLength, 1);
});
test('an aged line built anew lets its old material go once its primitive is gone', () => {
const { part, scene, frameAt } = agedDraw();
const set = part.port.lines({ id: 'trails' });
const deep = (times) => ({
...trail(along(3), times),
depthFail: { kind: 'solid', color: '#ffffff' },
});
set.set([deep([T0, T0 + 1, T0 + 2])]);
const record = part.sets.get('trails');
assert.equal(record.ages.size, 2, 'its line and the part behind the surface');
const [old] = record.ages.keys();
set.upsert([deep([T0 + 1, T0 + 2, T0 + 3])]);
frameAt(T0 + 10);
assert.ok(old.isDestroyed(), 'the old material went with its primitive');
assert.equal(record.ages.size, 2);
void scene;
});
test('a windowed line is cut on the scene clock: time passing changes its material, never its line', () => {
const { part, scene, frameAt } = agedDraw(fakeScene(), [
'lineAgeFade',
'lineTimeWindow',
]);
const set = part.port.lines({ id: 'trails' });
// A whole track, an hour of it, shown over its last minute.
const positions = along(61);
const times = positions.map((_, i) => T0 + i * 60_000);
set.set([trail(positions, times, { alphaFloor: 1, showMs: 60_000 })]);
const polylines = collectionOf(scene);
const polyline = polylines.get(0);
const material = polyline.material;
assert.equal(material.type, 'DrawAgedLine_solid');
assert.equal(material.uniforms.ageShow, 60);
assert.equal(material.uniforms.ageCount, 61);
const before = polyline.positions;
for (let k = 1; k <= 120; k++) {
frameAt(T0 + k * 30_000);
assert.equal(
material.uniforms.ageNow,
(k * 30_000 - 3_600_000) / 1000,
`seconds after its newest point, frame ${k}`,
);
}
assert.equal(collectionOf(scene), polylines, 'the same collection');
assert.equal(polylines.get(0), polyline, 'the same line');
assert.equal(polyline.material, material, 'the same material');
assert.equal(polyline.positions, before, 'its points untouched');
// A new span is a new look: drawn anew, with it.
set.upsert([trail(positions, times, { alphaFloor: 1, showMs: 120_000 })]);
assert.equal(collectionOf(scene).get(0).material.uniforms.ageShow, 120);
});
test('without the window’s capability a line ignores its span and draws whole', () => {
const { part, scene } = agedDraw();
const set = part.port.lines({ id: 'trails' });
set.set([trail(along(3), [T0, T0 + 1, T0 + 2], { showMs: 60_000 })]);
const material = collectionOf(scene).get(0).material;
assert.equal(material.type, 'DrawAgedLine_solid', 'still faded');
assert.equal(material.uniforms.ageShow, 0, 'never cut');
});
test('without the capability a line ignores its age fade; with it a bad fade is refused', () => {
const plain = agedDraw(fakeScene(), []);
const lines = plain.part.port.lines({ id: 'trails' });
lines.set([trail(along(3), [T0])]);
const material = collectionOf(plain.scene).get(0).material;
assert.equal(material.type, 'Color', 'drawn as its style alone');
const { part } = agedDraw();
const set = part.port.lines({ id: 'trails' });
assert.throws(
() => set.set([trail(along(3), [T0, T0])]),
TypeError,
'one time a position',
);
assert.throws(
() => set.set([trail(along(2), [T0, T0], { windowMs: 0 })]),
TypeError,
'a positive window',
);
assert.throws(
() => set.set([trail(along(2), [T0, T0], { widthFloor: 2 })]),
TypeError,
'floors from 0 to 1',
);
for (const showMs of [0, -1, Number.NaN])
assert.throws(
() => set.set([trail(along(2), [T0, T0], { showMs })]),
TypeError,
'a positive span',
);
assert.equal(set.size(), 0, 'nothing changed');
});
test('an aged line made first leaves its style’s type named as a plain material of it is', () => {
const lists = Cesium.Material._uniformList;
const was = lists.Color;
delete lists.Color;
try {
const { part, scene } = agedDraw();
const set = part.port.lines({ id: 'trails' });
set.set([trail(along(2), [T0, T0 + 1])]);
assert.deepEqual(lists.Color, ['color_0'], 'as a plain Color material');
// A plain line beside it then draws with it in its collection.
set.upsert([
{ ...trail(along(2), [T0, T0 + 1]), id: 'plain', ageFade: undefined },
]);
const plain = collectionOf(scene).get(1).material;
assert.equal(plain.type, 'Color');
assert.ok(
lists.Color.every((name) => typeof plain._uniforms[name] === 'function'),
);
} finally {
if (was) lists.Color = was;
}
});
+375
View File
@@ -0,0 +1,375 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test, { after } from 'node:test';
import { createCesiumDraw } from './draw.js';
// Node has no WebGL context to report line-width limits.
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
Cesium.ContextLimits._maximumAliasedLineWidth = 10;
// A material's texture uniform is told from the browser's image classes, which
// Node lacks.
const IMAGE_CLASSES = [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
];
const realClasses = IMAGE_CLASSES.map((name) => globalThis[name]);
for (const name of IMAGE_CLASSES) globalThis[name] ??= class {};
after(() =>
IMAGE_CLASSES.forEach((name, i) => (globalThis[name] = realClasses[i])),
);
/** A scene with what a line set touches: primitives, its events and its time. */
function fakeScene(ms = Date.UTC(2026, 0, 1)) {
const added = [];
return {
added,
postRender: new Cesium.Event(),
preRender: new Cesium.Event(),
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
frameState: {
mode: Cesium.SceneMode.SCENE3D,
time: Cesium.JulianDate.fromDate(new Date(ms)),
},
updateHeight: () => () => {},
getHeight: () => undefined,
primitives: {
add: (primitive) => (added.push(primitive), primitive),
remove: (primitive) => {
const at = added.indexOf(primitive);
if (at >= 0) added.splice(at, 1);
return at >= 0;
},
length: 0,
},
requestRender() {},
isDestroyed: () => false,
};
}
const T0 = Date.UTC(2026, 0, 1);
/** A port over a fake scene that draws lines in runs (and with `more`). */
function brokenDraw(capabilities = ['lineBreaks'], scene = fakeScene()) {
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
capabilities: new Set(capabilities),
});
return { part, scene, set: part.port.lines({ id: 'trails' }) };
}
/** Six positions west to east, `height` up. */
const along = (n = 6, height = 100) =>
Array.from({ length: n }, (_, i) =>
Cesium.Cartesian3.fromDegrees(i * 0.01, 10, height),
);
/** Three runs: positions 0-1, 2-4 and 5 alone (which draws nothing). */
const trails = (extra = {}) => ({
id: 'trails',
positions: along(),
breaks: [2, 5],
widthPx: 3,
mode: '3d',
style: { kind: 'solid', color: [0.2, 0.8, 1, 0.9] },
...extra,
});
/** Everything a set's host holds, collections opened. */
function everything(scene) {
const all = [];
const walk = (p) => {
all.push(p);
if (p instanceof Cesium.PrimitiveCollection)
for (let i = 0; i < p.length; i++) walk(p.get(i));
};
for (const p of scene.added) walk(p);
return all;
}
/** The polylines a set's collection draws. */
function polylinesOf(scene) {
const collection = everything(scene).find(
(p) => p instanceof Cesium.PolylineCollection,
);
const lines = [];
for (let i = 0; i < collection.length; i++) lines.push(collection.get(i));
return lines;
}
const lonOf = (p) =>
Number(
Cesium.Math.toDegrees(
Cesium.Cartographic.fromCartesian(p).longitude,
).toFixed(6),
);
test('an undraped line in runs is a polyline a run in its collection, each picked as the line', () => {
const { scene, set } = brokenDraw();
set.set([trails()]);
const lines = polylinesOf(scene);
assert.equal(lines.length, 2, 'a polyline a run with length');
assert.deepEqual(
lines.map((line) => line.positions.map(lonOf)),
[
[0, 0.01],
[0.02, 0.03, 0.04],
],
'nothing from position 1 to 2, nor 4 to 5',
);
assert.deepEqual(
lines.map((line) => line.id.id),
['trails', 'trails'],
'each run picks as its line',
);
assert.notEqual(lines[0].id, lines[1].id, 'under a pick id of its own');
assert.equal(set.size(), 1, 'one item');
});
test('a line in runs takes packed positions and breaks', () => {
const { scene, set } = brokenDraw();
const flat = new Float64Array(along().flatMap((p) => [p.x, p.y, p.z]));
set.set([trails({ positions: flat, breaks: new Uint32Array([3]) })]);
assert.deepEqual(
polylinesOf(scene).map((line) => line.positions.length),
[3, 3],
);
});
test('an arrow in runs has a head at the end of each run', () => {
const { scene, set } = brokenDraw();
set.set([trails({ style: { kind: 'arrow', color: '#ffffff' } })]);
assert.deepEqual(
polylinesOf(scene).map((line) => line.material.type),
['PolylineArrow', 'PolylineArrow'],
);
});
test('segment colours and shows stay a pair of positions; the pairs across a break draw nothing', () => {
const { scene, set } = brokenDraw();
const red = [1, 0, 0, 1];
const green = [0, 1, 0, 1];
const blue = [0, 0, 1, 1];
const line = (colors, shows) =>
trails({
style: { kind: 'glow', color: '#ffffff', power: 0.2 },
segmentColors: colors,
segmentShow: shows,
});
set.set([
line([red, blue, green, green, blue], [true, true, true, false, true]),
]);
const host = scene.added[0];
// In the set's collection, a polyline a segment.
const pieces = polylinesOf(scene);
assert.equal(pieces.length, 3, 'segments 0, 2 and 3; not 1 nor 4');
assert.equal(pieces[0].material.type, 'PolylineGlow');
const color = (p) => p.material.uniforms.color;
assert.deepEqual(
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
[
[1, 0, 0, true],
[0, 1, 0, true],
[0, 1, 0, false],
],
);
set.upsert([
line([green, red, red, blue, red], [true, false, true, true, true]),
]);
assert.equal(scene.added[0], host, 'recoloured and shown in place');
assert.deepEqual(
pieces.map((p) => [color(p).red, color(p).green, color(p).blue, p.show]),
[
[0, 1, 0, true],
[1, 0, 0, true],
[0, 0, 1, true],
],
);
});
test('a run of a line that fades with age takes its own points’ times', () => {
const { scene, set } = brokenDraw(['lineAgeFade', 'lineBreaks']);
const times = along().map((_, i) => T0 + i * 1000);
set.set([trails({ ageFade: { times, windowMs: 60_000, alphaFloor: 0.1 } })]);
const lines = polylinesOf(scene);
assert.deepEqual(
lines.map((line) => [line.material.type, line.material.uniforms.ageCount]),
[
['DrawAgedLine_solid', 2],
['DrawAgedLine_solid', 3],
],
);
});
test('a revealed line in runs reveals them in order, along their own length', () => {
const { scene, set } = brokenDraw();
// Runs of one leg and of two, all of one length, the gap between them
// (positions 1 to 2) none: half their length is all of the first run
// and a quarter of the second.
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.5 })]);
let lines = polylinesOf(scene);
const revealOf = (line) => line.material.materials?.revealed;
assert.equal(revealOf(lines[0]), undefined, 'the first run all shown');
assert.equal(lines[0].show, true);
const second = lines[1];
assert.ok(revealOf(second), 'the second run revealed');
// Half its first leg, of two.
assert.ok(
Math.abs(second.material.uniforms.reveal - 0.25) < 1e-9,
`revealed a quarter along (${second.material.uniforms.reveal})`,
);
set.set([trails({ positions: along(5), breaks: [2], revealFraction: 0.25 })]);
lines = polylinesOf(scene);
assert.equal(lines[1].show, false, 'a run not yet reached is hidden');
});
test('a draped line in runs drapes a ground piece a run; a solid segmented one a ground instance a segment, none across a break', () => {
const { scene, set } = brokenDraw();
set.set([trails({ mode: 'draped', positions: along(6, 0) })]);
const ground = everything(scene).filter(
(p) => p instanceof Cesium.GroundPolylinePrimitive,
);
assert.equal(ground.length, 2, 'a ground piece a run with length');
assert.deepEqual(
ground.map((p) => p.geometryInstances[0].geometry._positions.length),
[2, 3],
);
set.set([
trails({
mode: 'draped',
positions: along(6, 0),
segmentColors: along()
.slice(1)
.map(() => [0, 1, 0, 1]),
}),
]);
const batch = everything(scene).filter(
(p) => p instanceof Cesium.GroundPolylinePrimitive,
);
assert.equal(batch.length, 1, 'one batch');
assert.equal(
batch[0].geometryInstances.length,
3,
'segments 0, 2 and 3: not 1 nor 4',
);
});
test('changed breaks draw the line anew; the same ones change it in place', () => {
const { scene, set } = brokenDraw();
set.set([trails()]);
const host = scene.added[0];
set.upsert([trails({ show: false })]);
assert.equal(scene.added[0], host, 'shown in place');
assert.deepEqual(
polylinesOf(scene).map((line) => line.show),
[false, false],
);
set.upsert([trails({ breaks: [3] })]);
assert.notEqual(scene.added[0], host, 'built anew');
assert.deepEqual(
polylinesOf(scene).map((line) => line.positions.length),
[3, 3],
);
});
test('without the capability a line ignores its breaks; with it bad breaks are refused', () => {
const plain = brokenDraw([]);
plain.set.set([trails()]);
assert.equal(polylinesOf(plain.scene).length, 1, 'one line, joined');
const { set } = brokenDraw();
for (const breaks of [[0], [6], [3, 2], [2, 2], [1.5], ['2']])
assert.throws(
() => set.set([trails({ breaks })]),
TypeError,
`refused: ${JSON.stringify(breaks)}`,
);
assert.equal(set.size(), 0, 'nothing changed');
set.set([trails({ breaks: [] })]);
assert.equal(set.size(), 1, 'no breaks: one run');
});
test('where the scene cannot drape, a draped line in runs draws a run over the surface each, hidden past the horizon', () => {
const scene = fakeScene();
scene.frameState.context = { depthTexture: false };
const { part, set } = brokenDraw(['lineBreaks'], scene);
const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0);
set.set([
trails({
mode: 'draped',
positions: [at(0), at(0.01), at(0.02), at(0.03)],
breaks: [2],
// The overlay draws its shown segments only, from first to last.
segmentShow: [false, true, true],
}),
trails({
id: 'two',
mode: 'draped',
positions: [at(0), at(0.01), at(0.02), at(0.03)],
breaks: [2],
}),
]);
const frame = () => {
part.beforeRender();
part.afterRender();
};
const runs = everything(scene).filter(
(p) => p instanceof Cesium.Primitive && p.depthFailAppearance,
);
// The first line kept positions 1 to 3, its break at 1 of them: a run of
// one position and one of two; the second two runs of two.
assert.equal(runs.length, 3, 'a primitive a run with length');
scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0);
frame();
assert.deepEqual(
runs.map((p) => p.show),
[true, true, true],
);
scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0);
frame();
assert.deepEqual(
runs.map((p) => p.show),
[false, false, false],
'past the horizon',
);
});
test('a draped line in runs whose first run is later than its second times each run by its own points', () => {
const { scene, set } = brokenDraw([
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
]);
set.set([
trails({
mode: 'draped',
positions: along(4, 0),
breaks: [2],
ageFade: {
times: [T0 + 110_000, T0 + 120_000, T0, T0 + 10_000],
windowMs: 60_000,
alphaFloor: 1,
showMs: 30_000,
},
}),
]);
const ground = everything(scene).filter(
(p) => p instanceof Cesium.GroundPolylinePrimitive,
);
assert.equal(ground.length, 2, 'a ground piece a run');
const ages = ground.map((p) => p.appearance.material.uniforms);
assert.deepEqual(
ages.map((u) => [u.ageCount, u.ageByLength, u.ageShow]),
[
[2, 1, 30],
[2, 1, 30],
],
'its own two points each, along its length, cut to the span',
);
// Each run's clock reads from its own newest point: the first's is
// 110 s later than the second's.
assert.equal(ages[1].ageNow - ages[0].ageNow, 110);
});
+4
View File
@@ -72,6 +72,10 @@ export const CESIUM_CHECKS = new Set([
'draw.lines.drape',
'draw.lines.split',
'draw.lines.outlineDraped',
'draw.lines.ageFade',
'draw.lines.timeWindow',
'draw.lines.breaks',
'draw.lines.breaks.timeWindow',
'draw.lines.segments',
'draw.lines.segmentStyles',
'draw.sets.blend',
+8
View File
@@ -83,6 +83,14 @@ export function cesiumCapabilities(scene, only) {
'meshes',
// Raster shells; other field kinds are refused.
'fields',
// Lines faded with age in their material, from a floating-point
// texture of their points' times (`draw.js`).
// And cut by time there, within a span of the scene clock.
...(scene?.context?.floatingPointTexture
? ['lineAgeFade', 'lineTimeWindow']
: []),
// Lines in runs, a piece a run (`draw.js`).
'lineBreaks',
'followFrame',
'pointVisibility',
// Cesium's AUTODETECT tracking frame (`follow.js`).
+1
View File
@@ -43,6 +43,7 @@ test('capabilities follow what the scene supports', () => {
'quads',
'meshes',
'fields',
'lineBreaks',
];
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
// A scene with a globe reads its visibility back.
+373
View File
@@ -3453,6 +3453,379 @@ export function portChecks() {
}
},
),
check(
'draw.lines.ageFade',
'a line, draped or not, fades with the age of its points as scene time moves on, without being sent again',
async (h, r) => {
if (h.pixels === false)
return { skip: 'this harness reads no drawn pixels' };
await overAustin(h, r);
const t0 = Date.UTC(2026, 0, 1, 18);
r.frame.setTime(t0);
// Off the row under the camera, where a ground line can leave a gap.
const at = (dLon, dLat, height) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
const lines = r.draw.lines({ id: 'conf:line-age-fade' });
const line = (id, dLat, mode) => ({
id,
positions: [
at(-0.004, dLat, mode === 'draped' ? 0 : 20),
at(0.004, dLat, mode === 'draped' ? 0 : 20),
],
widthPx: 16,
mode,
style: { kind: 'solid', color: [0, 1, 0, 1] },
// Its west end a minute old at t0, its east end new.
ageFade: {
times: [t0 - 60_000, t0],
windowMs: 60_000,
alphaFloor: 0,
},
});
// Unfaded but narrowed to a quarter of its width where it is old.
const narrowed = {
...line('narrowed', 0.0035, '3d'),
ageFade: {
times: [t0 - 60_000, t0],
windowMs: 60_000,
alphaFloor: 1,
widthFloor: 0.25,
},
};
lines.set([
line('air', 0.002, '3d'),
line('ground', -0.002, 'draped'),
narrowed,
]);
// Whether the line at `dLon` is drawn green there, strongly, `dy`
// pixels off its middle.
const green = (dLon, dLat, dy = 0) => {
r.frame.renderNow();
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
const image = r.readPixels({
crop: {
x: Math.round(s.x),
y: Math.round(s.y) + dy,
width: 1,
height: 1,
},
});
const [red, g, blue] = image.data;
return g > red + 80 && g > blue + 80;
};
try {
await drawn(h, r);
await settled(r);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
ok(green(0.0035, dLat), `${what}: its new end drawn`);
ok(!green(-0.0035, dLat), `${what}: its old end faded`);
}
ok(green(-0.0035, 0.0035), 'narrowed: its old end drawn, unfaded');
ok(green(0.0035, 0.0035, 6), 'narrowed: its new end full width');
ok(
!green(-0.0035, 0.0035, 6),
'narrowed: its old end a quarter as wide',
);
// Two minutes on, all of it is old; back at t0 its new end is new.
r.frame.setTime(t0 + 120_000);
await drawn(h, r);
ok(!green(0.0035, 0.002), '3d: faded as time moved on');
ok(!green(0.0035, -0.002), 'draped: faded as time moved on');
r.frame.setTime(t0);
await drawn(h, r);
ok(green(0.0035, 0.002), '3d: new again back at t0');
ok(green(0.0035, -0.002), 'draped: new again back at t0');
equal(lines.size(), 3, 'never sent again');
} finally {
lines.dispose();
}
},
{ capability: 'lineAgeFade' },
),
check(
'draw.lines.timeWindow',
'a line, draped or not, draws only its part within a span of scene time, cut as the time moves on, without being sent again',
async (h, r) => {
if (h.pixels === false)
return { skip: 'this harness reads no drawn pixels' };
await overAustin(h, r);
const t0 = Date.UTC(2026, 0, 1, 18);
r.frame.setTime(t0);
// Off the row under the camera, where a ground line can leave a gap.
const at = (dLon, dLat, height) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
const lines = r.draw.lines({ id: 'conf:line-time-window' });
// West to east over two minutes, t0 at its middle; shown over the
// last 30 s, unfaded.
const line = (id, dLat, mode) => ({
id,
positions: [
at(-0.004, dLat, mode === 'draped' ? 0 : 20),
at(0.004, dLat, mode === 'draped' ? 0 : 20),
],
widthPx: 16,
mode,
style: { kind: 'solid', color: [0, 1, 0, 1] },
ageFade: {
times: [t0 - 60_000, t0 + 60_000],
windowMs: 60_000,
alphaFloor: 1,
showMs: 30_000,
},
});
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
// Whether the line at `dLon` is drawn green there, strongly.
const green = (dLon, dLat) => {
r.frame.renderNow();
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
const image = r.readPixels({
crop: {
x: Math.round(s.x),
y: Math.round(s.y),
width: 1,
height: 1,
},
});
const [red, g, blue] = image.data;
return g > red + 80 && g > blue + 80;
};
try {
await drawn(h, r);
await settled(r);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
// At t0 it shows from 30 s ago (a quarter along) to now (half).
ok(green(-0.001, dLat), `${what}: drawn within the span`);
ok(!green(0.002, dLat), `${what}: not drawn after now`);
ok(!green(-0.0035, dLat), `${what}: not drawn before the span`);
}
// 40 s on, it shows from 10 s to 40 s after t0.
r.frame.setTime(t0 + 40_000);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
ok(green(0.002, dLat), `${what}: drawn where now reached`);
ok(!green(-0.001, dLat), `${what}: cut as it grew old`);
}
r.frame.setTime(t0);
await drawn(h, r);
ok(green(-0.001, 0.002), '3d: drawn again back at t0');
ok(!green(0.002, -0.002), 'draped: cut again back at t0');
equal(lines.size(), 2, 'never sent again');
} finally {
lines.dispose();
}
},
{ capability: 'lineTimeWindow' },
),
check(
'draw.lines.breaks',
'a line in runs, draped or not, draws and picks each run, in its segment colours, and nothing between them',
async (h, r) => {
await overAustin(h, r);
// Off the row under the camera, where a ground line can leave a gap.
const at = (dLon, dLat, height) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
const lines = r.draw.lines({ id: 'conf:line-breaks' });
// Two runs, west and east, the second starting at position 2: the
// pair from position 1 to 2, across the break, is not drawn.
const lons = [-0.004, -0.002, 0.001, 0.004];
const line = (id, dLat, mode, segmentColors) => ({
id,
positions: lons.map((dLon) =>
at(dLon, dLat, mode === 'draped' ? 0 : 20),
),
breaks: [2],
widthPx: 16,
mode,
style: { kind: 'solid', color: [0, 1, 0, 1] },
...(segmentColors
? {
// The pair across the break has a colour, ignored.
segmentColors: [
[1, 0, 0, 1],
[0, 1, 0, 1],
[0, 0, 1, 1],
],
}
: {}),
});
const kinds = [
['3d', 0.003, false],
['draped', 0.001, false],
['3d coloured', -0.001, true],
['draped coloured', -0.003, true],
];
const lat = new Map(kinds.map(([what, dLat]) => [what, dLat]));
lines.set(
kinds.map(([what, dLat, coloured]) =>
line(
what,
dLat,
what.startsWith('draped') ? 'draped' : '3d',
coloured,
),
),
);
const where = (what, dLon) =>
at(dLon, lat.get(what), what.startsWith('draped') ? 0 : 20);
// The colour drawn there, strongly: 'r', 'g', 'b', or null.
const colour = (what, dLon) => {
r.frame.renderNow();
const s = r.query.project(where(what, dLon));
const image = r.readPixels({
crop: {
x: Math.round(s.x),
y: Math.round(s.y),
width: 1,
height: 1,
},
});
const [red, green, blue] = image.data;
if (red > green + 80 && red > blue + 80) return 'r';
if (green > red + 80 && green > blue + 80) return 'g';
if (blue > red + 80 && blue > green + 80) return 'b';
return null;
};
const picked = (what, dLon) => {
const s = r.query.project(where(what, dLon));
ok(s, `${what} projects`);
return r.query
.drillPick(s.x, s.y)
.filter((hit) => hit.set === 'conf:line-breaks')
.map((hit) => hit.id);
};
try {
await drawn(h, r);
await settled(r);
await drawn(h, r);
for (const [what, , coloured] of kinds) {
deepEqual(
picked(what, -0.003),
[what],
`${what}: its first run picks`,
);
deepEqual(
picked(what, -0.0005),
[],
`${what}: nothing between its runs`,
);
deepEqual(
picked(what, 0.0025),
[what],
`${what}: its second run picks`,
);
if (h.pixels === false) continue;
equal(
colour(what, -0.003),
coloured ? 'r' : 'g',
`${what}: its first run drawn`,
);
equal(
colour(what, -0.0005),
null,
`${what}: nothing drawn between its runs`,
);
equal(
colour(what, 0.0025),
coloured ? 'b' : 'g',
`${what}: its second run drawn`,
);
}
equal(lines.size(), kinds.length, 'one item a line');
} finally {
lines.dispose();
}
},
{ capability: 'lineBreaks' },
),
check(
'draw.lines.breaks.timeWindow',
'a line in runs, draped or not, whose first run is later than its second, cuts each run by its own times',
async (h, r) => {
if (!r.capabilities.has('lineBreaks'))
return { skip: 'the renderer draws no lines in runs' };
if (h.pixels === false)
return { skip: 'this harness reads no drawn pixels' };
await overAustin(h, r);
const t0 = Date.UTC(2026, 0, 1, 18);
r.frame.setTime(t0);
const at = (dLon, dLat, height) =>
h.toEcef({ lon: AUSTIN.lon + dLon, lat: AUSTIN.lat + dLat, height });
const lines = r.draw.lines({ id: 'conf:line-breaks-window' });
// Its first run, west, the last ten seconds to t0; its second, east,
// two minutes before.
const line = (id, dLat, mode) => ({
id,
positions: [-0.004, -0.001, 0.001, 0.004].map((dLon) =>
at(dLon, dLat, mode === 'draped' ? 0 : 20),
),
breaks: [2],
widthPx: 16,
mode,
style: { kind: 'solid', color: [0, 1, 0, 1] },
ageFade: {
times: [t0 - 10_000, t0, t0 - 120_000, t0 - 110_000],
windowMs: 60_000,
alphaFloor: 1,
showMs: 30_000,
},
});
lines.set([line('air', 0.002, '3d'), line('ground', -0.002, 'draped')]);
const green = (dLon, dLat) => {
r.frame.renderNow();
const s = r.query.project(at(dLon, dLat, dLat > 0 ? 20 : 0));
const image = r.readPixels({
crop: {
x: Math.round(s.x),
y: Math.round(s.y),
width: 1,
height: 1,
},
});
const [red, g, blue] = image.data;
return g > red + 80 && g > blue + 80;
};
try {
await drawn(h, r);
await settled(r);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
ok(green(-0.0025, dLat), `${what}: its later run drawn at t0`);
ok(!green(0.0025, dLat), `${what}: its earlier run too old at t0`);
ok(!green(0, dLat), `${what}: nothing between its runs`);
}
// 105 s before t0 the second run is within the span, the first
// not yet begun.
r.frame.setTime(t0 - 105_000);
await drawn(h, r);
for (const [what, dLat] of [
['3d', 0.002],
['draped', -0.002],
]) {
ok(green(0.0025, dLat), `${what}: its earlier run drawn then`);
ok(!green(-0.0025, dLat), `${what}: its later run not yet drawn`);
ok(!green(0, dLat), `${what}: still nothing between its runs`);
}
equal(lines.size(), 2, 'never sent again');
} finally {
lines.dispose();
}
},
{ capability: 'lineTimeWindow' },
),
check(
'draw.lines.segments',
'a draped line takes segment colours and shows, changed every frame in place, without stopping the frame or picks',
+6
View File
@@ -207,6 +207,12 @@ export type Capability =
| 'fields'
/** Rate-limited course easing (`IconItem.courseGlide`). */
| 'courseGlide'
/** Lines that fade with the age of their points (`LineItem.ageFade`). */
| 'lineAgeFade'
/** Lines drawn only within a span of the scene clock (`LineAgeFade.showMs`). */
| 'lineTimeWindow'
/** Lines drawn as several runs, not joined across their breaks (`LineItem.breaks`). */
| 'lineBreaks'
/** Screen-space clustering of icons. */
| 'cluster'
/** Post-processing styles. */
+66
View File
@@ -295,10 +295,74 @@ export type LineStyle =
rim?: { shade: number; widthFraction: number };
};
/**
* `lineAgeFade`: a line that fades with the age of its points, drawn by the
* renderer on the scene clock (`frame.setTime`), so a line whose points stay
* where they are is not sent again as time passes. A point's recency is
* `1 - clamp((now - time) / windowMs, 0, 1)`, its time running evenly
* between neighbouring positions, so the fade is smooth along the line, not
* stepped at its points. The line's colour (its style's, or a segment's from
* `segmentColors`) draws at its alpha times
* `mix(alphaFloor, 1, smoothstep(0, 1, recency))`, and with
* `squaredAlphaFloor` times `mix(squaredAlphaFloor, 1, recency²)` as well;
* with `widthFloor` it draws `widthPx` times `mix(widthFloor, 1, recency)`
* wide, about its path. A point at or past the window draws at the floors, a
* point at or after now at full strength. New `times` with new positions are
* an ordinary update.
*
* `lineTimeWindow`: with `showMs`, only the part of the line within `showMs`
* of now is drawn, cut along it where its interpolated time crosses: parts
* whose time is after now, or before `now - showMs`, are not drawn (nor
* picked). The cut follows the scene clock as the fade does, so a moving
* object's trail can be its whole track, sent once: drawn from `showMs` ago
* up to where the object is now. A renderer without the capability ignores
* `showMs` and draws the whole line.
*/
export interface LineAgeFade {
/** Each position's time, epoch ms on the scene clock: one per position. */
times: number[] | Float64Array;
/** The age a point fades over, ms; positive. */
windowMs: number;
/** A fully aged point's alpha multiplier, 0..1. */
alphaFloor: number;
/** A second alpha multiplier's floor, eased by recency squared, 0..1. */
squaredAlphaFloor?: number;
/** A fully aged point's width multiplier, 0..1 [1, no narrowing]. */
widthFloor?: number;
/**
* `lineTimeWindow`: draw only the part of the line from `showMs` before
* now up to now, ms; positive (`Infinity`: up to now, however old).
* [absent: the whole line]
*/
showMs?: number;
}
/**
* `lineBreaks`: a line drawn as several runs, so many lines in one style can
* be one item (thousands of moving objects' trails sent as one line, say),
* and the renderer handles one item instead of thousands. Each break is the
* index `i` of a position that starts a new run (`0 < i < positions.length`,
* strictly increasing): the segment from position `i - 1` to `i` is not
* drawn (nor picked), and the line does not join across it, each run having
* two ends of its own, capped and joined as a line of its own would be.
* `segmentColors` and `segmentShow` stay one a pair of neighbouring
* positions (`j`: from position `j` to `j + 1`), so a pair across a break
* has an entry that is ignored; `ageFade.times` stays one a position; and
* `revealFraction` runs along the runs, in order, as one length (the gaps
* between them have none). A renderer without the capability is never sent
* `breaks`: its lines are sent one item a run instead.
*/
export type LineBreaks = number[] | Uint32Array;
export interface LineItem {
id: string;
/** ECEF positions, or packed `x, y, z` triples. */
positions: Ecef[] | Float64Array;
/**
* `lineBreaks`: the positions that start a new run of the line
* (`LineBreaks`). [absent or empty: one run]
*/
breaks?: LineBreaks;
widthPx: number;
/**
* `3d`: straight in space; `geodesic`: along the ellipsoid; `draped`: on
@@ -321,6 +385,8 @@ export interface LineItem {
segmentShow?: boolean[];
/** Draw only the first fraction of the line, 0..1. */
revealFraction?: number;
/** `lineAgeFade`: fade the line with the age of its points (`LineAgeFade`). */
ageFade?: LineAgeFade;
/** Positions are in a frame rotating with the sky (orbits). */
frame?: 'fixed' | 'inertial';
meta?: Meta;
+3
View File
@@ -41,6 +41,9 @@ export const CAPABILITIES = Object.freeze([
'meshes',
'fields',
'courseGlide',
'lineAgeFade',
'lineTimeWindow',
'lineBreaks',
'cluster',
'styles',
'bloom',
+41 -2
View File
@@ -1330,9 +1330,19 @@ export function createStubRenderer(options = {}) {
return out;
}
/**
* The positions that start a run of a line in runs (`lineBreaks`), or
* null: nothing is drawn between two runs.
*/
const runStarts = (item) =>
capabilities.has('lineBreaks') && item.breaks?.length
? new Set(item.breaks)
: null;
/**
* A line's positions as ECEF, cut at its `revealFraction` of length (as
* drawn straight between its positions).
* drawn straight between its positions, along its runs, the gaps between
* them having none).
*/
function revealedLine(item) {
const flat = item.positions instanceof Float64Array;
@@ -1350,7 +1360,10 @@ export function createStubRenderer(options = {}) {
);
const fraction = item.revealFraction;
if (fraction === undefined || fraction >= 1) return points;
const at = alongLength(points, fraction);
const starts = runStarts(item);
const at = starts
? alongRuns(points, starts, fraction)
: alongLength(points, fraction);
if (!at) return [];
const { index, t } = at;
return [
@@ -1359,17 +1372,43 @@ export function createStubRenderer(options = {}) {
];
}
/**
* `alongLength` for a line in runs: the segment a fraction of its runs'
* length ends on, and how far along it, the segments between runs
* measuring nothing.
*/
function alongRuns(points, starts, fraction) {
if (!(fraction > 0) || points.length < 2) return null;
const lengths = [];
for (let i = 0; i + 1 < points.length; i++)
lengths.push(
starts.has(i + 1) ? 0 : magnitude(sub(points[i + 1], points[i])),
);
const total = lengths.reduce((sum, length) => sum + length, 0);
if (!(total > 0)) return null;
let left = fraction * total;
for (let i = 0; i < lengths.length; i++) {
if (lengths[i] > 0 && left <= lengths[i])
return { index: i, t: left / lengths[i] };
left -= lengths[i];
}
return { index: lengths.length - 1, t: 1 };
}
/**
* Where a line is under the pixel `(x, y)`: the nearest point of a
* drawn segment within half its width (and `slack`) of it, or null.
*/
function lineHit(item, x, y, slack) {
const points = revealedLine(item);
const starts = runStarts(item);
const reach = (item.widthPx ?? 1) / 2 + slack;
let best = null;
let bestDistance = Infinity;
for (let i = 0; i + 1 < points.length; i++) {
if (item.segmentShow?.[i] === false) continue;
// Nothing is drawn between two runs.
if (starts?.has(i + 1)) continue;
const a = points[i];
const b = points[i + 1];
if (isOccluded(a) && isOccluded(b)) continue;
+4 -1
View File
@@ -20,7 +20,7 @@ test('the stub passes the conformance suite', async () => {
.filter((r) => r.status === 'skip')
.map((r) => r.id);
// It draws only models into pixels, so the sweep's, a lit shape's, a line outline's, a
// split line's, a draped outlined line's and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
// split line's, a draped outlined line's, an aged line's, a time-windowed line's (in runs too) and the blends' (over a drawn shape), video tiles', the weather's pixels (drawn, and by scene time) and an encoded capture go unread; its camera takes no user gestures: the drag and wheel scripts are for a
// camera that does (a controller over it, say).
assert.deepEqual(skipped, [
'effects.screenModulation.pixels',
@@ -29,6 +29,9 @@ test('the stub passes the conformance suite', async () => {
'draw.sets.blend',
'draw.lines.split',
'draw.lines.outlineDraped',
'draw.lines.ageFade',
'draw.lines.timeWindow',
'draw.lines.breaks.timeWindow',
'draw.models.blend',
'draw.models.paint',
'globe.imagery.video',
-44
View File
@@ -2150,50 +2150,6 @@ test('a hold resumed partway waits for a clip that starts again, else only its r
assert.deepEqual(await hold(0), [2000]);
});
/** Drive frame-by-frame camera motion headlessly for one test. */
function installAnimationFrames() {
const original = globalThis.requestAnimationFrame;
const originalCancel = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(callback, 16);
globalThis.cancelAnimationFrame = (handle) => clearTimeout(handle);
return () => {
globalThis.requestAnimationFrame = original;
globalThis.cancelAnimationFrame = originalCancel;
};
}
test('a run resumed inside a flight goes on from that point of the path and clock', async () => {
const { director, viewer, restore } = makeDirector();
const restoreFrames = installAnimationFrames();
const clock = [];
director.subscribeSceneClock((snap) => clock.push(snap));
const poses = [];
const setView = director._setCameraView.bind(director);
director._setCameraView = (pose) => {
poses.push(pose);
return setView(pose);
};
try {
// 0.75 of a 0.4 s scene: halfway along shot B's 0.2 s flight.
const run = director.startScene('scene-1', {
single: true,
fromProgress: 0.75,
preview: false,
});
await settle(40);
const first = clock.find((snap) => snap.running);
assert.equal(first.shotId, 'shot-b', 'starts in the shot that moment is in');
assert.ok(Math.abs(first.sceneElapsedSec - 0.3) < 1e-9, 'the clock starts at the moment');
// The first frame is the seek's own framing, halfway from A to B.
assert.ok(poses.length, 'the camera is driven from where it is');
assert.ok(Math.abs(poses[0].lat - -10) < 0.5, 'halfway from A to B');
assert.deepEqual(await run, { started: true, shots: 1 });
assert.equal(poses.at(-1).lat, -30, 'and ends on shot B');
assert.equal(viewer.flights.length, 0, 'no fresh flight from the shot start');
assert.equal(director._lastRun.wasCancelled, false);
} finally { await director.destroy(); restoreFrames(); restore(); }
});
test('a run resumed inside a hold plays its layers on from the seek’s state and waits only the rest of it', async () => {
const project = structuredClone(PROJECT_FIXTURE);
project.scenes[0].shots[0].holdSec = 0.6;
+3 -1
View File
@@ -173,7 +173,8 @@ export const getCyclones = defineTool({
title: 'Tropical cyclones',
description:
'Active tropical cyclones from the NOAA National Hurricane Center and ' +
'Central Pacific Hurricane Center, optionally limited to an area.',
'Central Pacific Hurricane Center, and from the Joint Typhoon Warning ' +
'Center elsewhere, optionally limited to an area.',
inputSchema: {
type: 'object',
properties: { area: AREA_SCHEMA },
@@ -204,6 +205,7 @@ export const getCyclones = defineTool({
name: storm.name,
classification: storm.classification,
basin: storm.basin,
agency: storm.agency ?? 'nhc',
lat: storm.position.latitude,
lon: storm.position.longitude,
position_at: storm.positionAt,
-29
View File
@@ -908,9 +908,6 @@ export class StyleManager extends ShellFacade {
this._panelChrome.setPanelCollapsed(panelId, collapsed, options),
readPanel: (panel) => this._panelChrome._shownPanel(panel),
onSheetsClosed: () => this._syncShareState(),
onTabOpened: (sheet) => {
void this._onMobileTabOpened(sheet);
},
publish: (view) =>
useDisplayStore(applicationPinia()).publishPhoneShell(view),
afterPublish: (callback) => {
@@ -919,32 +916,6 @@ export class StyleManager extends ShellFacade {
});
}
/** Reveal a tracked aircraft through Contacts when its phone tab is opened. */
async _onMobileTabOpened(sheet) {
const context = this.getContextModeState();
if (
sheet !== 'context' ||
this._disposed ||
!context ||
context.mode ||
context.changing ||
context.entering ||
!this.getAircraftTrackingTarget()
)
return false;
try {
const result = await this.setContextMode('contacts');
if (result?.ok) return true;
if (result?.cancelled || this._disposed) return false;
} catch {
if (this._disposed) return false;
}
this._showToast(
t('Contacts could not complete the requested transition; try again'),
);
return false;
}
/**
* Renders the owner-approved map stack chip row from the matching controller
* entries. Cesium ion/Bing chips remain keyboard-focusable but unavailable,
+57 -8
View File
@@ -9,7 +9,13 @@ import {
subjectEntryAllowed,
} from '../contextModePolicy.js';
import { cockpitSubjectProviders } from '../cockpitSubjectProviders.js';
import { formatAwarenessLabel } from '../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
aircraftClassMatches,
formatAwarenessLabel,
} from '../data/militaryAwarenessEngine.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
import { findCamera } from '../render/rendererOf.js';
import { enterCockpitWithTracking } from '../cockpitTracking.js';
import { cockpitVisionModeForStyle } from '../cockpitVisionPolicy.js';
import { readEntityRecord } from '../data/entityRecords.js';
@@ -352,13 +358,41 @@ export class CockpitCoordinator {
};
}
/**
* Where a requested-layer entry searches from: the aircraft the camera
* follows, else the ground under the camera.
* @param {{layerId: string}|null} currentTarget The tracked aircraft.
* @returns {{x: number, y: number, z: number}|null}
*/
_cockpitEntrySearchOrigin(currentTarget) {
const { flightsLayer, militaryFlightsLayer } = this.services;
const layer =
currentTarget?.layerId === 'military'
? militaryFlightsLayer
: currentTarget?.layerId === 'flights'
? flightsLayer
: null;
const subject = layer?.getTrackedSubject?.();
if (subject?.position) return subject.position;
const pose = findCamera(this.viewer)?.pose?.();
if (!Number.isFinite(pose?.lat) || !Number.isFinite(pose?.lon)) return null;
return fromDegreesInto(pose.lon, pose.lat, 0, { x: 0, y: 0, z: 0 });
}
/**
* Retarget a voice entry to the requested layer and class before entering.
* It searches the aircraft that layer shows, under the person's own
* filters, nearest first, from the followed aircraft or the camera, and
* follows the nearest match; the aircraft already followed counts when it
* matches. It needs nothing from Contacts.
*/
_retargetCockpitEntryLayer({
targetLayer,
aircraftClass,
currentTarget,
selectedTarget,
}) {
const { militaryAwarenessLayer } = this.services;
const { flightsLayer, militaryFlightsLayer } = this.services;
if (!['flights', 'military'].includes(targetLayer)) {
return {
ok: false,
@@ -370,12 +404,27 @@ export class CockpitCoordinator {
const alreadyOnLayer = activeLayer === targetLayer;
if (alreadyOnLayer && !aircraftClass)
return { ok: true, retargeted: false };
const moved = militaryAwarenessLayer?.navigateNext
? !!militaryAwarenessLayer.navigateNext({
targetLayer,
aircraftClass,
origin: 'voice',
})
const layer =
targetLayer === 'military' ? militaryFlightsLayer : flightsLayer;
const origin = this._cockpitEntrySearchOrigin(currentTarget);
const nearby =
origin && typeof layer?.getNearby === 'function'
? layer.getNearby(
origin,
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
targetLayer === 'military' ? 5000 : 25000,
)
: [];
const match = nearby.find(
(item) => item?.icao24 && aircraftClassMatches(item, aircraftClass),
);
const followed =
match &&
currentTarget?.layerId === targetLayer &&
String(currentTarget.id) === String(match.icao24);
if (followed) return { ok: true, retargeted: false };
const moved = match
? !!layer.trackById?.(match.icao24, { origin: 'voice' })
: false;
if (moved) return { ok: true, retargeted: true };
// A filter that matched nothing still enters, as long as the layer is
+76
View File
@@ -869,3 +869,79 @@ test('a malformed provider is left out and the built-in kinds are unchanged', as
assert.equal(cockpit.enter(), true);
assert.equal(cockpit.subjectKind, 'aircraft');
});
// A requested-layer entry finds its aircraft in that layer, from the
// aircraft the camera follows; it never asks Contacts.
function retargetFixture(t, nearby) {
const { coordinator } = fixture(t, {
enabled: ['flights', 'military'],
tracked: { layerId: 'flights', info: CIVIL },
});
const tracked = [];
const searches = [];
coordinator.services.militaryAwarenessLayer.navigateNext = () =>
assert.fail('entry must not navigate through Contacts');
coordinator.services.flightsLayer.getTrackedSubject = () => ({
layerId: 'flights',
id: CIVIL.icao24,
position: { x: 1, y: 2, z: 3 },
});
coordinator.services.militaryFlightsLayer.getNearby = (...args) => {
searches.push(args);
return nearby;
};
coordinator.services.militaryFlightsLayer.trackById = (id, options) => {
tracked.push([id, options.origin]);
return true;
};
return { coordinator, tracked, searches };
}
test('a voice entry asking for a military class follows the nearest match without Contacts', (t) => {
const { coordinator, tracked, searches } = retargetFixture(t, [
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 20 },
{ icao24: 'helo2', aircraftClass: 'helicopter', distance: 30 },
]);
const result = coordinator._retargetCockpitEntryLayer({
targetLayer: 'military',
aircraftClass: 'helicopter',
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
selectedTarget: null,
});
assert.deepEqual(result, { ok: true, retargeted: true });
assert.deepEqual(tracked, [['helo1', 'voice']]);
// Searched from the followed aircraft, among the aircraft the person's
// filters show: never the hidden ones.
assert.deepEqual(searches[0][0], { x: 1, y: 2, z: 3 });
assert.equal(searches[0][3], undefined);
});
test('a voice entry whose followed aircraft already matches stays on it', (t) => {
const { coordinator, tracked } = retargetFixture(t, [
{ icao24: 'helo1', aircraftClass: 'helicopter', distance: 0 },
]);
const result = coordinator._retargetCockpitEntryLayer({
targetLayer: 'military',
aircraftClass: 'helicopter',
currentTarget: { layerId: 'military', id: 'helo1' },
selectedTarget: null,
});
assert.deepEqual(result, { ok: true, retargeted: false });
assert.deepEqual(tracked, []);
});
test('a voice entry with no matching aircraft says so and follows nothing', (t) => {
const { coordinator, tracked } = retargetFixture(t, [
{ icao24: 'jet1', aircraftClass: 'fighter', distance: 10 },
]);
const result = coordinator._retargetCockpitEntryLayer({
targetLayer: 'military',
aircraftClass: 'helicopter',
currentTarget: { layerId: 'flights', id: CIVIL.icao24 },
selectedTarget: null,
});
assert.equal(result.ok, false);
assert.match(result.error, /No helicopter military contact is available/);
assert.deepEqual(tracked, []);
});
-4
View File
@@ -98,8 +98,6 @@ function currentSheetOf(body) {
* @param {(callback: () => void) => number} [input.requestFrame]
* @param {() => void} [input.onSheetsClosed] Runs after the last sheet closes
* and its panels are put back (e.g. to refresh the share link).
* @param {(sheet: string) => void} [input.onTabOpened] Runs only when the user
* opens a sheet from its tab, never on close or programmatic presentation.
* @param {(view: ?{enabled: boolean, sheet: string|null, tabs: typeof MOBILE_TABS}) => void} [input.publish]
* Receives the tab bar: whether the shell is on, the open sheet and the
* tabs; null once the shell is destroyed.
@@ -117,7 +115,6 @@ export function initMobileShell({
ResizeObserverImpl = globalThis.ResizeObserver,
requestFrame = globalThis.requestAnimationFrame?.bind(globalThis),
onSheetsClosed = () => {},
onTabOpened = () => {},
publish = () => {},
afterPublish = (callback) => callback(),
} = {}) {
@@ -351,7 +348,6 @@ export function initMobileShell({
// Closing from the tab bar returns focus to the tab that was pressed.
if (!sheet) returnFocus = button;
setSheet(sheet);
if (sheet && currentSheetOf(body) === sheet) onTabOpened(sheet);
});
// Touch events let native scrolling continue until a downward pull at the
// top is intentional. Pointer capture/touch-action:none would also seize
+11 -155
View File
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { StyleManager } from './applicationShell.js';
import { ContextControls } from './contextControls.js';
import {
MOBILE_SHEET_PANELS,
MOBILE_TABS,
@@ -10,7 +9,6 @@ import {
nextSheet,
sheetForPanelId,
} from './mobileShell.js';
import { withEntityRecord } from '../data/entityRecords.js';
function element(tag, document) {
const node = new EventTarget();
@@ -111,12 +109,7 @@ function element(tag, document) {
const PANEL_IDS = [...new Set(Object.values(MOBILE_SHEET_PANELS).flat())];
function fixture({
mobile = true,
expanded = [],
onTabOpened = () => {},
afterPublish,
} = {}) {
function fixture({ mobile = true, expanded = [], afterPublish } = {}) {
const document = new EventTarget();
document.ids = new Map();
document.createElement = (tag) => element(tag, document);
@@ -208,7 +201,6 @@ function fixture({
}
const shell = initMobileShell({
documentRef: document,
onTabOpened,
publish,
afterPublish,
matchMedia: () => media,
@@ -587,7 +579,9 @@ test('the phone shell keeps the required attribution visible', () => {
};
const lift = (block) =>
Number(
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px \+ var\(--world-timeline-lift, 0px\)\)/.exec(block)?.[1],
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px \+ var\(--world-timeline-lift, 0px\)\)/.exec(
block,
)?.[1],
);
const z = (block) => Number(/z-index: (\d+);/.exec(block)?.[1]);
const idleCredit = rule(
@@ -803,157 +797,19 @@ test('touches outside the active sheet and destroyed listeners cannot dismiss or
assert.equal(shell.getSheet(), null);
});
test('the tab-open callback reports only a successful manual opening', () => {
const opened = [];
const phone = fixture({ onTabOpened: (sheet) => opened.push(sheet) });
phone.shell.setSheet('context');
assert.deepEqual(opened, []);
phone.press('context');
assert.deepEqual(opened, [], 'closing is not a new context request');
phone.press('context');
assert.deepEqual(opened, ['context']);
phone.setBodyClass('cockpit-mode');
test('opening the Context tab only presents its panel and starts no Context mode', () => {
const phone = fixture();
phone.press('context');
assert.equal(phone.shell.getSheet(), 'context');
assert.deepEqual(
opened,
['context'],
'blocked sheets cannot activate a mode',
phone.calls.map(({ panelId, collapsed }) => ({ panelId, collapsed })),
[{ panelId: 'global-context-panel', collapsed: false }],
);
// The application shell no longer starts Contacts when the tab opens.
assert.equal(StyleManager.prototype._onMobileTabOpened, undefined);
phone.shell.destroy();
});
test('manual Context opens the existing transaction without disabling the tracked aircraft', async () => {
const calls = [];
const tracked = { layerId: 'flights', icao24: 'abc123', callsign: 'EJA225' };
const viewer = { trackedEntity: withEntityRecord({}, { trackedId: 'flights:abc123' }) };
const entity = viewer.trackedEntity;
const enabled = new Set(['flights', 'weather']);
const controls = new ContextControls({
elements: {},
installations: {},
actions: {
getCockpit: () => null,
claimVisualAuthority: () => calls.push('claim'),
syncDetection() {},
scheduleLayout() {},
showToast() {},
},
});
controls.connect({
layers: new Map(
['flights', 'weather', 'military-awareness'].map((id) => [id, {}]),
),
getEnabledLayerIds: () => [...enabled],
getLayerParams: () => ({}),
isEffectivelyEnabled: (id) => enabled.has(id),
isEnabled: (id) => enabled.has(id),
setLayerParams: (id, params) => calls.push({ id, params }),
setEnabled: async (id, value) => {
calls.push({ id, value });
if (!value) enabled.delete(id);
if (id === 'flights' && !value) viewer.trackedEntity = null;
return true;
},
_setEnabledWithIntent: (id, value) => {
calls.push({ id, value });
enabled.add(id);
return { intentEpoch: 1, promise: Promise.resolve(true) };
},
});
const shell = {
cockpitView: {
readAircraftInfo: () => (viewer.trackedEntity ? tracked : null),
},
getAircraftTrackingTarget: StyleManager.prototype.getAircraftTrackingTarget,
getContextModeState: () => controls.getContextModeState(),
setContextMode: (mode) => controls.setContextMode(mode),
_showToast: () => assert.fail('successful entry must not report a failure'),
};
try {
assert.equal(
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
true,
);
assert.equal(controls.getContextModeState().mode, 'flights');
assert.equal(viewer.trackedEntity, entity);
assert.deepEqual(shell.getAircraftTrackingTarget(), {
layerId: 'flights',
id: 'abc123',
});
assert.ok(enabled.has('flights'));
assert.ok(
calls.some(
(call) => call.id === 'military-awareness' && call.value === true,
),
);
assert.ok(!calls.some((call) => call.id === 'flights'));
const count = calls.length;
assert.equal(
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
false,
);
assert.equal(
calls.length,
count,
'an already active Contacts session is not restarted',
);
} finally {
controls.stop();
controls.disconnect();
}
});
test('manual Context respects an active mode, busy transitions, missing tracks and disposal', async () => {
for (const state of [
{ mode: 'flights' },
{ changing: true },
{ entering: 'flights' },
{ noTrack: true },
{ disposed: true },
{ sheet: 'layers' },
]) {
const shell = {
_disposed: state.disposed,
getContextModeState: () => state,
getAircraftTrackingTarget: () =>
state.noTrack ? null : { layerId: 'flights', id: 'abc123' },
setContextMode: () =>
assert.fail('guarded tab must not mutate Context or tracking'),
};
assert.equal(
await StyleManager.prototype._onMobileTabOpened.call(
shell,
state.sheet || 'context',
),
false,
);
}
});
test('failed mobile Contacts entry uses the existing notice and cancelled/disposed entries stay quiet', async () => {
for (const outcome of ['failure', 'throw', 'cancelled', 'disposed']) {
const notices = [];
const shell = {
getContextModeState: () => ({ mode: null }),
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'abc123' }),
setContextMode: async () => {
if (outcome === 'throw') throw new Error('source unavailable');
if (outcome === 'disposed') shell._disposed = true;
return { ok: false, cancelled: outcome === 'cancelled' };
},
_showToast: (message) => notices.push(message),
};
assert.equal(
await StyleManager.prototype._onMobileTabOpened.call(shell, 'context'),
false,
);
assert.equal(
notices.length,
['failure', 'throw'].includes(outcome) ? 1 : 0,
);
}
});
test('a slow downward pull is claimed before Android native scroll takes ownership', () => {
const { document, shell, press } = fixture();
press('layers');
+40
View File
@@ -357,6 +357,13 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
* @param {boolean} [options.fly] Also fly the camera to it.
* @returns {boolean} Whether a card could be made.
*/
/**
* Counts card selections and clears, so a selection that was asked for
* before a newer one can tell it came too late.
*/
let generation = 0;
const selectionGeneration = () => generation;
/** Things that move are followed as soon as they are picked. */
const AUTO_FOLLOW = new Set(['flights', 'military', 'satellites']);
/**
@@ -374,6 +381,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
*/
function select(identity, { fly = false, follow: autoFollow = true } = {}) {
if (!read(identity)) return false;
generation++;
stopLocating();
away.value = false;
reference =
@@ -403,6 +411,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
}
function clear() {
generation++;
if (following.value) shell.value?.letGo?.(card.value);
following.value = null;
asked = null;
@@ -451,6 +460,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
locate,
connect,
select,
selectionGeneration,
clear,
refresh,
flyTo,
@@ -477,3 +487,33 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => {
askAboutView,
};
});
/**
* Opens what a voice or chat action selected in the Context panel, as a click
* on it does (`src/ui/entityContextBridge.js` selects the same way): its card
* opens, and the panel with it. The app hands it to voice, which reads
* `generation()` when a selection is asked and passes it back as `since`.
* The action has already selected or followed the item in its own layer, so
* the card does not follow it again (a click on a flight does not either). A
* card picked or cleared since the action was asked stays, and nothing opens
* in Cockpit, where Context is hidden.
* @param {import('pinia').Pinia} pinia
* @returns {{generation: () => number, show: (identity: {layerId: string, id: string|number, label?: string, lat?: number, lon?: number}, options?: {since?: number|null, cockpitActive?: boolean}) => boolean}}
*/
export function createContextCardOpener(pinia) {
const store = () => useEntityCardStore(pinia);
return {
generation: () => store().selectionGeneration(),
show(identity, { since = null, cockpitActive = false } = {}) {
if (!identity?.layerId || identity.id == null || identity.id === '')
return false;
if (cockpitActive) return false;
if (since !== null && store().selectionGeneration() !== since)
return false;
return store().select(
{ ...identity, id: String(identity.id) },
{ follow: false },
);
},
};
}
+13 -1
View File
@@ -28,8 +28,20 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(
.hud-readout:has(> #hud-mode) {
display: none;
}
/* The globe actions sit on the title row, level with the title, with the
loading line under them (status.css). Narrower, where the row would reach
the title, they drop to the HUD's top rows and the loading line drops
with them, so it never covers the actions. */
#top-center-actions {
top: clamp(86px, 9.55vh, 108px);
top: 32px;
}
@media (max-width: 1179px) {
#top-center-actions {
top: clamp(86px, 9.55vh, 108px);
}
#global-loading-status {
top: calc(clamp(86px, 9.55vh, 108px) + 42px);
}
}
#left-panel-stack.layout-focus {
bottom: var(--left-stack-safe-bottom, 4vh);
+113 -73
View File
@@ -1210,13 +1210,28 @@ export function createGevActionRunner({
args.type ||
args.filterType,
);
let contextChangedForEntry = false;
let priorContextMode = null;
let rollbackTarget = null;
if (
action === 'enter' &&
typeof styleManager.setContextMode === 'function'
) {
// Entry changes no Context mode, layer or detection setting, as the
// COCKPIT button does not. The one exception is a military entry while
// Military Flights is off: that layer is switched on as a plain layer
// the person can switch off, and switched off again if entry fails.
// Contacts stays as it is.
let rollbackTarget;
let switchedOn = null;
// A switch-off undoing this action's own switch-on; it runs even for a
// turn that went stale, so a failed entry leaves no layer behind.
const switchBackOff = async () => {
if (!switchedOn) return null;
return runGevAction(
'set_layer_visibility',
{ layerId: switchedOn, enabled: false },
{},
);
};
const failed = async (result) => {
const layerRollback = await switchBackOff();
return layerRollback ? { ...result, layerRollback } : result;
};
if (action === 'enter') {
if (!current()) {
return {
ok: false,
@@ -1227,51 +1242,37 @@ export function createGevActionRunner({
};
}
rollbackTarget = styleManager.getAircraftTrackingTarget?.() || null;
const contextState =
typeof styleManager.getContextModeState === 'function'
? styleManager.getContextModeState()
: {};
priorContextMode = contextState?.mode || null;
const contactsReady =
contextState?.mode === 'flights' &&
contextState?.active !== false &&
contextState?.changing !== true;
if (!contactsReady) {
const contextResult = await styleManager.setContextMode('flights', {
signal: runOptions.signal,
isCurrent: runOptions.isCurrent,
// Cockpit entry establishes Contacts as its own precondition. That
// is internal choreography, not an operator Context request, so it
// must stay inert: claiming here would cancel a pending shared
// style/detection restore the operator never overrode.
claimVisualAuthority: false,
});
contextChangedForEntry = contextResult?.ok === true;
if (contextResult?.ok !== true || !current()) {
const contextRollback = contextChangedForEntry
? await styleManager.setContextMode(priorContextMode, {
claimVisualAuthority: false,
})
: null;
return {
if (
targetLayer === 'military' &&
dataManager.layers?.has?.('military') &&
!dataManager.isEnabled?.('military')
) {
const layer = await runGevAction(
'set_layer_visibility',
{ layerId: 'military', enabled: true },
runOptions,
);
if (layer?.ok === true) switchedOn = 'military';
// The search needs the layer's aircraft, which arrive with its
// first data, not with the switch.
if (layer?.ok === true && current())
await waitForLayerFirstData(dataManager, 'military', runOptions);
if (layer?.ok !== true || !current()) {
return failed({
ok: false,
action: 'control_cockpit',
cancelled: !current() || Boolean(contextResult?.cancelled),
cancelled: !current() || Boolean(layer?.cancelled),
error:
contextResult?.error ||
'Contacts context could not be established for Cockpit entry',
context: contextResult
? withContextModeVocabulary(contextResult)
: null,
contextRollback: withContextModeVocabulary(contextRollback),
layer?.error ||
(layer?.ok === true
? 'Cockpit entry was cancelled before it could run'
: 'Military Flights could not be switched on'),
layer,
state: styleManager.getCockpitState?.() || null,
};
});
}
}
}
// Contacts activation can adopt a newer explicit aircraft selection.
// Sample only after that transaction settles so an older voice snapshot
// cannot overwrite the operator's newer choice.
const selectedTarget =
action === 'enter' ? selectedCockpitTarget(dataManager) : null;
let cockpitResult;
@@ -1291,30 +1292,7 @@ export function createGevActionRunner({
state: styleManager.getCockpitState?.() || null,
};
}
if (
action === 'enter' &&
cockpitResult?.ok !== true &&
contextChangedForEntry
) {
const contextRollback = await styleManager.setContextMode(
priorContextMode,
{
// Undoing this action's own precondition — still choreography.
claimVisualAuthority: false,
...(current()
? {
signal: runOptions.signal,
isCurrent: runOptions.isCurrent,
}
: {}),
},
);
return {
...cockpitResult,
contextRollback: withContextModeVocabulary(contextRollback),
};
}
return cockpitResult;
return cockpitResult?.ok === true ? cockpitResult : failed(cockpitResult);
}
if (name === 'show_data_layers_menu') {
@@ -2903,6 +2881,62 @@ export function formatTrackedEntityLabel(found, query = '') {
);
}
/**
* Wait for a layer just switched on to report its first data: its stats name
* an update, or its next update lands. Bounded by that update, the layer
* failing or going off, and the request's own cancellation.
* @returns {Promise<boolean>} Whether the layer has reported data.
*/
function waitForLayerFirstData(
dataManager,
layerId,
{ signal = null, isCurrent = null } = {},
) {
const reported = () => {
try {
const stats = dataManager.layers?.get?.(layerId)?.module?.getStats?.();
return stats?.lastUpdate != null;
} catch {
return false;
}
};
if (reported()) return Promise.resolve(true);
if (typeof dataManager.subscribeActivity !== 'function' || signal?.aborted)
return Promise.resolve(false);
return new Promise((resolve) => {
const offs = [];
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
for (const off of offs) off?.();
resolve(value);
};
const onAbort = () => done(false);
signal?.addEventListener?.('abort', onAbort, { once: true });
offs.push(() => signal?.removeEventListener?.('abort', onAbort));
offs.push(
dataManager.subscribeActivity((change) => {
if (
!dataManager.isEnabled?.(layerId) ||
(typeof isCurrent === 'function' && !isCurrent())
)
return done(false);
if (reported()) return done(true);
if (change?.type === 'data-updated' && change.layerId === layerId)
done(reported());
}),
);
offs.push(
dataManager.subscribe?.((change) => {
if (change?.layerId !== layerId) return;
if (change.type === 'refresh-failed' || change.enabled === false)
done(false);
}),
);
});
}
/** Finds and tracks/selects an entity by spoken query across layer families. */
async function trackEntity(
viewer,
@@ -3017,8 +3051,15 @@ async function trackEntity(
'track_entity',
() => {
let trackedOk = false;
// The id the layer selects by, which also names it in Context.
const id =
family.kind === 'vessel'
? (found.id ?? found.mmsi)
: family.kind === 'satellite'
? found.noradId
: found.icao24;
if (family.kind === 'vessel') {
trackedOk = !!module.selectById?.(found.id ?? found.mmsi);
trackedOk = !!module.selectById?.(id);
flyToLandmark(viewer, found.latitude, found.longitude, {
range: 6000,
pitch: -45,
@@ -3026,10 +3067,8 @@ async function trackEntity(
buildingHeight: 0,
duration: 2.0,
});
} else if (family.kind === 'satellite') {
trackedOk = !!module.trackById?.(found.noradId, { origin: 'voice' });
} else {
trackedOk = !!module.trackById?.(found.icao24, { origin: 'voice' });
trackedOk = !!module.trackById?.(id, { origin: 'voice' });
}
return {
@@ -3037,6 +3076,7 @@ async function trackEntity(
action: 'track_entity',
layerId: family.layerId,
kind: family.kind,
id: id == null ? null : String(id),
// Aircraft follow the flight layers' label convention (callsign →
// registration → icao24) so the spoken name matches what the UI shows;
// `registration` is absent on vessels/satellites and simply falls
+270 -275
View File
@@ -144,6 +144,9 @@ test('track_entity runner narrates a callsign-less aircraft by its registration'
`${layerId} narration must speak the registration, not the ICAO hex`,
);
assert.equal(trackedId, 'ae1fa4', `${layerId} must still TRACK by icao24`);
// The result names what it tracked, so Context can show it.
assert.equal(result.id, 'ae1fa4');
assert.equal(result.layerId, layerId);
}
});
@@ -2974,7 +2977,7 @@ test('control_cockpit resolves spoken TR-3B spellings to the tr3b class id', asy
}
});
test('control_cockpit delegates selected-flight adoption to the canonical cockpit owner', async () => {
test('control_cockpit delegates selected-flight adoption to the canonical cockpit owner and leaves Context alone', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
@@ -2995,16 +2998,7 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
changing: false,
};
},
async setContextMode(mode) {
calls.push({ action: 'context', mode });
contextActive = mode === 'flights';
return {
ok: contextActive,
mode,
active: contextActive,
changing: false,
};
},
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(action, options) {
calls.push({ action, selectedTarget: options.selectedTarget });
return {
@@ -3040,7 +3034,6 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, true);
assert.deepEqual(calls, [
{ action: 'context', mode: 'flights' },
{
action: 'enter',
selectedTarget: { layerId: 'flights', id: 'abc123' },
@@ -3048,46 +3041,6 @@ test('control_cockpit delegates selected-flight adoption to the canonical cockpi
]);
});
test('control_cockpit does not mutate selection when Contacts entry fails', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const styleManager = {
getContextModeState: () => ({ mode: null, active: false, changing: false }),
setContextMode: async () => ({
ok: false,
mode: null,
active: false,
changing: false,
error: 'Contacts activation failed',
}),
controlCockpit: () =>
assert.fail('Cockpit must not run after failed Contacts entry'),
getCockpitState: () => ({ active: false }),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map(),
isEnabled: () => false,
getAll: () => [],
},
});
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.equal(result.error, 'Contacts activation failed');
assert.deepEqual(result.state, { active: false });
});
test('control_cockpit cancellation is inert when Contacts is already active', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -3134,77 +3087,7 @@ test('control_cockpit cancellation is inert when Contacts is already active', as
assert.deepEqual(result.state, { active: false });
});
test('control_cockpit rolls Contacts back when the turn becomes stale at commit', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const calls = [];
let requestCurrent = true;
let contextMode = null;
const styleManager = {
getContextModeState: () => ({
mode: contextMode,
active: Boolean(contextMode),
changing: false,
}),
async setContextMode(mode, options) {
calls.push({ mode, options: options || null });
contextMode = mode;
if (mode === 'flights') requestCurrent = false;
return { ok: true, mode, active: Boolean(mode), changing: false };
},
controlCockpit: () => assert.fail('stale turn must not enter Cockpit'),
getCockpitState: () => ({ active: false }),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map(),
isEnabled: () => false,
getAll: () => [],
},
});
const result = await runner(
'control_cockpit',
{ action: 'enter' },
{
isCurrent: () => requestCurrent,
},
);
assert.equal(result.ok, false);
assert.equal(result.cancelled, true);
assert.equal(contextMode, null);
assert.deepEqual(
calls.map(({ mode }) => mode),
['flights', null],
);
assert.equal(
calls[1].options?.signal ?? null,
null,
'rollback must not inherit stale cancellation authority',
);
assert.equal(
calls[1].options?.isCurrent ?? null,
null,
'rollback must not inherit a stale currency probe',
);
assert.equal(
calls[1].options?.claimVisualAuthority,
false,
'rollback is cockpit choreography and must not claim the visual lane',
);
});
test('control_cockpit adopts the newest selection after Contacts settles', async () => {
test('control_cockpit enters on the current selection and keeps the prior track for rollback', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
@@ -3229,16 +3112,15 @@ test('control_cockpit adopts the newest selection after Contacts settles', async
);
contextStore.selectedEntityId = first.id;
contextStore.selectedAt = Date.now();
// A newer selection before the turn runs is the one entered.
contextStore.selectedEntityId = second.id;
contextStore.selectedAt = Date.now();
let receivedTarget = null;
let receivedRollbackTarget = null;
const styleManager = {
getAircraftTrackingTarget: () => ({ layerId: 'military', id: 'prior' }),
getContextModeState: () => ({ mode: null, active: false, changing: false }),
async setContextMode() {
contextStore.selectedEntityId = second.id;
contextStore.selectedAt = Date.now();
return { ok: true, mode: 'flights', active: true, changing: false };
},
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(_action, options) {
receivedTarget = options.selectedTarget;
receivedRollbackTarget = options.rollbackTarget;
@@ -3277,25 +3159,16 @@ test('control_cockpit adopts the newest selection after Contacts settles', async
});
});
test('control_cockpit restores the prior Context mode after Cockpit entry fails', async () => {
test('a failed voice Cockpit entry leaves the Context mode as it was', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const calls = [];
let contextMode = null;
const styleManager = {
getContextModeState: () => ({
mode: contextMode,
active: Boolean(contextMode),
changing: false,
}),
async setContextMode(mode) {
contextMode = mode;
calls.push(`context:${mode || 'off'}`);
return { ok: true, mode, active: Boolean(mode), changing: false };
},
getContextModeState: () => ({ mode: null, active: false, changing: false }),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit() {
calls.push('cockpit:enter');
return {
@@ -3322,31 +3195,21 @@ test('control_cockpit restores the prior Context mode after Cockpit entry fails'
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.deepEqual(calls, ['context:flights', 'cockpit:enter', 'context:off']);
assert.equal(contextMode, null);
assert.equal(result.contextRollback.ok, true);
assert.equal(result.error, 'Cockpit entry was unavailable');
assert.deepEqual(calls, ['cockpit:enter']);
assert.equal(result.contextRollback, undefined);
});
test('control_cockpit contains entry exceptions and still restores the prior Context mode', async () => {
test('control_cockpit contains entry exceptions and passes the prior track for rollback', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const calls = [];
let contextMode = null;
const styleManager = {
getAircraftTrackingTarget: () => ({ layerId: 'military', id: 'prior' }),
getContextModeState: () => ({
mode: contextMode,
active: Boolean(contextMode),
changing: false,
}),
async setContextMode(mode) {
contextMode = mode;
calls.push(`context:${mode || 'off'}`);
return { ok: true, mode, active: Boolean(mode), changing: false };
},
getContextModeState: () => ({ mode: null, active: false, changing: false }),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(_action, options) {
calls.push(['cockpit:enter', options.rollbackTarget]);
throw new Error('entry exploded');
@@ -3371,15 +3234,11 @@ test('control_cockpit contains entry exceptions and still restores the prior Con
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.equal(result.error, 'entry exploded');
assert.equal(result.contextRollback.ok, true);
assert.equal(contextMode, null);
assert.deepEqual(result.state, { active: false });
assert.deepEqual(calls, [
'context:flights',
['cockpit:enter', { layerId: 'military', id: 'prior' }],
'context:off',
]);
});
test('set_context_mode forwards cancellation authority and reports a stale turn', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -3538,11 +3397,7 @@ test('control_cockpit enter skips selected non-flight context', async () => {
active: contextActive,
changing: false,
}),
async setContextMode(mode) {
contextActive = mode === 'flights';
calls.push(`context:${mode}`);
return { ok: true, mode, active: true, changing: false };
},
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit(action) {
calls.push(`cockpit:${action}`);
return {
@@ -3577,7 +3432,7 @@ test('control_cockpit enter skips selected non-flight context', async () => {
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, true);
assert.deepEqual(calls, ['context:flights', 'cockpit:enter']);
assert.deepEqual(calls, ['cockpit:enter']);
});
test('voice CCTV select, next, prev, and nearest report tracking-refused flights after selection', async () => {
@@ -4543,6 +4398,66 @@ test('voice Radio Pause while disabled is a truthful playback-only no-op', async
// THE TWO APART, which a claim-count-only assertion cannot.
// ---------------------------------------------------------------------------
test('voice Cockpit entry, entered or failed, never changes the Context mode', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
for (const entered of [true, false]) {
const calls = [];
const styleManager = {
getContextModeState: () => ({
mode: null,
active: false,
changing: false,
}),
setPanelCollapsed() {},
setContextMode: async (mode) => {
calls.push(mode);
return { ok: true, mode, active: true };
},
controlCockpit: async () =>
entered
? { ok: true, action: 'control_cockpit', state: { active: true } }
: {
ok: false,
action: 'control_cockpit',
error: 'entry failed',
state: { active: false },
},
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => null,
};
const layerCalls = [];
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map([
['flights', { module: {} }],
['military', { module: {} }],
]),
isEnabled: (layerId) => layerId === 'flights',
setEnabled: async (...args) => {
layerCalls.push(args);
return true;
},
getAll: () => [],
},
});
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, entered);
assert.deepEqual(calls, [], 'no Context mode change');
assert.deepEqual(layerCalls, [], 'no layer change');
}
});
function contextClaimProbe({
entrySucceeds = true,
cockpitSucceeds = true,
@@ -4591,48 +4506,6 @@ function contextClaimProbe({
return { runner, calls };
}
test('Cockpit entry establishes Contacts WITHOUT claiming the visual lane', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const probe = contextClaimProbe();
await probe.runner('control_cockpit', { action: 'enter' });
assert.ok(probe.calls.length >= 1, 'Cockpit entry must establish Contacts');
for (const call of probe.calls) {
assert.equal(
call.claimVisualAuthority,
false,
`cockpit choreography must not claim (mode=${call.mode})`,
);
}
});
test('Cockpit entry rollback also stays inert on the visual lane', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const probe = contextClaimProbe({ cockpitSucceeds: false });
await probe.runner('control_cockpit', { action: 'enter' });
// Establish + roll back: BOTH are this action's own choreography.
assert.ok(
probe.calls.length >= 2,
`expected an entry and a rollback, saw ${probe.calls.length}`,
);
for (const call of probe.calls) {
assert.equal(
call.claimVisualAuthority,
false,
`rollback must not claim (mode=${call.mode})`,
);
}
});
test('a genuine set_context_mode request DOES claim the visual lane', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -5083,71 +4956,6 @@ test('an absent secondary mode stays absent instead of claiming to be off', asyn
);
});
test('a nested Cockpit rollback result is translated too', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
// The prior mode is Contacts, whose INTERNAL id is 'flights' — the id that
// must not reach the model. `active: false` keeps Contacts from reading as
// ready, so entry runs and the failed Cockpit rolls back to it.
let contextMode = 'flights';
const styleManager = {
getContextModeState: () => ({
mode: contextMode,
active: false,
changing: false,
}),
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => null,
async setContextMode(mode) {
// Entry to Contacts succeeds; Cockpit then fails and the prior mode is
// rolled back — the rollback result is what the model reads.
contextMode = mode;
return {
ok: true,
action: 'set_context_mode',
mode,
active: true,
changing: false,
};
},
controlCockpit: () => ({
ok: false,
error: 'Cockpit entry failed',
state: { active: false },
}),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map(),
isEnabled: () => false,
getAll: () => [],
},
});
const result = await runner('control_cockpit', { action: 'enter' });
assert.equal(result.ok, false);
assert.equal(
result.contextRollback?.mode,
'contacts',
'the rollback names the mode the tools name',
);
assert.equal(result.contextRollback?.modeInternal, 'flights');
assert.doesNotMatch(
JSON.stringify(result.contextRollback || {}),
/"mode":"flights"/,
'a nested rollback result must not leak the internal id either',
);
});
/**
* Front 5 (owner's live trial, 2026-08-22 01:42-01:44). Contacts was active
* with contact N546PC as its subject, a DATACENTER sat in the recency slot,
@@ -5294,7 +5102,6 @@ function analystRunner(awareness, { getAll } = {}) {
},
});
}
test('front5: a nearby ask centres on the Contacts SUBJECT, not the selected datacenter', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
@@ -8954,3 +8761,191 @@ test('show_street_level shows every photo it opens, also over a panel the user h
});
assert.deepEqual(missing.revealed, [], 'nothing opened, nothing revealed');
});
test('a military voice Cockpit entry switches Military Flights on as a plain layer, never Contacts', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
for (const militaryOn of [false, true]) {
const enabled = new Set(militaryOn ? ['flights', 'military'] : ['flights']);
const layerCalls = [];
const entries = [];
const styleManager = {
getContextModeState: () => ({
mode: null,
active: false,
changing: false,
}),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
setDetection: () => assert.fail('Cockpit entry must not touch detection'),
controlCockpit(action, options) {
entries.push([action, options.targetLayer, options.aircraftClass]);
return { ok: true, action: 'control_cockpit', state: { active: true } };
},
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'civil' }),
};
const viewer = {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
};
const runner = createGevActionRunner({
viewer,
styleManager,
dataManager: {
layers: new Map([
['flights', { module: {} }],
['military', { module: {} }],
]),
isEnabled: (layerId) => enabled.has(layerId),
async setEnabled(layerId, on, options) {
layerCalls.push([layerId, on, options.origin]);
if (on) enabled.add(layerId);
return true;
},
getAll: () => [],
},
});
const result = await runner('control_cockpit', {
action: 'enter',
targetLayer: 'military',
aircraftClass: 'helicopter',
});
assert.equal(result.ok, true, result.error);
assert.deepEqual(
layerCalls,
militaryOn ? [] : [['military', true, 'voice']],
'only a Military Flights layer that is off is switched on',
);
assert.deepEqual(entries, [['enter', 'military', 'helicopter']]);
}
});
// A data manager whose Military Flights layer is off, switches on empty and
// reports its first data only when the test lands it.
function militaryOffManager({ militaryOn = false } = {}) {
const enabled = new Set(militaryOn ? ['flights', 'military'] : ['flights']);
const activity = new Set();
const layerCalls = [];
let lastUpdate = militaryOn ? 1 : null;
const manager = {
layers: new Map([
['flights', { module: {} }],
['military', { module: { getStats: () => ({ lastUpdate }) } }],
]),
isEnabled: (layerId) => enabled.has(layerId),
async setEnabled(layerId, on, options) {
layerCalls.push([layerId, on, options.origin]);
if (on) enabled.add(layerId);
else enabled.delete(layerId);
return true;
},
subscribeActivity(callback) {
activity.add(callback);
return () => activity.delete(callback);
},
getAll: () => [],
};
return {
manager,
layerCalls,
enabled,
listening: () => activity.size,
landFirstData() {
lastUpdate = 2;
for (const callback of [...activity])
callback({ type: 'data-updated', layerId: 'military' });
},
};
}
function militaryEntryRunner(manager, controlCockpit) {
return createGevActionRunner({
viewer: {
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: { moveEnd: { addEventListener() {} } },
},
styleManager: {
getContextModeState: () => ({
mode: null,
active: false,
changing: false,
}),
setContextMode: () => assert.fail('Cockpit entry must not open Contacts'),
controlCockpit,
getCockpitState: () => ({ active: false }),
getAircraftTrackingTarget: () => ({ layerId: 'flights', id: 'civil' }),
},
dataManager: manager,
});
}
test('a military voice entry waits for a just-switched-on layer to report its first data', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
const fixture = militaryOffManager();
let searchedWithData = null;
const runner = militaryEntryRunner(fixture.manager, () => {
searchedWithData =
fixture.manager.layers.get('military').module.getStats().lastUpdate !==
null;
return { ok: true, action: 'control_cockpit', state: { active: true } };
});
const pending = runner('control_cockpit', {
action: 'enter',
targetLayer: 'military',
aircraftClass: 'helicopter',
});
for (let i = 0; i < 10; i++) await Promise.resolve();
assert.equal(searchedWithData, null, 'no search on an empty layer');
assert.equal(fixture.listening(), 1);
fixture.landFirstData();
const result = await pending;
assert.equal(result.ok, true, result.error);
assert.equal(searchedWithData, true);
assert.equal(fixture.listening(), 0, 'the wait lets go of the layer');
});
test('a failed military voice entry switches off only the layer it switched on', async () => {
globalThis.window = globalThis.window || {
clearTimeout,
setTimeout,
requestIdleCallback: null,
};
for (const militaryOn of [false, true]) {
const fixture = militaryOffManager({ militaryOn });
const runner = militaryEntryRunner(fixture.manager, () => ({
ok: false,
action: 'control_cockpit',
error: 'No helicopter military contact is available to enter',
state: { active: false },
}));
const pending = runner('control_cockpit', {
action: 'enter',
targetLayer: 'military',
aircraftClass: 'helicopter',
});
for (let i = 0; i < 10; i++) await Promise.resolve();
if (!militaryOn) fixture.landFirstData();
const result = await pending;
assert.equal(result.ok, false);
assert.match(result.error, /No helicopter military contact/);
assert.deepEqual(
fixture.layerCalls,
militaryOn
? []
: [
['military', true, 'voice'],
['military', false, 'voice'],
],
);
assert.equal(fixture.enabled.has('military'), militaryOn);
}
});
+231 -3
View File
@@ -5,6 +5,11 @@ import { readFileSync } from 'node:fs';
import { createPinia } from 'pinia';
import { createVoiceControl } from '../control.js';
import { useVoiceStore } from '../../ui/stores/voice.js';
import {
createContextCardOpener,
useEntityCardStore,
} from '../../ui/stores/entityCard.js';
import { applicationPinia } from '../../ui/vueRuntime.js';
import { createGevActionRunner } from '../gevActions.js';
import { createVoiceCommands as bind } from '../sessionCommands.js';
import { createVoiceCommands as compose } from '../commands.js';
@@ -138,6 +143,8 @@ function mounted(t, options = {}) {
createSession: factory(instances, options),
createControl: (control) => createTestVoiceUi({ ...control, pinia }),
panelHost: host,
styleManager: options.styleManager ?? null,
contextCard: createContextCardOpener(applicationPinia()),
nativePanelProvider: options.native
? (options.nativeProvider ?? 'gemini')
: null,
@@ -779,7 +786,7 @@ test('voice timeout change preserves a pending voice reveal', async (t) => {
assert.equal(f.commands.getVoicePreferences().minutes, 0);
});
test('active provider output reveals Preview after done; manual choice wins until genuine input, replays do not reset idle', async (t) => {
test('active provider output reveals Preview after done; manual choice wins until genuine input, replays change nothing', async (t) => {
const f = mounted(t, { native: true, nativeProvider: 'openai', view: true });
await f.commands.session.start();
const emit = f.instances[0].hooks.emit;
@@ -795,10 +802,12 @@ test('active provider output reveals Preview after done; manual choice wins unti
emit({ type: 'completion', responseId: 'r1' });
reply('Late answer');
assert.equal(f.commands.voicePanel.snapshot().panelOpen, true);
const timer = f.commands.voiceCard.hideTimer;
const shown = f.commands.voiceCard.state;
reply('Late answer');
reply('Late', 'r1', { final: false });
assert.equal(f.commands.voiceCard.hideTimer, timer);
assert.equal(f.commands.voiceCard.state, shown);
// The panel's card keeps its reply; it has no idle deadline.
assert.equal(f.commands.voiceCard.hideTimer, null);
assert.equal(f.commands.voiceCard.state.assistant, 'Late answer');
f.commands.voicePanel.close();
emit({
@@ -1444,3 +1453,222 @@ test('teardown inside sendText prevents appending the submitted message', async
0,
);
});
// What the selection actions report, as the real runner does.
const selectionRunner = async (name) =>
name === 'select_nearest_aircraft'
? {
ok: true,
action: name,
layerId: 'flights',
label: 'UAL12',
aircraft: { id: 'a1b2c3', callsign: 'UAL12' },
}
: name === 'track_entity'
? {
ok: true,
action: name,
layerId: 'military',
kind: 'aircraft',
id: 'ae01ce',
label: 'RCH401',
latitude: 42.3,
longitude: -71,
}
: { ok: true };
// The Context panel's entity card, cleared for each test.
function contextCard(t) {
const store = useEntityCardStore(applicationPinia());
store.clear();
t.after(() => store.clear());
return store;
}
// Docks the assistant panels into the right rail's lane for one test.
async function dockIntoRail(t, f) {
t.after(() => globalThis.localStorage.removeItem('gev.panel.docked'));
f.ui.emit('layout-dock');
await f.settle();
await f.settle();
}
test('a voice selection opens its Context card, steps the docked voice panel down and keeps the reply', async (t) => {
const context = contextCard(t);
const f = mounted(t, { view: true, runner: selectionRunner });
await f.settle();
await f.commands.session.start();
f.commands.voicePanel.select('preview');
await f.settle();
await dockIntoRail(t, f);
const panel = $('#gev-voice-panel');
assert.equal(panel.dataset.placement, 'docked');
assert.equal(globalThis.document.body.dataset.assistantDocked, 'true');
const { emit, runAction } = f.instances[0].hooks;
// A failed selection selects nothing, so the panel stays.
emit({
type: 'action-result',
name: 'track_entity',
result: { ok: false, error: 'Nothing matched' },
});
await f.settle();
assert.equal(panel.dataset.minimized, undefined);
assert.equal(context.card, null);
await runAction('select_nearest_aircraft', { location: 'Boston' });
// Context shows the aircraft, as after a click on it.
assert.equal(context.card.layerId, 'flights');
assert.equal(context.card.key, 'flights:a1b2c3');
emit({
type: 'transcript',
role: 'assistant',
text: 'The nearest aircraft is UAL12.',
final: true,
responseId: 'r1',
});
await f.settle();
assert.equal(panel.dataset.minimized, 'true');
// The rail, and its Context panel, show again.
assert.equal(globalThis.document.body.dataset.assistantDocked, undefined);
assert.equal(
$('#gev-voice-mini-assistant').textContent,
'The nearest aircraft is UAL12.',
);
// The reply is not retired on a timer: expanding the bar shows it.
assert.equal(f.commands.voiceCard.hideTimer, null);
f.commands.voicePanel.select('preview');
await f.settle();
assert.equal(panel.dataset.minimized, undefined);
assert.equal(f.commands.voicePanel.snapshot().previewVisible, true);
assert.equal($('#gev-voice-preview-empty').hidden, true);
assert.equal(
f.commands.voiceCard.snapshot().assistant.text,
'The nearest aircraft is UAL12.',
);
// The next turn replaces it.
emit({ type: 'interruption', reason: 'user-speech' });
assert.equal(f.commands.voiceCard.state.assistant, null);
});
test('a voice selection leaves a voice panel above the dock as it is', async (t) => {
const context = contextCard(t);
const f = mounted(t, { view: true, runner: selectionRunner });
await f.settle();
await f.commands.session.start();
f.commands.voicePanel.select('preview');
await f.settle();
assert.equal($('#gev-voice-panel').dataset.placement, 'compact');
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
await f.settle();
assert.equal(context.card.key, 'military:ae01ce');
assert.equal($('#gev-voice-panel').dataset.minimized, undefined);
});
test('a voice selection in Cockpit leaves the hidden Context card alone', async (t) => {
const context = contextCard(t);
const f = mounted(t, { view: true, runner: selectionRunner });
await f.settle();
await f.commands.session.start();
globalThis.document.body.classList.add('cockpit-mode');
t.after(() => globalThis.document.body.classList.remove('cockpit-mode'));
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
assert.equal(context.card, null);
});
test('a typed chat selection opens its Context card and steps the docked chat panel down', async (t) => {
const context = contextCard(t);
const f = mounted(t, { view: true, runner: selectionRunner });
typedChat(f);
await f.settle();
$('#gev-chat-button').click();
await f.settle();
await dockIntoRail(t, f);
assert.equal($('#gev-chat-panel').dataset.placement, 'docked');
await f.commands.session.start({ textOnly: true });
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
await f.settle();
assert.equal(context.card.key, 'military:ae01ce');
assert.equal($('#gev-chat-panel').dataset.minimized, 'true');
assert.equal(f.ui.state.chat.open, true);
assert.equal(globalThis.document.body.dataset.assistantDocked, undefined);
});
test('the voice panel keeps the last reply until the next turn starts', async (t) => {
const f = mounted(t, { view: true });
await f.settle();
await f.commands.session.start();
f.commands.voicePanel.select('preview');
const { emit } = f.instances[0].hooks;
emit({
type: 'transcript',
role: 'assistant',
text: 'Tracking UAL12.',
final: true,
responseId: 'r1',
});
await f.settle();
// Only the card floating on a control without the panel hides when idle.
assert.equal(f.commands.voiceCard.hideTimer, null);
assert.equal(f.commands.voicePanel.snapshot().previewVisible, true);
assert.equal($('#gev-voice-preview-empty').hidden, true);
emit({ type: 'interruption', reason: 'user-speech' });
emit({
type: 'transcript',
role: 'assistant',
text: 'Now following DAL4.',
final: true,
responseId: 'r2',
});
assert.equal(f.commands.voiceCard.state.assistant, 'Now following DAL4.');
});
test('a voice selection in Cockpit, as Cockpit reports it, leaves the Context card alone', async (t) => {
const context = contextCard(t);
let cockpit = true;
const f = mounted(t, {
view: true,
runner: selectionRunner,
styleManager: { getCockpitState: () => ({ active: cockpit }) },
});
await f.settle();
await f.commands.session.start();
// Cockpit's own state decides, not the page's classes.
assert.equal(
globalThis.document.body.classList.contains('cockpit-mode'),
false,
);
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
assert.equal(context.card, null);
cockpit = false;
await f.instances[0].hooks.runAction('track_entity', { query: 'RCH401' });
assert.equal(context.card.key, 'military:ae01ce');
});
test('a slow voice selection never replaces a card clicked since it was asked', async (t) => {
const context = contextCard(t);
let finish;
const f = mounted(t, {
view: true,
runner: (name) =>
name === 'track_entity'
? new Promise((resolve) => {
finish = () => resolve(selectionRunner(name));
})
: selectionRunner(name),
});
await f.settle();
await f.commands.session.start();
const pending = f.instances[0].hooks.runAction('track_entity', {
query: 'RCH401',
});
await Promise.resolve();
// The person clicks another aircraft while the lookup runs.
context.select({ layerId: 'flights', id: 'click1', label: 'CLICKED' });
const clicked = context.card.key;
finish();
await pending;
assert.equal(context.card.key, clicked);
// A selection with no newer pick still opens its card.
await f.instances[0].hooks.runAction('select_nearest_aircraft', {
location: 'Boston',
});
assert.equal(context.card.key, 'flights:a1b2c3');
});
+84 -2
View File
@@ -11,6 +11,31 @@ import { PointerReticle } from './pointerReticle.js';
import { VOICE_PROVIDERS } from './providerCapabilities.js';
import { t, translateKnown } from '../i18n/index.js';
/**
* Actions whose success selects an entity on the map, and the identity each
* result names it by.
*/
const SELECTION_ACTIONS = new Map([
[
'select_nearest_aircraft',
(result) => ({
layerId: result.layerId,
id: result.aircraft?.id,
label: result.label || result.aircraft?.callsign,
}),
],
[
'track_entity',
(result) => ({
layerId: result.layerId,
id: result.id,
label: result.label,
lat: result.latitude,
lon: result.longitude,
}),
],
]);
function createDefaultReticle(pointer) {
const element = pointer?.element;
if (!element?.ownerDocument) return null;
@@ -38,6 +63,12 @@ export function createVoiceCommands({
onSessionEvent,
canStartVoice,
createCard = (options) => new VoiceCardControls(options),
// Cockpit's own state; Context stays hidden while it runs.
styleManager = null,
// Opens a selection's card in the Context panel, as a click does
// (`createContextCardOpener` in src/ui/stores/entityCard.js); the app
// hands it in. Without one, selections open no card.
contextCard = null,
pointer = null,
referents = null,
createReticle = createDefaultReticle,
@@ -147,10 +178,14 @@ export function createVoiceCommands({
});
});
// Captions, plan and result card nested in the control; it only reads
// provider-neutral session events.
// provider-neutral session events. In the voice panel the card is the
// Preview's content, so the last reply stays until the next turn replaces
// it; only the card floating on the control hides when idle.
const card = createCard({
ui,
...(panelHost ? { onRender: () => panelMount?.panel.sync() } : {}),
...(panelHost
? { onRender: () => panelMount?.panel.sync(), idleMs: null }
: {}),
});
panelMount = panelHost?.mount({
ui,
@@ -279,6 +314,53 @@ export function createVoiceCommands({
}),
]
: [];
// A voice or chat selection shows in the right rail's Context panel, as a
// click's does: its card opens there, and the assistant panel docked over
// the rail steps down to its bar, where the latest reply stays readable. A
// panel above the dock leaves the rail in view, so it stays as it is.
const dockedOverRail = (name) => {
const panel = ui.element(name);
return Boolean(
panel &&
!panel.hidden &&
panel.dataset?.placement === 'docked' &&
!panel.dataset.minimized,
);
};
// The Context card generation each selection was asked at, by call, so a
// slow selection never replaces a card picked since.
const askedAt = new Map();
const callKey = (event) => event.callId ?? event.name;
const cockpitActive = () =>
typeof styleManager?.getCockpitState === 'function'
? styleManager.getCockpitState()?.active === true
: globalThis.document?.body?.classList?.contains('cockpit-mode') === true;
layouts.push(
session.subscribe((event) => {
if (!SELECTION_ACTIONS.has(event.name)) return;
if (event.type === 'action-call') {
askedAt.set(callKey(event), contextCard?.generation?.() ?? null);
return;
}
if (event.type !== 'action-result') return;
const since = askedAt.get(callKey(event)) ?? null;
askedAt.delete(callKey(event));
if (event.result?.ok !== true) return;
contextCard?.show?.(SELECTION_ACTIONS.get(event.name)(event.result), {
since,
cockpitActive: cockpitActive(),
});
if (!panelMount) return;
if (adapter.getStartOptions?.().textOnly) {
if (ui.state.chat.open && dockedOverRail('chatPanel'))
chat?.minimize({ focus: false });
} else if (
panelMount.panel.snapshot().panelOpen &&
dockedOverRail('voicePanel')
)
minimizeVoicePanel();
}),
);
const unbindMiniPreview = panelMount
? bindVoiceMiniPreview({ ui, session })
: null;
+3 -1
View File
@@ -20,7 +20,8 @@ export class VoiceCardControls {
/**
* @param {object} options
* @param {object} options.ui The voice control presenter.
* @param {number} [options.idleMs]
* @param {number|null} [options.idleMs] How long an idle card stays shown;
* null keeps it until the next turn, Stop or a dismissal.
* @param {Function} [options.setTimer]
* @param {Function} [options.clearTimer]
*/
@@ -103,6 +104,7 @@ export class VoiceCardControls {
scheduleIdle() {
this.cancelIdle();
if (this.idleMs === null) return;
this.hideTimer = this.setTimer(() => {
this.hideTimer = null;
if (this.destroyed) return;
+35 -3
View File
@@ -168,8 +168,7 @@ test('markup: the card nests inside the voice control with every element and a p
'the card is part of the voice control',
);
assert.equal(document.querySelectorAll('#gev-voice-card').length, 1);
if (panel)
assert.equal(card.parentElement.id, 'gev-voice-preview-panel');
if (panel) assert.equal(card.parentElement.id, 'gev-voice-preview-panel');
for (const id of [
'gev-voice-card-phase',
'gev-voice-card-dismiss',
@@ -531,7 +530,12 @@ test('additive presentation gates retain the current localized reducer labels',
const steps = card.state.steps;
const result = card.state.result;
const who = () => ui.state.card.user.label;
card.handle({ type: 'transcript', role: 'user', text: 'Same words', attribution: 'unverified' });
card.handle({
type: 'transcript',
role: 'user',
text: 'Same words',
attribution: 'unverified',
});
assert.equal(card.state.userAttribution, 'unverified');
assert.equal(card.snapshot().user.label, 'Habla reciente');
assert.equal(who(), 'Habla reciente');
@@ -615,3 +619,31 @@ test('manual panel and preference compose with the actual card without changing
panel.destroy();
card.destroy();
});
test('a card without an idle deadline keeps its reply until the next turn', () => {
const ui = createTestVoiceUi();
let timers = 0;
const card = new VoiceCardControls({
ui,
idleMs: null,
setTimer() {
timers++;
return timers;
},
clearTimer() {},
});
card.handle({ type: 'interruption' });
card.handle({
type: 'transcript',
role: 'assistant',
text: 'Tracking UAL12.',
final: true,
responseId: 'r1',
});
assert.equal(timers, 0);
assert.equal(card.hideTimer, null);
assert.equal(card.snapshot().visible, true);
card.handle({ type: 'interruption' });
assert.equal(card.snapshot().assistant.visible, false);
card.destroy();
});