Compare commits

..
Author SHA1 Message Date
Said Turksever 83f5a3e2bd docs(changelog): name the TomTom Orbis fragment after its PR 2026-11-20 14:35:46 +00:00
Said Turksever b711e9e412 fix(traffic): fall back to TomTom Orbis flow tiles when the key is refused
TomTom keys are assigned products. A key without the TomTom Maps Traffic
product gets HTTP 403 on traffic/map/4/tile/flow, the only endpoint the
proxy called, so live traffic never loaded and the layer reported
"TomTom upstream unreachable".

- Proxy: on 403, ask the Orbis Maps flow endpoint (apiVersion 2) and keep
  whichever endpoint answered until the key changes.
- Decoder: read Orbis relative_speed and road_category into the existing
  segment shape.
- When both endpoints refuse the key, answer 403 key_rejected, report
  keyRejected on /api/tomtom/status, show "TomTom key rejected" and leave
  upstream alone for five minutes instead of spending the tile budget.

Fixes #1809
2026-11-20 14:33:47 +00:00
199 changed files with 2474 additions and 12577 deletions

No files matched your search

+3
View File
@@ -205,6 +205,9 @@ AISSTREAM_API_KEY=
# Traffic Flow & Incidents tile requests per MONTH, not per day; no credit card
# required. Get a key at https://my.tomtom.com/keys). SERVER-SIDE ONLY:
# the browser fetches same-origin /api/tomtom/* and never sees the key.
# The key needs a traffic product assigned at my.tomtom.com: either the
# TomTom Maps Traffic API or the Orbis Maps one works (the proxy tries the
# first and falls back to Orbis on HTTP 403).
# Keyless fallback: the traffic layer runs its built-in simulation (white dots,
# hardcoded per-road-class speeds) — no key required for the layer to work.
# TOMTOM_API_KEY=
+2 -23
View File
@@ -20,7 +20,6 @@ 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 |
@@ -44,7 +43,7 @@ How to read this:
| **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |
| **Environment and Climate Change Canada** (MSC GeoMet OGC API) | Air quality (AQHI) — Canadian station observations | [ECCC Data Servers End-use Licence](https://eccc-msc.github.io/open-data/licence/readme_en/) (open, attribution required, no endorsement implied) | "Contains information licensed under the Environment and Climate Change Canada Data Servers End-use Licence" |
| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) |
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts; perimeters are coloured by when they were mapped (`poly_PolygonDateTime`, else the record's last edit `poly_DateCurrent`, which also moves when only the incident's attributes are edited, so such a fire can look newly grown) | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
| **NIFC WFIGS** (Wildland Fire Interagency Geospatial Services, ArcGIS feature service) | Fire Perimeters layer: current interagency wildfire incident perimeters, containment, and incident facts | U.S. public domain (interagency wildland-fire data published through the [NIFC Open Data portal](https://data-nifc.opendata.arcgis.com/)); fetched keyless through `/api/fire-perimeters` (5-minute server cache) with `exceededTransferLimit` paging | "Wildfire perimeters: National Interagency Fire Center (WFIGS)" |
| **S2 Underground GhostMaps** (`github.com/s2underground/GhostMaps`) | S2 GhostMaps layer: the current edition of S2's KMZ intel products (Common Intelligence Picture, 30-day kinetic pull, Border Crisis Map, Iran and Yemen products, newest incident drop). Keyless. `/api/ghostmaps` reads the branch head from git's ref advertisement every 15 s (`GHOSTMAPS_POLL_SECONDS`, minimum 5 s), lists the tree through the GitHub REST API only when the head changes (optional `GITHUB_TOKEN`), downloads files by commit-pinned raw URLs into `.gev-cache/ghostmaps/` and pushes new catalogs to browsers over server-sent events | [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) (repository README: "S2 Underground © 2025 by S2A1"); non-commercial, attribution required; files are fetched at runtime, never stored in this repository | "S2 GhostMaps intel products: S2 Underground © by S2A1, CC BY-NC-SA 4.0" — shown in-app |
| **News server** (`GEV_NEWS_ORIGIN`, optional; none by default) | News layer, both sections: the last 24 h of reports from many publishers. Set, the local server forwards the layer's `/api/news/hotspots`, `/feed` and `/outline` GET requests to it and Core reads none of the three sources below. Which providers stand behind its feed is the news server's to state | Each report stays its publisher's: headlines and summaries link to the original article, and pictures are hotlinked from the publisher's site (no referrer), never stored | Per report: publisher name and article link on every card; picture cards name the picture's publisher. The Data attribution popover states that places, categories, severity and English headlines are derived automatically and can be wrong |
| **GDELT 2.0 events and GKG** (`data.gdeltproject.org/gdeltv2/`; no key; used only without a news server) | News layer, Conflicts: the last 24 h of GDELT's 15-minute event exports (`*.export.CSV.zip`, about 100 KB each), read server-side as they appear. Physical violence only (CAMEO roots 18–20); one report per story, copies of one agency story merged; placed at GDELT's location for it (a town the article's words name beats a bare country). Titled by the article's page title from the GKG export of the same quarter hour (`*.gkg.csv.zip`, about 6 MB each) for the newest 3 h, else by the words of the article's address. GDELT's actor coding is never shown. Categories, relevance and severity by bundled rules | [GDELT Terms of Use](https://www.gdeltproject.org/about.html#termsofuse): unrestricted academic, commercial and governmental use, with citation and a link to the GDELT Project. Coded events, page titles and article links only; linked articles keep their publishers' terms | "GDELT Project" with a link to gdeltproject.org in the Data attribution popover; "via GDELT Project", the publisher's domain and the article link on every card |
@@ -282,7 +281,7 @@ The optional Local ADS-B layer and the broadcast-FM receiver use radio you recei
- **Radio country coverage (optional).** Set `RADIO_PRIORITY_COUNTRIES=IN,PL` in the local `.env` and restart to include stations beyond the global click charts. The operator may choose up to eight unique ISO alpha-2 country codes; no key is needed. Each country adds one bounded query (at most 200 rows) and reserves up to 40 unique, usable stations inside the existing 750-station catalog. Country seeds precede specialist-tag seeds and global popularity fill; unused slots return to the shared pool. This is a coverage preference, not an exhaustive national directory or a guarantee of stations in every city. Countries with no eligible HTTPS MP3/AAC geolocated stations remain empty. An unset list preserves global selection. Country requests share the directory cache and three-worker pool; failed country queries are reported in coverage without blocking a healthy global refresh. Failed/degraded refreshes back off for one minute, with at most three mirrors per query.
- **Radio Browser.** In every installation, including when `RADIO_PRIORITY_COUNTRIES` is unset, each request tries at most three mirror candidates (later fallback candidates are skipped), and failed or partial catalog refreshes back off for 60 seconds. A cold-start failure therefore continues returning 503 during that delay even if upstream recovers. `/api/radio/stations` discovers official API mirrors, makes bounded and coalesced healthy/geolocated HTTPS-station queries, caches the normalized public-domain directory for 45 minutes, and may serve the last good catalog for up to seven days during an outage. Refreshes must meet minimum accepted-query and station coverage before replacing a warm catalog; broad/specialist responses whose rows all fail the product's health policy do not count as successful queries. Optional priority-country outcomes are advisory: valid, in-limit responses with no eligible stations succeed as empty results, while failed or malformed country queries report unsuccessful coverage without degrading the global catalog. A usable partial cold catalog is explicitly `DEGRADED`, and non-array or empty broad/specialist payloads are rejected atomically. Individual structurally malformed rows are skipped rather than failing the whole query; the response carries their bounded `rejectedStationCount` (at most 10,000), which the client adds to its own rejected rows and reports as degraded coverage without discarding the accepted generation. Every directory and click-count request rejects redirects, validates all resolved addresses as globally routable (including reserved/documentation IPv4 and special/non-global IPv6 exclusions), and pins the TLS connection to a validated address. Only MP3/AAC non-HLS directory rows with public HTTPS stream targets are returned; favicons are intentionally omitted. Pressing play connects one browser audio element directly to the selected broadcaster and calls the directory's click counter through known-ID-only `POST /api/radio/click/:uuid`. GEV never proxies, caches, records, bundles, or redistributes audio. Radio Browser supplies station-level tags, not dependable current-song or upcoming-program metadata, so Radio filtering never claims either. Direct playback exposes the listener's IP address to the broadcaster, whose own stream terms apply.
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **TomTom Traffic.** Optional and BYOK: without `TOMTOM_API_KEY` the traffic layer runs its built-in simulation and no TomTom data (or attribution) appears. With a key, flow vector tiles are fetched through the server-side `/api/tomtom` proxy (from the TomTom Maps Traffic API, or the TomTom Orbis Maps Traffic API when the key is only assigned that product; 120 s cache + a daily tile-budget governor — `TOMTOM_DAILY_TILE_BUDGET`, default 6,000 — sized so a 31-day month stays inside TomTom's 200K monthly free allowance; still a configurable application safety ceiling, not a guarantee; TomTom's [current pricing](https://docs.tomtom.com/pricing/) lists 200K free tile requests per month) and the "Traffic flow data © TomTom" credit is registered in the Data attribution popover the moment live mode activates. TomTom data is served live and cached only transiently (≤120 s TTL under `.gev-cache/`, gitignored) — it is not bundled or redistributed. One 23 KB point-in-time tile snapshot is committed as a decode-test fixture (`src/data/fixtures/`, © TomTom, never served to the app).
- **Routing (OSRM / FOSSGIS).** `/api/route` proxies the public OSRM instances FOSSGIS e.V. runs for the OpenStreetMap community (car, bike, foot profiles). They are keyless and intended for fair, interactive use — the proxy rate-limits clients (60/min, 200/min total), caps route span and response size, caches each route for 10 minutes, and identifies itself in the User-Agent. Heavy or automated use must run its own OSRM. Routes are computed from OpenStreetMap data (ODbL); the Directions layer and voice routes never redistribute them. A route the router cannot find is reported as such; the Directions layer draws nothing in that case, and voice routes fall back to a clearly labeled straight line.
- **Re:Earth Terrain.** Keyless (no API key). Used two ways: (1) `src/mapStackController.js` swaps in a `Cesium.CesiumTerrainProvider` pointed at Re:Earth's `cesium-mesh/ellipsoid` quantized-mesh endpoint for globe stacks without a Cesium ion token (e.g. OSM), replacing a flat `EllipsoidTerrainProvider`; falls back to the flat provider if the endpoint can't be reached. (2) The server-side `/api/terrain/heights` proxy (disk-cached, serve-stale) resolves per-point ellipsoidal ground height for entity placement. Both are best-effort with a keyless-safe fallback (bundled EGM96 geoid math) if Re:Earth is unreachable.
- **OSRM on the FOSSGIS routing servers.** Keyless (no API key). Every route is requested by a person: clicking A and B in the Directions layer, or a voice "route from A to B". The server-side `/api/route` proxy sends an identifying `User-Agent`, pins the upstream host, accepts 2-12 coordinates, rejects any leg over 600 km or a total over 2,500 km, caps the buffered response at 8 MB, times the upstream out at 12 s, rate-limits per client, caches each route for 10 minutes, and coalesces identical requests that are in flight at the same time. Turn-by-turn maneuvers are asked for only when a caller wants them (`steps=1`), so the callers that do not read them send the smaller request. The "fix the map" link the policy asks for is in the Data attribution popover beside the OpenStreetMap credit.
@@ -710,26 +709,6 @@ 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),
+4 -6
View File
@@ -16,8 +16,6 @@ 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)
@@ -96,7 +94,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 and JTWC 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 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.
@@ -443,7 +441,7 @@ Twenty-three layers and map sources. **Twenty-one have a keyless path.** Some of
| ✈️ **Live Flights** | 11,000+ live aircraft + route history | OpenSky + adsb.lol | 🟢 (🟡 optional for more polling credits) |
| 🎖️ **Military Flights** | ADS-B military traffic in amber, emergency broadcasts in red | adsb.lol | 🟢 |
| 📡 **GNSS Integrity** | Regional navigation accuracy scores; anomalies do not confirm interference | adsb.lol, GPSJAM aggregation | 🟢 |
| 🔥 **Fire Perimeters** | Incident boundaries coloured by how recently they were mapped; size, containment and cause on each card when the source reports them | WFIGS / NIFC | 🟢 |
| 🔥 **Fire Perimeters** | Incident boundaries and reported containment | WFIGS / NIFC | 🟢 |
| 🚢 **Live Vessels** | Thousands of ships worldwide | AISStream | 🟡 |
| 🛰️ **Satellites** | About 1,300 objects in six classes (Stations, Imaging, Telecom, Starlink, Probes, Debris) with a toggle and a live count each; Starlink loads its whole shell | CelesTrak | 🟢 |
| 🌍 **Earthquakes** | Global seismic activity, last 24h | USGS | 🟢 |
@@ -466,11 +464,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 (Atlantic, eastern/central North Pacific); warnings with 34-knot wind danger areas elsewhere | NOAA NHC / CPHC · JTWC | 🟢 |
| 🌀 **Cyclones** | Advisory positions, forecast tracks and uncertainty cones for the Atlantic and eastern/central North Pacific | NOAA NHC / CPHC | 🟢 |
</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, 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.
**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.
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,6 +0,0 @@
- Recent Imagery takes a box dragged across the dateline as the short box across
±180° instead of refusing it as about 360° wide. A day counts when either side
has imagery. A side confirmed empty is not draped, and the VIIRS overview
drapes only a side confirmed to have data. Voice accepts named areas across
the dateline. EXPORT and `get_recent_imagery` refuse such a box, since
Worldview Snapshots cannot draw one (Byrd-IT, #1540).
@@ -1,4 +0,0 @@
- Stop fetching the active CCTV camera's pictures when nobody can see them. The
monitor plane skips its 10 s still while it is off screen or below the
horizon, and the still preview waits for a visible tab and an open panel or
Context camera card (on phones, the open Cameras or Context sheet) (Byrd-IT, #1543).
@@ -0,0 +1,5 @@
- Live traffic works with TomTom keys that are only assigned the Orbis Maps
traffic product: when TomTom refuses the key on the TomTom Maps flow tile
endpoint (HTTP 403), the proxy uses the Orbis one and keeps it. A key both
endpoints refuse now reads "TomTom key rejected" instead of "TomTom upstream
unreachable", and stops spending the daily tile budget on retries (#1809).
@@ -1,3 +0,0 @@
- 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).
@@ -1,3 +0,0 @@
- A voice or chat selection opens its card in the Context panel, as a click
does, and a docked assistant panel steps down so the card shows; the reply
stays until the next one (samehkhamis, #1890).
-5
View File
@@ -1,5 +0,0 @@
- Cyclone advisories show the Joint Typhoon Warning Center's storms beside
NHC's: the western Pacific, the Indian Ocean and the Southern Hemisphere.
JTWC's 34-knot wind danger area is drawn where it publishes no cone, its
cards say the regional centre's warning is the official one, and each storm
now ages out on its own (samehkhamis, #1891).
-4
View File
@@ -1,4 +0,0 @@
- 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).
@@ -1,2 +0,0 @@
- Opening the phone Context tab with an aircraft tracked shows its card and no
longer switches Contacts on (samehkhamis, #1893).
-5
View File
@@ -1,5 +0,0 @@
- A line can show only the part of it within a span of the scene clock
(`LineAgeFade.showMs`, capability `lineTimeWindow`): the renderer cuts it by
time on the GPU as the clock moves, so a moving trail can be sent once as
its whole track; the Cesium renderer draws it, draped or not (samehkhamis,
#1894).
-5
View File
@@ -1,5 +0,0 @@
- 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).
@@ -1,8 +0,0 @@
- Color Fire Perimeters by how recently each area was mapped instead of by
containment: each burned-area piece is yellow under 6 hours old, orange at
6–24 hours, red at 1–3 days and dark red when older or of unknown age, with
no line along the cuts between pieces. The legend counts fires by their last
growth, the card adds "last growth … ago" and keeps containment, and
`get_fire_perimeters` returns `last_growth`. A perimeter source now has one
`getSnapshot` method, and `perimeterOptions: { inciweb: false }` turns off
InciWeb links (gekh, #1910).
-4
View File
@@ -1,4 +0,0 @@
- Stop restyling the whole page on every DOM change. Rules that checked
`body:has(...)` now read classes on the page root that the components owning
that state set, and the Intel HUD runs no timers and writes nothing while it
is not displayed (samehkhamis, #1911).
-3
View File
@@ -1,3 +0,0 @@
- Leave the clock at live when Play is pressed at live. Play used to jump to
the start of the track and play the whole range from there; paused in the
past it still plays from that time (samehkhamis, #1915).
+30 -58
View File
@@ -1123,18 +1123,17 @@ Catalog calls check their cancellation signal immediately before executing a
tool. Already-cancelled queries do not start; cancellation after execution starts
continues to follow the existing tool and caller behavior.
Fire-perimeter queries test the polygon interiors and holes of each fire's
pieces on continuous unwrapped longitudes, matching the short-edge convention
used for boundary intersections: a fire is in the area when one of its pieces
is. An outline crossing ±180° contains nearby boxes and radius areas without
also containing their counterparts near Greenwich. A fire is returned at its
card anchor, which the source gives; for WFIGS it is a circular longitude mean
over the largest outer ring (excluding its repeated closing vertex), with the
relative-area comparison following short longitude edges so a small
dateline-crossing part cannot outweigh a larger ordinary part. Context's
hazard list measures distance to the same anchor. Regression coverage lives in
`src/tools/area.test.mjs`, `src/tools/queries/environment.test.mjs` and
`src/layers/perimeters/records.test.mjs`.
Fire-perimeter queries test polygon interiors and holes on continuous unwrapped
longitudes, matching the short-edge convention used for boundary intersections.
An outline crossing ±180° contains nearby boxes and radius areas without also
containing their counterparts near Greenwich. Returned perimeter coordinates
use a circular mean for longitude, including multipart outlines. Incident cards
also use a circular longitude mean over the largest outer ring (excluding its
repeated closing vertex). Their relative-area comparison follows short longitude
edges so a small dateline-crossing part cannot outweigh a larger ordinary part.
Regression coverage lives in `src/tools/area.test.mjs`,
`src/tools/queries/environment.test.mjs` and
`src/layers/perimeters/cards.test.mjs`.
## Scope display controls
@@ -1628,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. 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.
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.
Typed chat sits beside voice in the dock. Chat replies are silent and never
request microphone access. The first message connects with the selected
@@ -1658,12 +1657,6 @@ 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,
@@ -2094,16 +2087,6 @@ already shows, so the list cannot pick that camera: FOCUS does, and so does
NEAREST when that camera is the nearest. Closing the list without a choice
keeps automatic selection.
The active camera's pictures follow what can be seen. The monitor plane skips
its 10 s still while the renderer reports it off screen or below the horizon,
and fetches on the first refresh tick after it is back. Activating or
calibrating a camera bypasses visibility and the usual refresh interval, but
still waits for an in-flight request and the provider's minimum interval.
The panel's still and live video run only while the tab is visible and the
panel is open (on phones, the Cameras sheet). The still also loads while
Context shows the camera's card (on phones, the Context sheet) or its bigger
view is open.
Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them.
Traffic and bikeshare expose factories through `./layers/traffic` and
@@ -3753,10 +3736,9 @@ 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.
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.
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.
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
@@ -4045,6 +4027,14 @@ The TomTom `/api/tomtom/*` routes run the shared same-site admission gate before
status, cache or upstream work, refusing cross-site browser requests while
preserving same-origin app requests and non-browser local callers. The browser
layers and their rendering remain in their existing modules.
The proxy asks the TomTom Maps flow endpoint (`traffic/map/4/tile/flow/relative`)
first. On HTTP 403, which TomTom answers when a key is not assigned that
product, it asks the Orbis Maps one (`maps/orbis/traffic/flow/vector/tile`,
`apiVersion=2`) and keeps whichever answered until the key changes or the
process restarts; `flowDecode.js` reads both tile schemas into one segment
shape. When both refuse the key, tiles answer `403 {error:'key_rejected'}`
(shown as "TomTom key rejected"), `/api/tomtom/status` reports
`keyRejected: true`, and upstream is left alone for five minutes.
Past the daily tile budget, or while TomTom fails, the proxy answers with its
last copy of a tile (`x-tomtom-cache: STALE-BUDGET` / `STALE-ERROR`) however old
it is, and every tile carries `x-tomtom-fetched-at`, the proxy fetch time
@@ -6327,12 +6317,7 @@ Historical planning documents may not match runtime behavior.
## Runtime Stack
- Vite + CesiumJS app with Google Photorealistic 3D Tiles
- Scene/HUD/style systems in `src/ui/` and `src/hud.js`. While `#intel-hud` is
not displayed (it or a parent has `display: none`, or its view is
unmounted), the Intel HUD runs no timers, drops a summary it was working
out and publishes no readouts, only its own `active`, variant and colors,
which stylesheets and layout elsewhere read; it shows current readouts, and
a reply that was typing out in full, as soon as it is displayed again.
- Scene/HUD/style systems in `src/ui/` and `src/hud.js`
- Layer management in `src/data/manager.js`
- Map stack switching in `src/mapStackController.js`
- Voice control in `src/voice/` (OpenAI Realtime over WebRTC)
@@ -6410,11 +6395,7 @@ MLAT-positioned GPS loss, derived-field exclusions and the NIC 0 exception.
anchors, recovery, keyboard and mobile states; emergency repainting is covered
by `scripts/qa-emergency-squawk.mjs`. Both accept `--timeout-ms` for slow boot.
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Link checks cancel on disable or selection change.
Fire Perimeters draws the fires and burned-area pieces of its source's snapshot. The `getSnapshot` contract is documented in the JSDoc of `createFirePerimetersLayer` (`src/layers/perimeters/index.js`). Pieces are coloured by age at `at` (or now). Areas under 6 hours old are yellow, 6–24 hours orange, and 1–3 days red. Older areas, areas of unknown age and areas dated after `at` are dark red. The layer redraws when `revision` changes or a piece moves to another age band. A snapshot without a string `revision` is redrawn on every read. The legend counts fires by `lastGrowthTime` at the moment of the last successful read, matching the map, and shows the source's `note`. A failed read keeps the last picture and the row shows the error. For a snapshot with a past `at`, a card can link only to an InciWeb incident that began by that time. Of several same-name incidents in the fire's state, it links the one that began nearest the fire's discovery. If none of them began by then, or the ones that did failed to load, it links the fire's complex page by the same rule. A page that fails to load is skipped until the fire is selected again or a read finds its card without a link. `analyst_query` counts `ageHours` from `at` too and treats times after `at` as unknown.
WFIGS keeps one current perimeter per fire, so each of its polygons is one piece. Colour shows the age of the perimeter based on `poly_PolygonDateTime`. When that field is empty (8 of 54 fires on 2026-11-20), the source falls back to `poly_DateCurrent`, which changes with any edit to the record. A time more than 10 minutes ahead of the browser clock counts as unknown, a nearer one as now. The `revision` follows fire ids and `poly_DateCurrent`. For a fire without `poly_DateCurrent`, it follows the mapping time and outline. WFIGS snapshots always have `at: null`.
Fire Perimeters uses capped, timed server reads with stale-on-error caching and a per-client limit. A stale snapshot is served for at most 24 hours; the layer row then reads STALE, dated by that snapshot's fetch, and `get_fire_perimeters` returns `stale` and `retrieved_at` with "(data may be stale)" in its summary. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
The incident card rounds the WFIGS size to whole acres, except under one acre,
where it keeps the reported hundredths: a 0.25-acre fire reads `0.25 ac`, not
@@ -8900,10 +8881,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool,
pins and share links already supply complete boxes.
- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room.
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
- **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
@@ -9110,17 +9091,8 @@ 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, 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.
Cockpit actions, double-click and voice use the same gate; voice entry still
opens Contacts first, as its layer-targeted entry navigates through Contacts.
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)).
+3 -7
View File
@@ -105,13 +105,9 @@ 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 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.
- **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.
- **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
-59
View File
@@ -81,13 +81,6 @@ optional:
target's east-north-up frame, or the identity. `setView` keeps that frame
while it places a world pose. A share link's follow offset is
re-expressed in it, satellites included.
- `camera.visiblePoints(points, horizonMarginM)` (capability `pointVisibility`)
is whether any of the points may be on screen: `false` only when their
bounding sphere is outside the view or all of them are below the horizon
of the WGS84 ellipsoid shrunk by `horizonMarginM` metres; `null` when it
cannot tell (not a 3D scene, an empty point set, or a non-finite point or
camera vector), and callers count that as visible. Supply a finite,
nonnegative margin smaller than the shortest WGS84 radius.
- `globe.surfaceVersion()` (capability `surfaceIdentity`) is a number that
changes whenever what surface heights answer against changes (base,
terrain or photoreal route swapped, the globe shown or hidden) and never
@@ -122,58 +115,6 @@ 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
+1 -1
View File
@@ -310,7 +310,7 @@ and the development server's internal routes. See SECURITY.md.
| `get_bhote_koshi_flood` | `events` | The 2026 Bhote Koshi flood: evidence trail in story order, flood path and imagery dates (CC BY-NC 4.0) |
| `get_regional_brief` | `regional` | What and where a location is, its weather and recent headlines |
| `get_cyclones` | `cyclones` | Active NHC/CPHC tropical cyclones, optionally in an area |
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first, with when each was last mapped (WFIGS mapping time, else the record's last edit) |
| `get_fire_perimeters` | `perimeters` | Mapped WFIGS wildfire perimeters in an area, largest first |
| `get_terrain_height` | `terrain` | Ground, geoid and ellipsoid heights at up to 20 points |
| `find_military_installations` | `installations` | OpenStreetMap military sites in an area of at most 10° per side |
| `get_map_features` | `features` | Administrative areas, named places or monuments at a location (needs Overpass) |
+1 -28
View File
@@ -629,12 +629,7 @@ slot whenever its view is drawn.
store, which IntelHUD publishes to through its `publish` option: the
readouts, the typing summary, the REC blink, visibility, layout variant
and style colors; the vessel layer presents the selected vessel's
readout through `src/hudReadouts.js` instead of writing into the HUD;
the view reports through the store whether `#intel-hud` is displayed
(not displayed once it is unmounted), and while it is not IntelHUD runs
no timers and publishes only the root's `active`, variant and colors,
then shows current readouts as soon as it is; the readouts that change many times a
second keep their text node through `v-text-data`),
readout through `src/hudReadouts.js` instead of writing into the HUD),
the first-run mission launcher (the welcome view renders the card's
visibility, busy state, status line, copy and scroll fade from the
`gev-first-run` store that `initFirstRunExperience` publishes to, and its
@@ -705,28 +700,6 @@ slot whenever its view is drawn.
hosts to register panels and rail items is deferred until a host needs
one.
## Page-root state classes
A stylesheet that styles one surface by the state of another, in a different
view (the dock and credits while the Omnibar is on the page, the Stories
entry while the loading screen shows), selects a class on `<html>` rather
than `body:has(...)`. Chrome checks a `:has()` on body again after every node
added or removed anywhere on the page and restyles the whole page when it
does; a class changes only with the state it names. `src/ui/rail/rootClass.js`
holds them: `v-root-class` on the element whose presence or state it names
(the Omnibar, the voice control in the dock, `#intel-hud`, the first-run
launcher, the World Timeline, the language picker), its hooks running inside
Vue's patch so the class changes with the element; `followSelectorRootClass()`
for markup Vue does not render (the loading screen, followed by the Stories
view wherever in body it is added, removed or shown, as `:has()` would); and
`followRootClass()` for nodes that move at run time (the left panel stack's
own panels, followed by the layer panels view). They live on `<html>`, not
`<body>`, whose class changes several owners follow to lay the page out
again. A rule selects one as `body:is(.has-omnibar *, #gev-omnibar)`: the
second argument never matches body and keeps the specificity the
`:has(#gev-omnibar)` it replaced had. `src/ui/pageRootClasses.test.mjs`
holds each class to its state and every stylesheet to the pattern.
## Verification
- Unit tests: stores and components run under `npm test`. Single-file
+1 -5
View File
@@ -80,8 +80,6 @@
"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",
@@ -469,8 +467,6 @@
"src/layers/perimeters/cards.test.mjs",
"src/layers/perimeters/inciweb.test.mjs",
"src/layers/perimeters/ownership.test.mjs",
"src/app/layers/perimeters.test.mjs",
"src/ui/spotConditions.test.mjs",
"src/layers/droneAirspace/index.js",
"src/layers/droneAirspace/records.js",
"src/layers/droneAirspace/source.js",
@@ -1218,6 +1214,7 @@
"src/sources/militaryTileGeometry.test.mjs",
"src/layers/traffic/surface.test.mjs",
"src/layers/traffic/roadModes.test.mjs",
"src/layers/traffic/flowDecode.test.mjs",
"scripts/qa-traffic-motion.mjs",
"src/layers/traffic/motion.test.mjs",
"scripts/qa-journey-recorder.mjs",
@@ -1449,7 +1446,6 @@
"src/hudReadouts.js",
"src/ui/stores/hud.js",
"src/ui/views/intelHudView.test.mjs",
"src/ui/pageRootClasses.test.mjs",
"src/testSupport/hudReadouts.mjs",
"src/ui/stores/firstRun.js",
"src/firstRunLauncherView.test.mjs",
-8
View File
@@ -194,8 +194,6 @@
"src/ui/stores/owners.js",
"src/ui/rail/rangeValue.js",
"src/ui/rail/classToggle.js",
"src/ui/rail/rootClass.js",
"src/ui/rail/textData.js",
"src/ui/rail/focusSafeChildren.js",
"src/ui/rail/fieldValue.js",
"src/ui/rail/statusText.js",
@@ -281,7 +279,6 @@
"src/i18n/marker.js",
"src/sources/httpBody.js",
"src/layers/perimeters/source.js",
"src/layers/perimeters/records.js",
"src/ui/spotConditions.js",
"src/ui/views/panels/SpotConditions.vue",
"src/data/wikidataCities.js",
@@ -1106,7 +1103,6 @@
"src/ui/cctv.js",
"src/ui/cctvBindings.js",
"src/ui/cctvCalibration.js",
"src/ui/mobileSheets.js",
"src/ui/cctvControls.js",
"src/ui/cctvFrames.js",
"src/ui/cctvVideo.js",
@@ -1347,7 +1343,6 @@
"src/data/distanceFormat.js",
"src/i18n/marker.js",
"src/ui/mobileShell.js",
"src/ui/mobileSheets.js",
"src/exclusiveSurfaces.js",
"src/ui/placeNames.js",
"src/hudLayouts.js",
@@ -4800,7 +4795,6 @@
"src/ui/applicationShell.js",
"src/ui/railEdgeScroll.js",
"src/ui/mobileShell.js",
"src/ui/mobileSheets.js",
"src/ui/localePicker.js",
"src/ui/cyberSonarControls.js",
"src/ui/locationNavigation.js",
@@ -4855,7 +4849,6 @@
"src/ui/layerRowText.js",
"src/ui/layerPanel/LayerRows.vue",
"src/ui/rail/classToggle.js",
"src/ui/rail/rootClass.js",
"src/ui/rail/focusSafeChildren.js",
"src/ui/layerPanel/RowText.vue",
"src/ui/layerPanel/RowSwitch.vue",
@@ -8194,7 +8187,6 @@
"src/data/militaryInstallationData.js",
"src/layers/launches/source.js",
"src/layers/perimeters/source.js",
"src/layers/perimeters/records.js",
"src/layers/radio/source.js",
"src/layers/radio/policy.js",
"src/layers/satellites/source.js",
+12 -97
View File
@@ -1,8 +1,4 @@
import {
readResponseBytesCapped,
readResponseTextCapped,
} from './common/http.js';
import { JTWC_USABLE_MS, readJtwcStorms } from './jtwc.js';
import { readResponseTextCapped } from './common/http.js';
const STATUS_URL = 'https://www.nhc.noaa.gov/CurrentStorms.json';
const GIS =
@@ -11,14 +7,7 @@ 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 =
'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;
}
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
const LAYERS = [
{ id: 5, cap: 512 * 1024, count: 500, kind: 'points' },
{ id: 6, cap: 512 * 1024, count: 32, kind: 'track' },
@@ -125,7 +114,6 @@ 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(),
@@ -150,7 +138,6 @@ export function parseCycloneStatus(payload, now = Date.now()) {
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
});
}
@@ -275,13 +262,8 @@ 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) {
@@ -304,64 +286,7 @@ 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(),
@@ -398,14 +323,6 @@ 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;
@@ -448,8 +365,9 @@ export function cycloneProxy({
function describe(value, stale = false) {
return {
schemaVersion: 1,
source: SOURCE,
attribution: ATTRIBUTION,
source: 'NOAA NHC / CPHC',
attribution:
'NOAA/NWS National Hurricane Center / Central Pacific Hurricane Center',
coverage: COVERAGE,
fetchedAt: value?.fetchedAt ?? null,
stale: stale || !value,
@@ -484,16 +402,13 @@ export function cycloneProxy({
json(200, describe(await acquire(controller.signal)));
} catch (error) {
if (error.status === 429) return json(429, { error: 'cyclone_busy' });
// 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));
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));
}
} finally {
res.removeListener?.('close', close);
-1
View File
@@ -23,7 +23,6 @@ const API_URL =
'attr_IncidentTypeCategory',
'attr_FireDiscoveryDateTime',
'poly_DateCurrent',
'poly_PolygonDateTime',
'attr_FireCause',
'attr_FireBehaviorGeneral',
'attr_TotalIncidentPersonnel',
-459
View File
@@ -1,459 +0,0 @@
import { inflateRawSync } from 'node:zlib';
/**
* Joint Typhoon Warning Center (JTWC) warnings for the cyclone layer: the
* western North Pacific, North Indian Ocean and Southern Hemisphere, where
* NHC and CPHC issue none. Keyless; US government work.
*
* rss/jtwc.rss current warnings, product links in each item
* products/<prefix>.tcw JMV 3.0 warning data (position, forecast, text)
* products/<prefix>.kmz Google Earth overlay: the 34-knot danger swath
*
* JTWC publishes no schema for any of these. Each reader takes only what it
* recognises and throws on a product that lacks it. The danger swath is the
* swath of 34-knot winds widened by forecast track error; it is drawn as its
* own area (`dangerArea`), never as a cone of centre-track uncertainty.
*/
export const JTWC_ORIGIN = 'https://www.metoc.navy.mil';
export const JTWC_RSS_URL = `${JTWC_ORIGIN}/jtwc/rss/jtwc.rss`;
export const JTWC_PRODUCTS_URL = `${JTWC_ORIGIN}/jtwc/products`;
const WARNING_ITEMS = [
'NWPAC-NIO-WARNINGS',
'EPAC-CPAC-WARNINGS',
'SH-WARNINGS',
];
const NO_WARNINGS = 'No Current Tropical Cyclone Warnings';
const PREFIX = /^(?:wp|io|sh|ep|cp)\d{4}$/;
const HOUR = 3600_000;
/**
* A JTWC warning is usable for 13 hours after issuance: some storms are on
* 12-hourly warnings, and the next one posts shortly before its time.
*/
export const JTWC_USABLE_MS = 13 * HOUR;
const KML_MAX_BYTES = 4 * 1024 * 1024;
function invalid(what) {
return new Error(`invalid_jtwc_data: ${what}`);
}
/** Storm product prefixes (`sh0427`) the feed lists, in feed order. */
export function parseJtwcFeed(feed) {
if (typeof feed !== 'string' || !feed.includes('<rss')) throw invalid('feed');
const prefixes = [];
for (const guid of WARNING_ITEMS) {
const item = feed
.split('<item>')
.slice(1)
.map((part) => part.split('</item>')[0])
.find((part) => part.includes(`<guid>${guid}</guid>`));
if (!item) throw invalid(`feed item ${guid}`);
const found = [
...item.matchAll(
/\/jtwc\/products\/([a-z]{2}\d{4})(?:web\.txt|\.tcw|\.kmz)/g,
),
]
.map((match) => match[1])
.filter((prefix) => PREFIX.test(prefix));
if (!found.length && !item.includes(NO_WARNINGS))
throw invalid(`feed item ${guid}`);
for (const prefix of found)
if (!prefixes.includes(prefix)) prefixes.push(prefix);
}
return prefixes;
}
/** `sh0427` is ATCF `sh042027` (the season year). */
export function jtwcStormId(prefix) {
if (!PREFIX.test(prefix)) throw invalid('prefix');
return `${prefix.slice(0, 4)}20${prefix.slice(4)}`;
}
// JTWC's words for a storm, longest first, and their codes.
const KINDS = [
['SUPER TYPHOON', 'STY'],
['SUBTROPICAL STORM', 'SS'],
['SUBTROPICAL DEPRESSION', 'SD'],
['TROPICAL CYCLONE', 'TC'],
['TROPICAL STORM', 'TS'],
['TROPICAL DEPRESSION', 'TD'],
['TYPHOON', 'TY'],
['HURRICANE', 'HU'],
];
/** `115S` / `1642W` (tenths) or `11.6S` (degrees); south and west negative. */
function coordinate(word, tenths) {
const match = /^(\d+(?:\.\d+)?)([NSEW])$/.exec(word || '');
if (!match || (tenths && match[1].includes('.'))) return null;
const value = Number(match[1]) / (tenths ? 10 : 1);
const limit = 'NS'.includes(match[2]) ? 90 : 180;
if (!(value <= limit)) return null;
return 'SW'.includes(match[2]) ? -value : value;
}
function utc(year, month, day, hour, minute = 0) {
const at = Date.UTC(year, month - 1, day, hour, minute);
const date = new Date(at);
return date.getUTCDate() === day && date.getUTCHours() === hour ? at : NaN;
}
/** `ddhhmm` (optionally `Z`-suffixed) as the time nearest `near`. */
function nearest(dtg, near) {
const match = /^(\d\d)(\d\d)(\d\d)Z?[.,]?$/.exec(dtg || '');
if (!match) return NaN;
const base = new Date(near);
let best = NaN;
for (const offset of [-1, 0, 1]) {
const month = new Date(
Date.UTC(base.getUTCFullYear(), base.getUTCMonth() + offset, 1),
);
const at = utc(
month.getUTCFullYear(),
month.getUTCMonth() + 1,
Number(match[1]),
Number(match[2]),
Number(match[3]),
);
if (
Number.isFinite(at) &&
(!Number.isFinite(best) || Math.abs(at - near) < Math.abs(best - near))
)
best = at;
}
return best;
}
const iso = (ms) => new Date(ms).toISOString();
function titleCase(name) {
return name
.toLowerCase()
.replace(
/(^|[\s-])([a-z])/g,
(_, gap, letter) => gap + letter.toUpperCase(),
);
}
/**
* One storm's warning (`.tcw`) as a cyclone-snapshot storm, its geometry
* pending until `withJtwcDangerArea` gives it the warning's danger swath.
* Throws on a warning without its header, hour 0 or subject.
*/
export function parseJtwcWarning(prefix, text) {
const id = jtwcStormId(prefix);
if (typeof text !== 'string') throw invalid('tcw');
const lines = text.split(/\r?\n/).map((line) => line.replace(/\s+$/, ''));
const dtg = lines[0]?.split(/\s+/)[2];
const headerAt = lines.findIndex((line) => /^\d{10}\s/.test(line));
if (headerAt < 0 || !dtg) throw invalid('tcw header');
const header = lines[headerAt].split(/\s+/);
const synopticAt = utc(
Number(header[0].slice(0, 4)),
Number(header[0].slice(4, 6)),
Number(header[0].slice(6, 8)),
Number(header[0].slice(8, 10)),
);
if (!Number.isFinite(synopticAt)) throw invalid('tcw synoptic time');
const number = header[1];
let at = 2;
const nameWords = [];
while (at < header.length && !/^\d+$/.test(header[at]))
nameWords.push(header[at++]);
const numbers = header.slice(at);
const warningMatch = /^0*(\d{1,3})$/.exec(numbers[0] || '');
if (!warningMatch || !number) throw invalid('tcw warning number');
const advisoryNumber = String(Number(warningMatch[1]));
const issuedAt = nearest(dtg, synopticAt);
if (!Number.isFinite(issuedAt)) throw invalid('tcw message time');
const direction = Number(numbers[2]);
const speed = Number(numbers[3]);
const forecast = [];
for (const line of lines.slice(headerAt + 1)) {
const words = line.trim().split(/\s+/);
const tau = /^T(\d{3})$/.exec(words[0]);
if (!tau) break;
const latitude = coordinate(words[1], true);
const longitude = coordinate(words[2], true);
const windKt = Number(words[3]);
if (latitude === null || longitude === null || !/^\d+$/.test(words[3]))
throw invalid('tcw forecast line');
forecast.push({
position: { longitude, latitude },
tauHours: Number(tau[1]),
windKt,
gustKt: null,
});
}
if (forecast[0]?.tauHours !== 0) throw invalid('tcw hour 0');
const subjectAt = lines.findIndex((line) => /^\s*SUBJ/.test(line));
if (subjectAt < 0) throw invalid('tcw subject');
const subject = lines[subjectAt]
.replace(/^\s*SUBJ[:/]?/, '')
.replace(/\/+$/, '')
.trim();
let end = lines.findIndex((line, i) => i > subjectAt && line.trim() === '//');
if (end < 0) end = lines.length;
const body = lines.slice(subjectAt, end);
let tau = null;
for (const line of body) {
const trimmed = line.trim();
const hours = /^(\d+) HRS, VALID AT:$/.exec(trimmed);
if (trimmed.startsWith('WARNING POSITION')) tau = 0;
else if (hours) tau = Number(hours[1]);
else {
const gust = /GUSTS (\d+) KT/.exec(trimmed);
const point = gust && forecast.find((p) => p.tauHours === tau);
if (point && point.gustKt === null) point.gustKt = Number(gust[1]);
}
}
const remarksAt = body.findIndex((line) => /^\s*REMARKS/.test(line));
const remarks = (remarksAt < 0 ? [] : body.slice(remarksAt))
.join(' ')
.replace(/\s+/g, ' ');
const issue = /(\d{6})Z POSITION NEAR (\d+\.\d)([NS]) (\d+\.\d)([EW])/.exec(
remarks,
);
const issueAt = issue ? nearest(issue[1], synopticAt) : NaN;
const pressure = /CENTRAL PRESSURE AT \d{6}Z IS (\d{3,4}) MB/.exec(remarks);
const kind = KINDS.find(([words]) => subject.includes(words));
const first = forecast[0];
const position =
issue && Number.isFinite(issueAt)
? {
longitude: coordinate(`${issue[4]}${issue[5]}`, false),
latitude: coordinate(`${issue[2]}${issue[3]}`, false),
}
: first.position;
if (position.longitude === null || position.latitude === null)
throw invalid('tcw position');
const basin = id.slice(0, 2);
const longitude = position.longitude;
const outlook =
basin === 'io' || (basin === 'sh' && longitude >= 0 && longitude < 135)
? 'abioweb.txt'
: basin === 'wp' || basin === 'sh'
? 'abpwweb.txt'
: null;
const pressureHpa = pressure ? Number(pressure[1]) : null;
const storm = {
id,
agency: 'jtwc',
name: nameWords.length ? titleCase(nameWords.join(' ')) : number,
classification: kind ? kind[1] : 'TC',
basin: basin.toUpperCase(),
position,
positionAt: iso(Number.isFinite(issueAt) ? issueAt : synopticAt),
advisoryNumber,
issuedAt: iso(issuedAt),
windKt: first.windKt <= 300 ? first.windKt : null,
pressureHpa:
pressureHpa !== null && pressureHpa >= 800 && pressureHpa <= 1100
? pressureHpa
: null,
movement: {
directionDegrees:
Number.isInteger(direction) && direction <= 360 ? direction : null,
speedKt: Number.isInteger(speed) && speed <= 200 ? speed : null,
},
advisoryUrl: `${JTWC_PRODUCTS_URL}/${prefix}web.txt`,
outlookUrl: outlook ? `${JTWC_PRODUCTS_URL}/${outlook}` : null,
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
};
return { storm, forecast };
}
/**
* The storm with its forecast geometry, current only with the danger swath
* of its own warning number (JTWC posts the overlay before the text).
*/
export function withJtwcDangerArea({ storm, forecast }, overlay) {
if (
!overlay ||
overlay.advisoryNumber !== storm.advisoryNumber ||
!overlay.dangerArea ||
forecast.length < 2
)
return storm;
return {
...storm,
geometryStatus: 'current',
geometryAdvisoryNumber: storm.advisoryNumber,
forecastPoints: forecast.map((point) => ({
position: { ...point.position },
tauHours: point.tauHours,
windKt: point.windKt,
gustKt: point.gustKt,
})),
track: {
type: 'LineString',
coordinates: forecast.map((point) => [
point.position.longitude,
point.position.latitude,
]),
},
dangerArea: overlay.dangerArea,
};
}
/** The warning number and 34-knot danger swath of a warning's KML. */
export function parseJtwcKml(kml) {
if (typeof kml !== 'string') throw invalid('kml');
const number = /WARNING NR\s+0*(\d{1,3})\b/.exec(kml);
if (!number) throw invalid('kml warning number');
const polygons = [];
for (const part of kml.split('<Placemark').slice(1)) {
const placemark = part.split('</Placemark>')[0];
const name = /<name>([^<]*)<\/name>/.exec(placemark)?.[1] || '';
if (!/^\s*34 knot Danger Swath/i.test(name)) continue;
for (const polygonPart of placemark.split('<Polygon').slice(1)) {
const polygon = polygonPart.split('</Polygon>')[0];
const rings = [
...polygon.matchAll(/<coordinates>([\s\S]*?)<\/coordinates>/g),
]
.map((match) => ring(match[1]))
.filter(Boolean);
if (rings.length) polygons.push(rings);
}
}
return {
advisoryNumber: String(Number(number[1])),
dangerArea: !polygons.length
? null
: polygons.length === 1
? { type: 'Polygon', coordinates: polygons[0] }
: { type: 'MultiPolygon', coordinates: polygons },
};
}
/**
* `longitude` in -180..180 (180 stays 180). JTWC writes a ring crossing the
* antimeridian with longitudes past ±180 (`181.5`); wrapped, the ring crosses
* 180° as NHC's cones that cross it do.
*/
export function wrapJtwcLongitude(longitude) {
if (Math.abs(longitude) <= 180) return longitude;
const wrapped = ((((longitude + 180) % 360) + 360) % 360) - 180;
// JTWC writes two decimals; this drops the float noise of the wrap.
return Math.round(wrapped * 1e6) / 1e6;
}
function ring(text) {
const points = [];
for (const tuple of text.trim().split(/\s+/)) {
const [lon, lat] = tuple.split(',').map(Number);
if (
!Number.isFinite(lon) ||
!Number.isFinite(lat) ||
Math.abs(lon) > 540 ||
Math.abs(lat) > 90
)
return null;
points.push([wrapJtwcLongitude(lon), lat]);
}
if (!points.length) return null;
const [a, b] = [points[0], points.at(-1)];
if (a[0] !== b[0] || a[1] !== b[1]) points.push([...a]);
return points.length >= 4 ? points : null;
}
/**
* The first `.kml` entry of a KMZ (a zip), from its central directory.
* Stored and deflated entries only.
*/
export function kmlFromKmz(bytes) {
const data = Buffer.from(bytes);
let end = -1;
for (let i = data.length - 22; i >= Math.max(0, data.length - 65_557); i--)
if (data.readUInt32LE(i) === 0x06054b50) {
end = i;
break;
}
if (end < 0) throw invalid('kmz');
const entries = data.readUInt16LE(end + 10);
let at = data.readUInt32LE(end + 16);
for (let n = 0; n < entries; n++) {
if (at + 46 > data.length || data.readUInt32LE(at) !== 0x02014b50)
throw invalid('kmz directory');
const method = data.readUInt16LE(at + 10);
const compressed = data.readUInt32LE(at + 20);
const size = data.readUInt32LE(at + 24);
const nameLength = data.readUInt16LE(at + 28);
const extra = data.readUInt16LE(at + 30);
const comment = data.readUInt16LE(at + 32);
const local = data.readUInt32LE(at + 42);
const name = data.toString('utf8', at + 46, at + 46 + nameLength);
at += 46 + nameLength + extra + comment;
if (!name.toLowerCase().endsWith('.kml')) continue;
if (size > KML_MAX_BYTES || data.readUInt32LE(local) !== 0x04034b50)
throw invalid('kmz entry');
const start =
local +
30 +
data.readUInt16LE(local + 26) +
data.readUInt16LE(local + 28);
const raw = data.subarray(start, start + compressed);
if (method === 0) return raw.toString('utf8');
if (method === 8)
return inflateRawSync(raw, { maxOutputLength: KML_MAX_BYTES }).toString(
'utf8',
);
throw invalid('kmz compression');
}
throw invalid('kmz holds no kml');
}
/**
* Every storm JTWC lists, through `read(url, kind)` (kind `text` or
* `bytes`). A feed that cannot be read throws. One storm never stops the
* others: a warning that cannot be read or parsed leaves that storm out,
* and only when every listed storm's fails does the read throw. An overlay
* that cannot be read leaves its storm's geometry `unavailable`, and one
* JTWC has not posted yet (`read` resolving null), or posted for another
* warning, leaves it `pending`.
*/
export async function readJtwcStorms(read, now = Date.now()) {
const prefixes = parseJtwcFeed(await read(JTWC_RSS_URL, 'text'));
// Each storm's warning and overlay are read at once, every storm alike.
const readStorm = async (prefix) => {
const [text, overlay] = await Promise.all([
read(`${JTWC_PRODUCTS_URL}/${prefix}.tcw`, 'text'),
read(`${JTWC_PRODUCTS_URL}/${prefix}.kmz`, 'bytes')
.then((bytes) =>
bytes === null ? null : parseJtwcKml(kmlFromKmz(bytes)),
)
.catch((error) => {
if (error?.name === 'AbortError') throw error;
return undefined;
}),
]);
if (text === null) throw invalid(`${prefix}.tcw missing`);
const warning = parseJtwcWarning(prefix, text);
const issued = Date.parse(warning.storm.issuedAt);
// A warning past its use, or dated far ahead of this clock, is left out.
if (now - issued > JTWC_USABLE_MS || issued - now > 90 * 60_000)
return null;
// An overlay that could not be read: the geometry is unavailable.
return overlay === undefined
? { ...warning.storm, geometryStatus: 'unavailable' }
: withJtwcDangerArea(warning, overlay);
};
const results = await Promise.allSettled(prefixes.map(readStorm));
const failed = results.filter((result) => result.status === 'rejected');
const aborted = failed.find((result) => result.reason?.name === 'AbortError');
if (aborted) throw aborted.reason;
if (failed.length && failed.length === results.length) throw failed[0].reason;
const storms = [];
for (const result of results) {
const storm = result.status === 'fulfilled' ? result.value : null;
if (storm && !storms.some((held) => held.id === storm.id))
storms.push(storm);
}
return storms;
}
-332
View File
@@ -1,332 +0,0 @@
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);
});
+99 -7
View File
@@ -18,6 +18,18 @@ import { admitSameSite } from './common/same-site.js';
* "Traffic flow"). The key comes from TOMTOM_API_KEY server-side only — the
* browser fetches same-origin `/api/tomtom/flow/{z}/{x}/{y}.pbf`.
*
* Orbis fallback: TomTom keys are assigned products, and a key without the
* TomTom Maps traffic product gets 403 on the endpoint above while the same
* key works on the TomTom Orbis Maps one,
* https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/{z}/{x}/{y}?apiVersion=2
* (same "Traffic flow" layer; `relative_speed` and `road_category` replace
* `traffic_level` and `road_type`, which the client decoder reads either
* way). On 403 the proxy asks the other endpoint and keeps whichever
* answered for the rest of the process. When both refuse the key, tiles
* answer 403 {error:'key_rejected'} and upstream is left alone for
* KEY_REJECTED_TTL_MS, so a rejected key does not spend the daily budget one
* tile at a time. Changing the key clears both.
*
* Cache: memory + disk (.gev-cache/tomtom/), TTL 120 s (traffic is fresh
* data), single-flight per tile, serve-stale-on-failure — the celestrakProxy
* pattern. Cache hits never count against the budget.
@@ -43,7 +55,7 @@ import { admitSameSite } from './common/same-site.js';
* at distinct tiles, spend the TomTom quota and leave the traffic layer on
* 429 budget for the rest of the UTC day.
*
* GET /api/tomtom/status → {hasKey, dailyCount, budget, date}. Keyless mode:
* GET /api/tomtom/status → {hasKey, keyRejected, dailyCount, budget, date}. Keyless mode:
* status reports hasKey:false and the tile endpoint 503s {error:'no_key'}
* without touching upstream — the traffic layer then stays in simulation mode.
*
@@ -59,6 +71,37 @@ export function tomtomProxy() {
const UPSTREAM_TIMEOUT_MS = 15000;
/** Flow tiles are well under 1 MB; this bounds a runaway body, not a budget. */
const TOMTOM_TILE_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
/** How long a key both endpoints refused is left alone before a retry. */
const KEY_REJECTED_TTL_MS = 5 * 60_000;
/** Upstream flow-tile endpoints, in the order a new key is tried. */
const ENDPOINTS = {
legacy: (z, x, y, key) => ({
url:
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(key)}`,
}),
orbis: (z, x, y, key) => ({
url:
'https://api.tomtom.com/maps/orbis/traffic/flow/vector/tile/' +
`${z}/${x}/${y}?apiVersion=2`,
headers: { 'TomTom-Api-Key': key },
}),
};
/**
* What is known about the configured key: the endpoint that last served
* it, and until when both endpoints are known to refuse it. Reset when the
* key changes (Provider Settings rewrites process.env at runtime).
* @type {{key:string, endpoint:'legacy'|'orbis', rejectedUntil:number}}
*/
let keyState = { key: '', endpoint: 'legacy', rejectedUntil: 0 };
function currentKeyState() {
const key = process.env.TOMTOM_API_KEY || '';
if (keyState.key !== key)
keyState = { key, endpoint: 'legacy', rejectedUntil: 0 };
return keyState;
}
const isKeyRejected = () => Date.now() < currentKeyState().rejectedUntil;
/** @type {Map<string, {at:number, buf:Buffer}>} tile key `z/x/y` -> cached tile (kept past TTL for serve-stale). */
const mem = new Map();
@@ -149,14 +192,17 @@ export function tomtomProxy() {
mem.set(key, entry);
}
async function fetchUpstream(z, x, y) {
const url =
'https://api.tomtom.com/traffic/map/4/tile/flow/relative/' +
`${z}/${x}/${y}.pbf?key=${encodeURIComponent(process.env.TOMTOM_API_KEY)}`;
async function fetchEndpoint(name, z, x, y, key) {
const { url, headers } = ENDPOINTS[name](z, x, y, key);
recordUpstreamFetch(); // attempts count — upstream bills the request either way
const signal = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS);
const res = await fetch(url, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const res = await fetch(url, { signal, ...(headers ? { headers } : {}) });
if (!res.ok) {
await res.body?.cancel().catch(() => {});
throw Object.assign(new Error(`HTTP ${res.status}`), {
status: res.status,
});
}
const bytes = await readResponseBytesCapped(
res,
TOMTOM_TILE_MAX_RESPONSE_BYTES,
@@ -167,6 +213,41 @@ export function tomtomProxy() {
return buf;
}
/**
* Fetch one tile from the endpoint this key last worked on, asking the
* other one only when TomTom refuses the key (403). Both refusing marks
* the key rejected; any other failure is an ordinary upstream error.
*/
async function fetchUpstream(z, x, y) {
const state = currentKeyState();
const other = state.endpoint === 'legacy' ? 'orbis' : 'legacy';
try {
return await fetchEndpoint(state.endpoint, z, x, y, state.key);
} catch (err) {
if (err?.status !== 403) throw err;
}
try {
const buf = await fetchEndpoint(other, z, x, y, state.key);
if (keyState === state) {
state.endpoint = other;
console.warn(
`[tomtom-proxy] key refused on the ${other === 'orbis' ? 'TomTom Maps' : 'Orbis'} flow endpoint (HTTP 403); using the ${other === 'orbis' ? 'Orbis' : 'TomTom Maps'} one`,
);
}
return buf;
} catch (err) {
if (err?.status !== 403) throw err;
if (keyState === state)
state.rejectedUntil = Date.now() + KEY_REJECTED_TTL_MS;
throw Object.assign(
new Error(
'HTTP 403 on both flow endpoints: check the products assigned to the key and its domain whitelist at https://my.tomtom.com/keys',
),
{ status: 403 },
);
}
}
const installMiddleware = (server) => {
server.middlewares.use('/api/tomtom', async (req, res) => {
// Gate first: a cross-site <img>/fetch must not reach the budget counter.
@@ -204,6 +285,7 @@ export function tomtomProxy() {
const b = currentBudget();
sendJson(200, {
hasKey,
keyRejected: hasKey && isKeyRejected(),
dailyCount: b.count,
budget: dailyBudgetLimit(),
date: b.date,
@@ -242,6 +324,14 @@ export function tomtomProxy() {
return;
}
// TomTom refused the key on both endpoints: asking again per tile
// would only spend the budget. Last-good data still beats nothing.
if (isKeyRejected()) {
if (entry) sendTile(entry, 'STALE-ERROR');
else sendJson(403, { error: 'key_rejected' });
return;
}
// Budget governor: over the soft cap, last-good data beats a dead layer.
if (isTomTomOverBudget(currentBudget(), dailyBudgetLimit())) {
if (entry) {
@@ -277,6 +367,8 @@ export function tomtomProxy() {
sendTile(fresh, 'MISS');
} else if (entry) {
sendTile(entry, 'STALE-ERROR'); // upstream down — stale beats empty
} else if (isKeyRejected()) {
sendJson(403, { error: 'key_rejected' });
} else {
sendJson(502, { error: 'upstream' });
}
-4
View File
@@ -67,8 +67,6 @@ export const APPLICATION_LAYER_METADATA = Object.freeze([
* `placement`, a host-supplied placement provider (../data/placementProvider.js),
* places live aircraft, vessels, transit and trains; without one each layer
* uses its own motion.
* `perimeterOptions: { inciweb: false }` leaves the Fire Perimeters cards
* without InciWeb links, and the layer never asks InciWeb.
*/
export function createApplicationCatalog({
surface,
@@ -77,7 +75,6 @@ export function createApplicationCatalog({
metadata = APPLICATION_LAYER_METADATA,
vesselOptions,
newsOptions,
perimeterOptions,
resolveAsset,
nepalBoundaryResolver,
streetLevelProviders,
@@ -148,7 +145,6 @@ export function createApplicationCatalog({
createApplicationEarthquakes({ source: sources.earthquakes }),
createApplicationAirQuality({ source: sources['air-quality'] }),
createApplicationFirePerimeters({
...perimeterOptions,
source: sources['fire-perimeters'],
}),
createApplicationGnssIntegrity({
-47
View File
@@ -7,8 +7,6 @@ import { catalogControlServices } from './catalog.js';
import { LayerLifecycle } from '../data/lifecycle.js';
import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs';
import { worldClock } from '../time/worldClock.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../input/testDoubles.mjs';
const flush = async () => {
for (let i = 0; i < 20; i++) await Promise.resolve();
@@ -256,48 +254,3 @@ test('a GNSS integrity source can set the layer evidence window', (t) => {
`${String(windowMs)} falls back to the default`,
);
});
test('perimeterOptions reach Fire Perimeters: inciweb false never asks InciWeb', async (t) => {
const lifetime = new AbortController();
const { signal } = lifetime;
const sources = fixtureSources([], []);
sources['fire-perimeters'] = {
getSnapshot: async () => ({
at: null,
fetchedAt: null,
stale: false,
revision: 'r',
note: null,
fires: [],
pieces: [],
}),
};
const requested = [];
t.mock.method(globalThis, 'fetch', async (url) => {
requested.push(String(url));
return Response.json([]);
});
const viewer = { scene: { pick: () => null } };
bindFakeDraw(viewer);
const input = fakeInput(viewer);
const layer = createApplicationCatalog({
sources,
signal,
surface: fixtureSurface(signal),
perimeterOptions: { inciweb: false, inputFor: () => input.input },
}).get('fire-perimeters');
t.after(() => {
layer.destroy();
input.destroy();
lifetime.abort();
worldClock.goLive();
});
layer.init(viewer);
layer.enable(viewer);
assert.equal(await layer.update(viewer), true);
await new Promise(setImmediate);
assert.deepEqual(
requested.filter((url) => url.includes('inciweb')),
[],
);
});
+4 -14
View File
@@ -6,11 +6,8 @@ import {
import * as picking from '../../data/pickRegistry.js';
import * as overlays from '../../overlays/worldOverlay.js';
/** Wire fire perimeters into the application catalog. */
export function createApplicationFirePerimeters({
inciweb = true,
...options
} = {}) {
/** Wire WFIGS fire perimeters into the application catalog. */
export function createApplicationFirePerimeters(options) {
return createFirePerimetersLayer({
overlayHost: {
setEntries: overlays.setOverlayEntries,
@@ -18,17 +15,10 @@ export function createApplicationFirePerimeters({
clearSource: overlays.clearOverlaySource,
hitTest: overlays.hitTestWorldOverlay,
},
...(inciweb !== false && {
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
}),
inciwebSource: createInciwebIndexSource(),
inciwebPublications: createInciwebPublicationSource(),
openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
picking,
...options,
// inciweb: false outranks InciWeb sources in options.
...(inciweb === false && {
inciwebSource: null,
inciwebPublications: null,
}),
});
}
-54
View File
@@ -1,54 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createApplicationFirePerimeters } from './perimeters.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
const ring = [
[-108.1, 35.2],
[-108.0, 35.2],
[-108.0, 35.3],
[-108.1, 35.2],
];
const source = {
getSnapshot: async () => ({
at: null,
fetchedAt: null,
stale: false,
revision: 'r',
note: null,
fires: [{ id: 'f', name: 'Fixture', anchor: { lon: -108.05, lat: 35.25 } }],
pieces: [{ fireId: 'f', born: null, polygons: [[ring]], outline: [ring] }],
}),
};
for (const inciweb of [true, false]) {
test(`inciweb: ${inciweb} ${inciweb ? 'asks' : 'never asks'} InciWeb`, async (t) => {
const requested = [];
t.mock.method(globalThis, 'fetch', async (url) => {
requested.push(String(url));
return Response.json([]);
});
const viewer = { scene: { pick: () => null } };
bindFakeDraw(viewer);
const input = fakeInput(viewer);
t.after(() => input.destroy());
const getIndex = t.mock.fn(async () => []);
const layer = createApplicationFirePerimeters({
source,
inciweb,
...(inciweb === false && { inciwebSource: { getIndex } }),
inputFor: () => input.input,
});
layer.init(viewer);
layer.enable(viewer);
assert.equal(await layer.update(viewer), true);
await new Promise(setImmediate);
assert.deepEqual(
requested.filter((url) => url.includes('inciweb')),
inciweb ? ['/api/fire-perimeters/inciweb/index'] : [],
);
assert.equal(getIndex.mock.callCount(), 0);
layer.destroy(viewer);
});
}
+1 -6
View File
@@ -17,7 +17,6 @@ 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';
@@ -39,7 +38,6 @@ import { installLayerReleaseTrim } from '../sceneCommandRelease.js';
import {
getRenderGovernorDiagnostics,
governorRequestRender,
FOLLOW_FRAME_RATE,
holdContinuousRender,
releaseContinuousRender,
} from '../renderGovernor.js';
@@ -274,8 +272,7 @@ export function createApplicationTools({
// The follow camera recomputes the tracked target's dead-reckon position
// every frame — tracking anything is a per-frame animation. (perf wave 2)
const removeTrackingListener = onFollowChanged(viewer, (followed) => {
if (followed)
holdContinuousRender('tracked-entity', { maxFps: FOLLOW_FRAME_RATE });
if (followed) holdContinuousRender('tracked-entity');
else releaseContinuousRender('tracked-entity');
});
@@ -352,8 +349,6 @@ 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 });
+6 -20
View File
@@ -1165,10 +1165,7 @@ 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;/,
@@ -1188,14 +1185,8 @@ 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\(\);/,
@@ -1383,17 +1374,12 @@ test('voice Cockpit entry honours a requested contact layer before it enters', (
const retarget = ui.slice(
ui.indexOf(' _retargetCockpitEntryLayer({'),
ui.indexOf(' controlCockpit(\n'),
ui.indexOf(' * Controls cockpit entry/exit and context navigation.'),
);
assert.match(
retarget,
/layer\.trackById\?\.\(match\.icao24, \{ origin: 'voice' \}\)/,
'retargeting follows the match with durable voice selection authority',
);
assert.doesNotMatch(
retarget,
/militaryAwarenessLayer/,
'retargeting needs nothing from Contacts',
/militaryAwarenessLayer\.navigateNext\(\{\s*targetLayer,\s*aircraftClass,\s*origin: 'voice',\s*\}\)/,
'retargeting reuses filtered navigation with durable voice selection authority',
);
assert.match(
retarget,
+6 -6
View File
@@ -243,7 +243,7 @@ const RECOGNIZED = new Set([
// credit
'#cesium-credits',
'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits',
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits",
"body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits",
'body.ui-clean-view #cesium-credits',
'body.recording-mode #cesium-credits',
// dock
@@ -274,12 +274,12 @@ const DOCKED_RAIL = 'body.context-docked #right-context-rail';
// the Omnibar and the voice control share the dock; outside it the legacy
// layout below governs.
const OMNIBAR_SCOPE =
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(.has-omnibar.dock-has-voice *)';
'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(:has(#gev-omnibar):has(#command-dock > #gev-voice-control))';
const OMNIBAR = Object.freeze({
dock: `${OMNIBAR_SCOPE} #command-dock`,
credit: `${OMNIBAR_SCOPE} :is(#cesium-credits, #gev-credits)`,
minimalCredit: `${OMNIBAR_SCOPE}:is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`,
minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #right-context-rail`,
minimalCredit: `${OMNIBAR_SCOPE}:has(#intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`,
minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) #right-context-rail`,
trays: `${OMNIBAR_SCOPE} #command-dock > :is(#location-bar, #control-panel)`,
});
// What each Omnibar-scope rule may set on a modelled box; the Omnibar
@@ -518,7 +518,7 @@ const CREDIT_SELECTORS = [
'body:not(.ui-clean-view):not(.recording-mode) #cesium-credits',
];
const MINIMAL_HUD_CREDIT =
"body:not(.ui-clean-view):not(.recording-mode):is(.hud-minimal-active *, #intel-hud[data-variant='minimal'].active) #cesium-credits";
"body:not(.ui-clean-view):not(.recording-mode):has(#intel-hud[data-variant='minimal'].active) #cesium-credits";
const TRAY_ORDINARY = [
'#command-dock .dock-popover-content',
'#command-dock #location-bar .dock-popover-content',
@@ -1279,7 +1279,7 @@ test('expanded Context keeps the credits beside it right to left and with the mi
// The minimal HUD puts the credits bottom right, where the column docks.
assert.ok(
rule(
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):is\\( \\.hud-minimal-active \\*, #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
"^.*body\\.context-docked:not\\(\\.ui-clean-view\\):not\\(\\.recording-mode\\):has\\( #intel-hud\\[data-variant='minimal'\\]\\.active \\)",
'right: calc\\(36px \\+ var\\(--context-dock-width\\)\\)',
),
'with the minimal HUD, the credits end before the expanded column',
+12 -72
View File
@@ -10,7 +10,6 @@ import { straightSegment } from './fixCurve.js';
import {
norm180,
distance,
distanceSquared,
clone,
copyInto,
toDegrees,
@@ -386,32 +385,8 @@ let instances = 0;
/** A plan that ran out longer ago than this (ms) is not eased away from. */
const RECOVER_STALE_PLAN_MS = 1_000;
/** How far ahead (ms) a placed contact's segment runs before it is asked
* again, in view and near the eye. */
/** How far ahead (ms) a placed contact's segment runs before it is asked again. */
const PLACED_PLAN_MS = 1000;
/** The same out of view, or farther than PLACED_NEAR_M from the eye: off
* screen a contact's path is not seen, and that far a straight segment
* over this long (half as long again at most, as spread) is well under a
* pixel off it. Asking for each contact every second would rewrite the
* whole fleet every second. */
const PLACED_FAR_PLAN_MS = 4000;
/** Nearer the eye than this (m), a placed contact in view is planned every
* PLACED_PLAN_MS. */
const PLACED_NEAR_M = 300_000;
/**
* Each contact's plans run between 1/2 and 3/2 of their length, by its id,
* so the fleet's plans run out spread over the passes, not together in one
* (contacts first planned in the same pass would otherwise stay in step).
*/
export function placedPlanSpread(id) {
let hash = 2166136261;
for (let i = 0; i < id.length; i++) {
hash ^= id.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return 0.5 + ((hash >>> 0) % 1024) / 1024;
}
/** A display delay that never changes (ms). */
function fixedDelay(ms) {
@@ -490,8 +465,6 @@ export function createAircraftIcons({
* @type {Map<string, {drawn: number, checked: number}>}
*/
const rotors = new Map();
/** When a rotor in view was last given a new frame (wall ms). */
let rotorDrawnAtMs = -Infinity;
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
const _displayMs = () =>
@@ -519,8 +492,7 @@ export function createAircraftIcons({
const motionClock = (scene) =>
scene
? { kind: 'scene' }
: // The layer's pace asks for the frames its moving rows need.
{ kind: 'live', delayMs: displayDelay.currentMs, frames: 'owner' };
: { kind: 'live', delayMs: displayDelay.currentMs };
/**
* Once a frame: move the display delay on, and put the set's motion on
@@ -843,28 +815,12 @@ export function createAircraftIcons({
planFrom.set(icao24, validFrom);
}
/** The camera, while the fleet pass re-plans the rows that ran out:
* `{eye, inView(position)}` (null: every plan is a near one). */
let planView = null;
/** How long a placed contact at `position` is planned for (ms). */
function _placedPlanMs(icao24, position) {
const near =
!planView ||
(distanceSquared(planView.eye, position) <
PLACED_NEAR_M * PLACED_NEAR_M &&
planView.inView(position));
return (
(near ? PLACED_PLAN_MS : PLACED_FAR_PLAN_MS) * placedPlanSpread(icao24)
);
}
/**
* Plan a live contact a host-supplied placement places: from where it
* places it at `t` (display ms, the live clock's delayed time) to where it
* places it a plan's length on (`_placedPlanMs`), asked again when that
* runs out. Display time is wall time less the display delay, so the
* placement is asked at the wall times the segment's ends stand for.
* places it PLACED_PLAN_MS on, asked again when that runs out. Display
* time is wall time less the display delay, so the placement is asked at
* the wall times the segment's ends stand for.
* @returns {boolean} False when there is no placement, the layer follows
* the world clock, or it has no answer for this contact.
*/
@@ -883,7 +839,7 @@ export function createAircraftIcons({
)
return true;
easeEnds.delete(icao24);
const t1 = t + _placedPlanMs(icao24, from);
const t1 = t + PLACED_PLAN_MS;
const to = vec();
const end = placeAt(icao24, t1 + leadMs, info, history, to);
const motion = end
@@ -947,17 +903,12 @@ export function createAircraftIcons({
* moved back (a seek, or the clock run backward): it is drawn where it was
* then, as it is when the time moves on.
*/
function _replanExpired(t, view = null) {
planView = view;
try {
if (followsClock() && t < replannedAt)
for (const [icao24, from] of planFrom)
if (from > t) _planIcon(icao24, { rewound: true });
replannedAt = t;
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
} finally {
planView = null;
}
function _replanExpired(t) {
if (followsClock() && t < replannedAt)
for (const [icao24, from] of planFrom)
if (from > t) _planIcon(icao24, { rewound: true });
replannedAt = t;
for (const icao24 of state._icons.due(t)) _planIcon(icao24);
}
/**
@@ -979,7 +930,6 @@ export function createAircraftIcons({
const query = viewer ? findQuery(viewer) : null;
const eye = viewer ? findCamera(viewer)?.pose()?.position : null;
let active = 0;
let fading = 0;
for (const id of icons.ids()) {
if (!icons.shown(id) && !state._models.has(id)) continue;
const item = icons.item(id);
@@ -1002,13 +952,10 @@ export function createAircraftIcons({
spriteHalfHeightPx: item.size[1] * half,
});
if (focus.active || focus.transitioning) active++;
if (focus.transitioning) fading++;
if (focusAlphaNeedsWrite(current, focus.factor))
icons.setFocus(id, focus.factor);
}
state._iconFocusActive = active;
// Rows still fading in or out, for the layer's pace.
state._iconFocusFading = fading;
}
/**
@@ -1096,7 +1043,6 @@ export function createAircraftIcons({
if (!_aboveHorizon(position, occluder)) continue;
if (inView && !inView(position)) continue;
rotor.drawn = frame;
rotorDrawnAtMs = nowMs;
if (tracked) {
parts.tracking?._syncTrackedBillboardImage?.();
continue;
@@ -1160,11 +1106,6 @@ export function createAircraftIcons({
return rotors.size > 0;
}
/** When a rotor in view was last given a new frame (wall ms), for the pace. */
function _rotorDrawnAtMs() {
return rotorDrawnAtMs;
}
/** Add a row for a new contact, hidden while it is the tracked one. */
function _addIcon(icao24) {
state._icons.put(_baseItem(icao24, icao24 !== state._trackedIcao), {
@@ -1237,7 +1178,6 @@ export function createAircraftIcons({
_fleetLook,
_turnRotors,
_rotorsTurning,
_rotorDrawnAtMs,
_addIcon,
_forgetContact,
_iconIds,
+5 -133
View File
@@ -5,7 +5,6 @@ import {
createAircraftIcons,
createContactIcons,
floorCoastArc,
placedPlanSpread,
} from './aircraftIconLayer.js';
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
@@ -38,11 +37,7 @@ test('following the world clock, contacts draw at the world’s time on the scen
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
// Live: a poll interval behind real time, on the delayed live clock.
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 30_000,
frames: 'owner',
});
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.equal(icons._displayMs(), Date.now() - 30_000);
following = true;
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
@@ -50,11 +45,7 @@ test('following the world clock, contacts draw at the world’s time on the scen
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 30_000,
frames: 'owner',
});
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
icons._disposeIcons();
});
@@ -77,11 +68,7 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 30_000,
frames: 'owner',
});
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
@@ -89,11 +76,7 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 32_000,
frames: 'owner',
});
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
@@ -104,11 +87,7 @@ test('as the display delay moves, the renderer’s live clock and the layer’s
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, {
kind: 'live',
delayMs: 34_000,
frames: 'owner',
});
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
icons._disposeIcons();
});
@@ -502,110 +481,3 @@ test('back at live, a placed contact eases from where it is drawn over a recover
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
/** A layer whose placement has every contact flying east from `at(id)`. */
function placedFleet(ids, at) {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(ids.map((id) => [id, [{ epochMs: WORLD_MS }]])),
records: { data: new Map(ids.map((id) => [id, {}])) },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
placeAt: (id, wallMs, _info, _history, out) => {
Object.assign(out, at(id, wallMs));
return { courseDeg: 90, speedMps: 200 };
},
});
for (const id of ids)
state._icons.put(
{
id,
pos: at(id, WORLD_MS),
motion: { kind: 'hold', courseDeg: 90 },
course: 90,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
return { icons, set: state._icons };
}
test('a placed fleet planned in one pass runs out spread over the passes after it, not together', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const ids = Array.from({ length: 400 }, (_, i) =>
(0xa00000 + i * 37).toString(16),
);
const { icons, set } = placedFleet(ids, () => fromDegrees(0, 30, 3_000));
icons._replanExpired(Date.now());
const ends = ids.map((id) => set.expires(id) - WORLD_MS);
for (const ms of ends) assert.ok(ms >= 500 && ms < 1_500, `${ms} ms`);
// An 80 ms pass (the fleet's tick) has an eighth of the fleet at most.
const perPass = new Map();
for (const ms of ends) {
const pass = Math.floor(ms / 80);
perPass.set(pass, (perPass.get(pass) ?? 0) + 1);
}
assert.ok(
Math.max(...perPass.values()) <= ids.length / 8,
`${Math.max(...perPass.values())} in one pass`,
);
// Planned again when it runs out, each runs as long as before, from then.
const first = new Map(ids.map((id) => [id, set.expires(id)]));
t.mock.timers.tick(1_500);
icons._replanExpired(Date.now());
for (const id of ids) {
const item = set.item(id);
assert.equal(item.motion.t0, Date.now(), id);
assert.equal(
set.expires(id) - Date.now(),
first.get(id) - WORLD_MS,
`${id} runs as long`,
);
}
});
test('a placed contact far from the eye or out of view is planned for longer than a near one in view', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const where = {
n: fromDegrees(0, 30, 3_000),
f: fromDegrees(10, 30, 3_000),
o: fromDegrees(0.01, 30, 3_000),
};
const ids = Object.keys(where);
const { icons, set } = placedFleet(ids, (id) => where[id]);
const eye = fromDegrees(0, 30, 60_000);
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
// In view: all but 'o', told apart by where the placement puts it.
const view = { eye, inView: (p) => metres(p, where.o) > 1 };
const length = (id) =>
(set.expires(id) - set.item(id).motion.t0) / placedPlanSpread(id);
icons._replanExpired(Date.now(), view);
assert.ok(Math.abs(length('n') - 1_000) < 1, `near ${length('n')}`);
assert.ok(Math.abs(length('f') - 4_000) < 1, `far ${length('f')}`);
assert.ok(Math.abs(length('o') - 4_000) < 1, `out of view ${length('o')}`);
// The camera is the pass's only: a contact planned after it, as a new
// report plans it, takes a near plan, even after a pass that threw.
icons._planIcon('f');
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a pass ${length('f')}`);
t.mock.timers.tick(5_000);
assert.throws(() =>
icons._replanExpired(Date.now(), {
eye,
inView: () => {
throw new Error('camera gone');
},
}),
);
icons._planIcon('f');
assert.ok(Math.abs(length('f') - 1_000) < 1, `after a throw ${length('f')}`);
});
+1 -85
View File
@@ -14,12 +14,6 @@ import {
showModel,
} from './modelRecord.js';
import { modelDrawnScale } from './modelVisualAnchor.js';
import {
createRenderPace,
createScreenSpeed,
paceHzForSpeed,
} from '../renderPace.js';
import { ROTOR_FPS } from './rotorFrames.js';
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
import { aircraftLayerPartState } from './modelPartDrivers.js';
import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js';
@@ -125,70 +119,6 @@ export function createAircraftModels({
let instances = 0;
/** The fleet items this tick wrote, sent together when it ends. */
let pendingItems = [];
// The pace: how often the fleet is drawn while nothing else draws
// (renderPace.js). The icons move on the GPU, so a frame is all a move
// takes; an airliner crosses a hundredth of a pixel a second on the whole
// globe and hundreds from close by, so the rate follows the fastest icon
// in view.
const pace = createRenderPace({ owner: setPrefix, render: services.render });
const screenSpeed = createScreenSpeed();
/** How often the icons' on-screen speed is read, in ms. */
const PACE_READ_MS = 250;
/** Each icon's move is read over this much of its drawn path, in ms. */
const PACE_SPAN_MS = 1000;
/** While icons fade for a focus change, they are drawn this often. */
const PACE_FADE_HZ = 20;
/** A rotor drawn this recently is in view. */
const PACE_ROTOR_SEEN_MS = 600;
let paceReadMs = -Infinity;
let pacePxPerSec = 0;
/**
* The fastest icon in view's speed on screen, in pixels a second: each
* shown icon's drawn position now and PACE_SPAN_MS on, which takes in a
* new fix being blended in as well as its flight.
*/
function _readIconSpeed(pose) {
const icons = state._icons;
if (!icons || !screenSpeed.begin(pose, _viewport().height)) return 0;
const t = parts.icons._displayMs();
for (const id of icons.ids()) {
if (!icons.shown(id)) continue;
screenSpeed.add(
icons.position(id, t),
icons.position(id, t + PACE_SPAN_MS),
);
}
return screenSpeed.pxPerSec(PACE_SPAN_MS / 1000);
}
/**
* Draws a second the fleet needs as the camera stands (the pace clamps
* it to its range). Infinity: as often as the pace allows.
*/
function _paceHz(nowMs = Date.now()) {
const pose = _pose();
if (!pose?.position) return Infinity;
// Models, and the Cockpit's contacts, are moved on every frame.
if (
state._cockpitContactMode ||
state._models.size ||
_modelRegimeActive(pose)
)
return Infinity;
if (nowMs - paceReadMs >= PACE_READ_MS) {
paceReadMs = nowMs;
pacePxPerSec = _readIconSpeed(pose);
}
let hz = paceHzForSpeed(pacePxPerSec);
if (state._iconFocusFading > 0 && hz < PACE_FADE_HZ) hz = PACE_FADE_HZ;
// A helicopter in view turns its rotor ROTOR_FPS times a second.
const rotorAtMs = parts.icons._rotorDrawnAtMs?.() ?? -Infinity;
if (nowMs - rotorAtMs < PACE_ROTOR_SEEN_MS && hz < ROTOR_FPS)
hz = ROTOR_FPS;
return hz;
}
/** The ground sample's exclusions, kept while the sets they name live. */
let exclusions = null;
@@ -1022,7 +952,6 @@ export function createAircraftModels({
}
}
state._icons?.flush();
pace.set(_paceHz());
}
}
@@ -1041,14 +970,7 @@ export function createAircraftModels({
if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts();
parts.icons._syncImageSwitch();
// Far and out-of-view contacts are planned for longer (the camera says
// which are which).
parts.icons._replanExpired(
t,
pose?.position
? { eye: pose.position, inView: (position) => inView(pose, position) }
: null,
);
parts.icons._replanExpired(t);
const renderTime = parts.motion._displayTimeAt(
t,
state._scratchFleetRenderTime,
@@ -1214,11 +1136,5 @@ export function createAircraftModels({
_handBackDeselected,
_updateTrackedModel,
_fleetTick,
_paceHz,
_startPace: () => {
paceReadMs = -Infinity;
pace.start();
},
_stopPace: pace.stop,
};
}
+1 -19
View File
@@ -114,14 +114,11 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const replanViews = [];
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired(_t, view) {
replanViews.push(view);
},
_replanExpired() {},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
@@ -163,9 +160,6 @@ function fleetFixture(positions, { eyeM = EYE_M } = {}) {
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** The camera each fleet tick re-planned the icons with. */
replanViews,
eye,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
@@ -482,15 +476,3 @@ test('the selected contact keeps a loaded, hidden fleet model that takes it back
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(f.shown.get('a1'), false);
});
test('the fleet tick re-plans the icons with the camera: its eye, and what it sees', () => {
const f = fleetFixture(new Map([['a1', far(1)]]));
f.tick();
const [view] = f.replanViews;
assert.equal(view.eye, f.eye);
// The camera looks along -z: ahead of the eye is in view, behind it not.
const ahead = { x: f.eye.x, y: f.eye.y, z: f.eye.z - 10_000 };
const behind = { x: f.eye.x, y: f.eye.y, z: f.eye.z + 10_000 };
assert.equal(view.inView(ahead), true);
assert.equal(view.inView(behind), false);
});
+2 -12
View File
@@ -64,8 +64,7 @@ export const ANALYST_LAYERS = Object.freeze(
/** Fields every record carries regardless of layer. */
const COMMON_FIELDS = Object.freeze(['id', 'lat', 'lon']);
/** Derived per-record field for layers with a time field (hours before the
* moment the layer's records show: now, or its past snapshot's time). */
/** Derived per-record field for layers with a time field (hours before now). */
const AGE_FIELD = 'ageHours';
/** Spatial scope kinds `query()` accepts. */
const ANALYST_SCOPE_KINDS = Object.freeze([
@@ -583,8 +582,6 @@ function offerTop(top, candidate, limit, dir) {
* engine and the Contacts-window path so both format and rank alike.
* @param {Array<{key: string, rows: object[]}>} groups Candidate rows.
* @param {object} options
* @param {Map<string, number|null>} [options.recordsAt] Per-layer snapshot times in epoch ms.
* Ages count from the layer’s snapshot time when given, otherwise from now.
* @returns {Promise<object|null>} Selection, or null when cancelled.
*/
export async function selectAnalystRows(
@@ -598,7 +595,6 @@ export async function selectAnalystRows(
ref = null,
inScope = null,
now = Date.now(),
recordsAt = null,
isCurrent = () => true,
distanceOf = null,
} = {},
@@ -607,10 +603,8 @@ export async function selectAnalystRows(
const ageOf = (key, row) => {
const field = timeFieldOf(key);
const t = field ? row[field] : null;
const from = recordsAt?.get(key);
const ref = Number.isFinite(from) ? from : now;
return Number.isFinite(t)
? Math.round(((ref - t) / 3_600_000) * 10) / 10
? Math.round(((now - t) / 3_600_000) * 10) / 10
: null;
};
const distance = (row) => {
@@ -777,7 +771,6 @@ export function createAnalystEngine(providers) {
spec = normalized.spec;
// 1) Source records, grouped by layer and never copied.
const recordsAt = followUp ? lastResult.recordsAt : new Map();
let groups;
let layersQueried;
let queriedSnapshots;
@@ -793,7 +786,6 @@ export function createAnalystEngine(providers) {
queriedSnapshots = [];
for (const key of layers) {
const rows = providers.getRecords(key) || [];
recordsAt.set(key, providers.getRecordsAt?.(key) ?? null);
const snapshot = providers.getLayerSnapshot?.(key);
if (snapshot) queriedSnapshots.push(snapshot);
const coverage = providers.getRecordCoverage?.(key, rows) || {};
@@ -1056,7 +1048,6 @@ export function createAnalystEngine(providers) {
: null,
inScope,
now: providers.now?.() ?? Date.now(),
recordsAt,
isCurrent,
});
if (!selection || !isCurrent()) return cancelled();
@@ -1156,7 +1147,6 @@ export function createAnalystEngine(providers) {
if (!isCurrent()) return cancelled();
lastResult = {
matched: memoryOverride?.matched || selection.matched,
recordsAt,
distanceOf: memoryOverride?.distanceOf || rememberedDistanceOf,
layerKeys: [...(memoryOverride?.layerKeys || layers)],
coverage: memoryOverride?.coverage || result.coverage,
-18
View File
@@ -896,24 +896,6 @@ test('time fields filter by ISO and derive ageHours; the feed window is exposed'
assert.equal(age.coverage.layersQueried[0].window, 'last 24 h');
});
test('perimeter age follows the snapshot time of the remembered rows', async () => {
const discoveredTime = Date.UTC(2024, 6, 1);
let at = Date.UTC(2024, 6, 2);
const engine = createAnalystEngine({
now: () => Date.UTC(2026, 6, 2),
getRecords: () => [{ id: 'Pine', discoveredTime }],
getRecordsAt: () => at,
});
const first = await engine.query({
layers: ['fire-perimeters'],
scope: { kind: 'anywhere' },
});
assert.equal(first.items[0].ageHours, 24);
at = null;
const followUp = await engine.query({ followUp: true });
assert.equal(followUp.items[0].ageHours, 24);
});
test('follow-up provenance stays attached to old rows after a feed recovers', async () => {
let state = 'stale';
const engine = createAnalystEngine({
+2 -161
View File
@@ -74,12 +74,7 @@ function collections(adv = '10') {
}
function install(options = {}, preview = false) {
let handler;
// JTWC has its own tests below; these cover NHC alone.
const plugin = cycloneProxy({
now: () => NOW,
readJtwc: async () => [],
...options,
});
const plugin = cycloneProxy({ now: () => NOW, ...options });
plugin[preview ? 'configurePreviewServer' : 'configureServer']({
middlewares: {
use(path, callback) {
@@ -302,7 +297,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, /JTWC: western North Pacific/);
assert.match(snapshot.coverage, /not worldwide/);
assert.equal(snapshot.storms[0].geometryStatus, 'current');
assert.equal(snapshot.fetchedAt, NOW);
assert.equal(calls.length, 4);
@@ -496,157 +491,3 @@ test('shared refresh caps waiting consumers and rejects redirects without exposi
});
assert.equal(body(await redirected.request()).unavailable, true);
});
function jtwcStorm(overrides = {}) {
return {
id: 'sh042027',
agency: 'jtwc',
name: 'Xavier',
classification: 'TC',
basin: 'SH',
position: { longitude: -164.5, latitude: -11.6 },
positionAt: TIME,
advisoryNumber: '15',
issuedAt: TIME,
windKt: 45,
pressureHpa: 995,
movement: { directionDegrees: 245, speedKt: 4 },
advisoryUrl: 'https://www.metoc.navy.mil/jtwc/products/sh0427web.txt',
outlookUrl: 'https://www.metoc.navy.mil/jtwc/products/abpwweb.txt',
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
dangerArea: null,
...overrides,
};
}
test('JTWC storms join NHC’s, and NHC’s advisory wins for a storm both list', async () => {
const crossing = jtwcStorm({
id: 'ep152026',
basin: 'EP',
name: 'JTWC copy',
});
const { request } = install({
fetchImpl: fetcher(),
readJtwc: async () => [jtwcStorm(), crossing],
});
const snapshot = body(await request());
assert.deepEqual(
snapshot.storms.map((storm) => [storm.id, storm.agency, storm.name]),
[
['ep152026', 'nhc', 'Fifteen-E'],
['sh042027', 'jtwc', 'Xavier'],
],
);
assert.equal(snapshot.stale, false);
assert.match(snapshot.source, /JTWC/);
assert.match(snapshot.attribution, /Joint Typhoon Warning Center/);
});
test('JTWC reads go through the bounded fetch with no redirects', async () => {
const calls = [];
const { request } = install({
fetchImpl: async (url, options) => {
calls.push({ url, options });
if (url.includes('jtwc.rss'))
return new Response(
'<rss><item><guid>NWPAC-NIO-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>EPAC-CPAC-WARNINGS</guid>No Current Tropical Cyclone Warnings</item><item><guid>SH-WARNINGS</guid>No Current Tropical Cyclone Warnings</item></rss>',
);
return fetcher()(url, options);
},
readJtwc: undefined,
});
const snapshot = body(await request());
assert.equal(snapshot.stale, false);
const jtwc = calls.filter(({ url }) => url.includes('metoc.navy.mil'));
assert.deepEqual(
jtwc.map(({ url }) => url),
['https://www.metoc.navy.mil/jtwc/rss/jtwc.rss'],
);
assert.equal(jtwc[0].options.redirect, 'error');
});
test('a failed JTWC read keeps its last storms and leaves NHC’s answer fresh', async () => {
let fail = false;
let clock = NOW;
const { request } = install({
fetchImpl: fetcher(),
now: () => clock,
readJtwc: async () => {
if (fail) throw new Error('jtwc down');
return [jtwcStorm()];
},
});
assert.equal(body(await request()).storms.length, 2);
fail = true;
clock += 6 * 60_000;
const kept = body(await request());
assert.equal(kept.stale, false);
assert.equal(kept.reason, null);
assert.deepEqual(
kept.storms.map((storm) => storm.id),
['ep152026', 'sh042027'],
);
// Past their use, both advisories leave the cached answer.
clock = Date.parse(TIME) + 13 * 3600_000 + 60_000;
const later = body(await request());
assert.deepEqual(
later.storms.map((storm) => storm.id),
[],
);
});
test('a cached answer drops each storm whose own advisory is past use, not all of them', async () => {
let up = true;
let clock = NOW;
const { request } = install({
fetchImpl: async (url, options) => {
if (!up) throw new Error('down');
return fetcher()(url, options);
},
now: () => clock,
readJtwc: async () => [
jtwcStorm({ issuedAt: new Date(NOW - 30 * 60_000).toISOString() }),
],
});
assert.equal(body(await request()).storms.length, 2);
up = false;
// 12 h 10 min after the NHC advisory: NHC's is past use, JTWC's is not.
clock = Date.parse(TIME) + 12 * 3600_000 + 10 * 60_000;
const cached = body(await request());
assert.equal(cached.stale, true);
assert.deepEqual(
cached.storms.map((storm) => storm.id),
['sh042027'],
);
});
test('a JTWC that hangs or answers 500 leaves NHC’s answer unchanged', async (t) => {
const nhcOnly = body(await install({ fetchImpl: fetcher() }).request());
assert.equal(nhcOnly.stale, false);
const jtwcCalls = [];
for (const mode of ['500', 'hang']) {
const { request } = install({
readJtwc: undefined,
jtwcTimeoutMs: 20,
fetchImpl: async (url, options) => {
if (!String(url).includes('metoc.navy.mil'))
return fetcher()(url, options);
jtwcCalls.push(mode);
if (mode === '500') return new Response('down', { status: 500 });
// Hangs until its own deadline aborts it.
return new Promise((_, reject) =>
options.signal.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
),
);
},
});
const answer = body(await request());
assert.deepEqual(answer, nhcOnly, `JTWC ${mode}`);
}
assert.deepEqual(jtwcCalls, ['500', 'hang']);
});
+1 -1
View File
@@ -563,7 +563,7 @@ export const DATA_CREDITS = [
},
{
key: 'weather-cyclones',
html: 'Cyclone advisories: <a href="https://www.nhc.noaa.gov/" target="_blank" rel="noopener">NOAA/NWS NHC / CPHC</a> · Atlantic and eastern/central North Pacific; <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.',
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.',
},
{
key: 'weather-lightning',
+14 -18
View File
@@ -34,7 +34,6 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { PACE_MIN_HZ } from '../renderPace.js';
import {
DETECTION_ENABLE_FADE_MS,
@@ -449,34 +448,31 @@ test('the render-governor gate covers the parked case, with teeth on the painter
// until some unrelated frame happens along.
//
// It cannot, and the reason is structural rather than lucky: an AIR bracket can
// only exist while an aircraft layer is enabled, and both aircraft layers pace
// the render loop for their fleet (src/renderPace.js): never fewer than
// PACE_MIN_HZ frames a second however still the camera, more as the fleet
// moves faster on screen. So for exactly as long as there is anything to
// bracket, the scene keeps drawing and the overlay repaints with it, at most a
// third of a second behind. (Before the pace the layers held the loop on every
// frame; measured live 2026-08-23 on a parked camera, an outside-aircraft
// population change moved the painted bracket count with no camera input.)
// only exist while an aircraft layer is enabled, and both aircraft layers take a
// continuous-render hold for their own per-frame fleet animation. So for exactly
// as long as there is anything to bracket, the scene is rendering every frame
// and the overlay repaints with it. (Measured live 2026-08-23 on a parked
// camera: an outside-aircraft population change moved the painted bracket count
// with no camera input, holds = ["flights"], requestRenderMode = false.)
//
// That is a COUPLING, so it deserves a pin. If a later perf pass stops the
// aircraft layers pacing, or lets the pace's floor reach zero, bracket
// That is a COUPLING, so it deserves a pin. If a later perf pass strips these
// holds the way it stripped detection's — a reasonable-looking change — bracket
// promptness goes with them, silently. This test is where that shows up.
test('aircraft brackets stay prompt because the aircraft layers pace the render loop', async () => {
assert.ok(PACE_MIN_HZ >= 3, 'a still scene still draws a few times a second');
test('aircraft brackets stay prompt because the aircraft layers hold the render loop', async () => {
for (const file of ['./flights.js', './militaryFlights.js']) {
const source = readLayerSource(new URL(file, import.meta.url));
const enable = /\n([ \t]*)enable\([\s\S]*?\n\1\},/.exec(source)?.[0];
assert.ok(enable, `${file}: enable() is still identifiable`);
assert.match(
enable,
/parts\.rendering\._startPace\(\)/,
`${file}: enabling the layer must start its pace — detection no longer ` +
'holds the loop, so this is what keeps its AIR brackets repainting on a parked scene',
/holdContinuousRender\('(flights|military)'\)/,
`${file}: enabling the layer must hold continuous render — detection no longer ` +
'holds one, so this is what keeps its AIR brackets repainting on a parked scene',
);
assert.match(
source,
/parts\.rendering\._stopPace\(\)/,
`${file}: and the pace must be stopped, or the governor can never idle`,
/releaseContinuousRender\('(flights|military)'\)/,
`${file}: and the hold must be released, or the governor can never idle`,
);
}
});
-28
View File
@@ -57,34 +57,6 @@ function install(options = {}, hook = 'configureServer') {
};
}
test('the WFIGS query asks for the mapping and edit times, and rows keep both', async () => {
let url;
const request = install({
now: () => 1234,
fetchImpl: async (input) => {
url = new URL(input);
return Response.json({
features: [
{
...feature('timed'),
properties: {
attr_UniqueFireIdentifier: 'timed',
poly_PolygonDateTime: 100,
poly_DateCurrent: 200,
},
},
],
});
},
});
const res = await request();
const fields = url.searchParams.get('outFields').split(',');
assert.ok(fields.includes('poly_PolygonDateTime'));
assert.ok(fields.includes('poly_DateCurrent'));
assert.equal(res.body.rows[0].polygonTime, 100);
assert.equal(res.body.rows[0].updatedTime, 200);
});
for (const hook of ['configureServer', 'configurePreviewServer']) {
test(`${hook}: paging stops at five pages and normalizes the combined snapshot`, async () => {
const calls = [];
+5 -9
View File
@@ -65,10 +65,7 @@ const START_SIZE_PX = 1024;
const MAX_SIZE_PX = 4096;
function createAtlas() {
// By URL, then by size: a URL is hashed once as it is, where a key built
// from it would be a new string to hash on every look-up (an SVG data URL
// runs to kilobytes, and a fleet's write looks up two a row).
const slotsOfUrl = new Map();
const slotOfKey = new Map();
const entries = [];
const listeners = new Set();
const atlas = {
@@ -93,8 +90,8 @@ function createAtlas() {
* @returns {number}
*/
slot(url, sizePx, source) {
let bySize = slotsOfUrl.get(url);
const known = bySize?.get(sizePx);
const key = `${sizePx}|${url}`;
const known = slotOfKey.get(key);
if (known !== undefined) return known;
if (entries.length >= MAX_ICON_SLOTS)
throw new RangeError(
@@ -103,8 +100,7 @@ function createAtlas() {
const slot = entries.length;
const entry = { url, sizePx, image: null, x: 0, y: 0 };
entries.push(entry);
if (!bySize) slotsOfUrl.set(url, (bySize = new Map()));
bySize.set(sizePx, slot);
slotOfKey.set(key, slot);
if (source) placeLoaded(entry, source);
else load(entry);
return slot;
@@ -112,7 +108,7 @@ function createAtlas() {
/** Whether `url` at `sizePx` already has a slot. */
has(url, sizePx) {
return slotsOfUrl.get(url)?.has(sizePx) === true;
return slotOfKey.has(`${sizePx}|${url}`);
},
/** Whether a slot's image is packed and drawable. */
-24
View File
@@ -1,24 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { iconAtlas } from './iconAtlas.js';
test('an atlas slot is one per image and size, and has() agrees with slot()', () => {
const url = `data:image/svg+xml;charset=utf-8,${'%3Csvg%3E'.repeat(400)}#slots`;
const other = `${url}-other`;
assert.equal(iconAtlas.has(url, 20), false);
const small = iconAtlas.slot(url, 20);
assert.equal(iconAtlas.has(url, 20), true);
assert.equal(iconAtlas.slot(url, 20), small, 'the same image and size');
// A copy of the URL, not the same string, finds it too.
assert.equal(iconAtlas.slot(url.slice(0), 20), small);
assert.equal(iconAtlas.has(url, 40), false, 'another size is another slot');
const large = iconAtlas.slot(url, 40);
assert.notEqual(large, small);
assert.equal(iconAtlas.has(url, 40), true);
assert.equal(
iconAtlas.has(other, 20),
false,
'another image is another slot',
);
assert.notEqual(iconAtlas.slot(other, 20), small);
});
-29
View File
@@ -14,35 +14,6 @@ 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
+3
View File
@@ -46,6 +46,9 @@ test('hosted account limits and service failures name their own reason', () => {
assert.equal(failure(429, 'budget'), 'TomTom daily budget reached');
assert.equal(failure(503, 'no_key'), 'TomTom key unavailable');
assert.equal(failure(503, null), 'TomTom key unavailable');
// TomTom refused the key itself: not the generic HTTP 403 line.
assert.equal(failure(403, 'key_rejected'), 'TomTom key rejected');
assert.equal(failure(403, null), 'TomTom flow error (HTTP 403)');
assert.equal(
failure(503, 'USAGE_UNAVAILABLE'),
'Traffic service unavailable',
+3 -4
View File
@@ -920,7 +920,7 @@ test('the Stories announcement waits behind the welcome card', () => {
// the card is dismissed.
assert.match(
css,
/body:is\(\.launcher-shown \*, #first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
/body:has\(#first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
);
// The selector only works while Stories still renders the popup as #hPop
// inside #gev-stories.
@@ -1110,11 +1110,10 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
// Pistes extend the generated layer enums and alias hint; voice geometry
// adds the analyst area scopes and the osm-places layer.
// control_cockpit states the own-layer entry rule (Contacts not required).
// Fire Perimeters queries add lastGrowthTime.
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
assert.equal(
crypto.createHash('sha256').update(block).digest('hex'),
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
);
const instructions = fs.readFileSync(
+22 -140
View File
@@ -227,17 +227,6 @@ const NEARBY_POINTS = Object.values(CITY_POIS).flatMap((city) =>
* and the altitude-scaled GSD/NIIRS figures. Readouts update on independent
* fixed cadences.
*/
/**
* The view's attributes on #intel-hud itself: shown or not, layout variant
* and style colors. Stylesheets and layout elsewhere on the page read them.
*/
const HUD_FRAME_KEYS = Object.freeze(['active', 'variant', 'colors']);
/** @param {object} view @returns {object} Its {@link HUD_FRAME_KEYS}. */
function pickFrame(view) {
return Object.fromEntries(HUD_FRAME_KEYS.map((key) => [key, view[key]]));
}
export class IntelHUD {
/**
* @param {object} viewer - The scene the HUD sits over.
@@ -265,19 +254,6 @@ export class IntelHUD {
this.placeSearch = placeSearch;
this.viewer = viewer;
this._visible = false;
// Whether the HUD's view is on screen (setDisplayed). While it is not,
// no timer runs and no readout is worked out or published; what was
// skipped is caught up when it is back.
this._displayed = true;
this._unseen = { settle: false, show: false, summary: false };
/** Summary updates under way; one still running when the view goes is
* dropped and asked again when it is back. */
this._summaryRuns = 0;
/** The text the typewriter is typing out, while it types. */
this._summaryTypingText = null;
/** When the view stopped being displayed (Date.now()), or null. */
this._undisplayedAt = null;
this._destroyed = false;
this._autoMode = true; // auto show/hide based on style
this._currentStyle = 'normal';
/** The presented HUD; see {@link IntelHUD#_initView}. */
@@ -344,8 +320,20 @@ export class IntelHUD {
};
this._onCameraMoveEnd = () => {
this._markSummaryDirty();
if (this._displayed) this._settle();
else this._unseen.settle = true;
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
// leave the prior city on-screen after a long CCTV focus flight.
// Refresh deterministic camera context synchronously on settle; the AI
// summary can still upgrade it on its normal cadence.
if (this._visible) {
this._updateCameraData();
this._setSummaryText(this._composeSummary(), false);
}
// First settled view: request the AI summary now rather than waiting for
// the periodic tick (saves up to ~15s of "Awaiting telemetry...").
if (!this._firstSummaryKicked && this._visible && this._latestMetrics) {
this._firstSummaryKicked = true;
void this._updateSummary(true, true);
}
};
// Session-consistent pseudorandom identifiers (generated once at construction)
@@ -370,27 +358,6 @@ export class IntelHUD {
this._startTimers();
}
/**
* The camera has settled: show the readouts and the plain summary for the
* view it settled on.
*/
_settle() {
// The 250 ms telemetry timer and 15 s semantic-summary timer must not
// leave the prior city on-screen after a long CCTV focus flight.
// Refresh deterministic camera context synchronously on settle; the AI
// summary can still upgrade it on its normal cadence.
if (this._visible) {
this._updateCameraData();
this._setSummaryText(this._composeSummary(), false);
}
// First settled view: request the AI summary now rather than waiting for
// the periodic tick (saves up to ~15s of "Awaiting telemetry...").
if (!this._firstSummaryKicked && this._visible && this._latestMetrics) {
this._firstSummaryKicked = true;
void this._updateSummary(true, true);
}
}
/** Show the HUD's words in the new locale; drop AI text in the old one. */
_relocalize() {
this._markSummaryDirty();
@@ -407,8 +374,7 @@ export class IntelHUD {
? {}
: { vessel: { active: false, text: t('AIS: --') } }),
});
if (this._visible && this._displayed && this._latestMetrics)
this._updateCameraData();
if (this._visible && this._latestMetrics) this._updateCameraData();
this._setSummaryText(this._composeSummary(), false);
}
@@ -451,17 +417,10 @@ export class IntelHUD {
*/
_present(patch) {
Object.assign(this._view, patch);
// Not displayed: only the view's own attributes are published, which the
// page's stylesheets and layout read from #intel-hud while it is hidden
// too; the readouts wait until it is displayed again.
const view = this._displayed
? this._view
: { ...this._shown, ...pickFrame(this._view) };
const signature = JSON.stringify(view);
const signature = JSON.stringify(this._view);
if (signature === this._viewSignature) return;
this._viewSignature = signature;
this._shown = Object.freeze({ ...view });
this._publish(this._shown);
this._publish(Object.freeze({ ...this._view }));
}
/**
@@ -470,7 +429,6 @@ export class IntelHUD {
* cadences and are cleaned up in {@link destroy}.
*/
_startTimers() {
this._stopTimers();
// Timestamp — every second
this._timestampInterval = setInterval(() => {
this._present({ timestamp: this._formatUTC() });
@@ -497,18 +455,6 @@ export class IntelHUD {
}, HUD_SUMMARY_INTERVAL_MS);
}
/** Stop the periodic timers {@link _startTimers} started. */
_stopTimers() {
clearInterval(this._timestampInterval);
clearInterval(this._recBlinkInterval);
clearInterval(this._updateInterval);
clearInterval(this._summaryInterval);
this._timestampInterval = null;
this._recBlinkInterval = null;
this._updateInterval = null;
this._summaryInterval = null;
}
/**
* Format the HUD's world time as a UTC Zulu string.
* @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SSZ` format.
@@ -898,7 +844,6 @@ export class IntelHUD {
_stopSummaryTyping() {
clearInterval(this._summaryTypingInterval);
this._summaryTypingInterval = null;
this._summaryTypingText = null;
}
/**
@@ -908,7 +853,6 @@ export class IntelHUD {
*/
_typeSummary(text) {
clearInterval(this._summaryTypingInterval);
this._summaryTypingText = text;
let index = 0;
this._present({ summary: '' });
this._summaryTypingInterval = setInterval(() => {
@@ -917,7 +861,6 @@ export class IntelHUD {
this._present({ summary: text });
clearInterval(this._summaryTypingInterval);
this._summaryTypingInterval = null;
this._summaryTypingText = null;
return;
}
this._present({ summary: text.slice(0, index) });
@@ -930,16 +873,6 @@ export class IntelHUD {
* by character; otherwise sets it instantly.
*/
async _updateSummary(animate = false, force = false) {
this._summaryRuns += 1;
try {
await this._runSummaryUpdate(animate, force);
} finally {
this._summaryRuns -= 1;
}
}
/** {@link _updateSummary}'s work. */
async _runSummaryUpdate(animate, force) {
const fallbackText = this._composeSummary();
if (!this._latestMetrics) {
this._setSummaryText(fallbackText, animate);
@@ -1069,8 +1002,7 @@ export class IntelHUD {
}
_setSummaryText(text, animate) {
// Nothing types out off screen: the text is there when the view is back.
if (animate && this._displayed) {
if (animate) {
this._typeSummary(text);
return;
}
@@ -1191,63 +1123,11 @@ export class IntelHUD {
show() {
this._visible = true;
this._present({ active: true });
if (this._displayed) this._refreshShown();
else this._unseen.show = true;
}
/** Readouts and a fresh summary for a HUD just shown. */
_refreshShown() {
this._updateCameraData(); // immediate update
this._markSummaryDirty();
void this._updateSummary(false, true);
}
/**
* Whether the HUD's view is on screen. A stylesheet can give the view
* `display: none`, or the view can be unmounted; until it is displayed
* again no timer runs, a summary being worked out is dropped and only the
* view's own attributes ({@link HUD_FRAME_KEYS}) are published. Then the
* timers start again and current readouts show at once.
* @param {boolean} displayed
*/
setDisplayed(displayed) {
displayed = Boolean(displayed);
if (this._destroyed || displayed === this._displayed) return;
this._displayed = displayed;
if (!displayed) {
this._undisplayedAt = Date.now();
this._stopTimers();
// A reply still typing is finished: the view shows all of it when it
// is back, not the rest of it typing out.
const typing = this._summaryTypingText;
this._stopSummaryTyping();
if (typing !== null) this._present({ summary: typing });
// A summary being worked out is dropped, and asked again when the
// view is back.
if (this._summaryRuns > 0) {
this._unseen.summary = true;
this._markSummaryDirty();
this._summaryRequest?.abort();
}
return;
}
const { settle, show } = this._unseen;
// The summary refresh that would have come round while it was away.
const summary =
this._unseen.summary ||
Date.now() - (this._undisplayedAt ?? Date.now()) >=
HUD_SUMMARY_INTERVAL_MS;
this._unseen = { settle: false, show: false, summary: false };
this._undisplayedAt = null;
this._startTimers();
// Publishes the whole view: what changed while it was not displayed.
this._present({ timestamp: this._formatUTC() });
if (settle) this._settle();
if (show && this._visible) this._refreshShown();
else if (!settle && this._visible) this._updateCameraData();
if (summary && !show && this._visible) void this._updateSummary(true);
}
/** Hide the HUD overlay. */
hide() {
this._visible = false;
@@ -1334,8 +1214,10 @@ export class IntelHUD {
/** Tear down all running intervals. Call when discarding the HUD instance. */
destroy() {
this._destroyed = true;
this._stopTimers();
clearInterval(this._updateInterval);
clearInterval(this._recBlinkInterval);
clearInterval(this._timestampInterval);
clearInterval(this._summaryInterval);
clearInterval(this._summaryTypingInterval);
for (const off of this._offCamera.splice(0)) off();
this._dataManagerUnsubscribe?.();
+13 -21
View File
@@ -1521,6 +1521,7 @@
"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": "إعصار مداري محتمل",
@@ -1548,12 +1549,17 @@
"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": "مشي",
@@ -1845,6 +1851,11 @@
"Unnamed incident": "حادث بلا اسم",
"Open {title} on InciWeb": "فتح {title} على InciWeb",
"Perimeter source unavailable": "مصدر محيطات الحرائق غير متاح",
"Not contained or unknown": "بلا احتواء أو غير معروف",
"Under 50% contained": "الاحتواء: أقل من 50%",
"50–99% contained": "الاحتواء: 50–99%",
"Fully contained": "احتواء كامل",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "يبيّن اللون نسبة الاحتواء المُبلَّغ عنها. المحيطات مبسّطة إلى نحو 100 م.",
"Malformed perimeter snapshot": "لقطة المحيطات مشوّهة",
"radio tag|All": "الكل",
"Directory refresh degraded; showing the previous station catalog.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
@@ -1972,6 +1983,7 @@
"Moving dots colored by live flow": "نقاط متحركة ملوّنة حسب التدفق المباشر",
"Moving dots": "نقاط متحركة",
"TomTom key unavailable": "مفتاح TomTom غير متاح",
"TomTom key rejected": "تم رفض مفتاح TomTom",
"TomTom daily budget reached": "بلغت الحصة اليومية لـ TomTom",
"Monthly traffic allowance used": "تم استهلاك حصة حركة المرور الشهرية",
"Traffic rate limit reached": "تم بلوغ حد طلبات حركة المرور",
@@ -4838,25 +4850,5 @@
"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.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط.",
"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}",
"last growth {age} ago": "آخر توسّع قبل {age}",
"Last 6 hours": "آخر 6 ساعات",
"6–24 hours": "6–24 ساعة",
"1–3 days": "1–3 أيام",
"Older or unknown": "أقدم أو غير معروف",
"Colour shows the age of each area.": "يبيّن اللون عمر كل منطقة.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "يُحسب العمر من وقت رسم WFIGS للحدود، وإلا فمن آخر تعديل للسجل. الحدود مبسّطة إلى نحو 100 م."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "الألواح والمشعّات وأحد الأطباق تتبع القياسات الحية من ناسا. الطبق الآخر ثابت، والأذرع تتحرك للتوضيح فقط."
}
+13 -21
View File
@@ -1436,6 +1436,7 @@
"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",
@@ -1459,12 +1460,17 @@
"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",
@@ -1727,6 +1733,11 @@
"Unnamed incident": "Unbenannter Einsatz",
"Open {title} on InciWeb": "{title} auf InciWeb öffnen",
"Perimeter source unavailable": "Quelle der Brandgrenzen nicht verfügbar",
"Not contained or unknown": "Nicht eingedämmt oder unbekannt",
"Under 50% contained": "Unter 50 % eingedämmt",
"50–99% contained": "50–99 % eingedämmt",
"Fully contained": "Vollständig eingedämmt",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Die Farbe zeigt die gemeldete Eindämmung. Brandgrenzen sind auf etwa 100 m vereinfacht.",
"Malformed perimeter snapshot": "Fehlerhafter Brandgrenzen-Snapshot",
"radio tag|All": "Alle",
"Directory refresh degraded; showing the previous station catalog.": "Verzeichnisaktualisierung eingeschränkt; der vorherige Senderkatalog wird gezeigt.",
@@ -1849,6 +1860,7 @@
"Moving dots colored by live flow": "Bewegte Punkte nach Live-Verkehrsfluss gefärbt",
"Moving dots": "Bewegte Punkte",
"TomTom key unavailable": "TomTom-Schlüssel nicht verfügbar",
"TomTom key rejected": "TomTom-Schlüssel abgelehnt",
"TomTom daily budget reached": "TomTom-Tagesbudget erreicht",
"Monthly traffic allowance used": "Monatliches Verkehrskontingent aufgebraucht",
"Traffic rate limit reached": "Verkehrs-Anfragelimit erreicht",
@@ -4414,25 +4426,5 @@
"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.",
"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}",
"last growth {age} ago": "zuletzt gewachsen vor {age}",
"Last 6 hours": "Letzte 6 Stunden",
"6–24 hours": "6–24 Stunden",
"1–3 days": "1–3 Tage",
"Older or unknown": "Älter oder unbekannt",
"Colour shows the age of each area.": "Die Farbe zeigt das Alter jeder Fläche.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Alter ab der Kartierung durch WFIGS, sonst ab der letzten Änderung des Datensatzes. Brandgrenzen auf ca. 100 m vereinfacht."
"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."
}
+13 -21
View File
@@ -1342,6 +1342,7 @@
"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",
@@ -1364,12 +1365,17 @@
"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",
@@ -1411,6 +1417,11 @@
"Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
"Routing unavailable": "Rutas no disponibles",
"Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
"Not contained or unknown": "Sin contener o desconocido",
"Under 50% contained": "Contenido por debajo del 50%",
"50–99% contained": "Contenido al 50–99%",
"Fully contained": "Totalmente contenido",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
"MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
"DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
@@ -2452,6 +2463,7 @@
"Military area": "Zona militar",
"SIMULATED — {reason}": "SIMULADO — {reason}",
"TomTom key unavailable": "Clave de TomTom no disponible",
"TomTom key rejected": "Clave de TomTom rechazada",
"TomTom daily budget reached": "Se alcanzó el límite diario de TomTom",
"Monthly traffic allowance used": "Cupo mensual de tráfico agotado",
"Traffic rate limit reached": "Límite de peticiones de tráfico alcanzado",
@@ -4520,25 +4532,5 @@
"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.",
"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}",
"last growth {age} ago": "último crecimiento hace {age}",
"Last 6 hours": "Últimas 6 horas",
"6–24 hours": "6–24 horas",
"1–3 days": "1–3 días",
"Older or unknown": "Más antiguo o desconocido",
"Colour shows the age of each area.": "El color indica la antigüedad de cada zona.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Antigüedad desde el mapeo de WFIGS o, si falta, desde la última edición del registro. Perímetros simplificados a ~100 m."
"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."
}
+13 -21
View File
@@ -644,6 +644,7 @@
"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",
@@ -668,12 +669,17 @@
"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",
@@ -1070,6 +1076,11 @@
"Unnamed incident": "Incident sans nom",
"Open {title} on InciWeb": "Ouvrir {title} sur InciWeb",
"Perimeter source unavailable": "Source des périmètres indisponible",
"Not contained or unknown": "Non circonscrit ou inconnu",
"Under 50% contained": "Circonscrit à moins de 50 %",
"50–99% contained": "Circonscrit à 50–99 %",
"Fully contained": "Entièrement circonscrit",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "La couleur indique la part du périmètre déclarée circonscrite. Les périmètres sont simplifiés à environ 100 m.",
"Malformed perimeter snapshot": "Instantané des périmètres mal formé",
"radio tag|All": "Toutes",
"News": "Actualités",
@@ -1236,6 +1247,7 @@
"Moving dots colored by live flow": "Points mobiles colorés selon le trafic en direct",
"Moving dots": "Points mobiles",
"TomTom key unavailable": "Clé TomTom indisponible",
"TomTom key rejected": "Clé TomTom refusée",
"TomTom daily budget reached": "Quota quotidien TomTom atteint",
"Monthly traffic allowance used": "Quota mensuel de trafic épuisé",
"Traffic rate limit reached": "Limite de requêtes de trafic atteinte",
@@ -4520,25 +4532,5 @@
"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.",
"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}",
"last growth {age} ago": "dernière progression il y a {age}",
"Last 6 hours": "6 dernières heures",
"6–24 hours": "6–24 heures",
"1–3 days": "1–3 jours",
"Older or unknown": "Plus ancien ou inconnu",
"Colour shows the age of each area.": "La couleur indique l’âge de chaque zone.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Âge compté depuis la cartographie WFIGS, sinon depuis la dernière modification de la fiche. Périmètres simplifiés à ~100 m."
"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."
}
+13 -21
View File
@@ -532,6 +532,7 @@
"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": "ציקלון טרופי פוטנציאלי",
@@ -556,12 +557,17 @@
"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": "נסיעה",
@@ -919,6 +925,11 @@
"Unnamed incident": "אירוע ללא שם",
"Open {title} on InciWeb": "פתיחת {title} ב-InciWeb",
"Perimeter source unavailable": "מקור ההיקף אינו זמין",
"Not contained or unknown": "ללא הכלה או לא ידוע",
"Under 50% contained": "הכלה מתחת ל-50%",
"50–99% contained": "הכלה 50–99%",
"Fully contained": "הכלה מלאה",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "הצבע מציג את ההכלה שדווחה. ההיקפים מפושטים לכ-100 מ׳.",
"Malformed perimeter snapshot": "תמונת מצב היקף פגומה",
"radio tag|All": "הכול",
"News": "חדשות",
@@ -1081,6 +1092,7 @@
"TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "כבישי TomTom קודם; OpenStreetMap משלים את היתר, מדומים (דורש מפתח TomTom)",
"Hybrid": "היברידי",
"TomTom key unavailable": "מפתח TomTom אינו זמין",
"TomTom key rejected": "מפתח TomTom נדחה",
"TomTom daily budget reached": "תקציב TomTom היומי אזל",
"TomTom upstream unreachable": "שירות TomTom אינו נגיש",
"TomTom flow unavailable": "זרימת TomTom אינה זמינה",
@@ -4520,25 +4532,5 @@
"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.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד.",
"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}",
"last growth {age} ago": "התפשטות אחרונה לפני {age}",
"Last 6 hours": "6 השעות האחרונות",
"6–24 hours": "6–24 שעות",
"1–3 days": "1–3 ימים",
"Older or unknown": "ישן יותר או לא ידוע",
"Colour shows the age of each area.": "הצבע מציין את הגיל של כל שטח.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "הגיל נספר ממועד המיפוי של WFIGS, או מהעריכה האחרונה של הרשומה. קווי המתאר מפושטים לכ־100 מ׳."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "הלוחות, הרדיאטורים וצלחת אחת עוקבים אחר הטלמטריה החיה של נאס״א. הצלחת השנייה נשארת במקומה והזרועות נעות להמחשה בלבד."
}
+13 -21
View File
@@ -644,6 +644,7 @@
"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",
@@ -668,12 +669,17 @@
"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",
@@ -1070,6 +1076,11 @@
"Unnamed incident": "Incendio senza nome",
"Open {title} on InciWeb": "Apri {title} su InciWeb",
"Perimeter source unavailable": "Fonte dei perimetri non disponibile",
"Not contained or unknown": "Non contenuto o dato non disponibile",
"Under 50% contained": "Contenuto a meno del 50%",
"50–99% contained": "Contenuto al 50–99%",
"Fully contained": "Completamente contenuto",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Il colore indica il contenimento riportato. I perimetri sono semplificati a circa 100 m.",
"Malformed perimeter snapshot": "Snapshot dei perimetri non valido",
"radio tag|All": "Tutti",
"News": "Notizie",
@@ -1236,6 +1247,7 @@
"Moving dots colored by live flow": "Punti in movimento colorati in base al flusso live",
"Moving dots": "Punti in movimento",
"TomTom key unavailable": "Chiave TomTom non disponibile",
"TomTom key rejected": "Chiave TomTom rifiutata",
"TomTom daily budget reached": "Budget giornaliero TomTom esaurito",
"Monthly traffic allowance used": "Quota mensile del traffico esaurita",
"Traffic rate limit reached": "Limite di richieste del traffico raggiunto",
@@ -4520,25 +4532,5 @@
"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.",
"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}",
"last growth {age} ago": "ultima espansione {age} fa",
"Last 6 hours": "Ultime 6 ore",
"6–24 hours": "6–24 ore",
"1–3 days": "1–3 giorni",
"Older or unknown": "Più vecchio o sconosciuto",
"Colour shows the age of each area.": "Il colore indica l’età di ciascuna area.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Età dalla mappatura WFIGS, altrimenti dall’ultima modifica del record. Perimetri semplificati a ~100 m."
"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."
}
+13 -21
View File
@@ -616,6 +616,7 @@
"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,12 +639,17 @@
"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": "徒歩",
@@ -1024,6 +1030,11 @@
"Unnamed incident": "名称未設定の火災",
"Open {title} on InciWeb": "InciWebで{title}を開く",
"Perimeter source unavailable": "延焼範囲のソースを利用できません",
"Not contained or unknown": "封じ込め率0%または不明",
"Under 50% contained": "封じ込め率50%未満",
"50–99% contained": "封じ込め率50–99%",
"Fully contained": "封じ込め率100%",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "色は報告された封じ込め率を示します。延焼範囲の輪郭は約100 mの精度で簡略化されています。",
"Malformed perimeter snapshot": "延焼範囲スナップショットの形式が不正です",
"radio tag|All": "すべて",
"News": "ニュース",
@@ -1190,6 +1201,7 @@
"Moving dots colored by live flow": "ライブの交通流で色分けした移動ドット",
"Moving dots": "移動ドット",
"TomTom key unavailable": "TomTomキーを利用できません",
"TomTom key rejected": "TomTomキーが拒否されました",
"TomTom daily budget reached": "TomTomの1日の上限に達しました",
"Monthly traffic allowance used": "今月の交通情報の上限に達しました",
"Traffic rate limit reached": "交通情報のリクエスト上限に達しました",
@@ -4308,25 +4320,5 @@
"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基のアンテナは動かず、アームは説明用にゆっくり動きます。",
"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} 発表",
"last growth {age} ago": "{age}前に最終拡大",
"Last 6 hours": "過去6時間",
"6–24 hours": "6–24時間",
"1–3 days": "1–3日",
"Older or unknown": "それ以前または不明",
"Colour shows the age of each area.": "色は各区域の経過時間を示します。",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "経過時間は WFIGS の測図時刻から、なければ記録の最終編集時刻から数えます。境界線は約 100 m に簡略化されています。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽電池パネル、ラジエーター、アンテナの1基はNASAのライブテレメトリに従います。もう1基のアンテナは動かず、アームは説明用にゆっくり動きます。"
}
+13 -21
View File
@@ -644,6 +644,7 @@
"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",
@@ -668,12 +669,17 @@
"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É",
@@ -1068,6 +1074,11 @@
"Unnamed incident": "Sem nome",
"Open {title} on InciWeb": "Abrir {title} no InciWeb",
"Perimeter source unavailable": "Fonte de perímetros indisponível",
"Not contained or unknown": "Não contido ou desconhecido",
"Under 50% contained": "Menos de 50% contido",
"50–99% contained": "50–99% contido",
"Fully contained": "Totalmente contido",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "A cor indica a contenção informada. Os perímetros são simplificados para cerca de 100 m.",
"Malformed perimeter snapshot": "Snapshot de perímetros malformado",
"radio tag|All": "Todas",
"News": "Notícias",
@@ -1234,6 +1245,7 @@
"Moving dots colored by live flow": "Pontos em movimento coloridos pelo fluxo ao vivo",
"Moving dots": "Pontos em movimento",
"TomTom key unavailable": "Chave do TomTom indisponível",
"TomTom key rejected": "Chave do TomTom recusada",
"TomTom daily budget reached": "Limite diário do TomTom atingido",
"Monthly traffic allowance used": "Cota mensal de trânsito esgotada",
"Traffic rate limit reached": "Trânsito: limite de requisições atingido",
@@ -4520,25 +4532,5 @@
"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.",
"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}",
"last growth {age} ago": "último crescimento há {age}",
"Last 6 hours": "Últimas 6 horas",
"6–24 hours": "6–24 horas",
"1–3 days": "1–3 dias",
"Older or unknown": "Mais antigo ou desconhecido",
"Colour shows the age of each area.": "A cor indica a idade de cada área.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Idade a partir do mapeamento do WFIGS ou, na falta dele, da última edição do registro. Perímetros simplificados a ~100 m."
"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."
}
+13 -21
View File
@@ -1369,6 +1369,7 @@
"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": "Ураган",
@@ -1392,12 +1393,17 @@
"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": "ЩЁЛКНИТЕ ПО КАРТЕ",
@@ -1439,6 +1445,11 @@
"Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
"Routing unavailable": "Построение маршрута недоступно",
"Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
"Not contained or unknown": "Не локализован или неизвестно",
"Under 50% contained": "Локализован менее чем на 50%",
"50–99% contained": "Локализован на 50–99%",
"Fully contained": "Полностью локализован",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
"MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
"Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
"DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
@@ -2501,6 +2512,7 @@
"Military area": "Военная зона",
"SIMULATED — {reason}": "СИМУЛЯЦИЯ — {reason}",
"TomTom key unavailable": "Ключ TomTom недоступен",
"TomTom key rejected": "Ключ TomTom отклонён",
"TomTom daily budget reached": "Исчерпан дневной лимит TomTom",
"Monthly traffic allowance used": "Месячный лимит данных о трафике исчерпан",
"Traffic rate limit reached": "Достигнут лимит запросов данных о трафике",
@@ -4626,25 +4638,5 @@
"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 в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации.",
"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}",
"last growth {age} ago": "последний рост {age} назад",
"Last 6 hours": "Последние 6 часов",
"6–24 hours": "6–24 часа",
"1–3 days": "1–3 дня",
"Older or unknown": "Старше или неизвестно",
"Colour shows the age of each area.": "Цвет показывает возраст каждого участка.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Возраст — от картирования WFIGS, иначе от последней правки записи. Контуры упрощены до ~100 м."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панели, радиаторы и одна антенна следуют телеметрии NASA в реальном времени. Вторая антенна неподвижна, а манипуляторы движутся для иллюстрации."
}
+13 -21
View File
@@ -1352,6 +1352,7 @@
"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",
@@ -1375,12 +1376,17 @@
"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",
@@ -1643,6 +1649,11 @@
"Unnamed incident": "Namnlös händelse",
"Open {title} on InciWeb": "Öppna {title} på InciWeb",
"Perimeter source unavailable": "Källa för brandgränser otillgänglig",
"Not contained or unknown": "Inte under kontroll eller okänt",
"Under 50% contained": "Mindre än 50 % under kontroll",
"50–99% contained": "50–99 % under kontroll",
"Fully contained": "Helt under kontroll",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Färgen visar rapporterad kontrollgrad. Brandgränserna är förenklade till cirka 100 m.",
"Malformed perimeter snapshot": "Felformaterad ögonblicksbild av brandgränser",
"radio tag|All": "Alla",
"Directory refresh degraded; showing the previous station catalog.": "Uppdateringen av katalogen är begränsad; visar den tidigare stationskatalogen.",
@@ -1765,6 +1776,7 @@
"Moving dots colored by live flow": "Rörliga punkter färgade efter trafikflödet live",
"Moving dots": "Rörliga punkter",
"TomTom key unavailable": "TomTom-nyckel otillgänglig",
"TomTom key rejected": "TomTom-nyckeln avvisades",
"TomTom daily budget reached": "TomTom-dagsbudgeten är förbrukad",
"Monthly traffic allowance used": "Månadens trafikkvot är förbrukad",
"Traffic rate limit reached": "Trafiktjänsten har nått gränsen för förfrågningar",
@@ -4414,25 +4426,5 @@
"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.",
"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}",
"last growth {age} ago": "senaste tillväxt för {age} sedan",
"Last 6 hours": "Senaste 6 timmarna",
"6–24 hours": "6–24 timmar",
"1–3 days": "1–3 dagar",
"Older or unknown": "Äldre eller okänt",
"Colour shows the age of each area.": "Färgen visar åldern på varje område.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Åldern räknas från WFIGS kartläggning, annars från postens senaste ändring. Brandgränser förenklade till ~100 m."
"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."
}
+13 -21
View File
@@ -658,6 +658,7 @@
"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": "Потенційний тропічний циклон",
@@ -683,12 +684,17 @@
"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": "ПІШКИ",
@@ -1092,6 +1098,11 @@
"Unnamed incident": "Без назви",
"Open {title} on InciWeb": "Відкрити {title} в InciWeb",
"Perimeter source unavailable": "Джерело контурів пожеж недоступне",
"Not contained or unknown": "Не локалізовано або невідомо",
"Under 50% contained": "Локалізовано менш ніж на 50%",
"50–99% contained": "Локалізовано на 50–99%",
"Fully contained": "Повністю локалізовано",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "Колір показує заявлений ступінь локалізації. Контури спрощено приблизно до 100 м.",
"Malformed perimeter snapshot": "Некоректний знімок контурів пожеж",
"radio tag|All": "Усі",
"News": "Новини",
@@ -1258,6 +1269,7 @@
"Moving dots colored by live flow": "Рухомі точки, забарвлені за потоком онлайн",
"Moving dots": "Рухомі точки",
"TomTom key unavailable": "Ключ TomTom недоступний",
"TomTom key rejected": "Ключ TomTom відхилено",
"TomTom daily budget reached": "Вичерпано денний ліміт TomTom",
"Monthly traffic allowance used": "Місячний ліміт даних про дорожній рух вичерпано",
"Traffic rate limit reached": "Перевищено ліміт запитів до сервісу руху",
@@ -4626,25 +4638,5 @@
"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 в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації.",
"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}",
"last growth {age} ago": "останнє зростання {age} тому",
"Last 6 hours": "Останні 6 годин",
"6–24 hours": "6–24 години",
"1–3 days": "1–3 дні",
"Older or unknown": "Старше або невідомо",
"Colour shows the age of each area.": "Колір показує вік кожної ділянки.",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "Вік — від картування WFIGS, інакше від останнього редагування запису. Контури спрощено до ~100 м."
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "Панелі, радіатори й одна антена слідують телеметрії NASA в реальному часі. Друга антена нерухома, а маніпулятори рухаються для ілюстрації."
}
+13 -21
View File
@@ -615,6 +615,7 @@
"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": "潜在热带气旋",
@@ -637,12 +638,17 @@
"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": "步行",
@@ -1004,6 +1010,11 @@
"Unnamed incident": "未命名火情",
"Open {title} on InciWeb": "在 InciWeb 上打开 {title}",
"Perimeter source unavailable": "周界数据源不可用",
"Not contained or unknown": "未控制或未知",
"Under 50% contained": "控制低于 50%",
"50–99% contained": "控制 50–99%",
"Fully contained": "已全部控制",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "颜色表示报告的控制比例。周界简化至约 100 m。",
"Malformed perimeter snapshot": "周界快照格式错误",
"radio tag|All": "全部",
"News": "新闻",
@@ -1167,6 +1178,7 @@
"Moving dots colored by live flow": "按实时路况着色的移动圆点",
"Moving dots": "移动圆点",
"TomTom key unavailable": "TomTom 密钥不可用",
"TomTom key rejected": "TomTom 密钥被拒绝",
"TomTom daily budget reached": "已达 TomTom 每日配额",
"Monthly traffic allowance used": "本月交通数据配额已用完",
"Traffic rate limit reached": "已达到交通数据请求频率上限",
@@ -4308,25 +4320,5 @@
"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 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。",
"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}",
"last growth {age} ago": "最近一次扩展于 {age}前",
"Last 6 hours": "过去 6 小时",
"6–24 hours": "6–24 小时",
"1–3 days": "1–3 天",
"Older or unknown": "更早或未知",
"Colour shows the age of each area.": "颜色表示各区域在所示时刻的年龄。",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "时长从 WFIGS 测绘时间算起,否则从记录的最后编辑时间算起。边界已简化至约 100 米。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太阳能板、散热器和一副天线依据 NASA 的实时遥测转动。另一副天线保持不动,机械臂仅作演示性摆动。"
}
+13 -21
View File
@@ -615,6 +615,7 @@
"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": "潛在熱帶氣旋",
@@ -637,12 +638,17 @@
"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": "步行",
@@ -1004,6 +1010,11 @@
"Unnamed incident": "未命名火情",
"Open {title} on InciWeb": "在 InciWeb 上打開 {title}",
"Perimeter source unavailable": "周界數據源不可用",
"Not contained or unknown": "未控制或未知",
"Under 50% contained": "控制低於 50%",
"50–99% contained": "控制 50–99%",
"Fully contained": "已全部控制",
"Colour shows reported containment. Perimeters are simplified to about 100 m.": "顏色表示報告的控制比例。周界簡化至約 100 m。",
"Malformed perimeter snapshot": "周界快照格式錯誤",
"radio tag|All": "全部",
"News": "新聞",
@@ -1167,6 +1178,7 @@
"Moving dots colored by live flow": "按實時路況著色的移動圓點",
"Moving dots": "移動圓點",
"TomTom key unavailable": "TomTom 密鑰不可用",
"TomTom key rejected": "TomTom 密鑰被拒絕",
"TomTom daily budget reached": "已達 TomTom 每日配額",
"Monthly traffic allowance used": "本月交通數據配額已用完",
"Traffic rate limit reached": "已達到交通數據請求頻率上限",
@@ -4308,25 +4320,5 @@
"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 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。",
"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}",
"last growth {age} ago": "最近一次擴展於 {age}前",
"Last 6 hours": "過去 6 小時",
"6–24 hours": "6–24 小時",
"1–3 days": "1–3 天",
"Older or unknown": "更早或未知",
"Colour shows the age of each area.": "顏色表示各區域在所示時刻的年齡。",
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.": "時長從 WFIGS 測繪時間算起,否則從記錄的最後編輯時間算起。邊界已簡化至約 100 米。"
"Arrays, radiators and one dish follow NASA's live telemetry. The other dish holds still and the arms sway for illustration.": "太陽能板、散熱器和一副天線依據 NASA 的實時遙測轉動。另一副天線保持不動,機械臂僅作演示性擺動。"
}
+1 -1
View File
@@ -541,7 +541,7 @@
"Conversation",
"Country",
"Cyan",
"Cyclones · NHC / CPHC · JTWC",
"Cyclones · NHC / CPHC",
"DENSE",
"DEST ---°",
"DEST {bearing}",
+24 -2
View File
@@ -4,7 +4,6 @@ import {
AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
findByDoublingRadius,
AWARENESS_RADIUS_M,
aircraftClassMatches,
} from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_MAX_EXAMPLES,
@@ -53,7 +52,29 @@ export function createNavigation({
return layerId === 'flights' || layerId === 'military';
}
const aircraftClassMatchesFilter = aircraftClassMatches;
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),
);
}
function selectNavigationTargets(
sourceCohorts,
@@ -244,6 +265,7 @@ export function createNavigation({
summarizeAwarenessCohortForNavigation,
resetNavigationVisitedCycle,
isFlightLayer,
normalizeAircraftClass,
aircraftClassMatchesFilter,
selectNavigationTargets,
alternativeFlightAvailable,
-24
View File
@@ -1,4 +1,3 @@
import { findCamera } from '../../render/rendererOf.js';
import {
FRAME_SIGNATURE_W,
FRAME_SIGNATURE_H,
@@ -42,11 +41,6 @@ export function fitToProjection(sourceW, sourceH) {
};
}
const PLANE_POINTS = ['mount', 'tl', 'tr', 'br', 'bl'];
const _scratchPoints = [];
// Keep the occluding surface below common negative geoid undulations.
const HORIZON_MARGIN_M = 200;
export function createFrames({ state: layerState, services, parts, source }) {
/**
* FNV-1a over the RGB channels of a downsampled frame. Pure (takes the raw
@@ -242,22 +236,6 @@ export function createFrames({ state: layerState, services, parts, source }) {
ctx.fillText(status.slice(0, 58), 46, h - 42);
}
/**
* Whether a camera's monitor plane may be on screen; what cannot be judged counts as visible.
* @param {Object} record - Camera record.
* @returns {boolean}
*/
function projectionInView(record) {
const camera = findCamera(layerState._viewer);
if (typeof camera?.visiblePoints !== 'function') return true;
const placed = record.frustumPositions;
if (!placed) return true;
const points = _scratchPoints;
points.length = 0;
for (const key of PLANE_POINTS) points.push(placed[key]);
return camera.visiblePoints(points, HORIZON_MARGIN_M) !== false;
}
/**
* Triggers a new frame fetch for an image-mode projection if the refresh
* interval has elapsed. Active cameras refresh more frequently than idle ones.
@@ -291,8 +269,6 @@ export function createFrames({ state: layerState, services, parts, source }) {
// bypass a provider's explicit minimum between image requests.
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
if (!force && sinceLastRefresh < refreshMs) return;
// Skip before stamping lastImageRefreshAt, so the first tick back in view fetches.
if (!force && !projectionInView(record)) return;
runtime.lastImageRefreshAt = now;
const frameUrl = frameUrlFor(record.camera, refreshMs);
-108
View File
@@ -3,7 +3,6 @@
// 1920x1080 projection canvas, instead of being stretched to fill it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { bindRenderer } from '../../render/rendererOf.js';
import { createFrames, fitToProjection } from './frames.js';
import {
FRAME_SIGNATURE_W,
@@ -171,110 +170,3 @@ test('a failed pixel signature redraws rather than assuming equal content', () =
assert.deepEqual(load(640, 480).at(-1), ['drawImage', 240, 0, 1440, 1080]);
assert.equal(runtime.canvasStamp, 2);
});
const MOUNT = { x: 0, y: 0, z: 0 };
function planeRecord() {
return {
camera: { id: 'plane' },
position: MOUNT,
frustumPositions: {
mount: MOUNT,
capCenter: { x: 1, y: 0, z: 0 },
tl: { x: 1, y: -1, z: 1 },
tr: { x: 1, y: 1, z: 1 },
br: { x: 1, y: 1, z: -1 },
bl: { x: 1, y: -1, z: -1 },
},
projection: {
mode: 'image',
image: {},
imageLoading: false,
imageReady: false,
lastImageRefreshAt: 0,
},
};
}
function framesFor(viewer) {
const state = {
_viewer: viewer,
_healthById: new Map(),
_activeCameraId: 'plane',
};
return createFrames({
state,
services: {},
parts: {
model: {
safeNumber: (value, fallback) =>
Number.isFinite(Number(value)) ? Number(value) : fallback,
},
},
source: { getFrameUrl: () => '/api/cctv/frame?id=plane' },
});
}
function framesWithCamera(t, camera) {
const host = {};
t.after(bindRenderer(host, { camera }));
return framesFor(host);
}
test('a plane the renderer may show fetches its picture', (t) => {
const visiblePoints = t.mock.fn(() => true);
const frames = framesWithCamera(t, { visiblePoints });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(
record.projection.image.src,
/^\/api\/cctv\/frame\?id=plane&projTs=/,
);
assert.equal(record.projection.imageLoading, true);
assert.equal(visiblePoints.mock.callCount(), 1);
const [points, margin] = visiblePoints.mock.calls[0].arguments;
const { mount, tl, tr, br, bl } = record.frustumPositions;
assert.deepEqual(points, [mount, tl, tr, br, bl]);
assert.equal(points[0], mount);
assert.equal(margin, 200);
});
test('a plane the renderer cannot show is not fetched, but a forced refresh is', (t) => {
const frames = framesWithCamera(t, { visiblePoints: () => false });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
assert.equal(record.projection.lastImageRefreshAt, 0);
frames.refreshProjectionImage(record, true);
assert.match(record.projection.image.src, /projTs=/);
});
test('a skipped refresh does not use up the interval', (t) => {
let visible = false;
const frames = framesWithCamera(t, { visiblePoints: () => visible });
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.equal(record.projection.image.src, undefined);
visible = true;
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
});
test('what cannot be judged counts as visible', (t) => {
for (const frames of [
framesWithCamera(t, { visiblePoints: () => null }),
framesWithCamera(t, { pose: () => ({}) }),
framesFor(null),
]) {
const record = planeRecord();
frames.refreshProjectionImage(record);
assert.match(record.projection.image.src, /projTs=/);
}
const noGeometry = planeRecord();
delete noGeometry.frustumPositions;
const visiblePoints = t.mock.fn(() => false);
framesWithCamera(t, { visiblePoints }).refreshProjectionImage(noGeometry);
assert.equal(visiblePoints.mock.callCount(), 0);
assert.match(noGeometry.projection.image.src, /projTs=/);
});
+1 -1
View File
@@ -5,7 +5,7 @@ import { setLocale, t } from '../../i18n/index.js';
// The exact string the server sends (COVERAGE in server/providers/cyclones.js).
const SERVER_COVERAGE =
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.';
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
const time = '2026-09-16T03:00:00.000Z';
const storm = {
id: 'ep152026',
+30 -71
View File
@@ -32,14 +32,8 @@ const utc = (value) =>
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${isolate(value.slice(11, 16))}\u00a0UTC`
: t('Unavailable');
const COVERAGE = msg(
'NHC/CPHC: Atlantic and eastern/central North Pacific. JTWC: western North Pacific, North Indian Ocean and Southern Hemisphere.',
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
);
// 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) =>
@@ -50,9 +44,7 @@ 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. JTWC
// warns of typhoons (TY), super typhoons (STY), tropical cyclones (TC) and
// subtropical storms and depressions (SS, SD).
// potential tropical cyclone, and subtropical systems are STS and STD.
const CLASSIFICATION_NAMES = Object.freeze({
PC: msg('Potential tropical cyclone'),
PTC: msg('Post-tropical cyclone'),
@@ -61,11 +53,6 @@ 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)
@@ -136,7 +123,7 @@ export function createCyclonesLayer({
id: contextId,
layerId: 'weather-cyclones',
layerName: 'Cyclone advisories',
source: sourceOf(storm),
source: 'NOAA NHC / CPHC',
label: storm.name,
latitude: storm.position.latitude,
longitude: storm.position.longitude,
@@ -150,7 +137,6 @@ export function createCyclonesLayer({
? CLASSIFICATION_NAMES[storm.classification]
: undefined,
basin: storm.basin,
agency: storm.agency,
advisoryNumber: storm.advisoryNumber,
issuedAt: storm.issuedAt,
positionAt: storm.positionAt,
@@ -160,7 +146,7 @@ export function createCyclonesLayer({
movementDirectionDegrees: storm.movement?.directionDegrees,
movementSpeedKt: storm.movement?.speedKt,
advisoryUrl: storm.advisoryUrl,
// Only while the proxy serves its cache because a source is unreachable.
// Only while the proxy serves its cache because NHC is unreachable.
staleCacheFetchedAt:
snapshot.stale && Number.isFinite(snapshot.fetchedAt)
? new Date(snapshot.fetchedAt).toISOString()
@@ -219,7 +205,7 @@ export function createCyclonesLayer({
id: 'weather-cyclones',
name: 'Cyclone advisories',
icon: '◉',
source: SOURCE,
source: 'NOAA NHC / CPHC',
updateInterval: 300_000,
init(nextViewer) {
viewer = nextViewer;
@@ -375,28 +361,13 @@ export function createCyclonesLayer({
snapshot && !snapshot.unavailable && snapshot.storms.length === 0;
const geometry =
storm &&
(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.',
)
: '';
(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'));
const status =
errorText(error) ||
(snapshot?.stale
@@ -417,21 +388,14 @@ export function createCyclonesLayer({
: '';
const intensity = storm ? intensityText(storm) : '';
const detail = storm
? 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),
})
? 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 tropical cyclone warnings')
? t('No active NHC/CPHC systems')
: stormCount
? activeStorms
: loading
@@ -440,8 +404,8 @@ export function createCyclonesLayer({
const controls = {
readout: true,
summary: {
label: t('Cyclones · NHC / CPHC · JTWC'),
coverage: t('All tropical basins'),
label: t('Cyclones · NHC / CPHC'),
coverage: t('Atlantic · E/C Pacific'),
compact: stormCount
? storm
? t('{storms} · {name} selected', {
@@ -454,9 +418,7 @@ export function createCyclonesLayer({
? [
{
id: 'advisory',
label: isJtwc(storm)
? t('JTWC warning ↗')
: t('Official advisory ↗'),
label: t('Official advisory ↗'),
href: storm.advisoryUrl,
},
]
@@ -474,7 +436,6 @@ export function createCyclonesLayer({
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
{ id: 'note', text: note, muted: true },
].filter((line) => line.text)
: [],
detail,
@@ -482,7 +443,7 @@ export function createCyclonesLayer({
units: 'kt',
},
list: {
ariaLabel: t('Active cyclone advisories and warnings'),
ariaLabel: t('Active NHC and CPHC cyclone advisories'),
items: (snapshot?.storms || []).map((item, index) => ({
id: item.id,
ordinal: index + 1,
@@ -500,19 +461,17 @@ export function createCyclonesLayer({
label: t('Advisory center / forecast track'),
color: '#7fe6ed',
},
isJtwc(storm)
? { label: t(DANGER_AREA), color: '#ffb15c44' }
: {
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
{
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
]
: [],
info: storm
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}${note ? '\n' + note : ''}\n${coverageText(snapshot.coverage)}`
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\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 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.',
'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.',
),
};
return controls;
@@ -559,7 +518,7 @@ export function createCyclonesLayer({
loading,
error,
stale: Boolean(snapshot?.stale),
source: storm ? sourceOf(storm) : SOURCE,
source: 'NOAA NHC / CPHC',
advisoryAt: storm?.issuedAt || null,
empty: Boolean(
snapshot && !snapshot.unavailable && !snapshot.storms.length,
+3 -66
View File
@@ -861,7 +861,7 @@ test('advisory selection uses accessible row descriptors and shared camera hando
const controls = h.layer.getRowControls();
assert.equal(controls.readout, true);
assert.deepEqual(controls.chips, []);
assert.equal(controls.summary.coverage, 'All tropical basins');
assert.equal(controls.summary.coverage, 'Atlantic · E/C Pacific');
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, /cyclone advisories and warnings/);
assert.match(controls.list.ariaLabel, /NHC/);
assert.equal(controls.list.items.length, 2);
assert.equal(controls.list.items[0].active, true);
assert.match(controls.info, /awaiting advisory 10/);
@@ -912,10 +912,7 @@ 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 tropical cyclone warnings/,
);
assert.match(h.layer.getRowControls().summary.detail, /No active NHC\/CPHC/);
next = { ...snapshot(), stale: true };
await h.layer.update();
assert.match(h.layer.getRowControls().summary.status, /stale/);
@@ -990,63 +987,3 @@ 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 -35
View File
@@ -3,7 +3,6 @@ import {
setOverlayEntries,
setOverlaySourceVisible,
} from '../../overlays/worldOverlay.js';
import { t } from '../../i18n/index.js';
/**
* @module cyclones/labels
@@ -20,8 +19,6 @@ 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. */
@@ -115,32 +112,7 @@ function cycloneLeadEntry(stormId, point) {
}
/**
* 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.
* Storm cards for every storm and lead-hour labels for the selected one.
* @param {Array<object>} storms Renderer anchors with `forecasts`.
* @param {?string} selectedId
* @returns {Array<object>}
@@ -153,17 +125,13 @@ 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, lead-hour or area label id, else null. */
/** Storm id behind a published card or lead-hour label id, else null. */
export function cycloneStormIdFromEntryId(entryId) {
const match = /^(?:storm|lead|area):([^:]+)(?::|$)/.exec(
String(entryId ?? ''),
);
const match = /^(?:storm|lead):([^:]+)(?::|$)/.exec(String(entryId ?? ''));
return match ? match[1] : null;
}
-4
View File
@@ -198,7 +198,3 @@ 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');
});
+34 -94
View File
@@ -3,7 +3,6 @@ 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,
@@ -25,29 +24,6 @@ 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);
@@ -88,14 +64,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
const emptyCounts = () => ({
storms: 0,
tracks: 0,
cones: 0,
dangerAreas: 0,
forecastPoints: 0,
});
let counts = emptyCounts();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
let itemCount = 0;
function centerItem(storm) {
@@ -135,7 +104,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = emptyCounts();
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
@@ -161,7 +130,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
windKt: storm.windKt,
position: center,
forecasts: [],
dangerArea: null,
};
nextLabels.push(label);
nextCounts.storms++;
@@ -183,66 +151,38 @@ export function createCycloneRendering({ viewer, overlayHost }) {
});
nextCounts.tracks++;
});
// 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,
);
}
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),
},
});
});
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
@@ -312,7 +252,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = emptyCounts();
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
},
destroy() {
if (destroyed) return;
-49
View File
@@ -210,7 +210,6 @@ 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,
@@ -376,7 +375,6 @@ 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,
@@ -453,50 +451,3 @@ 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();
});
+17 -42
View File
@@ -45,33 +45,22 @@ const position = (value) => {
};
};
/** 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) {
function officialLink(value, outlook = false) {
if (value === null) return null;
const url = new URL(text(value, 256));
if (url.origin !== rules.origin || url.username || url.password || url.hash)
if (
url.origin !== 'https://www.nhc.noaa.gov' ||
url.username ||
url.password ||
url.hash
)
throw malformed();
if (
outlook
? !rules.outlook.test(url.pathname + url.search)
: url.search || !rules.advisory.test(url.pathname)
? !/^\/gtwo\.php\?basin=(?:atlc|epac|cpac)&fdays=7$/.test(
url.pathname + url.search,
)
: url.search || !/^\/text\/[A-Z0-9]+\.shtml$/.test(url.pathname)
)
throw malformed();
return url.href;
@@ -133,14 +122,8 @@ 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 (
!rules ||
!rules.id.test(raw?.id) ||
!/^(?:al|ep|cp)\d{6}$/.test(raw?.id) ||
seen.has(raw.id) ||
!['current', 'pending', 'unavailable'].includes(raw.geometryStatus)
)
@@ -175,27 +158,20 @@ export function validateCycloneSnapshot(value) {
};
});
const track = geometry(raw.track, 'track', 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();
cone = geometry(raw.cone, 'cone', budget);
if (
raw.geometryStatus !== 'current' &&
(track || area || forecastPoints.length)
(track || cone || forecastPoints.length)
)
throw malformed();
if (
raw.geometryStatus === 'current' &&
(!track || !area || !forecastPoints.length)
(!track || !cone || !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,
@@ -209,14 +185,13 @@ export function validateCycloneSnapshot(value) {
directionDegrees: number(raw.movement?.directionDegrees, 0, 360),
speedKt: number(raw.movement?.speedKt, 0, 200),
},
advisoryUrl: officialLink(raw.advisoryUrl, rules),
outlookUrl: officialLink(raw.outlookUrl, rules, true),
advisoryUrl: officialLink(raw.advisoryUrl),
outlookUrl: officialLink(raw.outlookUrl, true),
geometryStatus: raw.geometryStatus,
geometryAdvisoryNumber,
forecastPoints,
track,
cone,
dangerArea,
};
});
if (value.unavailable && storms.length) throw malformed();
-66
View File
@@ -230,69 +230,3 @@ 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',
);
});
+6 -11
View File
@@ -3,10 +3,7 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createIcons } from './icons.js';
import {
createContactIcons,
placedPlanSpread,
} from '../../data/aircraftIconLayer.js';
import { createContactIcons } from '../../data/aircraftIconLayer.js';
import { layerPlacement } from '../../data/placementProvider.js';
import {
aircraftMotionRegime,
@@ -272,10 +269,8 @@ test('a live contact a placement places is drawn along where it places it', (t)
const now = icons._displayMs();
const leadMs = Date.now() - now;
icons._planIcon('p');
// A plan's length, as this contact's are spread (a second on average).
const planMs = 1000 * placedPlanSpread('p');
// Asked for the wall times the segment's ends stand for.
assert.deepEqual(asked, [now + leadMs, now + planMs + leadMs]);
assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
assert.equal(regimes.length, 0, 'its own motion is not planned');
const item = set.item('p');
assert.equal(item.motion.kind, 'lerp');
@@ -289,16 +284,16 @@ test('a live contact a placement places is drawn along where it places it', (t)
Cesium.Cartesian3.distance(
item.motion.to,
Cesium.Cartesian3.fromDegrees(
(now + planMs + leadMs - t0) / 10_000,
(now + 1000 + leadMs - t0) / 10_000,
30,
2000,
),
) < 1e-6,
);
assert.equal(item.motion.t0, now);
assert.equal(item.motion.t1, now + planMs);
assert.ok(Math.abs(item.motion.courseSlopeDeg - planMs / 1000) < 1e-9);
assert.equal(set.expires('p'), now + planMs);
assert.equal(item.motion.t1, now + 1000);
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
assert.equal(set.expires('p'), now + 1000);
// No answer: the layer's own motion plans it.
places = false;
+4 -4
View File
@@ -11,6 +11,7 @@ export function createLifecycle({
}) {
const { clearFocusTarget } = services.focus;
const { onMilitaryLayerActiveChange } = services.militaryRegistry;
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { ensureGeoidReady } = services.geoid;
const { registerPickOwner, unregisterPickOwner } = services.picking;
@@ -111,8 +112,7 @@ export function createLifecycle({
*/
enable(viewer) {
if (flightState._icons) flightState._icons.show = true;
// Drawn as often as the fleet moves on screen (renderPace.js).
parts.rendering._startPace();
holdContinuousRender('flights'); // per-frame animator (perf wave 2)
parts.rendering._setModelsShown(true);
parts.tracking._setCockpitContactMode(
document.body.classList.contains('cockpit-mode'),
@@ -168,7 +168,7 @@ export function createLifecycle({
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
if (flightState._icons) flightState._icons.show = false;
parts.rendering._stopPace();
releaseContinuousRender('flights');
parts.rendering._releaseModels();
parts.rendering._setModelsShown(false);
parts.tracking._clearTracking();
@@ -208,7 +208,7 @@ export function createLifecycle({
flightState._enrichActive = 0;
flightState._enrichLastDispatchMs = 0;
parts.controller._abortActiveUpdates();
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
releaseContinuousRender('flights'); // direct-destroy path (perf wave 2 fix)
parts.tracking._clearTracking();
parts.tracking._destroyTrail();
parts.tracking._cancelPendingTrackingRestore();
+4 -4
View File
@@ -10,6 +10,7 @@ export function createLifecycle({
resolveAsset,
}) {
const { clearFocusTarget } = services.focus;
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { ensureGeoidReady } = services.geoid;
const { registerPickOwner, unregisterPickOwner } = services.picking;
const { setMilitaryLayerActive } = services.militaryRegistry;
@@ -92,8 +93,7 @@ export function createLifecycle({
*/
enable(viewer) {
if (flightState._icons) flightState._icons.show = true;
// Drawn as often as the fleet moves on screen (renderPace.js).
parts.rendering._startPace();
holdContinuousRender('military'); // per-frame animator (perf wave 2)
parts.rendering._setModelsShown(true);
parts.tracking._setCockpitContactMode(
document.body.classList.contains('cockpit-mode'),
@@ -151,7 +151,7 @@ export function createLifecycle({
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
if (flightState._icons) flightState._icons.show = false;
parts.rendering._stopPace();
releaseContinuousRender('military');
parts.rendering._releaseModels();
parts.rendering._setModelsShown(false);
parts.tracking._clearTracking();
@@ -191,7 +191,7 @@ export function createLifecycle({
flightState.timeline?.stop();
flightState.lifetime.abort();
parts.controller._abortActiveUpdates();
parts.rendering._stopPace(); // direct-destroy path (perf wave 2 fix)
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
parts.tracking._clearTracking();
parts.tracking._destroyTrail();
parts.tracking._cancelPendingTrackingRestore();
+3 -6
View File
@@ -8,14 +8,13 @@ import { buildIncidentCard } from './cards.js';
const now = Date.UTC(2026, 9, 14);
const row = {
id: 'x',
stableId: 'x',
name: 'Lake',
acres: 1200,
containedPct: 40,
state: 'CA',
discoveredTime: now - 2 * 3600e3,
updatedTime: now - 3600e3,
lastGrowthTime: now - 3 * 3600e3,
cause: 'Human',
behavior: 'Moderate',
complexity: 'Type 3 Incident',
@@ -34,7 +33,6 @@ test('en: the fire card keeps its English wording', () => {
'part of North Complex',
'Human cause · Moderate · Type 3 Incident',
'1,500 personnel · Plumas County · $4.2M to date',
'last growth 3h ago',
'discovered 2h ago · updated 1h ago',
'InciWeb ↗ · click card to open',
]);
@@ -46,8 +44,8 @@ for (const locale of ['es', 'ru']) {
setLocale(locale);
try {
assert.notEqual(
t('Older or unknown'),
'Older or unknown',
t('Fully contained'),
'Fully contained',
'legend is translated',
);
const card = buildIncidentCard(row, now, {
@@ -62,7 +60,6 @@ for (const locale of ['es', 'ru']) {
'contained',
'discovered',
'updated',
'last growth',
'part of',
'cause',
'personnel',
+59 -16
View File
@@ -3,7 +3,7 @@ import { formatNumber, t, tn } from '../../i18n/index.js';
export const PERIMETER_OVERLAY_SOURCE_ID = 'fire-perimeters';
/** CSS accent for a perimeter card by containment progress. */
/** CSS accent for a perimeter card by containment progress (mirrors the fill). */
export function containmentAccent(containedPct) {
if (!Number.isFinite(containedPct) || containedPct <= 0) return '#ff3b30';
if (containedPct < 50) return '#ff7a00';
@@ -11,6 +11,55 @@ export function containmentAccent(containedPct) {
return '#8bc34a';
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/**
* Compact USD in the UI language: en "$85K / $4.2M / $1.3B", ru "4,2 млн $",
* es "4,2 M$". Null under $1,000.
@@ -100,9 +149,8 @@ function formatAge(deltaMs) {
/**
* Build the overlay-host entry for one selected incident. The caller supplies
* `position` (Cartesian) separately — this model stays JSON-safe for tests.
* @param {Object} row - A snapshot fire (see records.js).
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
* `at`, or now.
* @param {Object} row - Normalized perimeter row (see records.js).
* @param {number} nowMs - Current epoch milliseconds.
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
* @returns {Object} World-overlay entry without `position`.
*/
@@ -146,17 +194,13 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
if (cost) response.push(t('{cost} to date', { cost }));
}
const ago = (time) => (time == null ? null : formatAge(nowMs - time));
const growth = ago(row.lastGrowthTime);
const lastGrowth = growth
? t('last growth {age} ago', { age: growth })
: null;
const ages = [];
const discovered = ago(row.discoveredTime);
if (discovered) ages.push(t('discovered {age} ago', { age: discovered }));
const updated = ago(row.updatedTime);
if (updated) ages.push(t('updated {age} ago', { age: updated }));
const discovered = formatAge(nowMs - row.discoveredTime);
if (row.discoveredTime != null && discovered)
ages.push(t('discovered {age} ago', { age: discovered }));
const updated = formatAge(nowMs - row.updatedTime);
if (row.updatedTime != null && updated)
ages.push(t('updated {age} ago', { age: updated }));
const details = [facts.join(' · ')];
if (row.complexName)
@@ -165,7 +209,6 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
);
if (situation.length) details.push(situation.join(' · '));
if (response.length) details.push(response.join(' · '));
if (lastGrowth) details.push(lastGrowth);
if (ages.length) details.push(ages.join(' · '));
if (link) details.push(t('InciWeb ↗ · click card to open'));
@@ -173,7 +216,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
name: row.name || t('Unnamed incident'),
});
return {
id: `fire-perimeter-card:${row.id}`,
id: `fire-perimeter-card:${row.stableId}`,
// `selected` picks the paint lane and collision protection; an explicit
// paintLane would override it in the host's lane resolver.
selected: true,
+97 -31
View File
@@ -1,12 +1,99 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildIncidentCard } from './cards.js';
import { perimeterAnchorDegrees, buildIncidentCard } from './cards.js';
const square = [
[-108.2, 35.0],
[-108.0, 35.0],
[-108.0, 35.2],
[-108.2, 35.2],
[-108.2, 35.0],
];
const tiny = [
[-107.01, 34.0],
[-107.0, 34.0],
[-107.0, 34.01],
[-107.01, 34.0],
];
test('the card anchors at the vertex mean of the largest polygon', () => {
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
});
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
const vertices = [
[179, 10],
[-179, 10],
[-179, 12],
[179, 12],
];
for (let start = 0; start < vertices.length; start++) {
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
for (const points of [rotated, [...rotated].reverse()]) {
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
}
}
});
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
for (const boundary of [-180, 180]) {
const ring = [
[179, 10],
[boundary, 10],
[-179, 10],
[-179, 12],
[179, 12],
[179, 10],
];
const anchor = perimeterAnchorDegrees([[ring]]);
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
}
});
test('multipart cards compare polygon areas along short dateline edges', () => {
const ordinary = [
[10, 20],
[11, 20],
[11, 21],
[10, 21],
[10, 20],
];
for (const width of [0.2, 2]) {
const crossing = [
[180 - width / 2, 10],
[-180 + width / 2, 10],
[-180 + width / 2, 10 + width],
[180 - width / 2, 10 + width],
[180 - width / 2, 10],
];
for (const ring of [crossing, [...crossing].reverse()]) {
for (const polygons of [
[[ring], [ordinary]],
[[ordinary], [ring]],
]) {
const anchor = perimeterAnchorDegrees(polygons);
if (width < 1) {
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
} else {
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
}
}
}
}
});
test('a full incident row renders name, size, containment, and ages', () => {
const now = 1758000000000;
const card = buildIncidentCard(
{
id: '2026-NMGNF-000123',
stableId: '2026-NMGNF-000123',
name: 'Frijoles',
acres: 15956.4,
containedPct: 74,
@@ -14,7 +101,6 @@ test('a full incident row renders name, size, containment, and ages', () => {
category: 'WF',
discoveredTime: now - 36 * 3600000,
updatedTime: now - 2 * 3600000,
lastGrowthTime: now - 5 * 3600000,
cause: 'Natural',
behavior: 'Active',
personnel: 380,
@@ -30,7 +116,6 @@ test('a full incident row renders name, size, containment, and ages', () => {
'15,956 ac · 74% contained · US-NM',
'Natural cause · Active · Type 3 Incident',
'380 personnel · Sandoval County · $4.2M to date',
'last growth 5h ago',
'discovered 1d ago · updated 2h ago',
]);
assert.equal(card.selected, true);
@@ -40,7 +125,7 @@ test('a full incident row renders name, size, containment, and ages', () => {
test('missing attributes degrade to available facts instead of placeholders', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: null,
acres: null,
containedPct: null,
@@ -64,7 +149,7 @@ test('missing attributes degrade to available facts instead of placeholders', ()
test('a known InciWeb page adds a link line to the card', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Timber',
acres: 25426,
containedPct: 44,
@@ -92,7 +177,7 @@ test('a known InciWeb page adds a link line to the card', () => {
test('the selected card claims the selected paint lane, not the ambient lane', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Any',
acres: 1,
containedPct: 1,
@@ -119,7 +204,7 @@ test('the selected card claims the selected paint lane, not the ambient lane', (
test('costs near a unit boundary promote to the larger unit', () => {
const base = {
id: 'x',
stableId: 'x',
name: 'Any',
acres: null,
containedPct: null,
@@ -147,7 +232,7 @@ test('costs near a unit boundary promote to the larger unit', () => {
test('a complex member names its complex on the card', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Crosswhite',
acres: 342923,
containedPct: 99,
@@ -171,7 +256,7 @@ test('a complex member names its complex on the card', () => {
test('a card without a link is not interactive', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Crosswhite',
acres: 1,
containedPct: 1,
@@ -194,7 +279,7 @@ test('a card without a link is not interactive', () => {
test('partial incident details render only the facts that exist', () => {
const card = buildIncidentCard(
{
id: 'x',
stableId: 'x',
name: 'Whiskey',
acres: 542,
containedPct: 48,
@@ -220,7 +305,7 @@ test('partial incident details render only the facts that exist', () => {
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
const row = {
id: 'x',
stableId: 'x',
name: 'Grey',
acres: 0.25,
containedPct: null,
@@ -248,22 +333,3 @@ test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () =>
'1 ac · containment unknown · US-WA',
);
});
test('ages count from the moment shown, not from the clock', () => {
const at = Date.UTC(2025, 7, 1, 12);
const card = buildIncidentCard(
{
id: 'past',
name: 'Past',
containedPct: 10,
discoveredTime: at - 3 * 86400000,
updatedTime: at - 30 * 60000,
lastGrowthTime: at - 7 * 3600000,
},
at,
);
assert.deepEqual(card.details.slice(-2), [
'last growth 7h ago',
'discovered 3d ago · updated 30m ago',
]);
});
+33 -35
View File
@@ -17,8 +17,19 @@ function normalizeName(name) {
.replace(/ fire$/, '');
}
function nodeCandidates(publications, { name, state }) {
if (!Array.isArray(publications) || !name) return [];
/**
* Resolve one WFIGS incident against the publication catalog.
* Only rows whose normalized title equals the incident's normalized name
* count. Ambiguity resolves by the tau dispatch unit's state prefix, then
* by newest incident id (same-state duplicates are usually reburns of the
* same name). The `/node/{id}` link 301s to the canonical page, so no slug
* construction is needed.
* @param {?Array} publications - Publication catalog rows.
* @param {{name: ?string, state: ?string}} incident - WFIGS row facts.
* @returns {?string} InciWeb node URL.
*/
export function resolveInciwebNodeLink(publications, { name, state }) {
if (!Array.isArray(publications) || !name) return null;
const wanted = normalizeName(name);
let candidates = publications.filter(
(row) =>
@@ -40,26 +51,20 @@ function nodeCandidates(publications, { name, state }) {
row.tau.slice(0, 2).toLowerCase() === statePrefix,
);
} else if (candidates.length > 1) {
return [];
return null;
}
// Same-state duplicates are usually reburns of the same name. Newest wins live.
return candidates
.sort((a, b) => Number(b.incident_id) - Number(a.incident_id))
.map((row) => `https://inciweb.wildfire.gov/node/${row.incident_id}`);
}
/**
* Resolve one WFIGS incident against the publication catalog.
* Only rows whose normalized title equals the incident's normalized name
* count. Matches are filtered by the tau dispatch unit's state prefix.
* The `/node/{id}` link 301s to the canonical page, so no slug construction
* is needed.
* @param {?Array} publications - Publication catalog rows.
* @param {{name: ?string, state: ?string}} incident - WFIGS row facts.
* @returns {?string} InciWeb node URL.
*/
export function resolveInciwebNodeLink(publications, incident) {
return nodeCandidates(publications, incident)[0] ?? null;
if (candidates.length > 1) {
// Same-state duplicates are usually reburns of the same name — newest
// wins here, and the publication-currency check guards the final link.
candidates = [
candidates.reduce((a, b) =>
Number(a.incident_id) >= Number(b.incident_id) ? a : b,
),
];
}
return candidates.length === 1
? `https://inciweb.wildfire.gov/node/${candidates[0].incident_id}`
: null;
}
/** The publication id inside a node link produced above, or null. */
@@ -74,8 +79,7 @@ export function inciwebNodeId(link) {
// whose page predates discovery by more than this is an archived
// same-name incident from a earlier season.
const CREATED_BEFORE_DISCOVERY_MS = 60 * 24 * 3600000;
// Without a discovery date, require editorial activity on the page in the
// 180 days up to the moment shown.
// Without a discovery date, require recent editorial activity on the page.
const CHANGED_WITHIN_MS = 180 * 24 * 3600000;
/**
@@ -93,8 +97,7 @@ export function isCurrentPublication(
return createdMs >= discoveredTime - CREATED_BEFORE_DISCOVERY_MS;
}
if (Number.isFinite(changedMs)) {
const age = nowMs - changedMs;
return age >= 0 && age <= CHANGED_WITHIN_MS;
return nowMs - changedMs <= CHANGED_WITHIN_MS;
}
return false;
}
@@ -129,14 +132,6 @@ export function createInciwebPublicationSource({
};
}
/** Every same-name page that could be this incident's, newest first: the own name's, else its complex's. */
export function findInciwebLinks(publications, { name, state, complexName }) {
const links = nodeCandidates(publications, { name, state });
return links.length
? links
: nodeCandidates(publications, { name: complexName, state });
}
/**
* Resolve one WFIGS incident to its InciWeb page, or null.
* The incident's own name is tried first; a member of a complex whose own
@@ -148,8 +143,11 @@ export function findInciwebLinks(publications, { name, state, complexName }) {
* - WFIGS row facts.
* @returns {?string} InciWeb URL.
*/
export function findInciwebLink(publications, incident) {
return findInciwebLinks(publications, incident)[0] ?? null;
export function findInciwebLink(publications, { name, state, complexName }) {
return (
resolveInciwebNodeLink(publications, { name, state }) ??
resolveInciwebNodeLink(publications, { name: complexName, state })
);
}
/** Fetch the full InciWeb incident catalog. */
-37
View File
@@ -2,7 +2,6 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import {
findInciwebLink,
findInciwebLinks,
resolveInciwebNodeLink,
createInciwebIndexSource,
createInciwebPublicationSource,
@@ -143,34 +142,6 @@ test('ambiguous titles disambiguate by state, then newest id', () => {
);
});
test('same-name pages list newest first, falling back to the complex', () => {
const rows = [
{
incident_id: '100',
tau: 'ORXXX Coyote Fire',
incident_title: 'Coyote Fire',
},
{
incident_id: '328922',
tau: 'OR95S Coyote Fire',
incident_title: 'Coyote Fire',
},
{ incident_id: '5', tau: 'ORXXX', incident_title: 'Big Complex' },
];
const incident = {
name: 'Coyote',
state: 'US-OR',
complexName: 'Big Complex',
};
assert.deepEqual(findInciwebLinks(rows, incident), [
'https://inciweb.wildfire.gov/node/328922',
'https://inciweb.wildfire.gov/node/100',
]);
assert.deepEqual(findInciwebLinks(rows, { ...incident, name: 'Nope' }), [
'https://inciweb.wildfire.gov/node/5',
]);
});
test('a complex member falls back to its complex page', () => {
assert.equal(
findInciwebLink(catalog, {
@@ -243,14 +214,6 @@ test('publication currency accepts pages created around or after discovery', ()
),
false,
);
// An edit after the moment shown says nothing about the page then.
assert.equal(
isCurrentPublication(
{ createdMs: now - 900 * day, changedMs: now + 10 * day },
{ discoveredTime: null, nowMs: now },
),
false,
);
// Unusable timestamps fail closed.
assert.equal(
isCurrentPublication(
+143 -277
View File
@@ -1,64 +1,34 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js';
import { drawOf } from '../../render/rendererOf.js';
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
import { hexColor } from '../../render/color.js';
import {
findInciwebLinks,
PERIMETER_OVERLAY_SOURCE_ID,
perimeterAnchorDegrees,
buildIncidentCard,
containmentAccent,
} from './cards.js';
import {
findInciwebLink,
inciwebNodeId,
isCurrentPublication,
} from './inciweb.js';
import { msg, t } from '../../i18n/index.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
export {
normalizeFirePerimeterSnapshot,
perimeterAnchorDegrees,
} from './records.js';
export { normalizeFirePerimeterSnapshot } from './records.js';
export { createWfigsPerimeterSource } from './source.js';
export * from './cards.js';
export * from './inciweb.js';
const HOUR_MS = 3600000;
/**
* Piece colours by age, newest first. A piece of unknown birth, or born after
* the moment shown, is drawn as the oldest; the legend counts fires by
* `lastGrowthTime` the same way.
* Fill/line colour for a perimeter by containment progress (same ramp as the
* card accent), as a renderer colour `[r, g, b, a]`.
*/
export const PERIMETER_AGE_BANDS = Object.freeze(
[
{ upToMs: 6 * HOUR_MS, color: '#ffc72e', label: msg('Last 6 hours') },
{ upToMs: 24 * HOUR_MS, color: '#ff730d', label: msg('6–24 hours') },
{ upToMs: 72 * HOUR_MS, color: '#d9290d', label: msg('1–3 days') },
{
upToMs: Infinity,
color: '#730f0a',
label: msg('Older or unknown'),
},
].map((band) => Object.freeze(band)),
);
function perimeterAgeBand(time, atMs) {
const last = PERIMETER_AGE_BANDS.length - 1;
if (!Number.isFinite(time) || time > atMs) return last;
return PERIMETER_AGE_BANDS.findIndex(({ upToMs }) => atMs - time < upToMs);
export function containmentColor(containedPct) {
return hexColor(containmentAccent(containedPct));
}
const FILL_ALPHA = 0.35;
const LINE_ALPHA = 0.9;
const LINE_WIDTH_PX = 2;
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
const validLine = (line, min) =>
Array.isArray(line) &&
line.length >= min &&
line.every(
(point) =>
Array.isArray(point) &&
Number.isFinite(point[0]) &&
Number.isFinite(point[1]),
);
const validAnchor = (anchor) =>
Number.isFinite(anchor?.lon) && Number.isFinite(anchor?.lat);
/**
* The draw sets the perimeters are drawn in start with this; each layer has
@@ -82,29 +52,10 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
/**
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
*
* `source.getSnapshot({signal})` resolves to the snapshot the layer draws
* (records.js `firePerimeterSnapshot` builds it from WFIGS):
* - `at`: the moment shown, epoch ms, or null for now. Ages, colours and the
* legend count from it.
* - `fetchedAt` (epoch ms or null) and `stale`: a stale snapshot is dated by
* its `fetchedAt`.
* - `revision`: a string that changes whenever any piece does. Without a
* string revision the layer redraws on every read.
* - `note`: text the layer row shows with the legend, or null.
* - `fires`: `id` (string), `anchor` (`{lon, lat}` degrees, where the card
* stands), `lastGrowthTime` (epoch ms or null; the legend counts by it) and
* the card facts (`name`, `acres`, `containedPct`, `state`,
* `discoveredTime`, `updatedTime`, …). A fire without an id or anchor is
* dropped. A fire may have no pieces: it keeps its card and legend count.
* - `pieces`: `fireId` (a listed fire's id; any other piece is dropped),
* `born` (epoch ms or null; the piece's colour), `polygons` (each
* `[outer, ...holes]`, rings of `[lon, lat]`) and `outline` (lines of
* `[lon, lat]` drawn as the fire line, apart from the fill, so a piece cut
* from a larger area has no line along the cut).
*
* When to read again (a timeline, the camera) is the host's call, through
* the manager's `refreshLayer`. Given a Cesium viewer with no renderer bound,
* the caller loads the package's `./render/cesium/unbound` export first.
* Each perimeter is a ground-clamped fill in one renderer draw set and its
* fire line a draped line in another (`drawOf(viewer)`), made at `init`.
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
*/
export function createFirePerimetersLayer({
source,
@@ -120,17 +71,12 @@ export function createFirePerimetersLayer({
let _viewer = null;
let _request = null;
let _linkRequest = null;
// What the sets show: the snapshot revision and each piece's age band.
let _drawnKey = null;
let _snapshotSignature = null;
let _fills = null;
let _lines = null;
let _setIds = new Set();
let _count = 0;
let _lastUpdate = null;
// The moment the snapshot shows (null: now), and the source's legend note.
let _at = null;
let _note = null;
// The moment the drawn colours were computed at; the legend counts at it
// too, so it matches the map between reads.
let _bandsAt = null;
// The proxy's last snapshot, served while WFIGS is unreachable.
let _stale = false;
let _lastError = null;
@@ -142,26 +88,16 @@ export function createFirePerimetersLayer({
let _inciwebIndex = [];
let _indexFetchedAt = 0;
let _indexFetchInFlight = false;
let _fireById = new Map();
/** `<set id>\n<item id>` → the fire that item belongs to. */
const _fireByItem = new Map();
const shownAt = () => _at ?? Date.now();
const _linkPublications = new Map();
// Retry failed pages on reselection or when a read finds the card linkless.
const _linkFailures = new Set();
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
const _rowById = new Map();
// Link → currency verdict from the publication check; unknown links are
// absent. Failed checks are not cached so a transient outage retries.
const _linkVerdicts = new Map();
function abortLinkVerification() {
_linkRequest?.controller.abort();
_linkRequest = null;
}
function resetSelection() {
abortLinkVerification();
_linkFailures.clear();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
}
const canSelect = () => overlayHost && inputFor && picking;
/**
@@ -205,57 +141,29 @@ export function createFirePerimetersLayer({
.getPublication(id, { signal })
.then((publication) => {
if (signal.aborted || _linkRequest !== request || !_enabled) return;
_linkPublications.set(link, publication ?? {});
if (_selectedId === row.id) publishSelectedCard();
_linkVerdicts.set(
link,
isCurrentPublication(publication, {
discoveredTime: row.discoveredTime,
}),
);
if (_selectedId === row.stableId) publishSelectedCard();
})
.catch(() => {
if (signal.aborted || _linkRequest !== request || !_enabled) return;
_linkFailures.add(link);
if (_selectedId === row.id) publishSelectedCard();
// Fail closed without caching: no link now, retry on reselection.
})
.finally(() => {
if (_linkRequest === request) _linkRequest = null;
});
}
function isCurrentLink(publication, row) {
if (
_at !== null &&
!(Number.isFinite(publication.createdMs) && publication.createdMs <= _at)
)
return false;
return isCurrentPublication(publication, {
discoveredTime: row.discoveredTime,
nowMs: shownAt(),
});
}
/**
* The current page among verified candidates: the one whose incident began
* nearest the fire's discovery, else (no discovery date) the newest.
*/
function chooseLink(links, row) {
let best = null;
let bestGap = Infinity;
for (const link of links) {
const publication = _linkPublications.get(link);
if (!publication || !isCurrentLink(publication, row)) continue;
const gap = Number.isFinite(row.discoveredTime)
? Math.abs(publication.createdMs - row.discoveredTime)
: 0;
if (best === null || gap < bestGap) {
best = link;
bestGap = gap;
}
}
return best;
}
function publishSelectedCard() {
if (!canSelect()) return;
const row = _selectedId ? _fireById.get(_selectedId) : null;
const row = _selectedId ? _rowById.get(_selectedId) : null;
if (!row) {
resetSelection();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
overlayHost.setEntries(
PERIMETER_OVERLAY_SOURCE_ID,
[],
@@ -263,36 +171,12 @@ export function createFirePerimetersLayer({
);
return;
}
// Live, the newest same-name page stands for the incident. A past `at`
// checks each own-name page, since the newest may postdate it, and the
// complex's pages only when none of those is current.
const groups =
_at === null
? [findInciwebLinks(_inciwebIndex, row).slice(0, 1)]
: [
findInciwebLinks(_inciwebIndex, {
name: row.name,
state: row.state,
}),
findInciwebLinks(_inciwebIndex, {
name: row.complexName,
state: row.state,
}),
];
_selectedLink = null;
for (const links of groups) {
const unverified = links.find(
(link) => !_linkPublications.has(link) && !_linkFailures.has(link),
);
if (unverified) {
verifyLink(unverified, row);
break;
}
_selectedLink = chooseLink(links, row);
if (_selectedLink) break;
}
const candidate = findInciwebLink(_inciwebIndex, row);
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
_selectedLink =
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
const card = {
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
position: fromDegrees(row.anchor.lon, row.anchor.lat),
};
if (!openExternal) card.interactive = false;
@@ -317,9 +201,11 @@ export function createFirePerimetersLayer({
* of this layer's own sets, for an incident drawn now; else null.
*/
function pickedIncidentId(hit) {
if (!hit || hit.surface) return null;
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
if (!hit || hit.surface || !_setIds.has(hit.set)) return null;
if (typeof hit.id !== 'string' || !hit.id.startsWith(PICK_PREFIX))
return null;
const incidentId = hit.id.slice(PICK_PREFIX.length).split(':')[0];
return _rowById.has(incidentId) ? incidentId : null;
}
function installClickHandler() {
@@ -350,7 +236,6 @@ export function createFirePerimetersLayer({
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
if (incidentId) {
abortLinkVerification();
_linkFailures.clear();
_selectedId = incidentId;
publishSelectedCard();
return;
@@ -362,67 +247,23 @@ export function createFirePerimetersLayer({
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
}
if (_selectedId) {
abortLinkVerification();
_selectedId = null;
publishSelectedCard();
}
});
}
function drawPieces(pieces, bands) {
const nextFills = [];
const nextLines = [];
const counts = new Map();
_fireByItem.clear();
// `fire-perimeter:<fire>:<n>` for fills, `…:<fire>:line:<n>` for lines.
const itemId = (fireId, kind) => {
const key = `${kind}${fireId}`;
const n = counts.get(key) ?? 0;
counts.set(key, n + 1);
const id = `${PICK_PREFIX}${fireId}:${kind}${n}`;
_fireByItem.set(`${kind ? _lines.id : _fills.id}\n${id}`, fireId);
return id;
};
for (const [index, piece] of pieces.entries()) {
const { color } = PERIMETER_AGE_BANDS[bands[index]];
// Each exterior keeps its own holes.
for (const rings of Array.isArray(piece.polygons) ? piece.polygons : []) {
if (!Array.isArray(rings) || !rings.every((ring) => validLine(ring, 3)))
continue;
nextFills.push({
id: itemId(piece.fireId, ''),
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: hexColor(color, FILL_ALPHA),
height: 'clampGround',
});
}
// The fire line: the piece's outline draped on the ground, apart from
// its fill, so a piece cut from a larger area has no line along the
// cut (lines take ECEF, draw.d.ts `LineItem`).
for (const line of Array.isArray(piece.outline) ? piece.outline : []) {
if (!validLine(line, 2)) continue;
nextLines.push({
id: itemId(piece.fireId, 'line:'),
positions: line.map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: LINE_WIDTH_PX,
mode: 'draped',
style: { kind: 'solid', color: hexColor(color, LINE_ALPHA) },
});
}
}
_fills.set(nextFills);
_lines.set(nextLines);
console.log(
`[Data:FirePerimeters] Drew ${pieces.length} pieces of ${_fireById.size} fires`,
);
}
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
}
function clearSelection() {
resetSelection();
abortLinkVerification();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
if (overlayHost) {
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
@@ -451,7 +292,9 @@ export function createFirePerimetersLayer({
clampTo: 'both',
show: false,
});
_setIds = new Set([_fills.id, _lines.id]);
_viewer = viewer;
_count = 0;
_lastUpdate = null;
_lastError = null;
_stale = false;
@@ -475,58 +318,87 @@ export function createFirePerimetersLayer({
clearSelection();
},
async update(_viewerArg, { signal } = {}) {
async update() {
if (!_enabled || !_fills) return false;
_request?.abort();
const request = new AbortController();
_request = request;
const abort = () => request.abort(signal.reason);
if (signal?.aborted) abort();
else signal?.addEventListener('abort', abort, { once: true });
refreshInciwebIndex(request.signal);
try {
refreshInciwebIndex(request.signal);
const snapshot = await source.getSnapshot({ signal: request.signal });
// The source contract is getSnapshot; a source that can also say how
// fresh its rows are (the WFIGS proxy) offers getSnapshotDetail.
const snapshot =
typeof source.getSnapshotDetail === 'function'
? await source.getSnapshotDetail({ signal: request.signal })
: { rows: await source.getSnapshot({ signal: request.signal }) };
if (request.signal.aborted || _request !== request || !_enabled)
return false;
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
throw new Error(msg('Malformed perimeter snapshot'));
const { rows } = snapshot;
_stale = snapshot.stale === true;
// A stale snapshot is as old as its fetch, not this poll.
const updatedAt =
_stale && Number.isFinite(snapshot.fetchedAt)
? snapshot.fetchedAt
: Date.now();
_at = Number.isFinite(snapshot.at) ? snapshot.at : null;
_note = typeof snapshot.note === 'string' ? snapshot.note : null;
// A fire needs an id and the anchor its card stands on; a piece
// needs its fire.
const fires = new Map();
for (const fire of snapshot.fires)
if (typeof fire?.id === 'string' && validAnchor(fire.anchor))
fires.set(fire.id, fire);
const pieces = snapshot.pieces.filter((piece) =>
fires.has(piece?.fireId),
// Incident facts may change independently of the polygon's source clock.
const signature = JSON.stringify(
rows
.map(({ polygons, ...facts }) => facts)
.sort((a, b) => a.stableId.localeCompare(b.stableId)),
);
const atMs = shownAt();
const bands = pieces.map((piece) => perimeterAgeBand(piece.born, atMs));
const drawKey =
typeof snapshot.revision === 'string'
? `${snapshot.revision}\n${bands.join('')}`
: null;
_fireById = fires;
_bandsAt = atMs;
if (drawKey === null || drawKey !== _drawnKey) {
drawPieces(pieces, bands);
_drawnKey = drawKey;
if (signature === _snapshotSignature) {
if (_selectedId) publishSelectedCard();
_lastUpdate = updatedAt;
_lastError = null;
return true;
}
// Refresh (or drop) the selected incident's card against the new
// snapshot: its ages move with `at` even when nothing is redrawn.
if (_selectedId) {
if (_selectedLink === null && !_linkRequest) _linkFailures.clear();
publishSelectedCard();
abortLinkVerification();
const nextFills = [];
const nextLines = [];
_rowById.clear();
for (const row of rows) {
const color = containmentColor(row.containedPct);
for (const [index, rings] of row.polygons.entries()) {
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
// Each exterior keeps its own holes.
nextFills.push({
id,
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: withAlpha(color, 0.25),
height: 'clampGround',
});
// The fire line: the exterior ring draped on the ground (lines
// take ECEF, draw.d.ts `LineItem`).
nextLines.push({
id,
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
style: { kind: 'solid', color: withAlpha(color, 0.9) },
});
}
// Keep a geometry-free projection: the coordinate arrays would
// otherwise be retained for the layer's lifetime while only the
// anchor is ever read again.
const { polygons, ...facts } = row;
_rowById.set(row.stableId, {
...facts,
anchor: perimeterAnchorDegrees(polygons),
});
}
_fills.set(nextFills);
_lines.set(nextLines);
_snapshotSignature = signature;
// Refresh (or drop) the selected incident's card against the new feed.
if (_selectedId) publishSelectedCard();
_count = rows.length;
_lastUpdate = updatedAt;
_lastError = null;
console.log(
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
);
return true;
} catch (e) {
if (request.signal.aborted || _request !== request || !_enabled)
@@ -537,7 +409,6 @@ export function createFirePerimetersLayer({
_stale = false;
return false;
} finally {
signal?.removeEventListener('abort', abort);
if (_request === request) _request = null;
}
},
@@ -547,20 +418,18 @@ export function createFirePerimetersLayer({
_request = null;
removeClickHandler();
clearSelection();
_fireById = new Map();
_fireByItem.clear();
_drawnKey = null;
_at = null;
_bandsAt = null;
_note = null;
_rowById.clear();
_snapshotSignature = null;
_inciwebIndex = [];
_indexFetchedAt = 0;
_linkPublications.clear();
_linkVerdicts.clear();
_viewer = null;
_enabled = false;
_fills?.dispose();
_lines?.dispose();
_fills = _lines = null;
_setIds = new Set();
_count = 0;
_lastUpdate = null;
_lastError = null;
_stale = false;
@@ -573,15 +442,11 @@ export function createFirePerimetersLayer({
? Math.max(1, Math.floor(maxCount))
: 2000;
const result = [];
for (const fire of _fireById.values()) {
for (const row of _rowById.values()) {
if (result.length >= limit) break;
const { anchor, id, ...facts } = fire;
// A time after the moment shown is unknown in this snapshot.
if (_at !== null)
for (const key of ['discoveredTime', 'updatedTime', 'lastGrowthTime'])
if (facts[key] > _at) facts[key] = null;
const { anchor, stableId, ...facts } = row;
result.push({
id,
id: stableId,
...facts,
lat: anchor.lat,
lon: anchor.lon,
@@ -590,33 +455,34 @@ export function createFirePerimetersLayer({
return result;
},
/** The moment the analyst records show: the snapshot's `at`, or null for now. */
getAnalystRecordsAt() {
return _at;
},
getRowControls() {
const atMs = _bandsAt;
const counts = PERIMETER_AGE_BANDS.map(() => 0);
for (const fire of _fireById.values())
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
const bands = [
{ label: t('Not contained or unknown'), color: containmentAccent(0) },
{ label: t('Under 50% contained'), color: containmentAccent(1) },
{ label: t('50–99% contained'), color: containmentAccent(50) },
{ label: t('Fully contained'), color: containmentAccent(100) },
];
return {
chips: [],
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
label: t(band.label),
color: band.color,
count: counts[index],
legend: bands.map((band, index) => ({
...band,
count: [..._rowById.values()].filter(
(row) => containmentAccent(row.containedPct) === band.color,
).length,
...(index === 0
? { blurb: t('Colour shows the age of each area.') }
? {
blurb: t(
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
),
}
: {}),
})),
...(_note ? { info: t(_note) } : {}),
};
},
getStats() {
return {
count: _fireById.size,
count: _count,
lastUpdate: _lastUpdate,
error: _lastError,
stale: _stale,
File diff suppressed because it is too large. Load diff
-123
View File
@@ -1,14 +1,3 @@
/**
* WFIGS perimeters: the proxy's rows (normalizeFirePerimeterSnapshot) and
* the snapshot the layer draws (firePerimeterSnapshot).
*
* The server and the package's `./layers/perimeters/source` export import
* this module, so it marks text with msg() only. The layer translates `note`
* when it shows it.
*/
import { msg } from '../../i18n/marker.js';
/**
* Normalize a WFIGS feed, skipping individually invalid features.
* Only a payload that is not a feature collection at all rejects the whole
@@ -91,7 +80,6 @@ export function normalizeFirePerimeterSnapshot(geojson) {
: null,
discoveredTime: finiteOrNull(properties.attr_FireDiscoveryDateTime),
updatedTime: finiteOrNull(properties.poly_DateCurrent),
polygonTime: finiteOrNull(properties.poly_PolygonDateTime),
cause: textOrNull(properties.attr_FireCause),
behavior: textOrNull(properties.attr_FireBehaviorGeneral),
personnel: finiteOrNull(properties.attr_TotalIncidentPersonnel),
@@ -104,114 +92,3 @@ export function normalizeFirePerimeterSnapshot(geojson) {
}
return rows;
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/** WFIGS times up to this far ahead of our clock (clock skew) are taken as now; later ones are unknown. */
const CLOCK_SKEW_MS = 10 * 60 * 1000;
/**
* The WFIGS snapshot for the Fire Perimeters layer (contract:
* `createFirePerimetersLayer`), from the proxy's rows.
*
* WFIGS keeps one perimeter per fire, so each of its polygons is one piece,
* born when the perimeter was mapped (`poly_PolygonDateTime`, else the
* record's last edit `poly_DateCurrent`).
* @param {object[]} rows - normalizeFirePerimeterSnapshot rows.
* @param {{fetchedAt?: number|null, stale?: boolean, now?: number}} [options]
* @returns {{at: null, fetchedAt: number|null, stale: boolean,
* revision: string, note: string, fires: object[], pieces: object[]}}
*/
export function firePerimeterSnapshot(
rows,
{ fetchedAt = null, stale = false, now = Date.now() } = {},
) {
const fires = [];
const pieces = [];
const versions = [];
for (const row of rows) {
const { stableId, polygons, polygonTime, ...facts } = row;
const mapped = polygonTime ?? facts.updatedTime;
const grown =
Number.isFinite(mapped) && mapped <= now + CLOCK_SKEW_MS
? Math.min(mapped, now)
: null;
fires.push({
...facts,
id: stableId,
lastGrowthTime: grown,
anchor: perimeterAnchorDegrees(polygons),
});
for (const rings of polygons)
pieces.push({
fireId: stableId,
born: grown,
polygons: [rings],
outline: rings,
});
// Without poly_DateCurrent, the mapping time and outline stand in for it.
versions.push(
Number.isFinite(facts.updatedTime)
? `${stableId}@${facts.updatedTime}`
: `${stableId}@${polygonTime ?? ''}:${JSON.stringify(polygons)}`,
);
}
return {
at: null,
fetchedAt: Number.isFinite(fetchedAt) ? fetchedAt : null,
stale: stale === true,
revision: versions.sort().join('|'),
note: msg(
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
),
fires,
pieces,
};
}
+1 -230
View File
@@ -1,10 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
perimeterAnchorDegrees,
normalizeFirePerimeterSnapshot,
firePerimeterSnapshot,
} from './records.js';
import { normalizeFirePerimeterSnapshot } from './records.js';
const ring = [
[-108.1, 35.2],
@@ -26,7 +22,6 @@ function feature(overrides = {}) {
attr_IncidentTypeCategory: 'WF',
attr_FireDiscoveryDateTime: 1757900000000,
poly_DateCurrent: 1757950000000,
poly_PolygonDateTime: 1757940000000,
attr_FireCause: 'Natural',
attr_FireBehaviorGeneral: 'Active',
attr_TotalIncidentPersonnel: 380,
@@ -64,7 +59,6 @@ test('a valid snapshot yields one row per incident with polygons preserved', ()
category: 'WF',
discoveredTime: 1757900000000,
updatedTime: 1757950000000,
polygonTime: 1757940000000,
cause: 'Natural',
behavior: 'Active',
personnel: 380,
@@ -96,7 +90,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
attr_IncidentTypeCategory: null,
attr_FireDiscoveryDateTime: null,
poly_DateCurrent: null,
poly_PolygonDateTime: null,
attr_FireCause: null,
attr_FireBehaviorGeneral: null,
attr_TotalIncidentPersonnel: null,
@@ -117,7 +110,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
category: rows[0].category,
discoveredTime: rows[0].discoveredTime,
updatedTime: rows[0].updatedTime,
polygonTime: rows[0].polygonTime,
cause: rows[0].cause,
behavior: rows[0].behavior,
personnel: rows[0].personnel,
@@ -134,7 +126,6 @@ test('optional attributes normalize to null rather than leaking undefined', () =
category: null,
discoveredTime: null,
updatedTime: null,
polygonTime: null,
cause: null,
behavior: null,
personnel: null,
@@ -208,223 +199,3 @@ test('a perimeter with no rings is skipped rather than rendered empty', () => {
assert.equal(rows.length, 1);
assert.equal(rows[0].stableId, 'other');
});
const NOW = 1758000000000;
const rowsOf = (...features) => normalizeFirePerimeterSnapshot({ features });
// feature() replaces all properties with the overrides' own: keep the rest.
const fixture = (id, properties) =>
feature({ id, properties: { ...feature().properties, ...properties } });
test('each WFIGS polygon becomes one piece of its fire, born when it was mapped', () => {
const hole = [
[-108.08, 35.22],
[-108.02, 35.22],
[-108.02, 35.25],
[-108.08, 35.22],
];
const snapshot = firePerimeterSnapshot(
rowsOf(
feature({
geometry: { type: 'MultiPolygon', coordinates: [[ring, hole], [ring]] },
}),
),
{ fetchedAt: NOW - 1000, now: NOW },
);
assert.equal(snapshot.at, null);
assert.equal(snapshot.stale, false);
assert.equal(snapshot.fetchedAt, NOW - 1000);
assert.equal(
snapshot.note,
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
);
assert.equal(snapshot.fires.length, 1);
const [fire] = snapshot.fires;
assert.equal(fire.id, '2026-NMGNF-000123');
assert.equal(fire.lastGrowthTime, 1757940000000);
assert.equal(fire.containedPct, 40);
assert.equal('stableId' in fire || 'polygons' in fire, false);
assert.ok(Math.abs(fire.anchor.lat - 35.2333) < 0.01);
assert.deepEqual(
snapshot.pieces.map(({ fireId, born, polygons, outline }) => [
fireId,
born,
polygons,
outline,
]),
[
['2026-NMGNF-000123', 1757940000000, [[ring, hole]], [ring, hole]],
['2026-NMGNF-000123', 1757940000000, [[ring]], [ring]],
],
'the outline is every ring, holes included',
);
});
test('a perimeter without its mapping time falls back to the last edit; a future time is unknown', () => {
const [fallback, future, futureEdit, none] = firePerimeterSnapshot(
rowsOf(
fixture(1, { poly_PolygonDateTime: null }),
fixture(2, {
attr_UniqueFireIdentifier: 'future',
poly_PolygonDateTime: NOW + 3600000,
}),
fixture(3, {
attr_UniqueFireIdentifier: 'future-edit',
poly_PolygonDateTime: null,
poly_DateCurrent: NOW + 3600000,
}),
fixture(4, {
attr_UniqueFireIdentifier: 'none',
poly_PolygonDateTime: null,
poly_DateCurrent: null,
}),
),
{ now: NOW },
).fires;
assert.equal(fallback.lastGrowthTime, 1757950000000);
assert.equal(future.lastGrowthTime, null);
assert.equal(futureEdit.lastGrowthTime, null);
assert.equal(none.lastGrowthTime, null);
// A clock a few minutes ahead of ours is taken as now.
const skewed = firePerimeterSnapshot(
rowsOf(fixture(1, { poly_PolygonDateTime: NOW + 60000 })),
{ now: NOW },
);
assert.equal(skewed.fires[0].lastGrowthTime, NOW);
assert.equal(skewed.pieces[0].born, NOW);
});
test('the revision follows fire ids and update times, not feed order', () => {
const a = feature();
const b = fixture(2, { attr_UniqueFireIdentifier: 'b' });
const revision = (...features) =>
firePerimeterSnapshot(rowsOf(...features), { now: NOW }).revision;
assert.equal(revision(a, b), revision(b, a));
assert.notEqual(
revision(a, b),
revision(
a,
fixture(2, { attr_UniqueFireIdentifier: 'b', poly_DateCurrent: 1 }),
),
);
assert.notEqual(revision(a, b), revision(a));
const undated = fixture(1, { poly_DateCurrent: null });
const shifted = ring.map(([lon, lat]) => [lon + 1, lat]);
assert.notEqual(
revision(undated),
revision({
...undated,
geometry: { type: 'Polygon', coordinates: [shifted] },
}),
);
assert.notEqual(
revision(undated),
revision(
fixture(1, {
poly_DateCurrent: null,
poly_PolygonDateTime: NOW,
}),
),
);
});
test('the snapshot carries staleness', () => {
const snapshot = firePerimeterSnapshot(rowsOf(feature()), {
stale: true,
fetchedAt: 'yesterday',
now: NOW,
});
assert.equal(snapshot.stale, true);
assert.equal(snapshot.fetchedAt, null);
assert.deepEqual(
snapshot.fires.map(({ id }) => id),
['2026-NMGNF-000123'],
);
});
const square = [
[-108.2, 35.0],
[-108.0, 35.0],
[-108.0, 35.2],
[-108.2, 35.2],
[-108.2, 35.0],
];
const tiny = [
[-107.01, 34.0],
[-107.0, 34.0],
[-107.0, 34.01],
[-107.01, 34.0],
];
test('the card anchors at the vertex mean of the largest polygon', () => {
const anchor = perimeterAnchorDegrees([[tiny], [square]]);
assert.ok(Math.abs(anchor.lon - -108.1) < 1e-9);
assert.ok(Math.abs(anchor.lat - 35.1) < 1e-9);
});
test('incident cards stay at the dateline for closed, reversed and rotated outlines', () => {
const vertices = [
[179, 10],
[-179, 10],
[-179, 12],
[179, 12],
];
for (let start = 0; start < vertices.length; start++) {
const rotated = [...vertices.slice(start), ...vertices.slice(0, start)];
for (const points of [rotated, [...rotated].reverse()]) {
const anchor = perimeterAnchorDegrees([[points.concat([points[0]])]]);
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
}
}
});
test('incident card longitude treats vertices at either sign of 180 as the same meridian', () => {
for (const boundary of [-180, 180]) {
const ring = [
[179, 10],
[boundary, 10],
[-179, 10],
[-179, 12],
[179, 12],
[179, 10],
];
const anchor = perimeterAnchorDegrees([[ring]]);
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
assert.ok(Math.abs(anchor.lat - 10.8) < 1e-9);
}
});
test('multipart cards compare polygon areas along short dateline edges', () => {
const ordinary = [
[10, 20],
[11, 20],
[11, 21],
[10, 21],
[10, 20],
];
for (const width of [0.2, 2]) {
const crossing = [
[180 - width / 2, 10],
[-180 + width / 2, 10],
[-180 + width / 2, 10 + width],
[180 - width / 2, 10 + width],
[180 - width / 2, 10],
];
for (const ring of [crossing, [...crossing].reverse()]) {
for (const polygons of [
[[ring], [ordinary]],
[[ordinary], [ring]],
]) {
const anchor = perimeterAnchorDegrees(polygons);
if (width < 1) {
assert.ok(Math.abs(anchor.lon - 10.5) < 1e-9);
assert.ok(Math.abs(anchor.lat - 20.5) < 1e-9);
} else {
assert.ok(Math.abs(Math.abs(anchor.lon) - 180) < 1e-9);
assert.ok(Math.abs(anchor.lat - 11) < 1e-9);
}
}
}
}
});
+32 -25
View File
@@ -1,35 +1,42 @@
import { msg } from '../../i18n/marker.js';
import { readResponseJsonCapped } from '../../sources/httpBody.js';
import { firePerimeterSnapshot } from './records.js';
// Failures stay English data. The Layers panel shows them translated.
// A portable export (package.json): no i18n here. Failures stay English data;
// the Layers panel shows them translated.
const msg = (text) => text;
/** Request a snapshot through the bounded, same-origin WFIGS proxy. */
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
export function createWfigsPerimeterSource({
fetchImpl = (...args) => globalThis.fetch(...args),
} = {}) {
/**
* The rows with how fresh they are: the proxy answers from its last
* snapshot, marked stale, while WFIGS is unreachable.
* @returns {Promise<{rows: object[], stale: boolean, fetchedAt: number|null}>}
*/
async function getSnapshotDetail({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/fire-perimeters', { signal });
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
80 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
if (!Array.isArray(payload?.rows))
throw new Error(msg('Malformed perimeter snapshot'));
return {
rows: payload.rows,
stale: payload.stale === true,
fetchedAt: Number.isFinite(payload.fetchedAt) ? payload.fetchedAt : null,
};
}
return {
/**
* Current perimeters as fires and their pieces (firePerimeterSnapshot).
* The proxy answers from its last snapshot, marked stale, while WFIGS is
* unreachable.
*/
async getSnapshot({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/fire-perimeters', { signal });
if (!response.ok) throw new Error(`WFIGS HTTP ${response.status}`);
const payload = await readResponseJsonCapped(
response,
80 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
if (!Array.isArray(payload?.rows))
throw new Error(msg('Malformed perimeter snapshot'));
return firePerimeterSnapshot(payload.rows, {
fetchedAt: payload.fetchedAt,
stale: payload.stale === true,
});
/** The perimeter rows (see getSnapshotDetail for staleness). */
async getSnapshot(options = {}) {
return (await getSnapshotDetail(options)).rows;
},
getSnapshotDetail,
};
}
+12 -14
View File
@@ -20,7 +20,7 @@ const validPayload = {
],
};
test('a successful response yields the snapshot of fires and pieces', async () => {
test('a successful response yields normalized perimeter rows', async () => {
let requested;
const source = createWfigsPerimeterSource({
fetchImpl: async (url) => {
@@ -30,13 +30,9 @@ test('a successful response yields the snapshot of fires and pieces', async () =
});
},
});
const snapshot = await source.getSnapshot();
assert.deepEqual(
snapshot.fires.map((fire) => fire.id),
['2026-NMGNF-000123'],
);
assert.deepEqual(snapshot.pieces[0].polygons, [[ring]]);
assert.equal(snapshot.at, null);
const rows = await source.getSnapshot();
assert.equal(rows.length, 1);
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
assert.equal(requested, '/api/fire-perimeters');
});
@@ -164,20 +160,22 @@ test('a failed refresh serves the last snapshot marked stale for a day, then ref
assert.equal((await ask()).status, 502, 'a day-old snapshot is not served');
});
test('the snapshot carries the proxy staleness and fetch time', async () => {
test('the snapshot detail carries the proxy staleness and fetch time', async () => {
const fetchedAt = Date.UTC(2026, 9, 25, 12);
const source = createWfigsPerimeterSource({
fetchImpl: async () => Response.json({ rows: [], stale: true, fetchedAt }),
});
const snapshot = await source.getSnapshot();
assert.equal(snapshot.stale, true);
assert.equal(snapshot.fetchedAt, fetchedAt);
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
assert.deepEqual(await source.getSnapshotDetail(), {
rows: [],
stale: true,
fetchedAt,
});
assert.deepEqual(await source.getSnapshot(), []);
});
test('getSnapshot works when taken off its source object', async () => {
const { getSnapshot } = createWfigsPerimeterSource({
fetchImpl: async () => Response.json({ rows: [] }),
});
assert.deepEqual((await getSnapshot()).fires, []);
assert.deepEqual(await getSnapshot(), []);
});
+2 -18
View File
@@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => {
};
await assert.rejects(
searchHls({
box: { west: -181, south: 0, east: -179, north: 1 },
box: { west: 179, south: 0, east: -179, north: 1 },
fetchImpl,
}),
/±180/,
/dateline/,
);
await assert.rejects(
searchHls({ box: BOX, now: 'never', fetchImpl }),
@@ -251,22 +251,6 @@ test('an invalid box or clock is refused before any request', async () => {
assert.equal(called, false);
});
test('a dateline box goes to CMR as it is: CMR reads west > east as the short box', async () => {
const calls = [];
const result = await searchHls({
box: { west: 179, south: 0, east: -179, north: 1 },
days: 2,
now: '2026-09-21T00:00:00Z',
fetchImpl: async (url) => {
calls.push(url);
return response({ json: { hits: 1, items: [ummItem({})] } });
},
});
assert.equal(calls.length, 2, 'one search per product');
assert.ok(calls.every((url) => url.includes('bounding_box=179,0,-179,1')));
assert.ok(result.candidates.some((candidate) => candidate.product === 'S30'));
});
test('CMR pages follow the CMR-Search-After cursor up to 2,000 records and truncation stays honest', async () => {
const items = (count) =>
Array.from({ length: count }, (_, i) => ummItem({ conceptId: `G-${i}` }));
+4 -9
View File
@@ -581,8 +581,6 @@ export function createRecentImageryLayer({
for (const slotId of SLOT_IDS) {
const candidate = candidateFor(shown[slotId]);
if (candidate && _hostInfo.collection) {
const { availableBoxes, emptyBoxes } =
thumbnails.get(candidate.key) ?? {};
renderer.showSlot(slotId, candidate, _box, {
alpha: _alpha,
splitDirection: !live
@@ -590,8 +588,6 @@ export function createRecentImageryLayer({
: (slotId === 'a') !== _swapped
? 'left'
: 'right',
availableBoxes,
emptyBoxes,
});
} else {
renderer.hideSlot(slotId);
@@ -901,22 +897,21 @@ export function createRecentImageryLayer({
// The new automatic day's probe may have been cancelled off-screen.
requestThumbnails();
}
if (pruned) syncRender();
const followed =
Boolean(_followKey) &&
_followKey === _focusKey &&
drapable(candidateFor(_followKey)) &&
applyPreview(_followKey);
// A pinned or previewed day that was still being probed drapes now.
const shown = plan();
const owned = renderer.getOwned?.() || {};
const drapesChanged = SLOT_IDS.some(
(slotId) => (owned[slotId]?.key || null) !== shown[slotId],
);
// One render per probe: the key can stay the same while its halves change.
// A host found moved changes the divider, so the panel renders in full.
const moved = !followed && syncHost();
if (!followed) syncRender();
if (drapesChanged && !pruned && !followed) syncRender();
notify('thumbnail');
if (pruned || followed || drapesChanged || moved) notify();
if (pruned || followed || drapesChanged) notify();
});
syncHost();
if (_box && !_candidates.length) void runSearch();
+1 -428
View File
@@ -1,10 +1,6 @@
import test from 'node:test';
import * as Cesium from 'cesium';
import assert from 'node:assert/strict';
import { until } from '../../testSupport/kartaViewFakes.mjs';
import { createRecentImagerySource } from './source.js';
import { createThumbnailLoader } from './thumbnails.js';
import { boxKey, nonCrossingBoxes } from './model.js';
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
import { acquireImageryComparison } from '../../maps/imageryComparison.js';
import { MapSourceController } from '../../maps/controller.js';
@@ -18,16 +14,11 @@ import {
SPLIT_PUBLISH_MS,
createRecentImageryLayer,
} from './index.js';
import {
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { createImageryBoxPreview } from './rendering.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import {
BOX,
CANDIDATES,
FIJI_BOX,
boxToolFakes,
candidate,
fakeCatalog,
@@ -1573,424 +1564,6 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy
assert.equal(f.snap().notice, 'Search cancelled');
});
test('a box dragged across the dateline is searched, listed and draped as one box', async () => {
const f = fixture();
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
f.layer.enable();
assert.equal(f.layer.setBox(box), true);
assert.equal(f.snap().boxError, null);
assert.deepEqual(f.catalog.searches.at(-1).request.box, box);
f.catalog.resolveLast();
await settle();
assert.equal(f.snap().candidates.length, 4);
assert.equal(f.snap().preview.key, S18);
assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped');
assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°');
});
test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => {
const f = fixture();
const priorGet = f.thumbnails.get;
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
const [west, east] = nonCrossingBoxes(box);
let boxes = [west];
f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes });
f.layer.enable();
f.layer.setBox(box);
f.catalog.resolveLast();
await settle();
f.thumbnails.probeRequested();
const slot = Object.keys(f.owned()).find((id) => f.owned()[id]);
assert.ok(slot, 'a day is already on the map');
const key = f.owned()[slot].key;
assert.deepEqual(f.owned()[slot].availableBoxes, [west]);
boxes = [west, east];
f.thumbnails.probe(key, 'present');
assert.deepEqual(f.owned()[slot].availableBoxes, boxes);
f.layer.destroy();
});
const sideOf = (url) =>
Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0
? 'west'
: 'east';
/** A snapshot response; `present: null` sends no Data-Present header. */
const snapshotAnswer = (present, status = 200) =>
new Response('img', {
status,
headers: present === null ? {} : { 'Data-Present': String(present) },
});
function realLayer({
fetchImpl,
candidates,
maxDecoded = 16,
halfDeadlineMs = 50,
}) {
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs });
let nextUrl = 0;
const loader = createThumbnailLoader({
requestThumbnail: source.getThumbnail,
createObjectUrl: () => `blob:${++nextUrl}`,
revokeObjectUrl: () => {},
maxDecoded,
});
const globe = fakeGlobePort();
const layer = createRecentImageryLayer({
catalog: {
searchHls: async () => ({ candidates, truncated: false, errors: [] }),
},
renderer: createRecentImageryRenderer(),
thumbnails: loader,
host: () => ({ collection: globe.imagery, kind: 'globe' }),
globeOf: () => globe,
now: () => new Date('2026-11-13T15:00:00Z'),
});
layer.init({ camera: {} });
return { layer, loader, globe };
}
test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => {
const day = candidate('VIIRS', '2026-11-10');
const sides = [];
const { layer, loader, globe } = realLayer({
candidates: [day],
fetchImpl: async (url) => {
const side = sideOf(url);
sides.push(side);
return snapshotAnswer(side === 'east');
},
});
layer.setSources({ viirs: true });
layer.enable();
assert.equal(layer.setBox(FIJI_BOX), true);
// The probe asks about both halves, wider first. The layer drapes the one with data.
assert.equal(
await until(() => globe.layers.length > 0, { ticks: 2000 }),
true,
);
assert.deepEqual(sides, ['east', 'west']);
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
[nonCrossingBoxes(FIJI_BOX)[1]],
);
assert.equal(loader.get(day.key).status, 'present');
const snapshot = layer.getSnapshot();
assert.equal(snapshot.candidates[0].thumbnail.status, 'present');
assert.equal(snapshot.candidates[0].drapable, true);
assert.equal(snapshot.auto?.key, day.key);
layer.destroy();
assert.equal(globe.layers.length, 0);
});
test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => {
const day = candidate('VIIRS', '2026-11-10');
const { layer, loader, globe } = realLayer({
candidates: [day],
fetchImpl: async () => snapshotAnswer(false),
});
layer.setSources({ viirs: true });
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }),
true,
);
assert.equal(globe.layers.length, 0);
assert.equal(
layer.getSnapshot().candidates.some((c) => c.key === day.key),
false,
'an empty day leaves the strip',
);
layer.destroy();
});
for (const [label, box] of [
['a plain box', { west: -98, south: 30, east: -97, north: 31 }],
['a dateline box', FIJI_BOX],
]) {
test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => {
const day = candidate('S30', '2026-11-10');
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const { layer, loader, globe } = realLayer({
candidates: [day],
halfDeadlineMs: 5000,
fetchImpl: async () => {
await gate;
return snapshotAnswer(true);
},
});
layer.enable();
layer.setBox(box);
assert.equal(
await until(() => globe.layers.length === nonCrossingBoxes(box).length, {
ticks: 2000,
}),
true,
);
const before = [...globe.layers];
const added = globe.added.length;
release();
assert.equal(
await until(() => loader.get(day.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(globe.added.length, added);
assert.deepEqual(globe.layers, before);
layer.destroy();
});
}
test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => {
const day1 = candidate('VIIRS', '2026-11-10');
const day2 = candidate('VIIRS', '2026-11-11');
let eastCalls = 0;
let releaseDay2;
const gate = new Promise((resolve) => {
releaseDay2 = resolve;
});
const { layer, loader, globe } = realLayer({
candidates: [day2, day1],
maxDecoded: 1,
halfDeadlineMs: 5000,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) await gate;
else if (sideOf(url) === 'east' && ++eastCalls === 2)
throw new TypeError('Failed to fetch');
return snapshotAnswer(true);
},
});
layer.setSources({ hls: false, viirs: true });
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day1.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
releaseDay2();
assert.equal(
await until(() => loader.get(day2.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).objectUrl, null);
layer.setAssignment('a', day1.key);
assert.equal(
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).status, 'present');
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
const [west, east] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
[west, east],
'a half that failed on the re-probe stays draped',
);
layer.destroy();
});
test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => {
const day1 = candidate('S30', '2026-11-10');
const day2 = candidate('S30', '2026-11-11');
let eastCalls = 0;
let releaseDay2;
const gate = new Promise((r) => (releaseDay2 = r));
const { layer, loader, globe } = realLayer({
candidates: [day2, day1],
maxDecoded: 1,
halfDeadlineMs: 5000,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) {
await gate;
return snapshotAnswer(true);
}
if (sideOf(url) === 'east') {
eastCalls += 1;
if (eastCalls === 1) return snapshotAnswer(false);
throw new TypeError('Failed to fetch');
}
return snapshotAnswer(true);
},
});
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day1.key).status === 'present', {
ticks: 2000,
}),
true,
);
const [west] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
assert.equal(loader.get(day1.key).emptyBoxes.length, 1);
releaseDay2();
assert.equal(
await until(() => loader.get(day2.key).status === 'present', {
ticks: 2000,
}),
true,
);
assert.equal(loader.get(day1.key).objectUrl, null);
layer.setAssignment('a', day1.key);
assert.equal(
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
ticks: 2000,
}),
true,
);
await until(() => false, { ticks: 50 });
const entry = loader.get(day1.key);
assert.deepEqual(
{
available: entry.availableBoxes.length,
empty: entry.emptyBoxes.length,
layers: globe.layers.length,
},
{ available: 1, empty: 1, layers: 1 },
);
layer.destroy();
});
test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => {
const day = candidate('S30', '2026-11-10');
let release;
const gate = new Promise((r) => (release = r));
const { layer, loader, globe } = realLayer({
candidates: [day],
halfDeadlineMs: 5000,
fetchImpl: async () => {
await gate;
return snapshotAnswer(null);
},
});
layer.enable();
layer.setBox({ west: -98, south: 30, east: -97, north: 31 });
assert.equal(
await until(() => globe.layers.length === 1, { ticks: 2000 }),
true,
);
release();
assert.equal(
await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }),
true,
);
await until(() => false, { ticks: 50 });
assert.equal(globe.layers.length, 1);
layer.destroy();
});
for (const [label, failEast] of [
['answers 503', async () => snapshotAnswer(null, 503)],
[
'rejects',
async () => {
throw new TypeError('Failed to fetch');
},
],
['never answers', () => new Promise(() => {})],
]) {
test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => {
const day = candidate('S30', '2026-11-10');
const { layer, loader, globe } = realLayer({
candidates: [day],
fetchImpl: async (url) =>
sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(),
});
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day.key)?.status === 'error', {
ticks: 2000,
}),
true,
);
layer.setAssignment('a', day.key);
await until(() => false, { ticks: 50 });
const entry = loader.get(day.key);
const [west] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(
{
empty: (entry.emptyBoxes ?? []).map(boxKey),
layers: globe.layers.length,
},
{ empty: [boxKey(west)], layers: 1 },
);
layer.destroy();
});
}
test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => {
const day1 = candidate('S30', '2026-11-10');
const day2 = candidate('S30', '2026-11-11');
let round = 0;
let releaseDay2;
const gate = new Promise((r) => (releaseDay2 = r));
const { layer, loader, globe } = realLayer({
candidates: [day2, day1],
maxDecoded: 1,
halfDeadlineMs: 5000,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) {
await gate;
return snapshotAnswer(true);
}
if (round === 0)
return sideOf(url) === 'west'
? snapshotAnswer(true)
: snapshotAnswer(null);
return sideOf(url) === 'west'
? snapshotAnswer(null)
: snapshotAnswer(false);
},
});
layer.enable();
layer.setBox(FIJI_BOX);
assert.equal(
await until(() => loader.get(day1.key)?.status === 'present', {
ticks: 2000,
}),
true,
);
round = 1;
releaseDay2();
assert.equal(
await until(
() =>
loader.get(day2.key)?.status === 'present' &&
loader.get(day1.key).objectUrl === null,
{ ticks: 2000 },
),
true,
);
layer.setAssignment('a', day1.key);
await until(() => false, { ticks: 50 });
await until(() => !loader.get(day1.key).loading, { ticks: 2000 });
await until(() => false, { ticks: 50 });
const entry = loader.get(day1.key);
const [, east] = nonCrossingBoxes(FIJI_BOX);
assert.deepEqual(
{
status: entry.status,
empty: (entry.emptyBoxes ?? []).map(boxKey),
layers: globe.layers.length,
},
{ status: 'present', empty: [boxKey(east)], layers: 1 },
);
layer.destroy();
});
test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => {
for (const order of [
[S18, V15],
+24 -93
View File
@@ -72,11 +72,13 @@ export const PRODUCTS = Object.freeze({
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/** A longitude brought back into ±180 after one step past it. */
const wrapLon = (value) =>
value > 180 ? value - 360 : value < -180 ? value + 360 : value;
const pad2 = (value) => String(value).padStart(2, '0');
/**
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
* east are not swapped: west > east crosses the dateline and `validateBox`
* rejects it. Null when any edge is nonfinite.
*/
/** A box edge as a number, or null when it is missing, blank or not numeric. */
function edgeNumber(value) {
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
@@ -85,11 +87,6 @@ function edgeNumber(value) {
return Number.isFinite(number) ? number : null;
}
/**
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
* east are not swapped: west > east is the short arc across the dateline.
* Null when any edge is nonfinite.
*/
function normalizeBox(box) {
if (!box || typeof box !== 'object') return null;
const [west, south, east, north] = [
@@ -108,45 +105,8 @@ function normalizeBox(box) {
}
/**
* Degrees of longitude going east from `west` to `east`. A west > east pair
* wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and
* `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`,
* even the long way round.
* @param {number} west Degrees.
* @param {number} east Degrees.
* @returns {number}
*/
export function lonSpanDeg(west, east) {
return east >= west ? east - west : east + 360 - west;
}
/** A comparable key for a degrees box. */
export const boxKey = (box) =>
[box.west, box.south, box.east, box.north].map(Number).join(',');
/**
* One or two boxes with west <= east that cover the same area. A dateline
* box is split at ±180 so each side is a plain rectangle for a draped layer
* or a Worldview request. A box with a missing or nonfinite edge is [].
* So is a dateline box of zero width (west 180, east -180).
* @param {object} box Degrees box.
* @returns {Array<object>}
*/
export function nonCrossingBoxes(box) {
const normalized = normalizeBox(box);
if (!normalized) return [];
const { west, south, east, north } = normalized;
if (!(west > east)) return [normalized];
const parts = [];
if (west < 180) parts.push({ west, south, east: 180, north });
if (east > -180) parts.push({ west: -180, south, east, north });
return parts;
}
/**
* Side lengths of a box in km: the longitude span at its mid-latitude (the
* short arc when the box crosses the dateline; a west <= east box is not
* shortened), and its latitude span.
* Side lengths of a box in km: the box's own longitude span (never the
* shorter way round the globe) at its mid-latitude, and its latitude span.
* @param {object} box Degrees box.
* @returns {{ width: number, height: number }}
*/
@@ -156,7 +116,7 @@ export function boxSideKm(box) {
const midLat = (normalized.south + normalized.north) / 2;
return {
width:
lonSpanDeg(normalized.west, normalized.east) *
(normalized.east - normalized.west) *
KM_PER_DEG_LAT *
Math.cos(toRadians(midLat)),
height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,
@@ -166,11 +126,9 @@ export function boxSideKm(box) {
const refuse = (reason, message) => ({ ok: false, reason, message });
/**
* Validate a selection box for the catalog and the tile providers. A box
* with west > east is the short arc across the dateline and is accepted
* when that arc is under the size cap.
* Validate a selection box for the catalog and the tile providers.
* @param {object} box Degrees box.
* @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
* @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
*/
export function validateBox(box) {
const normalized = normalizeBox(box);
@@ -178,6 +136,8 @@ export function validateBox(box) {
const { west, south, east, north } = normalized;
if (Math.abs(west) > 180 || Math.abs(east) > 180)
return refuse('invalid', msg('Longitudes must be within ±180°'));
if (west > east)
return refuse('dateline', msg('Select one side of the dateline'));
if (
Math.abs(south) > MERCATOR_LAT_LIMIT ||
Math.abs(north) > MERCATOR_LAT_LIMIT
@@ -186,7 +146,7 @@ export function validateBox(box) {
'polar',
`Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,
);
if (lonSpanDeg(west, east) === 0 || north === south)
if (east === west || north === south)
return refuse('degenerate', msg('Box must enclose an area'));
const { width, height } = boxSideKm(normalized);
if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM)
@@ -223,9 +183,7 @@ export function fitViewHeightM({ width, height, fovy } = {}) {
}
/**
* The centre of a box, in degrees. A dateline box (west > east) is centred
* on the short arc, not the arithmetic mean, which would be the other side
* of the globe.
* The centre of a box that does not cross the dateline, in degrees.
* @param {object} box Degrees box.
* @returns {{ lon: number, lat: number } | null}
*/
@@ -233,18 +191,14 @@ export function boxCentre(box) {
const normalized = normalizeBox(box);
if (!normalized) return null;
return {
lon: wrapLon(
normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2,
),
lon: (normalized.west + normalized.east) / 2,
lat: (normalized.south + normalized.north) / 2,
};
}
/**
* A square box centred on a pin, `sideKm` on the ground (the east–west extent
* widens by 1/cos(lat)); null when the result would not validate. A pin whose
* box passes ±180 gets the short-arc box (west > east), the same convention
* as a dragged dateline box, with edges wrapped into ±180.
* widens by 1/cos(lat)); null when the result would not validate.
* @param {number} lon Degrees.
* @param {number} lat Degrees.
* @param {number} [sideKm]
@@ -253,19 +207,16 @@ export function boxCentre(box) {
export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) {
if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0)
return null;
if (Math.abs(lon) > 180) return null;
const cosLat = Math.cos(toRadians(lat));
if (cosLat <= 0) return null;
const halfLat = sideKm / 2 / KM_PER_DEG_LAT;
const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat);
// A half-width of 90° or more is not a short arc; refuse rather than wrap.
if (halfLon >= 90) return null;
const clampLat = (value) =>
Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value));
const result = validateBox({
west: wrapLon(lon - halfLon),
west: lon - halfLon,
south: clampLat(lat - halfLat),
east: wrapLon(lon + halfLon),
east: lon + halfLon,
north: clampLat(lat + halfLat),
});
return result.ok ? result.box : null;
@@ -498,31 +449,15 @@ export function coverageFor(candidate, box) {
.filter((ring) => Array.isArray(ring) && ring.length >= 3);
if (!normalized || !footprints.length) return 'unknown';
const { west, south, east, north } = normalized;
const centre = boxCentre(normalized);
// A dateline box is one continuous range starting at its west edge. A
// longitude on the east side (at or past ±180) shifts by 360. One just
// outside the west corner stays put: shifting every value below west would
// send that corner the long way round and miss a footprint that covers it.
const crossing = west > east;
const project = (lon) =>
crossing && lon < west && (lon <= east || lon - east < west - lon)
? lon + 360
: lon;
const samples = [
[project(west), south],
[project(east), south],
[project(east), north],
[project(west), north],
[project(centre.lon), centre.lat],
[west, south],
[east, south],
[east, north],
[west, north],
[(west + east) / 2, (south + north) / 2],
];
return samples.every(([lon, lat]) =>
footprints.some((ring) =>
pointInPolygon(
lon,
lat,
crossing ? ring.map(([x, y]) => [project(x), y]) : ring,
),
),
footprints.some((ring) => pointInPolygon(lon, lat, ring)),
)
? 'full'
: 'partial';
@@ -671,10 +606,6 @@ export function wvsSnapshotUrl({
const normalized = normalizeBox(box);
if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);
if (!normalized) throw new TypeError('A finite box is required');
// Worldview Snapshots rejects a BBOX whose west is greater than its east
// (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse.
if (normalized.west > normalized.east)
throw new TypeError('A snapshot cannot cross the dateline');
const bbox = [
normalized.south,
normalized.west,
+9 -120
View File
@@ -3,8 +3,6 @@ import assert from 'node:assert/strict';
import {
boxFromPin,
lonSpanDeg,
nonCrossingBoxes,
boxFromRectangle,
boxSideKm,
coverageFor,
@@ -53,20 +51,11 @@ function hls(product, day, clouds, extra = {}) {
return { ...groupGranulesByDay(granules)[0], ...extra };
}
test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => {
test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {
const reason = (box) => validateBox(box).reason;
const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 });
assert.equal(dateline.ok, true);
assert.equal(dateline.box.west, 179);
assert.equal(dateline.box.east, -179);
assert.equal(
reason({ west: 170, south: 0, east: -170, north: 1 }),
'too-large',
'a 20° dateline arc is still over the 1,000 km cap',
);
assert.equal(
reason({ west: 180, south: 0, east: -180, north: 1 }),
'degenerate',
reason({ west: 179, south: 0, east: -179, north: 1 }),
'dateline',
);
assert.equal(
reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),
@@ -81,6 +70,10 @@ test('validateBox refuses polar, degenerate, invalid and oversized boxes, and ac
validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message,
'Imagery stops at ±85.05° latitude',
);
assert.equal(
validateBox({ west: 179, south: 0, east: -179, north: 1 }).message,
'Select one side of the dateline',
);
assert.equal(
validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok,
true,
@@ -144,14 +137,10 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400
lon: 10,
lat: 5,
});
assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), {
lon: 180,
lat: 1,
});
assert.equal(boxCentre(null), null);
});
test('box width is the longitude span at the mid-latitude; a dateline box uses the short arc', () => {
test('box width is the longitude span at the mid-latitude, never the shortest arc', () => {
const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 });
assert.ok(Math.abs(equator.width - 111.32) < 1e-6);
assert.ok(Math.abs(equator.height - 111.32) < 1e-6);
@@ -160,13 +149,6 @@ test('box width is the longitude span at the mid-latitude; a dateline box uses t
const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 };
assert.ok(boxSideKm(nearlyGlobal).width > 30000);
assert.equal(validateBox(nearlyGlobal).reason, 'too-large');
const crossing = boxSideKm({
west: 179,
south: -0.5,
east: -179,
north: 0.5,
});
assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width));
});
test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => {
@@ -185,12 +167,7 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha
assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1);
assert.equal(boxFromPin(NaN, 0), null);
assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap');
assert.equal(boxFromPin(181, 0), null, 'longitude out of range');
assert.equal(
boxFromPin(0, 0, 400000),
null,
'half-width of 90 degrees or more',
);
assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');
assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');
assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');
});
@@ -321,34 +298,6 @@ test('coverage samples the box corners and centre against the union of footprint
assert.equal(coverageFor(withRings(null), BOX), 'unknown');
});
test('coverage of a dateline box uses the short arc, not the long way', () => {
const box = { west: 179, south: 0, east: -179, north: 1 };
const ring = (west, east, south = -0.1, north = 1.1) => [
[west, south],
[east, south],
[east, north],
[west, north],
];
const withRings = (...rings) => ({
granules: rings.map((footprint) => granule({ footprint })),
});
assert.equal(
coverageFor(withRings(ring(178.5, -178.5)), box),
'full',
'one footprint that crosses ±180',
);
assert.equal(
coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box),
'full',
'a pair split exactly at ±180',
);
assert.equal(
coverageFor(withRings(ring(179, 180)), box),
'partial',
'one side does not cover the other',
);
});
test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => {
const candidates = [
hls('S30', '2026-09-20', [10, null]),
@@ -480,17 +429,6 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e
() => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }),
TypeError,
);
assert.throws(
() =>
wvsSnapshotUrl({
product: 'S30',
day: '2026-09-18',
box: { west: 179, south: 0, east: -179, north: 1 },
width: 64,
height: 64,
}),
/snapshot cannot cross the dateline/,
);
});
test('thumbnails load the focused card, then the visible cards outward, then the margins', () => {
@@ -499,52 +437,3 @@ test('thumbnails load the focused card, then the visible cards outward, then the
assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]);
assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []);
});
test('boxFromPin returns the short-arc box for a pin near the dateline', () => {
const near = (a, b) => Math.abs(a - b) < 1e-6;
const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492
const spanOk = (box) => {
const { width, height } = boxSideKm(box);
assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`);
assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`);
assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span');
};
// 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side.
for (const lon of [179.9, -179.9]) {
const box = boxFromPin(lon, 0);
spanOk(box);
assert.ok(box.west < box.east, `no wrap needed at ${lon}`);
assert.ok(near((box.west + box.east) / 2, lon));
}
// A pin on the line, or close enough that the box passes it, wraps.
for (const lon of [180, -180, 179.99, -179.99]) {
const box = boxFromPin(lon, 0);
spanOk(box);
assert.ok(box.west > box.east, `crossing at ${lon}`);
assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180');
assert.ok(
near(
box.west,
(lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half,
),
);
assert.equal(
nonCrossingBoxes(box).length,
2,
'splits for tiling and Worldview',
);
assert.ok(
Math.abs(
Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon),
) < 1e-6,
);
}
// 0 is an ordinary box.
const mid = boxFromPin(0, 0);
spanOk(mid);
assert.ok(mid.west < mid.east && near(mid.west, -half));
// Off the equator the east-west extent widens but stays a short arc.
const high = boxFromPin(-179.99, 60);
spanOk(high);
assert.ok(high.west > high.east);
});
+24 -97
View File
@@ -1,7 +1,7 @@
/**
* Recent Imagery drapes two slots through the renderer's globe port, slot
* `a` left of a swipe and slot `b` right. Each slot drapes up to two GIBS
* layers, one per available part, on whichever surface the map stack draws.
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
* imagery layers (slot `a`, left of a swipe; slot `b`, right) through the
* renderer's globe port, draped on whichever surface the map stack draws.
* Against the basemap slot `a` splits left and slot `b` stays empty. Tile
* requests pass a small semaphore of our own, shared by both slots, through
* each layer's admission hook; the renderer's own request limits stay
@@ -15,13 +15,7 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { markBaseTileset } from '../../render/baseTilesets.js';
import { drawOf } from '../../render/rendererOf.js';
import {
PRODUCTS,
boxKey,
gibsTemplate,
lonSpanDeg,
nonCrossingBoxes,
} from './model.js';
import { PRODUCTS, gibsTemplate } from './model.js';
const SLOT_IDS = ['a', 'b'];
const SPLITS = new Set(['left', 'right', 'none']);
@@ -35,27 +29,8 @@ function clampAlpha(value) {
return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;
}
/** One comparable key for a slot's draped parts. */
const partsKey = (parts) => parts.map(boxKey).sort().join(';');
/**
* The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would
* draw an empty side black, so it drapes only parts Worldview confirmed
* present, and no part of a dateline box before the probe answers. A PNG
* drapes every part not confirmed empty.
*/
function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) {
const parts = nonCrossingBoxes(box);
const keys = (list) => new Set(list.map(boxKey));
if (PRODUCTS[candidate.product]?.format !== 'jpg') {
if (!Array.isArray(emptyBoxes)) return parts;
const empty = keys(emptyBoxes);
return parts.filter((part) => !empty.has(boxKey(part)));
}
if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts;
const proven = keys(availableBoxes);
return parts.filter((part) => proven.has(boxKey(part)));
}
const boxKey = (box) =>
[box.west, box.south, box.east, box.north].map(Number).join(',');
/**
* Admit a tile request while the semaphore has room. A request that finds
@@ -102,7 +77,7 @@ export function createRecentImageryRenderer({
let host = NO_HOST;
let destroyed = false;
const admission = { limit: maxTileRequests, inFlight: 0 };
/** @type {Record<'a'|'b', null | { layers: Array<object>, globe: object, candidate: object, parts: Array<object>, alpha: number, split: string }>} */
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
const owned = { a: null, b: null };
const admit = admitTileRequests(admission, requestRender);
@@ -130,53 +105,36 @@ export function createRecentImageryRenderer({
const record = owned[slotId];
if (!record) return false;
owned[slotId] = null;
for (const layer of record.layers) layer.remove();
record.layer.remove();
return true;
}
function applyLook(record) {
for (const layer of record.layers) {
layer.alpha = record.alpha;
layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
record.layer.alpha = record.alpha;
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
}
function mount(slotId, { candidate, parts, alpha, split }) {
if (!parts.length) return false;
owned[slotId] = {
layers: parts.map((part) =>
host.globe.imagery.add(specFor(candidate, part)),
),
globe: host.globe,
candidate,
parts,
alpha,
split,
};
function mount(slotId, { candidate, box, alpha, split }) {
const layer = host.globe.imagery.add(specFor(candidate, box));
owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split };
applyLook(owned[slotId]);
return true;
}
return {
/**
* Drape the parts of a candidate's box that the evidence allows (see drapedParts).
* The same candidate on the same port keeps the layer of each unchanged part.
* Drape a candidate into a slot. The same candidate on the same host only
* updates its look; anything else replaces the slot's layer.
* @param {'a'|'b'} slotId
* @param {object} candidate
* @param {object} box Degrees box.
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look]
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]
* @returns {boolean} Whether a layer is now draped for the slot.
*/
showSlot(
slotId,
candidate,
box,
{
alpha = 1,
splitDirection = 'none',
availableBoxes = null,
emptyBoxes = null,
} = {},
{ alpha = 1, splitDirection = 'none' } = {},
) {
if (destroyed || !candidate?.key || !box) return false;
if (!host.globe) {
@@ -185,52 +143,21 @@ export function createRecentImageryRenderer({
}
const current = owned[slotId];
const look = { alpha: clampAlpha(alpha), split: splitDirection };
const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes });
if (
current &&
current.globe === host.globe &&
current.candidate.key === candidate.key &&
parts.length
boxKey(current.box) === boxKey(box)
) {
if (partsKey(current.parts) !== partsKey(parts)) {
const previous = new Map(
current.parts.map((part, i) => [boxKey(part), current.layers[i]]),
);
// A new half goes right above the slot's surviving half, so both
// halves keep the same place against the other slot.
const survivor = parts
.map((part) => previous.get(boxKey(part)))
.find(Boolean);
const at = survivor
? host.globe.imagery.list().indexOf(survivor) + 1
: undefined;
const layers = parts.map((part) => {
const key = boxKey(part);
const layer = previous.get(key);
previous.delete(key);
return (
layer ?? host.globe.imagery.add(specFor(candidate, part), at)
);
});
for (const layer of previous.values()) layer.remove();
Object.assign(current, { layers, parts, ...look });
applyLook(current);
requestRender('recent-imagery-show');
} else if (
current.alpha !== look.alpha ||
current.split !== look.split
) {
if (current.alpha !== look.alpha || current.split !== look.split) {
Object.assign(current, look);
applyLook(current);
requestRender('recent-imagery-look');
}
return true;
}
const removed = removeOwned(slotId);
if (!mount(slotId, { candidate, parts, ...look })) {
if (removed) requestRender('recent-imagery-hide');
return false;
}
removeOwned(slotId);
mount(slotId, { candidate, box, ...look });
requestRender('recent-imagery-show');
return true;
},
@@ -294,7 +221,7 @@ export function createRecentImageryRenderer({
return out;
},
/** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */
/** Number of layers this renderer owns (never above two). */
ownedCount() {
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
},
@@ -320,11 +247,11 @@ let previewSeq = 0;
/** A box with no area has no fill: a press, or a drag along one axis. */
const hasArea = (box) =>
Boolean(box) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south;
Boolean(box) && box.east > box.west && box.north > box.south;
/** A box with no extent draws nothing: a press that has not moved yet. */
const hasExtent = (box) =>
Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south);
Boolean(box) && (box.east > box.west || box.north > box.south);
/**
* The box tool's preview: the box being dragged, a translucent fill and a
+1 -210
View File
@@ -5,9 +5,7 @@ import {
createImageryBoxPreview,
createRecentImageryRenderer,
} from './rendering.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { boxKey, nonCrossingBoxes } from './model.js';
import { BOX, FIJI_BOX } from './testDoubles.mjs';
import { BOX } from './testDoubles.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
@@ -273,210 +271,3 @@ test('the box preview draws a ground fill and a draped dashed edge, hidden rathe
box = { west: -96, south: 32, east: -95, north: 33 };
assert.doesNotThrow(() => preview.changed());
});
test('a dateline box drapes one layer on each side of ±180 and removes both', () => {
const { renderer, globe } = fixture();
const box = { west: 179, south: 0, east: -179, north: 1 };
assert.equal(
renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }),
true,
);
assert.equal(renderer.ownedCount(), 1);
assert.equal(globe.layers.length, 2);
assert.deepEqual(
globe.layers.map((item) => item.spec.rectangle),
[
{ west: 179, south: 0, east: 180, north: 1 },
{ west: -180, south: 0, east: -179, north: 1 },
],
);
assert.equal(globe.layers[0].alpha, 0.4);
assert.equal(globe.layers[1].alpha, 0.4);
assert.equal(globe.layers[0].split, 'left');
assert.equal(globe.layers[1].split, 'left');
renderer.setAlpha('a', 0.2);
assert.equal(globe.layers[0].alpha, 0.2);
assert.equal(globe.layers[1].alpha, 0.2);
renderer.showSlot('a', S30, box, { alpha: 0.2 });
assert.equal(globe.added.length, 2, 'the same box does not remount');
renderer.hideSlot('a');
assert.equal(globe.layers.length, 0);
});
test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => {
const { renderer, globe } = fixture();
const [west, east] = nonCrossingBoxes(FIJI_BOX);
assert.equal(
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }),
true,
);
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
[east],
);
renderer.showSlot('b', VIIRS, FIJI_BOX, {
availableBoxes: [east, west],
splitDirection: 'right',
});
assert.deepEqual(
globe.layers.map((layer) => layer.split),
['none', 'right', 'right'],
);
assert.equal(globe.layers.length, 3);
const next = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe: next });
assert.deepEqual(
next.layers.map((layer) => layer.spec.rectangle),
[east, west, east],
);
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] });
assert.equal(next.layers.length, 4);
renderer.destroy();
assert.equal(next.layers.length, 0);
});
test('no allowed half, or halves of another box, drapes nothing', () => {
const { renderer, globe } = fixture();
for (const availableBoxes of [[], [BOX]]) {
assert.equal(
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }),
false,
);
assert.equal(globe.layers.length, 0);
}
});
test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => {
const { renderer, globe } = fixture();
assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false);
assert.equal(globe.layers.length, 0);
assert.equal(renderer.showSlot('a', VIIRS, BOX), true);
assert.equal(globe.layers.length, 1);
assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true);
assert.equal(globe.layers.length, 3);
renderer.destroy();
});
test('evidence going from none to empty removes the drape', () => {
const { renderer, globe } = fixture();
renderer.showSlot('a', S30, FIJI_BOX);
assert.equal(globe.layers.length, 2);
assert.equal(
renderer.showSlot('a', S30, FIJI_BOX, {
availableBoxes: [],
emptyBoxes: nonCrossingBoxes(FIJI_BOX),
}),
false,
);
assert.equal(globe.layers.length, 0);
renderer.destroy();
});
test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => {
const [west, east] = nonCrossingBoxes(FIJI_BOX);
for (const [product, expected] of [
[S30, [west, east]],
[VIIRS, [east]],
]) {
const { renderer, globe } = fixture();
renderer.showSlot('a', product, FIJI_BOX, {
availableBoxes: [east],
emptyBoxes: [],
});
assert.deepEqual(
globe.layers.map((layer) => layer.spec.rectangle),
expected,
);
renderer.destroy();
}
});
test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => {
const renderer = createRecentImageryRenderer();
const globe = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe });
const [west, east] = nonCrossingBoxes(FIJI_BOX);
const layerFor = (box) =>
globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box));
// An HLS day drapes both halves before its probe answers.
renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' });
const kept = layerFor(west);
assert.ok(kept);
const added = globe.added.length;
// The probe confirms the east half empty: only the east layer goes.
renderer.showSlot('a', S30, FIJI_BOX, {
alpha: 0.4,
splitDirection: 'left',
availableBoxes: [west],
emptyBoxes: [east],
});
assert.equal(kept.removed, false, 'the west layer survives the narrowing');
assert.equal(globe.added.length, added, 'narrowing adds no layer');
assert.equal(layerFor(east), undefined);
// A later probe admits east again: only the east layer is added.
renderer.showSlot('a', S30, FIJI_BOX, {
alpha: 0.4,
splitDirection: 'left',
availableBoxes: [west, east],
emptyBoxes: [],
});
assert.equal(kept.removed, false, 'the west layer survives the widening');
assert.equal(globe.added.length, added + 1);
assert.equal(kept.alpha, 0.4);
assert.equal(kept.split, 'left');
renderer.destroy();
});
test('widening slot a over the dateline keeps it below slot b on both sides', () => {
const { renderer, globe } = fixture();
const [west, east] = nonCrossingBoxes(FIJI_BOX);
const topOn = (box) =>
globe.layers
.filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box))
.at(-1)
.spec.url.includes('S30')
? 'A'
: 'B';
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] });
renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] });
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] });
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
renderer.destroy();
});
test('the drag preview draws a wrapped fill and outline across the dateline', async () => {
const draw = fakeDrawPort();
let box = { west: 179, south: 0, east: 179, north: 0 };
const preview = createImageryBoxPreview({}, () => box, { draw });
const [fills, outlines] = draw.sets.values();
preview.setVisible(true);
box = { ...box, east: -179 };
preview.changed();
assert.equal(fills.items.size, 0);
assert.equal(outlines.items.get('edge').show, true);
assert.deepEqual(
outlines.items.get('edge').positions[1],
fromDegrees(-179, 0),
);
box = { ...box, north: 1 };
preview.changed();
assert.equal(fills.items.get('box').show, true);
assert.deepEqual(fills.items.get('box').geometry.rect, box);
const edge = outlines.items.get('edge');
assert.equal(edge.show, true);
assert.deepEqual(edge.positions, [
fromDegrees(179, 0),
fromDegrees(-179, 0),
fromDegrees(-179, 1),
fromDegrees(179, 1),
fromDegrees(179, 0),
]);
await preview.destroy();
});
+11 -152
View File
@@ -1,107 +1,10 @@
import { searchHls } from './catalog.js';
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
/**
* Deadline for one half's response headers, so a day whose other half
* answered is not held at "checking".
*/
const DEFAULT_HALF_DEADLINE_MS = 15_000;
/**
* Worldview Snapshots rejects a BBOX with west > east, so a dateline box is
* probed as its two non-crossing halves, wider first. A plain box is its
* one normalized half. A day has data when either half does.
*/
function requestBoxes(box) {
return nonCrossingBoxes(box).sort(
(a, b) => b.east - b.west - (a.east - a.west),
);
}
/** A response's Data-Present answer in lower case, or '' when it failed or has none. */
export const dataPresent = (response) =>
response?.ok
? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase()
: '';
/**
* One half's snapshot fetch, raced against its own deadline so a half that
* never answers, even over a transport that ignores AbortSignal, still
* settles. Its deadline cancels only this half. The caller can cancel it
* at any time, including while its body is being read.
*/
function probeHalf(
url,
{ fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl },
) {
const controller = new AbortController();
return new Promise((resolve, reject) => {
let timer = null;
const finishTimeout = () => {
if (timer !== null) clearTimeoutImpl(timer);
timer = null;
};
const stop = (reason) => {
controller.abort(reason);
finishTimeout();
// Settle even if the transport ignores abort.
reject(reason);
};
if (signal?.aborted) {
stop(signal.reason);
return;
}
signal?.addEventListener('abort', () => stop(signal.reason), {
once: true,
});
if (deadlineMs > 0)
timer = setTimeoutImpl(
() =>
stop(new DOMException('Thumbnail half timed out', 'TimeoutError')),
deadlineMs,
);
let promise;
try {
promise = Promise.resolve(fetchImpl(url, { signal: controller.signal }));
} catch (error) {
finishTimeout();
reject(error);
return;
}
promise.then(
(value) => {
finishTimeout();
resolve(value);
},
(error) => {
finishTimeout();
reject(error);
},
);
});
}
/**
* Non-enumerable per-half evidence for the box's non-crossing halves:
* presentBoxes lists the halves Worldview confirmed present, emptyBoxes
* the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js.
*/
function withHalves(response, { presentBoxes, emptyBoxes }) {
Object.defineProperties(response, {
presentBoxes: { value: presentBoxes, configurable: true },
emptyBoxes: { value: emptyBoxes, configurable: true },
});
return response;
}
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
/**
* NASA-compatible imagery acquisition; transport and URL builders are replaceable.
* Thumbnail responses must expose Data-Present: true for image admission, or
* false for confirmed empty coverage, including injected getThumbnail sources.
* getThumbnail also sets presentBoxes and emptyBoxes (see withHalves),
* also on the error it throws when another half was confirmed empty.
* Without per-half evidence the renderer drapes every side of an HLS
* dateline box and no side of a VIIRS one.
*/
export function createRecentImagerySource({
fetchImpl = (...args) => globalThis.fetch(...args),
@@ -109,68 +12,24 @@ export function createRecentImagerySource({
thumbnailUrl = wvsSnapshotUrl,
tileTemplate = gibsTemplate,
credit = 'NASA GIBS',
halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS,
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
clearTimeoutImpl = (id) => globalThis.clearTimeout(id),
} = {}) {
return {
credit,
searchHls: (query) => search({ ...query, fetchImpl }),
async getThumbnail(candidate, box, { size = 256, signal } = {}) {
signal?.throwIfAborted();
const halves = requestBoxes(box);
const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0;
const results = await Promise.allSettled(
halves.map((half) =>
probeHalf(
thumbnailUrl({
product: candidate.product,
day: candidate.day,
box: half,
width: size,
height: size,
}),
{
fetchImpl,
signal,
deadlineMs,
setTimeoutImpl,
clearTimeoutImpl,
},
),
),
const response = await fetchImpl(
thumbnailUrl({
product: candidate.product,
day: candidate.day,
box,
width: size,
height: size,
}),
{ signal },
);
signal?.throwIfAborted();
// Per half, its Data-Present answer or null when it did not answer.
const answers = results.map((result) =>
result.status === 'fulfilled' ? dataPresent(result.value) : null,
);
const halvesWhere = (value) =>
halves.filter((_, i) => answers[i] === value);
// A missing answer is an error unless another half proved data. The
// error keeps a half confirmed empty (see withHalves).
const failure = results.find((result) => result.status === 'rejected');
if (failure && !answers.includes('true')) {
const emptyBoxes = halvesWhere('false');
if (Object.isExtensible(failure.reason))
withHalves(
failure.reason,
emptyBoxes.length
? { presentBoxes: [], emptyBoxes }
: { presentBoxes: null, emptyBoxes: null },
);
throw failure.reason;
}
// Show the first half with data (the wider wins a tie), else the first
// not confirmed empty, so an unreadable answer is never called empty.
// Every half answered here unless one proved data.
let shown = answers.indexOf('true');
if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false');
if (shown < 0) shown = 0;
return withHalves(results[shown].value, {
presentBoxes: halvesWhere('true'),
emptyBoxes: halvesWhere('false'),
});
return response;
},
getTileTemplate: (product, day) => tileTemplate(product, day),
};
+10 -253
View File
@@ -1,20 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { manualTimers } from './testDoubles.mjs';
import { createRecentImagerySource } from './source.js';
test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => {
const controller = new AbortController();
const query = {
box: { west: 0, east: 1, south: 0, north: 1 },
signal: controller.signal,
};
const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal };
const candidate = { product: 'S30', day: '2026-10-01' };
const calls = [];
const fetchImpl = async (...args) => {
calls.push(args);
return new Response('image');
};
const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); };
const source = createRecentImagerySource({
fetchImpl,
search: async (request) => {
@@ -23,263 +16,27 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt
assert.equal(request.box, query.box);
return [candidate];
},
thumbnailUrl: ({ product, day, width }) =>
`https://imagery.example/${product}/${day}/${width}`,
tileTemplate: (product, day) =>
`https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`,
tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
credit: 'Example imagery',
});
assert.deepEqual(await source.searchHls(query), [candidate]);
assert.equal(
await (
await source.getThumbnail(candidate, query.box, {
signal: controller.signal,
})
).text(),
'image',
);
assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image');
assert.equal(calls.length, 1);
assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256');
// The fetch gets a private signal chained to the caller's.
const halfSignal = calls[0][1].signal;
assert.notEqual(halfSignal, controller.signal);
assert.equal(halfSignal.aborted, false);
controller.abort();
assert.equal(halfSignal.aborted, true);
assert.equal(
source.getTileTemplate(candidate.product, candidate.day),
'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}',
);
assert.equal(calls[0][1].signal, controller.signal);
assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}');
assert.equal(source.credit, 'Example imagery');
});
test('cancelled thumbnail acquisition does not return stale responses or retry', async () => {
const controller = new AbortController();
const box = { west: 0, south: 0, east: 1, north: 1 };
let calls = 0;
const source = createRecentImagerySource({
thumbnailUrl: () => 'https://imagery.example/thumbnail',
fetchImpl: async () => {
calls++;
controller.abort();
return new Response('image');
},
fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); },
});
await assert.rejects(
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
assert.equal(calls, 1);
});
test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => {
const requested = [];
const source = createRecentImagerySource({
thumbnailUrl: ({ box }) => {
requested.push(box);
return 'https://imagery.example/thumbnail';
},
fetchImpl: async () => new Response('image'),
});
const candidate = { product: 'S30', day: '2026-10-01' };
await source.getThumbnail(candidate, {
west: 179.9,
south: 0,
east: -179,
north: 1,
});
assert.deepEqual(requested, [
{ west: -180, south: 0, east: -179, north: 1 },
{ west: 179.9, south: 0, east: 180, north: 1 },
]);
requested.length = 0;
await source.getThumbnail(candidate, {
west: 179,
south: 0,
east: -179.9,
north: 1,
});
assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 });
assert.equal(requested.length, 2);
assert.ok(requested.every((box) => box.west <= box.east));
});
const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 };
// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG.
const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' };
const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 };
const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 };
const dated = (present, body = 'image') =>
new Response(body, { headers: { 'Data-Present': present } });
function halvesSource(answers, options = {}) {
const requested = [];
const source = createRecentImagerySource({
...options,
thumbnailUrl: ({ box }) =>
`https://imagery.example/${box.west}/${box.east}`,
fetchImpl: async (url) => {
requested.push(url);
const answer = answers[url.split('imagery.example/')[1]];
if (answer instanceof Error) throw answer;
return answer.clone ? answer : answer();
},
});
return { source, requested };
}
const candidate = { product: 'S30', day: '2026-10-01' };
test('a crossing box probes both halves and is present when only the narrow half has data', async () => {
const { source, requested } = halvesSource({
'-180/-179': dated('false'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(requested.length, 2);
assert.equal(response.headers.get('Data-Present'), 'true');
assert.equal(await response.text(), 'narrow');
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
assert.deepEqual(response.emptyBoxes, [WIDE_BOX]);
});
test('a crossing box with data only on the wider half is present and shows the wider side', async () => {
const { source } = halvesSource({
'-180/-179': dated('true', 'wide'),
'179.9/180': dated('false'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(await response.text(), 'wide');
});
test('a crossing box is empty only when both halves are confirmed empty', async () => {
const { source } = halvesSource({
'-180/-179': dated('false'),
'179.9/180': dated('false'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(response.headers.get('Data-Present'), 'false');
assert.deepEqual(response.presentBoxes, []);
assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]);
});
test('a crossing box is not called empty when the other half failed', async () => {
const { source } = halvesSource({
'-180/-179': dated('false'),
'179.9/180': () => new Response('x', { status: 503 }),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(response.ok, false);
});
test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => {
const { source } = halvesSource({
'-180/-179': dated('true', 'wide'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(await response.text(), 'wide');
assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]);
});
test('a rejected half does not hide data on the other half, and never reads as empty', async () => {
const { source } = halvesSource({
'-180/-179': new Error('network'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(candidate, NARROW_WEST);
assert.equal(await response.text(), 'narrow');
const failing = halvesSource({
'-180/-179': new Error('network'),
'179.9/180': dated('false'),
});
await assert.rejects(
failing.source.getThumbnail(candidate, NARROW_WEST),
/network/,
);
});
for (const [label, answer] of [
['rejected', new Error('network')],
['hung', () => new Promise(() => {})],
['answered without a presence', () => dated('unknown', 'maybe')],
]) {
for (const product of [JPEG_CANDIDATE, candidate]) {
test(`a ${product.product} half that ${label} is neither present nor empty`, async () => {
const { source } = halvesSource(
{ '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') },
{ halfDeadlineMs: 20 },
);
const response = await source.getThumbnail(product, NARROW_WEST);
assert.equal(response.headers.get('Data-Present'), 'true');
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
assert.deepEqual(response.emptyBoxes, []);
});
}
}
test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => {
const controller = new AbortController();
const source = createRecentImagerySource({
thumbnailUrl: () => 'https://example.invalid/',
halfDeadlineMs: 10000,
fetchImpl: () => {
controller.abort();
return new Promise(() => {});
},
});
const outcome = await Promise.race([
source
.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal })
.then(
() => 'resolved',
(error) => error.name,
),
new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)),
]);
assert.equal(outcome, 'AbortError');
});
test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => {
const hang = () => new Promise(() => {});
const { source, requested } = halvesSource(
{ '-180/-179': hang, '179.9/180': hang },
{ halfDeadlineMs: 10 },
);
await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), {
name: 'TimeoutError',
});
assert.equal(requested.length, 2);
});
test("the caller's cancellation rejects at once and stops every half", async () => {
const aborted = [];
const source = createRecentImagerySource({
thumbnailUrl: ({ box }) => String(box.west),
fetchImpl: (url, { signal }) => {
signal.addEventListener('abort', () => aborted.push(url), { once: true });
return new Promise(() => {});
},
});
const controller = new AbortController();
const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, {
signal: controller.signal,
});
controller.abort();
await assert.rejects(result, { name: 'AbortError' });
assert.deepEqual(aborted, ['-180', '179.9']);
});
test('a successful probe leaves no deadline timer behind', async () => {
const timers = manualTimers();
const { source } = halvesSource(
{ '-180/-179': dated('true'), '179.9/180': dated('false') },
timers,
);
await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
assert.equal(timers.armed(), 0);
assert.equal(timers.cleared.length, 2);
});
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff. Show more