mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ba53f6d0e | ||
|
|
2eef8cd902 | ||
|
|
d9d79ebc4d | ||
|
|
e4caf5d3af | ||
|
|
561f5885c2 | ||
|
|
7ff536299a | ||
|
|
918435ddc7 | ||
|
|
fbbe6cd91f | ||
|
|
5608b12a25 | ||
|
|
ae212e5b63 | ||
|
|
deff042265 | ||
|
|
aac6be7773 | ||
|
|
84324ea678 | ||
|
|
a01eaff89e | ||
|
|
d8a8f1b917 | ||
|
|
678a816e65 | ||
|
|
bfcf12af49 | ||
|
|
a073e6e658 | ||
|
|
f2e8e63c48 | ||
|
|
5668c0c08b | ||
|
|
2e2cae4701 | ||
|
|
d380977928 | ||
|
|
9bb557bc2a | ||
|
|
0c1b017699 | ||
|
|
22804a46da | ||
|
|
65018015a0 |
No files matched your search
@@ -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),
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
- Stop the Satellites layer row reading `DEGRADED` with "1 CelesTrak group
|
||||
unavailable" on every update: the core catalog asked CelesTrak for a `sar`
|
||||
group that does not exist, so that read always failed (asturksever, #1883).
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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).
|
||||
@@ -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,11 @@
|
||||
- Stop the OpenSky track-backfill proxy from turning a varied `icao24` into
|
||||
unbounded upstream spend. `/api/flights/track` carries an always-on
|
||||
30-per-minute per-client limiter (90 global) on upstream calls (a cached
|
||||
answer or a malformed request is not charged), and a
|
||||
`429` from OpenSky `/tracks/all` now starts a cooldown for that credit
|
||||
bucket: until OpenSky's retry-after passes, any cached track is served and
|
||||
other lookups are answered `429` locally instead of asking for 4 more
|
||||
credits. The `/tracks/*` bucket is separate from the `/states/*` one
|
||||
`/api/flights` spends, so a flights cooldown does not block backfill. The
|
||||
existing 60-second per-key cache bounds memory, not spend. Single-aircraft
|
||||
backfill, issued once per selected contact, is unaffected (daikaginza, #685).
|
||||
+24
-7
@@ -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
|
||||
@@ -7803,7 +7810,7 @@ silently demoting every later lookup for the session.
|
||||
- **Satellite classes** (`src/layers/satellites/classes.js`): every satellite is filed under one of six classes, each with its own point colour, legend swatch and toggle: STATIONS (warm white), IMAGING (cyan), TELECOM (violet; communications and navigation, so GPS, GLONASS, Galileo and BeiDou read as one family), STARLINK (dim slate), PROBES (muted blue-gray) and DEBRIS (receding brown-gray). That module is the single source of truth for class, label and colour, so the dot, the card and the legend swatch cannot disagree. Two deliberate palette rules: no class may sit in the 40–48° amber band, which is the app-wide known-military convention; and STARLINK stays far below PROBES in Rec.601 luminance so the dense shell stays separable when NVG/FLIR collapse the scene to one channel. The ISS keeps its long-standing red hero dot rather than the STATIONS colour — it carries a permanent name label and its card still reads `STATIONS · ISS`; it is a station whichever group ingested it, so a stations-feed outage cannot refile it. `src/data/satelliteClass.js` keeps the group-based labels beneath the classes: the constellation subtype and a group's own label for a satellite with no class. The tracked satellite's dot keeps that colour too: tracking draws it larger (14 px), white-outlined and over everything, never in another colour (`_addTrackedEntity`, `src/layers/satellites/rendering.js`).
|
||||
- Class is also a **text field**, not just a color: `TELECOM · GPS` / `STARLINK` / `STATIONS · ISS` leads the tracked card's detail block and replaces the raw CelesTrak tag on the detection-overlay label. Because that canvas composites above the post-FX chain, the class stays readable in NVG/FLIR after the in-scene dot colors are flattened.
|
||||
- The satellites row in DATA LAYERS carries per-layer sub-controls (`DataLayerManager._syncRowControls`, the first consumer of the optional `getRowControls()` layer hook): one chip per class (the STARLINK chip exposes the existing `catalog` param), a swatch legend with live per-class counts, and an info line while SATCAT is stale or unavailable (`Classes may lag: SATCAT is a cached copy` / `Classes may lag: SATCAT unavailable`). Default is the sparse core catalog. The chips are stateless — each declares the params to apply and the manager owns the write — so the Space Missions capture/restore path over the same param stays authoritative. Controls stay hidden while the layer is off. An explicit CORE or DENSE choice participates in versioned local and share-link state; temporary Space Missions overrides do not.
|
||||
- **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and the legend keys only the classes on screen. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/<group>`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead.
|
||||
- **Class toggles** (`src/layers/satellites/classes.js`): the layer row carries one chip per class — STATIONS, IMAGING, TELECOM (communications and navigation), PROBES (science, technology development and demonstration, unknown purpose) and DEBRIS (rocket bodies, fragments, unknown objects launched before last year and dead payloads) on by default, so the layer shows what it did before classes; STARLINK off, as DENSE was. Points of a hidden class stay built and are only hidden, so a toggle needs no reload; hidden classes are left out of the detection overlay, the voice/framing position lists and analyst answers (the tracked satellite still answers), and the legend keys only the classes on screen. The class comes, strongest evidence first, from CelesTrak SATCAT (object type and operational status, fetched per group through `/api/celestrak-satcat/<group>`, cached a day by the proxy; the layer keeps a current read six hours rather than asking on every five-minute update), the bundled UCS Satellite Database pack (UCS-Satellite-Database 5-1-2023: operator, owner country and purpose; `src/data/local_data/ucs_satellites/`), name patterns for satellites launched after May 2023, and finally the CelesTrak groups the TLE came in (a mission group such as `weather` before the orbit group `geo`; a UCS purpose of "Unknown" counts as none). Only crewed stations and the craft that visit them, by name, are STATIONS: the CubeSats CelesTrak's stations group also carries after their deployment from the ISS are classed like any other satellite. A payload whose SATCAT record gives no status, with no UCS record and no recognisable name, that launched 20 or more years ago (SATCAT's launch date, else the TLE designator's year) is presumed dead and filed as debris; without a SATCAT record (a failed read) nothing is presumed. To cover imaging launched after the UCS snapshot the core catalog also reads CelesTrak's `resource`, `weather`, `planet`, `sar` and `science` groups. Debris can be tracked but is never ridden: the orbital entry gate (`orbitEntryAllowed`) refuses it, so no ORBIT entry is offered and double-click does nothing for it. Retired stations and the shuttles have re-entered and have no orbit to show. An explicit class choice is kept in local and share-link state as the `classes` option, one letter per class shown (`sitpd`: stations, imaging, telecom, probes, debris; `0`: none; `src/data/satelliteClassMask.js`), and the layer takes those letters back through `setParams({classes})`; STARLINK maps to the existing `catalog: 'dense'` param instead.
|
||||
- The satellite Cockpit subject (`getCockpitSubject()`) also carries `satelliteClass`, `cosparId` (from SATCAT, else TLE line 1), `tle` (`{line1, line2, epochMs}`), `owner` (`{countryCode, label}`: ISO 3166-1 alpha-2 for a single country, `null` code for organisations such as ESA, EUMETSAT or Intelsat and for joint owners) and `operator` (UCS; SpaceX for Starlink). UCS names the operator's country and wins over the SATCAT owner code; CelesTrak's CIS (former USSR) is filed under Russia.
|
||||
- **The STARLINK chip (formerly DENSE) reports the dense LOAD, not the catalog param.** The param flips synchronously while the Starlink shell takes seconds to arrive over a chunked load, and CelesTrak 502s that feed regularly. So the chip reads `STARLINK ···` (busy, disabled) while loading, ACTIVE only once dense points are actually on screen, and `STARLINK ✕` with the reason on hover when the load fails — a failure also reverts `catalog` to `core`, drops any partial chunk, and leaves the chip clickable to retry. A load is judged by points added, not by HTTP status: a 200 carrying an empty body, a passed-through HTML error page, or only TLEs the core catalog already owns fails with the same revert semantics as a 502. Any explicit request for `core` clears a latched error even when the mode does not change, so a Space Missions restore of an already-core snapshot never leaves the user with a failure they did not cause. Because the load settles asynchronously, the layer pushes a re-render through the optional `setRowControlsListener()` hook; nothing else would repaint that row before the 5-minute catalog refresh, so the count and legend would otherwise sit stale.
|
||||
- **A dependency owner takes the row with it.** Space Missions borrows this layer for TLE lookup with `showPoints:false`; while points are hidden the layer returns empty row controls, so the legend never describes an empty sky and the chip cannot accept a write that the owner's restore would silently revert.
|
||||
@@ -9004,6 +9011,7 @@ apply to `public/` assets or built-preview serving.
|
||||
- `/api/flights`, `/api/military`, and `/api/route` answer `405 Method Not Allowed` with `Allow: GET` to anything but `GET`, before rate limiting and any upstream call.
|
||||
- `/api/flights` negotiates gzip. The cached global snapshot and the regional adsb.lol fallback are each gzipped once per refresh (about 860 KB becomes about 250 KB). Clients that offer gzip get that frame; other clients, and bodies under 1 KiB or that gzip cannot shrink, get identity bytes. Both answers carry `Vary: Accept-Encoding`. Uncached bodies, such as auth failures, are never sent under a cached frame's encoding.
|
||||
- Track endpoints: `/api/vessels/track?mmsi=` (server-accumulated ring buffers; sub-route handled before the rows snapshot), `/api/flights/track?icao24=` (OAuth, 60s cache, sanitized errors, independent OpenSky credit bucket), `/api/military/track?hex=` (400 for an invalid hex, otherwise `503 history_unavailable` with `Retry-After: 1800` and `Cache-Control: no-store`, no upstream request; military tracking uses its locally accumulated trail).
|
||||
- `/api/flights/track` carries an always-on per-client limiter of 30 upstream calls/minute (90 global; refusals send `Retry-After: 60`; cached answers and malformed requests are not charged), because its 60s per-key cache bounds memory rather than spend: a caller varying `icao24` produces a fresh key and a fresh upstream call each time. A `429` from OpenSky `/tracks/all` starts a cooldown for the `/tracks/*` credit bucket (OpenSky's retry-after, bounded 30 s–30 min): while it runs, `/api/flights/track` serves any cached track (not a cached error) and otherwise answers `429` with the remaining cooldown, including to the request that tripped it, instead of spending 4 more credits. It does not read `/api/flights`'s `/states/*` cooldown, since OpenSky meters the two buckets independently.
|
||||
- Realtime debug logs redact API keys, bearer tokens, client secrets, and image data URLs before writing to disk; request bodies are size-capped.
|
||||
- `/api/realtime/debug-log` enforces an always-on 120-per-client/400-global one-minute limiter (not the opt-in `GEV_RATELIMIT_OPENAI_PER_MIN` bucket the cost-bearing OpenAI routes share), appends asynchronously through a serialized queue, and rotates `realtime-conversations.jsonl` at 32 MB keeping one prior generation, so the sink is bounded at twice that regardless of session length. A malformed record answers 400 and a failed write 500, both with a fixed message.
|
||||
|
||||
@@ -9093,8 +9101,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)).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,6 @@
|
||||
"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/openSkyTrackGovernor.test.mjs"
|
||||
]
|
||||
@@ -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",
|
||||
|
||||
@@ -43,11 +43,13 @@ const OPENSKY_STATES_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Credit-governor cooldown for a 429: OpenSky's retry-after bounded to
|
||||
* 30 s … 30 min, or 2 min when the header is absent.
|
||||
* 30 s … 30 min, or 2 min when the header is absent. Exported for the
|
||||
* `/tracks/*` governor in tracks.js, which reads the same header for its own
|
||||
* bucket.
|
||||
* @param {Response} upstream Rate-limited response.
|
||||
* @returns {number} Cooldown (ms).
|
||||
*/
|
||||
function openSkyRateLimitCooldownMs(upstream) {
|
||||
export function openSkyRateLimitCooldownMs(upstream) {
|
||||
// headers.get() gives null when absent, and Number(null) is 0, not NaN.
|
||||
const header = upstream.headers.get('x-rate-limit-retry-after-seconds');
|
||||
const retryAfterSec =
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import { getOpenSkyToken } from './opensky.js';
|
||||
import { getOpenSkyToken, openSkyRateLimitCooldownMs } from './opensky.js';
|
||||
import { readCappedResponseText } from '../common/http.js';
|
||||
import { makeRateLimiter, clientKey } from '../common/rate-limit.js';
|
||||
/**
|
||||
* Vite plugin: aircraft track-history backfill proxies (PRD WS-F F1/F2).
|
||||
*
|
||||
* /api/flights/track?icao24=<hex6> — OpenSky GET /tracks/all (experimental;
|
||||
* own credit bucket, 4 credits per call on the free tier). OAuth via the
|
||||
* 4 credits per call from the `/tracks/*` bucket, which OpenSky keeps
|
||||
* separate from the `/states/*` one `/api/flights` spends). OAuth via the
|
||||
* shared coalesced token. 60s per-icao cache; 404/429 forwarded so the
|
||||
* client can fall back to its accumulated trail silently.
|
||||
* client can fall back to its accumulated trail silently. It has its own
|
||||
* per-IP limiter, and a 429 from /tracks starts a cooldown for that
|
||||
* bucket — the per-icao cache bounds memory, not spend, since a different
|
||||
* `icao24` is simply a different key. The limiter counts upstream calls
|
||||
* only: a malformed request or one answered from the cache costs OpenSky
|
||||
* nothing and is not charged.
|
||||
* /api/military/track?hex=<hex> — compatibility refusal for the retired,
|
||||
* undocumented ADSB.lol trace route. The standalone military source uses
|
||||
* locally accumulated trails; provider-supplied history remains optional.
|
||||
@@ -15,9 +22,52 @@ export function trackBackfillProxies() {
|
||||
const TRACK_CACHE_MS = 60000;
|
||||
const TRACK_CACHE_MAX = 200;
|
||||
const RESPONSE_CAP_BYTES = 5 * 1024 * 1024;
|
||||
/**
|
||||
* Requests/min/IP. The per-icao cache below bounds MEMORY, not request
|
||||
* volume: every distinct `icao24` is a fresh key, and `icao24` is 6 hex
|
||||
* digits, so varying it walks straight past the cache into a live call.
|
||||
*
|
||||
* Sized against demand, not guessed: a backfill is issued once per aircraft
|
||||
* the operator SELECTS (`_backfillTrail`, fired from the tracked-contact
|
||||
* path in the flights layer), and re-selecting the
|
||||
* same aircraft inside a minute is served from cache. The assistant's
|
||||
* `get_aircraft_track` tool asks once per call, a handful per turn. 30/min
|
||||
* is a target switch every two seconds, sustained — well clear of either,
|
||||
* and the same band `/api/geocode` and `/api/regional-brief` already use.
|
||||
*/
|
||||
const TRACK_RATE_PER_MIN = 30;
|
||||
const TRACK_RATE_WINDOW_MS = 60_000;
|
||||
const allowOpenSky = makeRateLimiter({
|
||||
windowMs: TRACK_RATE_WINDOW_MS,
|
||||
max: TRACK_RATE_PER_MIN,
|
||||
globalMax: TRACK_RATE_PER_MIN * 3,
|
||||
});
|
||||
/**
|
||||
* `/tracks/*` credit governor: a 429 from /tracks/all means that bucket is
|
||||
* empty for every `icao24`, so no upstream call is made until OpenSky's
|
||||
* retry-after passes. The `/states/*` cooldown in opensky.js is a different
|
||||
* bucket and does not apply here.
|
||||
*/
|
||||
let openSkyTracksCooldownUntil = 0;
|
||||
const openSkyTracksGovernor = {
|
||||
remainingMs: () => Math.max(0, openSkyTracksCooldownUntil - Date.now()),
|
||||
arm(upstream) {
|
||||
openSkyTracksCooldownUntil =
|
||||
Date.now() + openSkyRateLimitCooldownMs(upstream);
|
||||
},
|
||||
};
|
||||
/** @type {Map<string, {at:number,status:number,body:string}>} */
|
||||
const cache = new Map();
|
||||
|
||||
/** Shared refusal shape, matching the other rate-limited proxies. */
|
||||
function refuse(res, retryAfterSeconds) {
|
||||
res.writeHead(429, {
|
||||
'Content-Type': 'application/json',
|
||||
'Retry-After': String(Math.max(1, Math.ceil(retryAfterSeconds))),
|
||||
});
|
||||
res.end(JSON.stringify({ error: 'Rate limit exceeded' }));
|
||||
}
|
||||
|
||||
function cachePut(key, entry) {
|
||||
cache.set(key, entry);
|
||||
if (cache.size > TRACK_CACHE_MAX) {
|
||||
@@ -26,19 +76,63 @@ export function trackBackfillProxies() {
|
||||
}
|
||||
}
|
||||
|
||||
async function proxyJson(res, key, upstreamUrl, headers = {}) {
|
||||
/**
|
||||
* @param {object} [options]
|
||||
* @param {() => Promise<object>|object} [options.headers] Request headers,
|
||||
* resolved only when the upstream is actually called.
|
||||
* @param {{remainingMs: () => number, arm: (upstream: Response) => void}} [options.governor]
|
||||
* Credit cooldown for a metered upstream. While it is cooling the upstream
|
||||
* is not called, though an already-fetched track may still be served (it
|
||||
* costs nothing further); an upstream 429 arms it.
|
||||
* @param {() => boolean} [options.admit] Asked once, immediately before an
|
||||
* upstream call; false refuses the request with a 429.
|
||||
*/
|
||||
async function proxyJson(
|
||||
res,
|
||||
key,
|
||||
upstreamUrl,
|
||||
{ headers = () => ({}), governor, admit } = {},
|
||||
) {
|
||||
const blockedMs = governor?.remainingMs() ?? 0;
|
||||
const cached = cache.get(key);
|
||||
if (cached && Date.now() - cached.at < TRACK_CACHE_MS) {
|
||||
const fresh = cached && Date.now() - cached.at < TRACK_CACHE_MS;
|
||||
// Serve-stale while the account is cooling, the way `/api/flights` does:
|
||||
// a stale trail beats no trail, and replaying a cached body spends no
|
||||
// credits. Only a track is worth replaying past its window: an old error
|
||||
// says nothing about now, so it gives way to the cooldown refusal.
|
||||
const replayable =
|
||||
cached && (fresh || (blockedMs > 0 && cached.status === 200));
|
||||
if (replayable) {
|
||||
res.statusCode = cached.status;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.end(cached.body);
|
||||
return;
|
||||
}
|
||||
if (blockedMs > 0) {
|
||||
refuse(res, blockedMs / 1000);
|
||||
return;
|
||||
}
|
||||
if (admit && !admit()) {
|
||||
refuse(res, TRACK_RATE_WINDOW_MS / 1000);
|
||||
return;
|
||||
}
|
||||
const upstream = await fetch(upstreamUrl, {
|
||||
headers,
|
||||
headers: await headers(),
|
||||
signal: AbortSignal.timeout(12000),
|
||||
});
|
||||
if (upstream.status === 429 && governor) {
|
||||
// The cooldown now answers for every key, with the time left; caching
|
||||
// this 429 would replay it for the key without one.
|
||||
governor.arm(upstream);
|
||||
try {
|
||||
await upstream.body?.cancel();
|
||||
} catch {
|
||||
/* nothing left to release */
|
||||
}
|
||||
refuse(res, governor.remainingMs() / 1000);
|
||||
return;
|
||||
}
|
||||
const { tooLarge, text } = await readCappedResponseText(
|
||||
upstream,
|
||||
RESPONSE_CAP_BYTES,
|
||||
@@ -78,12 +172,20 @@ export function trackBackfillProxies() {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const token = await getOpenSkyToken();
|
||||
await proxyJson(
|
||||
res,
|
||||
`osky:${icao24}`,
|
||||
`https://opensky-network.org/api/tracks/all?icao24=${icao24}&time=0`,
|
||||
token ? { Authorization: `Bearer ${token}` } : {},
|
||||
{
|
||||
// Resolved only for a live call: no token is minted for a cached
|
||||
// answer, a refusal, or while the /tracks bucket is cooling.
|
||||
headers: async () => {
|
||||
const token = await getOpenSkyToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
},
|
||||
governor: openSkyTracksGovernor,
|
||||
admit: () => allowOpenSky(clientKey(req)),
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
res.statusCode = 502;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -49,6 +49,7 @@ export function celestrakProxy() {
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
];
|
||||
const feeds = [
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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} 発表"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -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}"
|
||||
}
|
||||
@@ -541,7 +541,7 @@
|
||||
"Conversation",
|
||||
"Country",
|
||||
"Cyan",
|
||||
"Cyclones · NHC / CPHC",
|
||||
"Cyclones · NHC / CPHC · JTWC",
|
||||
"DENSE",
|
||||
"DEST ---°",
|
||||
"DEST {bearing}",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
@@ -136,6 +136,7 @@ const GROUP_CLASS = Object.freeze({
|
||||
resource: 'imaging',
|
||||
weather: 'imaging',
|
||||
planet: 'imaging',
|
||||
sar: 'imaging',
|
||||
'gps-ops': 'telecom',
|
||||
glonass: 'telecom',
|
||||
'glo-ops': 'telecom',
|
||||
|
||||
@@ -381,6 +381,7 @@ test('every ingested group names the class its unnamed members fall back to', ()
|
||||
resource: 'imaging',
|
||||
weather: 'imaging',
|
||||
planet: 'imaging',
|
||||
sar: 'imaging',
|
||||
science: 'probes',
|
||||
};
|
||||
assert.deepEqual(
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -16,7 +16,7 @@ export const SATCAT_WAIT_MS = 3000;
|
||||
/**
|
||||
* How long a complete, current SATCAT read is kept before the layer asks
|
||||
* again, ms. SATCAT changes daily and the proxy caches it a day, so the
|
||||
* five-minute TLE update does not read all ten groups each time.
|
||||
* five-minute TLE update does not read all eleven groups each time.
|
||||
*/
|
||||
export const SATCAT_KEEP_MS = 6 * 60 * 60 * 1000;
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
|
||||
/**
|
||||
* Satellite Orbits — Real-time positions via CelesTrak TLE + SGP4 propagation.
|
||||
*
|
||||
* Loads ten CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
|
||||
* geosynchronous belt, and the Earth resources, weather, Planet and science
|
||||
* groups. Each object is filed under one of six classes
|
||||
* Loads eleven CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
|
||||
* geosynchronous belt, and the Earth resources, weather, Planet, SAR and
|
||||
* science groups. Each object is filed under one of six classes
|
||||
* (src/layers/satellites/classes.js) whose visibility the layer row toggles; dense mode
|
||||
* (setParams catalog:'dense', the STARLINK toggle) adds the Starlink shell as
|
||||
* points-only extras.
|
||||
@@ -211,9 +211,6 @@ export const RING_ROTATION_MS = 1000;
|
||||
* proxy; `tag` is the internal group key used for POINT_STYLES lookup.
|
||||
* Note: CelesTrak's GLONASS group is named 'glo-ops' (not
|
||||
* 'glonass-operational' — that name 404s upstream).
|
||||
* Every entry must be a group CelesTrak serves: one that is not fails on every
|
||||
* update, so the layer row reads DEGRADED ("1 CelesTrak group unavailable")
|
||||
* for good. CelesTrak has no `sar` group (`sarsat` is search and rescue).
|
||||
*/
|
||||
|
||||
export const CATALOG_GROUPS = [
|
||||
@@ -228,6 +225,7 @@ export const CATALOG_GROUPS = [
|
||||
{ tag: 'resource', path: 'resource' },
|
||||
{ tag: 'weather', path: 'weather' },
|
||||
{ tag: 'planet', path: 'planet' },
|
||||
{ tag: 'sar', path: 'sar' },
|
||||
{ tag: 'science', path: 'science' },
|
||||
];
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ const GROUPS = new Set([
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
]);
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ const GROUPS = [
|
||||
'resource',
|
||||
'weather',
|
||||
'planet',
|
||||
'sar',
|
||||
'science',
|
||||
];
|
||||
/** The core catalog's groups, one owned satellite each. */
|
||||
|
||||
@@ -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?.();
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
// OPENSKY TRACK BACKFILL — the credit budget the per-icao cache does not guard.
|
||||
//
|
||||
// `/api/flights/track` spends 4 OpenSky credits per call from the `/tracks/*`
|
||||
// bucket. OpenSky keeps three independent daily buckets (`/states/*`,
|
||||
// `/tracks/*`, `/flights/*`), so this route neither spends nor is blocked by
|
||||
// the `/states/all` budget `/api/flights` governs. Its 60s per-icao cache
|
||||
// bounds MEMORY, not spend: `icao24` is six hex digits, so a caller that varies
|
||||
// it walks past the cache into a live, credit-consuming call every time.
|
||||
//
|
||||
// These cases drive the real exported route handlers. No network: `fetch` is
|
||||
// stubbed per test and restored afterwards, so a case that reaches upstream
|
||||
// fails loudly rather than making a request.
|
||||
//
|
||||
// NOTE: the `/states/all` cooldown is module-scoped state in `opensky.js` and,
|
||||
// once set, stays set for the life of the process (bounded 30s…30min). The case
|
||||
// that arms it therefore runs LAST. The tracks cooldown lives in each
|
||||
// `trackBackfillProxies()` instance, so every test gets a clear one.
|
||||
//
|
||||
// Run with: npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { trackBackfillProxies } from '../server/providers/aircraft/tracks.js';
|
||||
import { openSkyProxy } from '../server/providers/aircraft/opensky.js';
|
||||
|
||||
/** Collect a plugin's routes into a path → handler map. */
|
||||
function install(plugin) {
|
||||
const routes = new Map();
|
||||
const server = {
|
||||
middlewares: {
|
||||
use(path, handler) {
|
||||
routes.set(path, handler);
|
||||
},
|
||||
},
|
||||
};
|
||||
plugin.configureServer(server);
|
||||
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,
|
||||
setHeader(name, value) {
|
||||
headers.set(String(name).toLowerCase(), String(value));
|
||||
},
|
||||
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 one test, restoring it afterwards. */
|
||||
function stubFetch(t, impl) {
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = impl;
|
||||
t.after(() => {
|
||||
globalThis.fetch = original;
|
||||
});
|
||||
}
|
||||
|
||||
/** An OpenSky /tracks/all answer, shaped like the real one. */
|
||||
const trackOk = () =>
|
||||
new Response(JSON.stringify({ path: [] }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
test('a caller cycling icao24 cannot walk past the per-icao cache unthrottled', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
const allowed = [];
|
||||
for (let i = 0; i < 30; i += 1) {
|
||||
// A DIFFERENT icao24 every time: each one is a fresh cache key, which is
|
||||
// exactly the path the 60s cache cannot see.
|
||||
const icao24 = (0x400000 + i).toString(16).padStart(6, '0');
|
||||
allowed.push(await request(track, { url: `/?icao24=${icao24}` }));
|
||||
}
|
||||
assert.equal(
|
||||
allowed.filter((r) => r.statusCode === 429).length,
|
||||
0,
|
||||
'the first 30 distinct lookups in a minute are ordinary use',
|
||||
);
|
||||
|
||||
const refused = await request(track, { url: '/?icao24=4affff' });
|
||||
assert.equal(refused.statusCode, 429, 'the 31st distinct lookup is refused');
|
||||
assert.deepEqual(refused.body, { error: 'Rate limit exceeded' });
|
||||
assert.equal(
|
||||
refused.headers['retry-after'],
|
||||
'60',
|
||||
'a refusal names the limiter window, not a shorter guess',
|
||||
);
|
||||
assert.equal(
|
||||
upstreamCalls,
|
||||
30,
|
||||
'the refused request never reached OpenSky — the point is the credits',
|
||||
);
|
||||
});
|
||||
|
||||
test('each client gets its own quota rather than sharing one bucket', async (t) => {
|
||||
stubFetch(t, async () => trackOk());
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
for (let i = 0; i < 30; i += 1)
|
||||
await request(track, {
|
||||
url: `/?icao24=${(0x500000 + i).toString(16)}`,
|
||||
remoteAddress: '198.51.100.7',
|
||||
});
|
||||
const exhausted = await request(track, {
|
||||
url: '/?icao24=5affff',
|
||||
remoteAddress: '198.51.100.7',
|
||||
});
|
||||
assert.equal(exhausted.statusCode, 429);
|
||||
|
||||
const neighbour = await request(track, {
|
||||
url: '/?icao24=5abbbb',
|
||||
remoteAddress: '198.51.100.8',
|
||||
});
|
||||
assert.notEqual(
|
||||
neighbour.statusCode,
|
||||
429,
|
||||
'one noisy host must not take the layer away from everyone else',
|
||||
);
|
||||
});
|
||||
|
||||
test('the retired military route is not metered, so the OpenSky limiter never reaches it', async (t) => {
|
||||
let militaryUpstreamCalls = 0;
|
||||
stubFetch(t, async (url) => {
|
||||
if (String(url).includes('/tracks/all')) return trackOk();
|
||||
militaryUpstreamCalls += 1;
|
||||
return new Response('{"trace":[]}', { status: 200 });
|
||||
});
|
||||
const routes = install(trackBackfillProxies());
|
||||
const track = routes.get('/api/flights/track');
|
||||
const trace = routes.get('/api/military/track');
|
||||
|
||||
for (let i = 0; i < 30; i += 1)
|
||||
await request(track, { url: `/?icao24=${(0x610000 + i).toString(16)}` });
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=61ffff' })).statusCode,
|
||||
429,
|
||||
);
|
||||
// It answers a fixed refusal without any upstream call, so a limiter would
|
||||
// only turn that refusal into a different one.
|
||||
for (let i = 0; i < 31; i += 1) {
|
||||
const military = await request(trace, {
|
||||
url: `/?hex=${(0x620000 + i).toString(16)}`,
|
||||
});
|
||||
assert.equal(military.statusCode, 503);
|
||||
}
|
||||
assert.equal(militaryUpstreamCalls, 0, 'the refusal makes no upstream call');
|
||||
});
|
||||
|
||||
test('a 429 from /tracks stands every other icao24 down until it clears', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
const first = await request(track, { url: '/?icao24=71a001' });
|
||||
assert.equal(first.statusCode, 429);
|
||||
assert.equal(upstreamCalls, 1);
|
||||
|
||||
// A DIFFERENT key: the per-icao cache cannot see it, only the cooldown can.
|
||||
const second = await request(track, { url: '/?icao24=71a002' });
|
||||
assert.equal(second.statusCode, 429, 'refused locally');
|
||||
assert.equal(
|
||||
upstreamCalls,
|
||||
1,
|
||||
'the /tracks bucket is empty, so no further credits are asked for',
|
||||
);
|
||||
const retryAfter = Number(second.headers['retry-after']);
|
||||
assert.ok(
|
||||
retryAfter > 60 && retryAfter <= 120,
|
||||
`the refusal carries OpenSky's remaining cooldown (got ${retryAfter})`,
|
||||
);
|
||||
});
|
||||
|
||||
test('a cached track is still served while /tracks is cooling', async (t) => {
|
||||
let cooling = false;
|
||||
stubFetch(t, async () =>
|
||||
cooling
|
||||
? new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
})
|
||||
: trackOk(),
|
||||
);
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=72b001' })).statusCode,
|
||||
200,
|
||||
);
|
||||
cooling = true;
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=72b002' })).statusCode,
|
||||
429,
|
||||
);
|
||||
const replay = await request(track, { url: '/?icao24=72b001' });
|
||||
assert.equal(
|
||||
replay.statusCode,
|
||||
200,
|
||||
'replaying a fetched body costs nothing',
|
||||
);
|
||||
});
|
||||
|
||||
test('a malformed icao24 is still rejected before any upstream call', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
const bad = await request(track, { url: '/?icao24=nothex' });
|
||||
assert.equal(bad.statusCode, 400);
|
||||
assert.equal(upstreamCalls, 0);
|
||||
});
|
||||
|
||||
// --- LAST: arming the /states/all cooldown is one-way for this process.
|
||||
test('only upstream calls are charged: cached answers and malformed requests are free', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
// Re-selecting one aircraft, and a burst of malformed requests: more than a
|
||||
// window's worth of each, none of which costs OpenSky anything.
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
const repeat = await request(track, { url: '/?icao24=73c000' });
|
||||
assert.equal(repeat.statusCode, 200);
|
||||
const malformed = await request(track, { url: '/?icao24=nothex' });
|
||||
assert.equal(malformed.statusCode, 400);
|
||||
}
|
||||
assert.equal(upstreamCalls, 1, 'one live call, 39 answers from the cache');
|
||||
|
||||
// The window still holds 29 more live calls for this client.
|
||||
for (let i = 1; i < 30; i += 1) {
|
||||
const icao24 = (0x73c000 + i).toString(16);
|
||||
const live = await request(track, { url: `/?icao24=${icao24}` });
|
||||
assert.equal(live.statusCode, 200, `live lookup ${i + 1} of 30 is allowed`);
|
||||
}
|
||||
const refused = await request(track, { url: '/?icao24=73cfff' });
|
||||
assert.equal(refused.statusCode, 429, 'the 31st live lookup is refused');
|
||||
assert.equal(upstreamCalls, 30);
|
||||
});
|
||||
|
||||
test('the request that trips the cooldown, and repeats of it, carry the time left', async (t) => {
|
||||
let upstreamCalls = 0;
|
||||
stubFetch(t, async () => {
|
||||
upstreamCalls += 1;
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
});
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
for (const attempt of ['first', 'repeat']) {
|
||||
const refused = await request(track, { url: '/?icao24=74d001' });
|
||||
assert.equal(refused.statusCode, 429);
|
||||
const retryAfter = Number(refused.headers['retry-after']);
|
||||
assert.ok(
|
||||
retryAfter > 60 && retryAfter <= 120,
|
||||
`the ${attempt} refusal names OpenSky's cooldown (got ${retryAfter})`,
|
||||
);
|
||||
}
|
||||
assert.equal(upstreamCalls, 1, 'the repeat was answered by the cooldown');
|
||||
});
|
||||
|
||||
test('an error cached before the cooldown is not replayed as stale', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: 1_800_000_000_000 });
|
||||
let mode = 'missing';
|
||||
stubFetch(t, async () =>
|
||||
mode === 'missing'
|
||||
? new Response('{}', { status: 404 })
|
||||
: new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '600' },
|
||||
}),
|
||||
);
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=75e001' })).statusCode,
|
||||
404,
|
||||
);
|
||||
t.mock.timers.tick(61_000); // the 404 has left its 60 s window
|
||||
mode = 'cooling';
|
||||
assert.equal(
|
||||
(await request(track, { url: '/?icao24=75e002' })).statusCode,
|
||||
429,
|
||||
);
|
||||
const later = await request(track, { url: '/?icao24=75e001' });
|
||||
assert.equal(
|
||||
later.statusCode,
|
||||
429,
|
||||
'the old 404 is not served as if it were current',
|
||||
);
|
||||
assert.ok(Number(later.headers['retry-after']) > 60);
|
||||
});
|
||||
|
||||
test('a /states/all 429 does not block track backfill: separate OpenSky buckets', async (t) => {
|
||||
let trackUpstreamCalls = 0;
|
||||
stubFetch(t, async (url) => {
|
||||
if (String(url).includes('states/all')) {
|
||||
return new Response('{}', {
|
||||
status: 429,
|
||||
headers: { 'x-rate-limit-retry-after-seconds': '120' },
|
||||
});
|
||||
}
|
||||
trackUpstreamCalls += 1;
|
||||
return trackOk();
|
||||
});
|
||||
|
||||
const states = install(openSkyProxy()).get('/api/flights');
|
||||
await request(states, { url: '/' });
|
||||
|
||||
const track = install(trackBackfillProxies()).get('/api/flights/track');
|
||||
const backfill = await request(track, { url: '/?icao24=7a1b2c' });
|
||||
assert.equal(
|
||||
backfill.statusCode,
|
||||
200,
|
||||
'the /tracks bucket still has credits, so the trail is fetched',
|
||||
);
|
||||
assert.equal(trackUpstreamCalls, 1);
|
||||
});
|
||||
+672
-69
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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',
|
||||
|
||||
Vendored
+6
@@ -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. */
|
||||
|
||||
Vendored
+66
@@ -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;
|
||||
|
||||
@@ -41,6 +41,9 @@ export const CAPABILITIES = Object.freeze([
|
||||
'meshes',
|
||||
'fields',
|
||||
'courseGlide',
|
||||
'lineAgeFade',
|
||||
'lineTimeWindow',
|
||||
'lineBreaks',
|
||||
'cluster',
|
||||
'styles',
|
||||
'bloom',
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -374,10 +374,7 @@ test('a SATCAT failure never holds off the TLEs, but CelesTrak throttling holds
|
||||
: new Response(tle);
|
||||
});
|
||||
const request = install(celestrakProxy());
|
||||
assert.equal(
|
||||
(await request('/api/celestrak-satcat', '/science')).status,
|
||||
502,
|
||||
);
|
||||
assert.equal((await request('/api/celestrak-satcat', '/sar')).status, 502);
|
||||
const starlink = await request('/api/celestrak', '/starlink');
|
||||
assert.equal(starlink.status, 200, 'the TLE feed is not cooling down');
|
||||
assert.equal(starlink.body, tle);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
@@ -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
@@ -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');
|
||||
|
||||
@@ -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 },
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
Reference in new issue
Block a user