mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 11:42:21 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc77f265a8 |
No files matched your search
+1
-1
@@ -44,7 +44,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 | 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; 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)" |
|
||||
| **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 |
|
||||
|
||||
@@ -443,7 +443,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 and reported containment | WFIGS / NIFC | 🟢 |
|
||||
| 🔥 **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 | 🟢 |
|
||||
| 🚢 **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 | 🟢 |
|
||||
|
||||
@@ -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,6 +0,0 @@
|
||||
- The app opens with the loading screen's logo turning into the globe: the
|
||||
eye's arcs fly out, the planet in the pupil becomes the real globe, which
|
||||
spins, grows and stops with the whole planet in view over your country, taken
|
||||
from the browser's time zone. The title's logo goes back to that view. A
|
||||
share link, a Stories link, reduced motion and `?intro=0` open as before
|
||||
(gekh, #1909).
|
||||
+20
-15
@@ -1123,17 +1123,18 @@ 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 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`.
|
||||
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`.
|
||||
|
||||
## Scope display controls
|
||||
|
||||
@@ -6404,7 +6405,11 @@ 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. Unchanged snapshots retain geometry; link checks cancel on disable or selection change, and the row legend shows reported containment.
|
||||
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. `analyst_query` counts `ageHours` from `at` too.
|
||||
|
||||
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`.
|
||||
|
||||
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
|
||||
@@ -8890,10 +8895,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).
|
||||
|
||||
+1
-1
@@ -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 |
|
||||
| `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_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,101 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
// Writes src/data/homeCountries.js: each time zone's country, and where the
|
||||
// opening stops over that country.
|
||||
//
|
||||
// node scripts/build-home-countries.mjs [path/to/zone.tab]
|
||||
//
|
||||
// Zones come from tzdata's zone.tab (macOS and most Linux systems ship it at
|
||||
// /usr/share/zoneinfo/zone.tab), with the older names ICU still reports for
|
||||
// some of them (Asia/Calcutta for Asia/Kolkata): a browser may give either.
|
||||
// A country's point is the centroid of its largest part in the Natural Earth
|
||||
// countries pack (the contiguous United States, mainland France), or the
|
||||
// zone's own place where the pack has no such country.
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { geometryOf } from '../src/data/adminBoundaries.js';
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const zoneTab = process.argv[2] ?? '/usr/share/zoneinfo/zone.tab';
|
||||
const pack = JSON.parse(
|
||||
readFileSync(
|
||||
new URL('src/data/local_data/natural_earth/countries.json', root),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const out = new URL('src/data/homeCountries.js', root);
|
||||
|
||||
const round = (value) => Math.round(value * 10) / 10;
|
||||
|
||||
/** ISO 6709 `±DDMM[SS]±DDDMM[SS]` → [lat, lon]. */
|
||||
function iso6709(text) {
|
||||
const [, lat, lon] = text.match(/^([+-]\d+)([+-]\d+)$/);
|
||||
const part = (s, degreeDigits) => {
|
||||
const sign = s[0] === '-' ? -1 : 1;
|
||||
const d = s.slice(1);
|
||||
const deg = Number(d.slice(0, degreeDigits));
|
||||
const min = Number(d.slice(degreeDigits, degreeDigits + 2));
|
||||
const sec = Number(d.slice(degreeDigits + 2) || 0);
|
||||
return sign * (deg + min / 60 + sec / 3600);
|
||||
};
|
||||
return [part(lat, 2), part(lon, 3)];
|
||||
}
|
||||
|
||||
const largest = new Map();
|
||||
for (const feature of pack.features) {
|
||||
if (feature.type !== 'Country' || !/^[A-Z]{2}$/.test(feature.iso2)) continue;
|
||||
const geometry = geometryOf({ feature, decimals: pack.meta.decimals });
|
||||
const held = largest.get(feature.iso2);
|
||||
if (!held || geometry.areaKm2 > held.areaKm2)
|
||||
largest.set(feature.iso2, geometry);
|
||||
}
|
||||
|
||||
const zones = new Map();
|
||||
const centres = new Map();
|
||||
const icuName = (zone) => {
|
||||
try {
|
||||
return new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions()
|
||||
.timeZone;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
for (const line of readFileSync(zoneTab, 'utf8').split('\n')) {
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const [country, place, zone] = line.split('\t');
|
||||
zones.set(zone, country);
|
||||
const icu = icuName(zone);
|
||||
if (icu && icu !== zone && !zones.has(icu)) zones.set(icu, country);
|
||||
if (centres.has(country)) continue;
|
||||
const label = largest.get(country)?.label;
|
||||
centres.set(
|
||||
country,
|
||||
label ? [round(label.lat), round(label.lon)] : iso6709(place).map(round),
|
||||
);
|
||||
}
|
||||
|
||||
const sortedEntries = (map) =>
|
||||
[...map].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
const lines = [
|
||||
'// Generated by scripts/build-home-countries.mjs. Do not edit by hand.',
|
||||
'// Sources: tzdata zone.tab (public domain) and the Natural Earth countries',
|
||||
'// pack in src/data/local_data/natural_earth (public domain).',
|
||||
'',
|
||||
'/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */',
|
||||
'export const COUNTRY_CENTRES = {',
|
||||
...sortedEntries(centres).map(
|
||||
([country, [lat, lon]]) => ` ${country}: [${lat}, ${lon}],`,
|
||||
),
|
||||
'};',
|
||||
'',
|
||||
'/** Time zone (tzdata and ICU names) → ISO 3166 country. */',
|
||||
'export const ZONE_COUNTRIES = {',
|
||||
...sortedEntries(zones).map(
|
||||
([zone, country]) => ` '${zone}': '${country}',`,
|
||||
),
|
||||
'};',
|
||||
'',
|
||||
];
|
||||
writeFileSync(out, lines.join('\n'));
|
||||
console.log(
|
||||
`${fileURLToPath(out)}: ${centres.size} countries, ${zones.size} zones`,
|
||||
);
|
||||
@@ -469,6 +469,8 @@
|
||||
"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",
|
||||
|
||||
@@ -279,6 +279,7 @@
|
||||
"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",
|
||||
@@ -4303,7 +4304,6 @@
|
||||
"src/render/contract/index.js",
|
||||
"src/sources/sourceSlot.js",
|
||||
"src/app/sources.js",
|
||||
"src/app/openingIntro.js",
|
||||
"src/app/startupChrome.js",
|
||||
"src/app/stateChannel.js",
|
||||
"src/app/surfaceServices.js",
|
||||
@@ -8191,6 +8191,7 @@
|
||||
"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",
|
||||
|
||||
@@ -23,6 +23,7 @@ const API_URL =
|
||||
'attr_IncidentTypeCategory',
|
||||
'attr_FireDiscoveryDateTime',
|
||||
'poly_DateCurrent',
|
||||
'poly_PolygonDateTime',
|
||||
'attr_FireCause',
|
||||
'attr_FireBehaviorGeneral',
|
||||
'attr_TotalIncidentPersonnel',
|
||||
|
||||
@@ -67,6 +67,8 @@ 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,
|
||||
@@ -75,6 +77,7 @@ export function createApplicationCatalog({
|
||||
metadata = APPLICATION_LAYER_METADATA,
|
||||
vesselOptions,
|
||||
newsOptions,
|
||||
perimeterOptions,
|
||||
resolveAsset,
|
||||
nepalBoundaryResolver,
|
||||
streetLevelProviders,
|
||||
@@ -145,6 +148,7 @@ export function createApplicationCatalog({
|
||||
createApplicationEarthquakes({ source: sources.earthquakes }),
|
||||
createApplicationAirQuality({ source: sources['air-quality'] }),
|
||||
createApplicationFirePerimeters({
|
||||
...perimeterOptions,
|
||||
source: sources['fire-perimeters'],
|
||||
}),
|
||||
createApplicationGnssIntegrity({
|
||||
|
||||
@@ -7,6 +7,8 @@ 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();
|
||||
@@ -254,3 +256,48 @@ 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')),
|
||||
[],
|
||||
);
|
||||
});
|
||||
@@ -6,8 +6,11 @@ import {
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import * as overlays from '../../overlays/worldOverlay.js';
|
||||
|
||||
/** Wire WFIGS fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters(options) {
|
||||
/** Wire fire perimeters into the application catalog. */
|
||||
export function createApplicationFirePerimeters({
|
||||
inciweb = true,
|
||||
...options
|
||||
} = {}) {
|
||||
return createFirePerimetersLayer({
|
||||
overlayHost: {
|
||||
setEntries: overlays.setOverlayEntries,
|
||||
@@ -15,10 +18,17 @@ export function createApplicationFirePerimeters(options) {
|
||||
clearSource: overlays.clearOverlaySource,
|
||||
hitTest: overlays.hitTestWorldOverlay,
|
||||
},
|
||||
inciwebSource: createInciwebIndexSource(),
|
||||
inciwebPublications: createInciwebPublicationSource(),
|
||||
...(inciweb !== false && {
|
||||
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,
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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,281 +0,0 @@
|
||||
import { cameraOf } from '../render/rendererOf.js';
|
||||
|
||||
/**
|
||||
* The opening: once the world has loaded, the loading screen's logo turns
|
||||
* into the globe. The words fade and the logo glides to the centre; the eye's
|
||||
* arcs fly at the viewer; the drawn planet in the pupil gives way to the real
|
||||
* one, drawn the same size behind it; the real one spins and grows, slowing
|
||||
* until it stops, the whole planet in view, over the start view (the
|
||||
* visitor's country). Everything is timed from one clock, in ms.
|
||||
*/
|
||||
export const OPENING = Object.freeze({
|
||||
/** The words fade and the logo moves to the centre. */
|
||||
centreMs: 450,
|
||||
// The rest is timed from the end of the move.
|
||||
/** The arcs grow and fade. */
|
||||
arcsMs: 700,
|
||||
/** The background clears to the globe. */
|
||||
veilMs: Object.freeze([200, 700]),
|
||||
/** The drawn planet fades into the real one. */
|
||||
pupilMs: Object.freeze([500, 1100]),
|
||||
/** The camera's flight in. */
|
||||
flightStartMs: 300,
|
||||
flightMs: 4200,
|
||||
/** How far the globe turns on the way in, degrees. */
|
||||
spinDeg: 360,
|
||||
});
|
||||
|
||||
const EARTH_RADIUS_M = 6371000;
|
||||
// logo.svg: its viewBox width and the drawn planet's radius, in its units.
|
||||
const LOGO_WIDTH = 775;
|
||||
const PUPIL_RADIUS = 120.33;
|
||||
/** Never start further out than this, metres. */
|
||||
const MAX_FAR_HEIGHT_M = 4e8;
|
||||
|
||||
/** Openings in progress on this page. */
|
||||
let playing = 0;
|
||||
|
||||
/**
|
||||
* Whether an opening is playing: the far start shows the globe as a speck,
|
||||
* which the globe-in-view recovery would otherwise turn the camera back to.
|
||||
*/
|
||||
export function openingPlaying() {
|
||||
return playing > 0;
|
||||
}
|
||||
|
||||
const clamp01 = (x) => Math.min(1, Math.max(0, x));
|
||||
const easeInCubic = (x) => x ** 3;
|
||||
const easeOutCubic = (x) => 1 - (1 - x) ** 3;
|
||||
const easeInOutCubic = (x) =>
|
||||
x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;
|
||||
const span = (t, [from, to]) => clamp01((t - from) / (to - from));
|
||||
|
||||
/**
|
||||
* Where each part of the opening stands `t` ms after it starts.
|
||||
* @param {number} t
|
||||
*/
|
||||
export function openingStage(t, timing = OPENING) {
|
||||
const move = clamp01(t / timing.centreMs);
|
||||
const after = t - timing.centreMs;
|
||||
const arcs = easeInCubic(clamp01(after / timing.arcsMs));
|
||||
const flight = clamp01((after - timing.flightStartMs) / timing.flightMs);
|
||||
return {
|
||||
/** The words' opacity. */
|
||||
text: 1 - move,
|
||||
/** How far the logo has moved to the centre, 0–1. */
|
||||
centre: easeInOutCubic(move),
|
||||
arcsScale: 1 + 5 * arcs,
|
||||
arcsOpacity: 1 - arcs,
|
||||
/** The loading screen's background opacity. */
|
||||
veil: 1 - span(after, timing.veilMs),
|
||||
pupilOpacity: 1 - span(after, timing.pupilMs),
|
||||
/** The flight's progress, 0–1. */
|
||||
flight,
|
||||
done: flight >= 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera `flight` (0–1) of the way in: from `farHeight` over the
|
||||
* equator, a turn of `spinDeg` west to east that slows to a stop over
|
||||
* `target`, closing in on `target.height`.
|
||||
*/
|
||||
export function openingPose(
|
||||
flight,
|
||||
{ target, farHeight, spinDeg = OPENING.spinDeg },
|
||||
) {
|
||||
const f = clamp01(flight);
|
||||
const closing = easeInOutCubic(f);
|
||||
const height = Math.exp(
|
||||
Math.log(farHeight) +
|
||||
(Math.log(target.height) - Math.log(farHeight)) * closing,
|
||||
);
|
||||
const lon = target.lon + spinDeg * (1 - easeOutCubic(f));
|
||||
return {
|
||||
lon: ((((lon + 180) % 360) + 360) % 360) - 180,
|
||||
lat: target.lat * closing,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The globe's radius on screen, pixels, from `height` metres straight above
|
||||
* it, through a lens of vertical angle `fovy` on a view `viewportHeight`
|
||||
* pixels tall.
|
||||
*/
|
||||
export function globeRadiusPx(height, { fovy, viewportHeight }) {
|
||||
const angle = Math.asin(EARTH_RADIUS_M / (EARTH_RADIUS_M + height));
|
||||
return (Math.tan(angle) / Math.tan(fovy / 2)) * (viewportHeight / 2);
|
||||
}
|
||||
|
||||
/** The height at which the globe's radius on screen is `radiusPx`. */
|
||||
export function heightForGlobeRadius(radiusPx, { fovy, viewportHeight }) {
|
||||
const tangent = (radiusPx * Math.tan(fovy / 2)) / (viewportHeight / 2);
|
||||
return EARTH_RADIUS_M / Math.sin(Math.atan(tangent)) - EARTH_RADIUS_M;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page opens with the opening: not where motion is reduced, not
|
||||
* on a Stories link (Stories opens its own view) and not with `?intro=0`.
|
||||
*/
|
||||
export function openingWanted(win = globalThis.window) {
|
||||
if (!win) return false;
|
||||
if (win.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
|
||||
return false;
|
||||
const params = new URLSearchParams(win.location?.search ?? '');
|
||||
return !(
|
||||
params.get('intro') === '0' ||
|
||||
params.has('story') ||
|
||||
params.has('stories')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Play the opening over `loadingScreen`, from where the camera stands (the
|
||||
* start view). Returns null when it does not play; else `done`, which
|
||||
* settles when the camera has stopped, and `cancel()`. A click, a key or the
|
||||
* wheel skips to the start view; any other camera move stops it where it is. The loading
|
||||
* screen is `hidden` once the real globe shows, or at once on a cancel.
|
||||
* @param {{viewer: object, loadingScreen: HTMLElement, win?: Window,
|
||||
* camera?: object}} options `camera` is the viewer's camera port unless given.
|
||||
*/
|
||||
export function playOpeningIntro({
|
||||
viewer,
|
||||
loadingScreen,
|
||||
win = globalThis.window,
|
||||
camera = null,
|
||||
}) {
|
||||
if (!openingWanted(win)) return null;
|
||||
try {
|
||||
camera ??= cameraOf(viewer);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const target = camera.pose();
|
||||
if (
|
||||
!Number.isFinite(target?.height) ||
|
||||
!Number.isFinite(target.lon) ||
|
||||
!Number.isFinite(target.lat)
|
||||
)
|
||||
return null;
|
||||
const doc = loadingScreen.ownerDocument;
|
||||
const logo = loadingScreen.querySelector('.loader-logo');
|
||||
const svg = logo?.querySelector('svg');
|
||||
const part = (id) => svg?.querySelector(`#${id}`);
|
||||
const arcs = [part('outer_eye'), part('inner_eye')].filter(Boolean);
|
||||
// The drawn planet; the whole logo where it is an <img>.
|
||||
const pupil = svg
|
||||
? [part('globe'), part('globe_cage')].filter(Boolean)
|
||||
: [logo].filter(Boolean);
|
||||
|
||||
loadingScreen.classList.add('opening');
|
||||
playing += 1;
|
||||
// The planet looks out of the middle of the eye again.
|
||||
for (const element of pupil) element.style.transform = 'none';
|
||||
const globe = part('globe');
|
||||
const pupilRect = (globe ?? logo)?.getBoundingClientRect();
|
||||
const view = (
|
||||
doc.getElementById('cesiumContainer') ?? doc.documentElement
|
||||
).getBoundingClientRect();
|
||||
const viewportHeight = view.height || win.innerHeight;
|
||||
const aspect = (view.width || win.innerWidth) / viewportHeight;
|
||||
// Cesium's default lens: 60° across the wider side.
|
||||
const fovy = Number.isFinite(target.fovy)
|
||||
? target.fovy
|
||||
: aspect > 1
|
||||
? 2 * Math.atan(Math.tan(Math.PI / 6) / aspect)
|
||||
: Math.PI / 3;
|
||||
const lens = { fovy, viewportHeight };
|
||||
const pupilRadius = pupilRect
|
||||
? globe
|
||||
? pupilRect.width / 2
|
||||
: (pupilRect.width * PUPIL_RADIUS) / LOGO_WIDTH
|
||||
: 20;
|
||||
const farHeight = Math.min(
|
||||
MAX_FAR_HEIGHT_M,
|
||||
Math.max(target.height * 2, heightForGlobeRadius(pupilRadius, lens)),
|
||||
);
|
||||
const toCentre = pupilRect
|
||||
? {
|
||||
x: view.left + view.width / 2 - (pupilRect.left + pupilRect.width / 2),
|
||||
y: view.top + view.height / 2 - (pupilRect.top + pupilRect.height / 2),
|
||||
}
|
||||
: { x: 0, y: 0 };
|
||||
const startRadius = globeRadiusPx(farHeight, lens);
|
||||
|
||||
let driving = false;
|
||||
const place = (pose, heading = 0, pitch = -Math.PI / 2) => {
|
||||
driving = true;
|
||||
try {
|
||||
camera.setView({
|
||||
destination: pose,
|
||||
orientation: { heading, pitch, roll: 0 },
|
||||
});
|
||||
} finally {
|
||||
driving = false;
|
||||
}
|
||||
};
|
||||
|
||||
let resolveDone;
|
||||
const done = new Promise((resolve) => {
|
||||
resolveDone = resolve;
|
||||
});
|
||||
let frame = 0;
|
||||
let finished = false;
|
||||
const hide = () => loadingScreen.classList.add('hidden');
|
||||
const stopCommands = camera.onCommand?.(() => {
|
||||
if (!driving) finish();
|
||||
});
|
||||
const inputs = ['pointerdown', 'wheel', 'keydown', 'touchstart'];
|
||||
// The person's own input skips to the end; another camera move stops it.
|
||||
const onInput = () => finish({ land: true });
|
||||
for (const type of inputs)
|
||||
win.addEventListener(type, onInput, { capture: true, passive: true });
|
||||
|
||||
function finish({ land = false } = {}) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
playing -= 1;
|
||||
if (frame) win.cancelAnimationFrame(frame);
|
||||
stopCommands?.();
|
||||
for (const type of inputs)
|
||||
win.removeEventListener(type, onInput, { capture: true });
|
||||
if (land)
|
||||
place(
|
||||
{ lon: target.lon, lat: target.lat, height: target.height },
|
||||
target.heading ?? 0,
|
||||
target.pitch ?? -Math.PI / 2,
|
||||
);
|
||||
hide();
|
||||
resolveDone();
|
||||
}
|
||||
|
||||
const start = win.performance.now();
|
||||
const step = () => {
|
||||
frame = 0;
|
||||
if (finished) return;
|
||||
const stage = openingStage(win.performance.now() - start);
|
||||
if (stage.done) {
|
||||
finish({ land: true });
|
||||
return;
|
||||
}
|
||||
const pose = openingPose(stage.flight, { target, farHeight });
|
||||
place(pose);
|
||||
const scale = globeRadiusPx(pose.height, lens) / startRadius;
|
||||
loadingScreen.style.setProperty('--opening-text', stage.text);
|
||||
loadingScreen.style.setProperty('--opening-veil', stage.veil);
|
||||
if (logo)
|
||||
logo.style.transform = `translate(${toCentre.x * stage.centre}px, ${
|
||||
toCentre.y * stage.centre
|
||||
}px) scale(${scale})`;
|
||||
for (const element of arcs) {
|
||||
element.style.transform = `scale(${stage.arcsScale})`;
|
||||
element.style.opacity = stage.arcsOpacity;
|
||||
}
|
||||
for (const element of pupil) element.style.opacity = stage.pupilOpacity;
|
||||
if (stage.pupilOpacity === 0) hide();
|
||||
frame = win.requestAnimationFrame(step);
|
||||
};
|
||||
step();
|
||||
return { done, cancel: () => finish() };
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import {
|
||||
OPENING,
|
||||
globeRadiusPx,
|
||||
heightForGlobeRadius,
|
||||
openingPlaying,
|
||||
openingPose,
|
||||
openingStage,
|
||||
openingWanted,
|
||||
playOpeningIntro,
|
||||
} from './openingIntro.js';
|
||||
|
||||
const LENS = { fovy: Math.PI / 4, viewportHeight: 800 };
|
||||
const TARGET = { lon: 10.4, lat: 51.1, height: 23e6, heading: 0, pitch: -1 };
|
||||
const LANDED = { lon: TARGET.lon, lat: TARGET.lat, height: TARGET.height };
|
||||
const END_MS = OPENING.centreMs + OPENING.flightStartMs + OPENING.flightMs + 1;
|
||||
|
||||
test('the arcs fly out and the words fade before the globe arrives', () => {
|
||||
const start = openingStage(0);
|
||||
assert.equal(start.text, 1);
|
||||
assert.equal(start.veil, 1);
|
||||
assert.equal(start.pupilOpacity, 1);
|
||||
assert.equal(start.flight, 0);
|
||||
const centred = openingStage(OPENING.centreMs);
|
||||
assert.equal(centred.text, 0);
|
||||
assert.equal(centred.centre, 1);
|
||||
const arcsGone = openingStage(OPENING.centreMs + OPENING.arcsMs);
|
||||
assert.equal(arcsGone.arcsOpacity, 0);
|
||||
assert.ok(arcsGone.arcsScale > 5);
|
||||
const real = openingStage(OPENING.centreMs + OPENING.pupilMs[1]);
|
||||
assert.equal(real.pupilOpacity, 0);
|
||||
assert.equal(real.veil, 0);
|
||||
assert.ok(real.flight > 0 && real.flight < 1);
|
||||
assert.equal(openingStage(END_MS).done, true);
|
||||
});
|
||||
|
||||
test('the flight turns west to east, slows and stops over the target', () => {
|
||||
const far = 4e8;
|
||||
const start = openingPose(0, { target: TARGET, farHeight: far });
|
||||
assert.ok(Math.abs(start.height - far) < 1);
|
||||
assert.equal(start.lat, 0);
|
||||
const end = openingPose(1, { target: TARGET, farHeight: far });
|
||||
assert.ok(Math.abs(end.lon - TARGET.lon) < 1e-9);
|
||||
assert.ok(Math.abs(end.lat - TARGET.lat) < 1e-9);
|
||||
assert.ok(Math.abs(end.height - TARGET.height) < 1e-3);
|
||||
// Unwrapped longitude falls all the way (the camera moves west, so the
|
||||
// surface turns east), fastest at first.
|
||||
let previous = Infinity;
|
||||
let previousStep = Infinity;
|
||||
for (let i = 0; i <= 10; i++) {
|
||||
const f = i / 10;
|
||||
const unwrapped = TARGET.lon + OPENING.spinDeg * (1 - (1 - (1 - f) ** 3));
|
||||
assert.ok(unwrapped <= previous);
|
||||
if (i > 0) {
|
||||
const step = previous - unwrapped;
|
||||
assert.ok(step <= previousStep + 1e-9, 'the turn slows');
|
||||
previousStep = step;
|
||||
}
|
||||
previous = unwrapped;
|
||||
const pose = openingPose(f, { target: TARGET, farHeight: far });
|
||||
assert.ok(pose.lon >= -180 && pose.lon < 180);
|
||||
}
|
||||
});
|
||||
|
||||
test('the far start draws the globe the size of the pupil', () => {
|
||||
for (const radius of [12, 20, 64]) {
|
||||
const height = heightForGlobeRadius(radius, LENS);
|
||||
assert.ok(Math.abs(globeRadiusPx(height, LENS) - radius) < 1e-6);
|
||||
}
|
||||
assert.ok(globeRadiusPx(4e8, LENS) < globeRadiusPx(23e6, LENS));
|
||||
});
|
||||
|
||||
test('reduced motion, Stories links and ?intro=0 open without it', () => {
|
||||
const win = (search, reduced = false) => ({
|
||||
location: { search },
|
||||
matchMedia: () => ({ matches: reduced }),
|
||||
});
|
||||
assert.equal(openingWanted(win('')), true);
|
||||
assert.equal(openingWanted(win('', true)), false);
|
||||
assert.equal(openingWanted(win('?intro=0')), false);
|
||||
assert.equal(openingWanted(win('?story=abc')), false);
|
||||
assert.equal(openingWanted(win('?stories')), false);
|
||||
assert.equal(openingWanted(win('?intro=1')), true);
|
||||
});
|
||||
|
||||
// A loading screen and a camera port; the test runs the frames by hand.
|
||||
function stage() {
|
||||
const window = new Window({ width: 1280, height: 800 });
|
||||
const doc = window.document;
|
||||
doc.body.innerHTML = `
|
||||
<div id="cesiumContainer"></div>
|
||||
<div id="loading-screen"><span class="loader-logo"><svg>
|
||||
<path id="outer_eye"/><path id="inner_eye"/>
|
||||
<path id="globe"/><path id="globe_cage"/>
|
||||
</svg></span></div>`;
|
||||
const screen = doc.getElementById('loading-screen');
|
||||
let now = 0;
|
||||
let frames = [];
|
||||
window.performance.now = () => now;
|
||||
window.requestAnimationFrame = (fn) => frames.push(fn);
|
||||
window.cancelAnimationFrame = () => {
|
||||
frames = [];
|
||||
};
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
const views = [];
|
||||
const commandListeners = new Set();
|
||||
const camera = {
|
||||
pose: () => ({ ...TARGET, fovy: Math.PI / 4 }),
|
||||
setView(spec) {
|
||||
views.push(spec);
|
||||
for (const cb of commandListeners) cb({ kind: 'setView' });
|
||||
},
|
||||
onCommand(cb) {
|
||||
commandListeners.add(cb);
|
||||
return () => commandListeners.delete(cb);
|
||||
},
|
||||
};
|
||||
return {
|
||||
window,
|
||||
screen,
|
||||
views,
|
||||
camera,
|
||||
commandListeners,
|
||||
play: () =>
|
||||
playOpeningIntro({
|
||||
viewer: {},
|
||||
loadingScreen: screen,
|
||||
win: window,
|
||||
camera,
|
||||
}),
|
||||
advance(ms) {
|
||||
now += ms;
|
||||
const run = frames;
|
||||
frames = [];
|
||||
for (const fn of run) fn();
|
||||
},
|
||||
otherMove: () => {
|
||||
for (const cb of [...commandListeners]) cb({ kind: 'flyTo' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the opening runs to the start view, then hides the cover', async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
assert.ok(opening);
|
||||
assert.equal(openingPlaying(), true);
|
||||
assert.ok(s.screen.classList.contains('opening'));
|
||||
assert.ok(s.views[0].destination.height > TARGET.height * 2, 'far start');
|
||||
s.advance(OPENING.centreMs + OPENING.pupilMs[1]);
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
s.advance(OPENING.flightMs);
|
||||
await opening.done;
|
||||
const last = s.views.at(-1);
|
||||
assert.deepEqual(last.destination, LANDED);
|
||||
assert.equal(last.orientation.pitch, TARGET.pitch);
|
||||
assert.equal(openingPlaying(), false);
|
||||
assert.equal(s.commandListeners.size, 0);
|
||||
});
|
||||
|
||||
test("the person's input skips to the start view", async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
s.window.dispatchEvent(new s.window.Event('keydown'));
|
||||
await opening.done;
|
||||
assert.deepEqual(s.views.at(-1).destination, LANDED);
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
assert.equal(openingPlaying(), false);
|
||||
});
|
||||
|
||||
test('another camera move stops it where it is', async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
const count = s.views.length;
|
||||
s.otherMove();
|
||||
await opening.done;
|
||||
s.advance(1000);
|
||||
assert.equal(s.views.length, count, 'no more frames');
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
});
|
||||
@@ -1,9 +1,6 @@
|
||||
import { initFirstRunExperience } from '../firstRunExperience.js';
|
||||
|
||||
/**
|
||||
* Reveal welcome controls only after restoration and the loading transition.
|
||||
* `playOpening` plays the opening on a bare address (src/app/openingIntro.js).
|
||||
*/
|
||||
/** Reveal welcome controls only after restoration and the loading transition. */
|
||||
export function startApplicationChrome({
|
||||
loadingScreen,
|
||||
styleManager,
|
||||
@@ -11,11 +8,9 @@ export function startApplicationChrome({
|
||||
signal,
|
||||
initializeWelcome = initFirstRunExperience,
|
||||
initializeSettings,
|
||||
playOpening = null,
|
||||
}) {
|
||||
let disposed = false;
|
||||
let firstRun;
|
||||
let opening = null;
|
||||
let revealTimer;
|
||||
let resolveDelay;
|
||||
const minimumDelay = new Promise((resolve) => {
|
||||
@@ -34,14 +29,6 @@ export function startApplicationChrome({
|
||||
})
|
||||
.then(() => {
|
||||
if (disposed || signal.aborted) return;
|
||||
// A bare address opens with the opening; welcome waits for its end.
|
||||
opening = styleManager.hasShareState
|
||||
? null
|
||||
: playOpening?.({ viewer: styleManager.viewer, loadingScreen });
|
||||
if (opening) {
|
||||
void opening.done.then(revealFirstRun);
|
||||
return;
|
||||
}
|
||||
loadingScreen.classList.add('hidden');
|
||||
loadingScreen.addEventListener('transitionend', revealFirstRun, {
|
||||
once: true,
|
||||
@@ -57,7 +44,6 @@ export function startApplicationChrome({
|
||||
);
|
||||
return async () => {
|
||||
disposed = true;
|
||||
opening?.cancel();
|
||||
clearTimeout(delayTimer);
|
||||
clearTimeout(revealTimer);
|
||||
resolveDelay();
|
||||
|
||||
+2
-4
@@ -22,7 +22,6 @@ import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
|
||||
import { createRecentImageryPanel } from '../ui/recentImagery.js';
|
||||
import { createDataLibrary } from '../library/controller.js';
|
||||
import { flyToLibraryExtent } from '../library/camera.js';
|
||||
import { openingPlaying } from './openingIntro.js';
|
||||
import { createLibraryBrowser } from '../ui/libraryBrowser.js';
|
||||
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
|
||||
import { localGeoJsonServices } from './localGeojsonServices.js';
|
||||
@@ -89,9 +88,8 @@ export function createApplicationTools({
|
||||
installGlobeInViewRecovery(viewer, {
|
||||
// The scope mask hides everything outside its keyhole.
|
||||
keyholeRadius: () => (isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0),
|
||||
// An authored scene frames its own shots, holds included, and the
|
||||
// opening starts with the globe as a speck.
|
||||
paused: () => sceneDirector.running || openingPlaying(),
|
||||
// An authored scene frames its own shots, holds included.
|
||||
paused: () => sceneDirector.running,
|
||||
}),
|
||||
);
|
||||
onSceneDirector?.(sceneDirector);
|
||||
|
||||
@@ -64,7 +64,8 @@ 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 now). */
|
||||
/** 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). */
|
||||
const AGE_FIELD = 'ageHours';
|
||||
/** Spatial scope kinds `query()` accepts. */
|
||||
const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
@@ -582,6 +583,8 @@ 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(
|
||||
@@ -595,6 +598,7 @@ export async function selectAnalystRows(
|
||||
ref = null,
|
||||
inScope = null,
|
||||
now = Date.now(),
|
||||
recordsAt = null,
|
||||
isCurrent = () => true,
|
||||
distanceOf = null,
|
||||
} = {},
|
||||
@@ -603,8 +607,10 @@ 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(((now - t) / 3_600_000) * 10) / 10
|
||||
? Math.round(((ref - t) / 3_600_000) * 10) / 10
|
||||
: null;
|
||||
};
|
||||
const distance = (row) => {
|
||||
@@ -771,6 +777,7 @@ 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;
|
||||
@@ -786,6 +793,7 @@ 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) || {};
|
||||
@@ -1048,6 +1056,7 @@ export function createAnalystEngine(providers) {
|
||||
: null,
|
||||
inScope,
|
||||
now: providers.now?.() ?? Date.now(),
|
||||
recordsAt,
|
||||
isCurrent,
|
||||
});
|
||||
if (!selection || !isCurrent()) return cancelled();
|
||||
@@ -1147,6 +1156,7 @@ 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,
|
||||
|
||||
@@ -896,6 +896,24 @@ 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({
|
||||
|
||||
@@ -57,6 +57,34 @@ 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 = [];
|
||||
|
||||
@@ -1,695 +0,0 @@
|
||||
// Generated by scripts/build-home-countries.mjs. Do not edit by hand.
|
||||
// Sources: tzdata zone.tab (public domain) and the Natural Earth countries
|
||||
// pack in src/data/local_data/natural_earth (public domain).
|
||||
|
||||
/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */
|
||||
export const COUNTRY_CENTRES = {
|
||||
AD: [42.5, 1.6],
|
||||
AE: [23.9, 54.3],
|
||||
AF: [33.8, 66],
|
||||
AG: [17.1, -61.8],
|
||||
AI: [18.2, -63.1],
|
||||
AL: [41.1, 20.1],
|
||||
AM: [40.3, 44.9],
|
||||
AO: [-12.3, 17.6],
|
||||
AQ: [-80.6, 20.8],
|
||||
AR: [-35.2, -65.1],
|
||||
AS: [-14.3, -170.7],
|
||||
AT: [47.6, 14.1],
|
||||
AU: [-25.6, 134.4],
|
||||
AW: [12.5, -70],
|
||||
AX: [60.2, 19.9],
|
||||
AZ: [40.3, 47.7],
|
||||
BA: [44.2, 17.8],
|
||||
BB: [13.2, -59.6],
|
||||
BD: [23.9, 90.2],
|
||||
BE: [50.6, 4.6],
|
||||
BF: [12.3, -1.8],
|
||||
BG: [42.8, 25.2],
|
||||
BH: [26.1, 50.5],
|
||||
BI: [-3.4, 29.9],
|
||||
BJ: [9.6, 2.3],
|
||||
BL: [17.9, -62.8],
|
||||
BM: [32.3, -64.8],
|
||||
BN: [4.5, 114.6],
|
||||
BO: [-16.7, -64.7],
|
||||
BQ: [12.2, -68.3],
|
||||
BR: [-10.8, -53.1],
|
||||
BS: [24.7, -78],
|
||||
BT: [27.4, 90.4],
|
||||
BW: [-22.2, 23.8],
|
||||
BY: [53.5, 28],
|
||||
BZ: [17.2, -88.7],
|
||||
CA: [57.9, -102.4],
|
||||
CC: [-12.2, 96.9],
|
||||
CD: [-2.9, 23.6],
|
||||
CF: [6.6, 20.5],
|
||||
CG: [-0.8, 15.2],
|
||||
CH: [46.8, 8.2],
|
||||
CI: [7.6, -5.6],
|
||||
CK: [-21.2, -159.8],
|
||||
CL: [-35.4, -71.2],
|
||||
CM: [5.7, 12.7],
|
||||
CN: [36.6, 103.8],
|
||||
CO: [3.9, -73.1],
|
||||
CR: [10, -84.2],
|
||||
CU: [21.6, -79],
|
||||
CV: [15.1, -23.6],
|
||||
CW: [12.2, -69],
|
||||
CX: [-10.4, 105.7],
|
||||
CY: [34.9, 33],
|
||||
CZ: [49.7, 15.3],
|
||||
DE: [51.1, 10.4],
|
||||
DJ: [11.8, 42.6],
|
||||
DK: [56.2, 9.4],
|
||||
DM: [15.4, -61.4],
|
||||
DO: [18.9, -70.5],
|
||||
DZ: [28.1, 2.7],
|
||||
EC: [-1.4, -78.4],
|
||||
EE: [58.7, 25.8],
|
||||
EG: [26.5, 29.9],
|
||||
EH: [24.2, -12.2],
|
||||
ER: [15.4, 38.8],
|
||||
ES: [40.4, -3.6],
|
||||
ET: [8.6, 39.6],
|
||||
FI: [64.5, 26.3],
|
||||
FJ: [-17.8, 178],
|
||||
FK: [-51.7, -58.8],
|
||||
FM: [6.9, 158.2],
|
||||
FO: [62.1, -7],
|
||||
FR: [46.6, 2.5],
|
||||
GA: [-0.6, 11.8],
|
||||
GB: [53.9, -2.5],
|
||||
GD: [12.1, -61.7],
|
||||
GE: [42.2, 43.5],
|
||||
GF: [4.9, -52.3],
|
||||
GG: [49.5, -2.6],
|
||||
GH: [8, -1.2],
|
||||
GI: [36.1, -5.3],
|
||||
GL: [74.8, -41.4],
|
||||
GM: [13.4, -15.4],
|
||||
GN: [10.4, -10.9],
|
||||
GP: [16.2, -61.5],
|
||||
GQ: [1.6, 10.5],
|
||||
GR: [39.5, 22.6],
|
||||
GS: [-54.4, -36.7],
|
||||
GT: [15.7, -90.4],
|
||||
GU: [13.4, 144.8],
|
||||
GW: [12.1, -14.9],
|
||||
GY: [4.8, -59],
|
||||
HK: [22.4, 114.2],
|
||||
HN: [14.8, -86.6],
|
||||
HR: [45.2, 16.4],
|
||||
HT: [18.9, -72.7],
|
||||
HU: [47.2, 19.4],
|
||||
ID: [-0.2, 114],
|
||||
IE: [53.2, -8.1],
|
||||
IL: [31.4, 35],
|
||||
IM: [54.2, -4.5],
|
||||
IN: [22.9, 79.6],
|
||||
IO: [-7.3, 72.4],
|
||||
IQ: [33, 43.7],
|
||||
IR: [32.6, 54.3],
|
||||
IS: [65, -18.6],
|
||||
IT: [43.5, 12.2],
|
||||
JE: [49.2, -2.1],
|
||||
JM: [18.2, -77.3],
|
||||
JO: [31.2, 36.8],
|
||||
JP: [36.7, 138],
|
||||
KE: [0.6, 37.8],
|
||||
KG: [41.5, 74.5],
|
||||
KH: [12.7, 104.9],
|
||||
KI: [1.9, -157.4],
|
||||
KM: [-11.7, 43.3],
|
||||
KN: [17.3, -62.8],
|
||||
KP: [40.2, 127.2],
|
||||
KR: [36.5, 127.9],
|
||||
KW: [29.3, 47.6],
|
||||
KY: [19.3, -81.3],
|
||||
KZ: [48.2, 67.3],
|
||||
LA: [18.5, 103.7],
|
||||
LB: [33.9, 35.9],
|
||||
LC: [13.9, -61],
|
||||
LI: [47.1, 9.5],
|
||||
LK: [7.6, 80.7],
|
||||
LR: [6.5, -9.3],
|
||||
LS: [-29.6, 28.2],
|
||||
LT: [55.3, 23.9],
|
||||
LU: [49.8, 6.1],
|
||||
LV: [56.9, 24.9],
|
||||
LY: [27, 18],
|
||||
MA: [29.8, -8.4],
|
||||
MC: [43.7, 7.4],
|
||||
MD: [47.2, 28.5],
|
||||
ME: [42.8, 19.2],
|
||||
MF: [18.1, -63.1],
|
||||
MG: [-19.4, 46.7],
|
||||
MH: [7.1, 171.2],
|
||||
MK: [41.6, 21.7],
|
||||
ML: [17.3, -3.5],
|
||||
MM: [21.2, 96.5],
|
||||
MN: [46.8, 103.1],
|
||||
MO: [22.1, 113.6],
|
||||
MP: [15.2, 145.7],
|
||||
MQ: [14.6, -61.1],
|
||||
MR: [20.3, -10.3],
|
||||
MS: [16.7, -62.2],
|
||||
MT: [35.9, 14.4],
|
||||
MU: [-20.3, 57.6],
|
||||
MV: [4.2, 73.5],
|
||||
MW: [-13.2, 34.3],
|
||||
MX: [23.9, -102.5],
|
||||
MY: [3.6, 114.7],
|
||||
MZ: [-17.3, 35.5],
|
||||
NA: [-22.1, 17.2],
|
||||
NC: [-21.3, 165.5],
|
||||
NE: [17.4, 9.4],
|
||||
NF: [-29, 168],
|
||||
NG: [9.6, 8.1],
|
||||
NI: [12.8, -85],
|
||||
NL: [52.3, 5.6],
|
||||
NO: [64.2, 14],
|
||||
NP: [28.2, 83.9],
|
||||
NR: [-0.5, 166.9],
|
||||
NU: [-19, -169.9],
|
||||
NZ: [-44, 170.5],
|
||||
OM: [20.6, 56.1],
|
||||
PA: [8.5, -80.1],
|
||||
PE: [-9.2, -74.4],
|
||||
PF: [-17.7, -149.4],
|
||||
PG: [-6.6, 144.3],
|
||||
PH: [16, 121.4],
|
||||
PK: [29.9, 69.3],
|
||||
PL: [52.1, 19.4],
|
||||
PM: [47, -56.3],
|
||||
PN: [-24.4, -128.3],
|
||||
PR: [18.2, -66.5],
|
||||
PS: [31.9, 35.3],
|
||||
PT: [39.7, -8],
|
||||
PW: [7.5, 134.6],
|
||||
PY: [-23.2, -58.4],
|
||||
QA: [25.3, 51.2],
|
||||
RE: [-20.9, 55.5],
|
||||
RO: [45.9, 25],
|
||||
RS: [44.2, 20.8],
|
||||
RU: [61.7, 99.1],
|
||||
RW: [-2, 29.9],
|
||||
SA: [24.1, 44.5],
|
||||
SB: [-9.6, 160.2],
|
||||
SC: [-4.7, 55.5],
|
||||
SD: [16, 29.9],
|
||||
SE: [62.8, 16.7],
|
||||
SG: [1.4, 103.8],
|
||||
SH: [-16, -5.7],
|
||||
SI: [46.1, 14.8],
|
||||
SJ: [78, 16],
|
||||
SK: [48.7, 19.5],
|
||||
SL: [8.6, -11.8],
|
||||
SM: [43.9, 12.4],
|
||||
SN: [14.4, -14.5],
|
||||
SO: [4.8, 45.7],
|
||||
SR: [4.1, -55.9],
|
||||
SS: [7.3, 30.3],
|
||||
ST: [0.2, 6.6],
|
||||
SV: [13.7, -88.9],
|
||||
SX: [18, -63.1],
|
||||
SY: [35, 38.5],
|
||||
SZ: [-26.6, 31.5],
|
||||
TC: [21.8, -71.7],
|
||||
TD: [15.3, 18.6],
|
||||
TF: [-49.3, 69.5],
|
||||
TG: [8.5, 1],
|
||||
TH: [15.1, 101],
|
||||
TJ: [38.5, 71],
|
||||
TK: [-9.4, -171.2],
|
||||
TL: [-8.8, 125.9],
|
||||
TM: [39.1, 59.4],
|
||||
TN: [34.1, 9.5],
|
||||
TO: [-21.2, -175.2],
|
||||
TR: [39, 35.4],
|
||||
TT: [10.4, -61.3],
|
||||
TV: [-8.5, 179.2],
|
||||
TW: [23.8, 121],
|
||||
TZ: [-6.3, 34.8],
|
||||
UA: [49.2, 31.3],
|
||||
UG: [1.3, 32.4],
|
||||
UM: [5.9, -162.1],
|
||||
US: [39.5, -99.1],
|
||||
UY: [-32.8, -56],
|
||||
UZ: [41.8, 63.1],
|
||||
VA: [41.9, 12.5],
|
||||
VC: [13.3, -61.2],
|
||||
VE: [7.1, -66.2],
|
||||
VG: [18.4, -64.6],
|
||||
VI: [17.7, -64.8],
|
||||
VN: [16.7, 106.3],
|
||||
VU: [-15.2, 166.9],
|
||||
WF: [-13.3, -176.2],
|
||||
WS: [-13.6, -172.4],
|
||||
YE: [15.9, 47.5],
|
||||
YT: [-12.8, 45.2],
|
||||
ZA: [-29, 25.2],
|
||||
ZM: [-13.5, 27.8],
|
||||
ZW: [-19, 29.9],
|
||||
};
|
||||
|
||||
/** Time zone (tzdata and ICU names) → ISO 3166 country. */
|
||||
export const ZONE_COUNTRIES = {
|
||||
'Africa/Abidjan': 'CI',
|
||||
'Africa/Accra': 'GH',
|
||||
'Africa/Addis_Ababa': 'ET',
|
||||
'Africa/Algiers': 'DZ',
|
||||
'Africa/Asmara': 'ER',
|
||||
'Africa/Asmera': 'ER',
|
||||
'Africa/Bamako': 'ML',
|
||||
'Africa/Bangui': 'CF',
|
||||
'Africa/Banjul': 'GM',
|
||||
'Africa/Bissau': 'GW',
|
||||
'Africa/Blantyre': 'MW',
|
||||
'Africa/Brazzaville': 'CG',
|
||||
'Africa/Bujumbura': 'BI',
|
||||
'Africa/Cairo': 'EG',
|
||||
'Africa/Casablanca': 'MA',
|
||||
'Africa/Ceuta': 'ES',
|
||||
'Africa/Conakry': 'GN',
|
||||
'Africa/Dakar': 'SN',
|
||||
'Africa/Dar_es_Salaam': 'TZ',
|
||||
'Africa/Djibouti': 'DJ',
|
||||
'Africa/Douala': 'CM',
|
||||
'Africa/El_Aaiun': 'EH',
|
||||
'Africa/Freetown': 'SL',
|
||||
'Africa/Gaborone': 'BW',
|
||||
'Africa/Harare': 'ZW',
|
||||
'Africa/Johannesburg': 'ZA',
|
||||
'Africa/Juba': 'SS',
|
||||
'Africa/Kampala': 'UG',
|
||||
'Africa/Khartoum': 'SD',
|
||||
'Africa/Kigali': 'RW',
|
||||
'Africa/Kinshasa': 'CD',
|
||||
'Africa/Lagos': 'NG',
|
||||
'Africa/Libreville': 'GA',
|
||||
'Africa/Lome': 'TG',
|
||||
'Africa/Luanda': 'AO',
|
||||
'Africa/Lubumbashi': 'CD',
|
||||
'Africa/Lusaka': 'ZM',
|
||||
'Africa/Malabo': 'GQ',
|
||||
'Africa/Maputo': 'MZ',
|
||||
'Africa/Maseru': 'LS',
|
||||
'Africa/Mbabane': 'SZ',
|
||||
'Africa/Mogadishu': 'SO',
|
||||
'Africa/Monrovia': 'LR',
|
||||
'Africa/Nairobi': 'KE',
|
||||
'Africa/Ndjamena': 'TD',
|
||||
'Africa/Niamey': 'NE',
|
||||
'Africa/Nouakchott': 'MR',
|
||||
'Africa/Ouagadougou': 'BF',
|
||||
'Africa/Porto-Novo': 'BJ',
|
||||
'Africa/Sao_Tome': 'ST',
|
||||
'Africa/Tripoli': 'LY',
|
||||
'Africa/Tunis': 'TN',
|
||||
'Africa/Windhoek': 'NA',
|
||||
'America/Adak': 'US',
|
||||
'America/Anchorage': 'US',
|
||||
'America/Anguilla': 'AI',
|
||||
'America/Antigua': 'AG',
|
||||
'America/Araguaina': 'BR',
|
||||
'America/Argentina/Buenos_Aires': 'AR',
|
||||
'America/Argentina/Catamarca': 'AR',
|
||||
'America/Argentina/Cordoba': 'AR',
|
||||
'America/Argentina/Jujuy': 'AR',
|
||||
'America/Argentina/La_Rioja': 'AR',
|
||||
'America/Argentina/Mendoza': 'AR',
|
||||
'America/Argentina/Rio_Gallegos': 'AR',
|
||||
'America/Argentina/Salta': 'AR',
|
||||
'America/Argentina/San_Juan': 'AR',
|
||||
'America/Argentina/San_Luis': 'AR',
|
||||
'America/Argentina/Tucuman': 'AR',
|
||||
'America/Argentina/Ushuaia': 'AR',
|
||||
'America/Aruba': 'AW',
|
||||
'America/Asuncion': 'PY',
|
||||
'America/Atikokan': 'CA',
|
||||
'America/Bahia': 'BR',
|
||||
'America/Bahia_Banderas': 'MX',
|
||||
'America/Barbados': 'BB',
|
||||
'America/Belem': 'BR',
|
||||
'America/Belize': 'BZ',
|
||||
'America/Blanc-Sablon': 'CA',
|
||||
'America/Boa_Vista': 'BR',
|
||||
'America/Bogota': 'CO',
|
||||
'America/Boise': 'US',
|
||||
'America/Buenos_Aires': 'AR',
|
||||
'America/Cambridge_Bay': 'CA',
|
||||
'America/Campo_Grande': 'BR',
|
||||
'America/Cancun': 'MX',
|
||||
'America/Caracas': 'VE',
|
||||
'America/Catamarca': 'AR',
|
||||
'America/Cayenne': 'GF',
|
||||
'America/Cayman': 'KY',
|
||||
'America/Chicago': 'US',
|
||||
'America/Chihuahua': 'MX',
|
||||
'America/Ciudad_Juarez': 'MX',
|
||||
'America/Coral_Harbour': 'CA',
|
||||
'America/Cordoba': 'AR',
|
||||
'America/Costa_Rica': 'CR',
|
||||
'America/Coyhaique': 'CL',
|
||||
'America/Creston': 'CA',
|
||||
'America/Cuiaba': 'BR',
|
||||
'America/Curacao': 'CW',
|
||||
'America/Danmarkshavn': 'GL',
|
||||
'America/Dawson': 'CA',
|
||||
'America/Dawson_Creek': 'CA',
|
||||
'America/Denver': 'US',
|
||||
'America/Detroit': 'US',
|
||||
'America/Dominica': 'DM',
|
||||
'America/Edmonton': 'CA',
|
||||
'America/Eirunepe': 'BR',
|
||||
'America/El_Salvador': 'SV',
|
||||
'America/Fort_Nelson': 'CA',
|
||||
'America/Fortaleza': 'BR',
|
||||
'America/Glace_Bay': 'CA',
|
||||
'America/Godthab': 'GL',
|
||||
'America/Goose_Bay': 'CA',
|
||||
'America/Grand_Turk': 'TC',
|
||||
'America/Grenada': 'GD',
|
||||
'America/Guadeloupe': 'GP',
|
||||
'America/Guatemala': 'GT',
|
||||
'America/Guayaquil': 'EC',
|
||||
'America/Guyana': 'GY',
|
||||
'America/Halifax': 'CA',
|
||||
'America/Havana': 'CU',
|
||||
'America/Hermosillo': 'MX',
|
||||
'America/Indiana/Indianapolis': 'US',
|
||||
'America/Indiana/Knox': 'US',
|
||||
'America/Indiana/Marengo': 'US',
|
||||
'America/Indiana/Petersburg': 'US',
|
||||
'America/Indiana/Tell_City': 'US',
|
||||
'America/Indiana/Vevay': 'US',
|
||||
'America/Indiana/Vincennes': 'US',
|
||||
'America/Indiana/Winamac': 'US',
|
||||
'America/Indianapolis': 'US',
|
||||
'America/Inuvik': 'CA',
|
||||
'America/Iqaluit': 'CA',
|
||||
'America/Jamaica': 'JM',
|
||||
'America/Jujuy': 'AR',
|
||||
'America/Juneau': 'US',
|
||||
'America/Kentucky/Louisville': 'US',
|
||||
'America/Kentucky/Monticello': 'US',
|
||||
'America/Kralendijk': 'BQ',
|
||||
'America/La_Paz': 'BO',
|
||||
'America/Lima': 'PE',
|
||||
'America/Los_Angeles': 'US',
|
||||
'America/Louisville': 'US',
|
||||
'America/Lower_Princes': 'SX',
|
||||
'America/Maceio': 'BR',
|
||||
'America/Managua': 'NI',
|
||||
'America/Manaus': 'BR',
|
||||
'America/Marigot': 'MF',
|
||||
'America/Martinique': 'MQ',
|
||||
'America/Matamoros': 'MX',
|
||||
'America/Mazatlan': 'MX',
|
||||
'America/Mendoza': 'AR',
|
||||
'America/Menominee': 'US',
|
||||
'America/Merida': 'MX',
|
||||
'America/Metlakatla': 'US',
|
||||
'America/Mexico_City': 'MX',
|
||||
'America/Miquelon': 'PM',
|
||||
'America/Moncton': 'CA',
|
||||
'America/Monterrey': 'MX',
|
||||
'America/Montevideo': 'UY',
|
||||
'America/Montserrat': 'MS',
|
||||
'America/Nassau': 'BS',
|
||||
'America/New_York': 'US',
|
||||
'America/Nome': 'US',
|
||||
'America/Noronha': 'BR',
|
||||
'America/North_Dakota/Beulah': 'US',
|
||||
'America/North_Dakota/Center': 'US',
|
||||
'America/North_Dakota/New_Salem': 'US',
|
||||
'America/Nuuk': 'GL',
|
||||
'America/Ojinaga': 'MX',
|
||||
'America/Panama': 'PA',
|
||||
'America/Paramaribo': 'SR',
|
||||
'America/Phoenix': 'US',
|
||||
'America/Port-au-Prince': 'HT',
|
||||
'America/Port_of_Spain': 'TT',
|
||||
'America/Porto_Velho': 'BR',
|
||||
'America/Puerto_Rico': 'PR',
|
||||
'America/Punta_Arenas': 'CL',
|
||||
'America/Rankin_Inlet': 'CA',
|
||||
'America/Recife': 'BR',
|
||||
'America/Regina': 'CA',
|
||||
'America/Resolute': 'CA',
|
||||
'America/Rio_Branco': 'BR',
|
||||
'America/Santarem': 'BR',
|
||||
'America/Santiago': 'CL',
|
||||
'America/Santo_Domingo': 'DO',
|
||||
'America/Sao_Paulo': 'BR',
|
||||
'America/Scoresbysund': 'GL',
|
||||
'America/Sitka': 'US',
|
||||
'America/St_Barthelemy': 'BL',
|
||||
'America/St_Johns': 'CA',
|
||||
'America/St_Kitts': 'KN',
|
||||
'America/St_Lucia': 'LC',
|
||||
'America/St_Thomas': 'VI',
|
||||
'America/St_Vincent': 'VC',
|
||||
'America/Swift_Current': 'CA',
|
||||
'America/Tegucigalpa': 'HN',
|
||||
'America/Thule': 'GL',
|
||||
'America/Tijuana': 'MX',
|
||||
'America/Toronto': 'CA',
|
||||
'America/Tortola': 'VG',
|
||||
'America/Vancouver': 'CA',
|
||||
'America/Whitehorse': 'CA',
|
||||
'America/Winnipeg': 'CA',
|
||||
'America/Yakutat': 'US',
|
||||
'Antarctica/Casey': 'AQ',
|
||||
'Antarctica/Davis': 'AQ',
|
||||
'Antarctica/DumontDUrville': 'AQ',
|
||||
'Antarctica/Macquarie': 'AU',
|
||||
'Antarctica/Mawson': 'AQ',
|
||||
'Antarctica/McMurdo': 'AQ',
|
||||
'Antarctica/Palmer': 'AQ',
|
||||
'Antarctica/Rothera': 'AQ',
|
||||
'Antarctica/Syowa': 'AQ',
|
||||
'Antarctica/Troll': 'AQ',
|
||||
'Antarctica/Vostok': 'AQ',
|
||||
'Arctic/Longyearbyen': 'SJ',
|
||||
'Asia/Aden': 'YE',
|
||||
'Asia/Almaty': 'KZ',
|
||||
'Asia/Amman': 'JO',
|
||||
'Asia/Anadyr': 'RU',
|
||||
'Asia/Aqtau': 'KZ',
|
||||
'Asia/Aqtobe': 'KZ',
|
||||
'Asia/Ashgabat': 'TM',
|
||||
'Asia/Atyrau': 'KZ',
|
||||
'Asia/Baghdad': 'IQ',
|
||||
'Asia/Bahrain': 'BH',
|
||||
'Asia/Baku': 'AZ',
|
||||
'Asia/Bangkok': 'TH',
|
||||
'Asia/Barnaul': 'RU',
|
||||
'Asia/Beirut': 'LB',
|
||||
'Asia/Bishkek': 'KG',
|
||||
'Asia/Brunei': 'BN',
|
||||
'Asia/Calcutta': 'IN',
|
||||
'Asia/Chita': 'RU',
|
||||
'Asia/Colombo': 'LK',
|
||||
'Asia/Damascus': 'SY',
|
||||
'Asia/Dhaka': 'BD',
|
||||
'Asia/Dili': 'TL',
|
||||
'Asia/Dubai': 'AE',
|
||||
'Asia/Dushanbe': 'TJ',
|
||||
'Asia/Famagusta': 'CY',
|
||||
'Asia/Gaza': 'PS',
|
||||
'Asia/Hebron': 'PS',
|
||||
'Asia/Ho_Chi_Minh': 'VN',
|
||||
'Asia/Hong_Kong': 'HK',
|
||||
'Asia/Hovd': 'MN',
|
||||
'Asia/Irkutsk': 'RU',
|
||||
'Asia/Jakarta': 'ID',
|
||||
'Asia/Jayapura': 'ID',
|
||||
'Asia/Jerusalem': 'IL',
|
||||
'Asia/Kabul': 'AF',
|
||||
'Asia/Kamchatka': 'RU',
|
||||
'Asia/Karachi': 'PK',
|
||||
'Asia/Kathmandu': 'NP',
|
||||
'Asia/Katmandu': 'NP',
|
||||
'Asia/Khandyga': 'RU',
|
||||
'Asia/Kolkata': 'IN',
|
||||
'Asia/Krasnoyarsk': 'RU',
|
||||
'Asia/Kuala_Lumpur': 'MY',
|
||||
'Asia/Kuching': 'MY',
|
||||
'Asia/Kuwait': 'KW',
|
||||
'Asia/Macau': 'MO',
|
||||
'Asia/Magadan': 'RU',
|
||||
'Asia/Makassar': 'ID',
|
||||
'Asia/Manila': 'PH',
|
||||
'Asia/Muscat': 'OM',
|
||||
'Asia/Nicosia': 'CY',
|
||||
'Asia/Novokuznetsk': 'RU',
|
||||
'Asia/Novosibirsk': 'RU',
|
||||
'Asia/Omsk': 'RU',
|
||||
'Asia/Oral': 'KZ',
|
||||
'Asia/Phnom_Penh': 'KH',
|
||||
'Asia/Pontianak': 'ID',
|
||||
'Asia/Pyongyang': 'KP',
|
||||
'Asia/Qatar': 'QA',
|
||||
'Asia/Qostanay': 'KZ',
|
||||
'Asia/Qyzylorda': 'KZ',
|
||||
'Asia/Rangoon': 'MM',
|
||||
'Asia/Riyadh': 'SA',
|
||||
'Asia/Saigon': 'VN',
|
||||
'Asia/Sakhalin': 'RU',
|
||||
'Asia/Samarkand': 'UZ',
|
||||
'Asia/Seoul': 'KR',
|
||||
'Asia/Shanghai': 'CN',
|
||||
'Asia/Singapore': 'SG',
|
||||
'Asia/Srednekolymsk': 'RU',
|
||||
'Asia/Taipei': 'TW',
|
||||
'Asia/Tashkent': 'UZ',
|
||||
'Asia/Tbilisi': 'GE',
|
||||
'Asia/Tehran': 'IR',
|
||||
'Asia/Thimphu': 'BT',
|
||||
'Asia/Tokyo': 'JP',
|
||||
'Asia/Tomsk': 'RU',
|
||||
'Asia/Ulaanbaatar': 'MN',
|
||||
'Asia/Urumqi': 'CN',
|
||||
'Asia/Ust-Nera': 'RU',
|
||||
'Asia/Vientiane': 'LA',
|
||||
'Asia/Vladivostok': 'RU',
|
||||
'Asia/Yakutsk': 'RU',
|
||||
'Asia/Yangon': 'MM',
|
||||
'Asia/Yekaterinburg': 'RU',
|
||||
'Asia/Yerevan': 'AM',
|
||||
'Atlantic/Azores': 'PT',
|
||||
'Atlantic/Bermuda': 'BM',
|
||||
'Atlantic/Canary': 'ES',
|
||||
'Atlantic/Cape_Verde': 'CV',
|
||||
'Atlantic/Faeroe': 'FO',
|
||||
'Atlantic/Faroe': 'FO',
|
||||
'Atlantic/Madeira': 'PT',
|
||||
'Atlantic/Reykjavik': 'IS',
|
||||
'Atlantic/South_Georgia': 'GS',
|
||||
'Atlantic/St_Helena': 'SH',
|
||||
'Atlantic/Stanley': 'FK',
|
||||
'Australia/Adelaide': 'AU',
|
||||
'Australia/Brisbane': 'AU',
|
||||
'Australia/Broken_Hill': 'AU',
|
||||
'Australia/Darwin': 'AU',
|
||||
'Australia/Eucla': 'AU',
|
||||
'Australia/Hobart': 'AU',
|
||||
'Australia/Lindeman': 'AU',
|
||||
'Australia/Lord_Howe': 'AU',
|
||||
'Australia/Melbourne': 'AU',
|
||||
'Australia/Perth': 'AU',
|
||||
'Australia/Sydney': 'AU',
|
||||
'Europe/Amsterdam': 'NL',
|
||||
'Europe/Andorra': 'AD',
|
||||
'Europe/Astrakhan': 'RU',
|
||||
'Europe/Athens': 'GR',
|
||||
'Europe/Belgrade': 'RS',
|
||||
'Europe/Berlin': 'DE',
|
||||
'Europe/Bratislava': 'SK',
|
||||
'Europe/Brussels': 'BE',
|
||||
'Europe/Bucharest': 'RO',
|
||||
'Europe/Budapest': 'HU',
|
||||
'Europe/Busingen': 'DE',
|
||||
'Europe/Chisinau': 'MD',
|
||||
'Europe/Copenhagen': 'DK',
|
||||
'Europe/Dublin': 'IE',
|
||||
'Europe/Gibraltar': 'GI',
|
||||
'Europe/Guernsey': 'GG',
|
||||
'Europe/Helsinki': 'FI',
|
||||
'Europe/Isle_of_Man': 'IM',
|
||||
'Europe/Istanbul': 'TR',
|
||||
'Europe/Jersey': 'JE',
|
||||
'Europe/Kaliningrad': 'RU',
|
||||
'Europe/Kiev': 'UA',
|
||||
'Europe/Kirov': 'RU',
|
||||
'Europe/Kyiv': 'UA',
|
||||
'Europe/Lisbon': 'PT',
|
||||
'Europe/Ljubljana': 'SI',
|
||||
'Europe/London': 'GB',
|
||||
'Europe/Luxembourg': 'LU',
|
||||
'Europe/Madrid': 'ES',
|
||||
'Europe/Malta': 'MT',
|
||||
'Europe/Mariehamn': 'AX',
|
||||
'Europe/Minsk': 'BY',
|
||||
'Europe/Monaco': 'MC',
|
||||
'Europe/Moscow': 'RU',
|
||||
'Europe/Oslo': 'NO',
|
||||
'Europe/Paris': 'FR',
|
||||
'Europe/Podgorica': 'ME',
|
||||
'Europe/Prague': 'CZ',
|
||||
'Europe/Riga': 'LV',
|
||||
'Europe/Rome': 'IT',
|
||||
'Europe/Samara': 'RU',
|
||||
'Europe/San_Marino': 'SM',
|
||||
'Europe/Sarajevo': 'BA',
|
||||
'Europe/Saratov': 'RU',
|
||||
'Europe/Simferopol': 'UA',
|
||||
'Europe/Skopje': 'MK',
|
||||
'Europe/Sofia': 'BG',
|
||||
'Europe/Stockholm': 'SE',
|
||||
'Europe/Tallinn': 'EE',
|
||||
'Europe/Tirane': 'AL',
|
||||
'Europe/Ulyanovsk': 'RU',
|
||||
'Europe/Vaduz': 'LI',
|
||||
'Europe/Vatican': 'VA',
|
||||
'Europe/Vienna': 'AT',
|
||||
'Europe/Vilnius': 'LT',
|
||||
'Europe/Volgograd': 'RU',
|
||||
'Europe/Warsaw': 'PL',
|
||||
'Europe/Zagreb': 'HR',
|
||||
'Europe/Zurich': 'CH',
|
||||
'Indian/Antananarivo': 'MG',
|
||||
'Indian/Chagos': 'IO',
|
||||
'Indian/Christmas': 'CX',
|
||||
'Indian/Cocos': 'CC',
|
||||
'Indian/Comoro': 'KM',
|
||||
'Indian/Kerguelen': 'TF',
|
||||
'Indian/Mahe': 'SC',
|
||||
'Indian/Maldives': 'MV',
|
||||
'Indian/Mauritius': 'MU',
|
||||
'Indian/Mayotte': 'YT',
|
||||
'Indian/Reunion': 'RE',
|
||||
'Pacific/Apia': 'WS',
|
||||
'Pacific/Auckland': 'NZ',
|
||||
'Pacific/Bougainville': 'PG',
|
||||
'Pacific/Chatham': 'NZ',
|
||||
'Pacific/Chuuk': 'FM',
|
||||
'Pacific/Easter': 'CL',
|
||||
'Pacific/Efate': 'VU',
|
||||
'Pacific/Enderbury': 'KI',
|
||||
'Pacific/Fakaofo': 'TK',
|
||||
'Pacific/Fiji': 'FJ',
|
||||
'Pacific/Funafuti': 'TV',
|
||||
'Pacific/Galapagos': 'EC',
|
||||
'Pacific/Gambier': 'PF',
|
||||
'Pacific/Guadalcanal': 'SB',
|
||||
'Pacific/Guam': 'GU',
|
||||
'Pacific/Honolulu': 'US',
|
||||
'Pacific/Kanton': 'KI',
|
||||
'Pacific/Kiritimati': 'KI',
|
||||
'Pacific/Kosrae': 'FM',
|
||||
'Pacific/Kwajalein': 'MH',
|
||||
'Pacific/Majuro': 'MH',
|
||||
'Pacific/Marquesas': 'PF',
|
||||
'Pacific/Midway': 'UM',
|
||||
'Pacific/Nauru': 'NR',
|
||||
'Pacific/Niue': 'NU',
|
||||
'Pacific/Norfolk': 'NF',
|
||||
'Pacific/Noumea': 'NC',
|
||||
'Pacific/Pago_Pago': 'AS',
|
||||
'Pacific/Palau': 'PW',
|
||||
'Pacific/Pitcairn': 'PN',
|
||||
'Pacific/Pohnpei': 'FM',
|
||||
'Pacific/Ponape': 'FM',
|
||||
'Pacific/Port_Moresby': 'PG',
|
||||
'Pacific/Rarotonga': 'CK',
|
||||
'Pacific/Saipan': 'MP',
|
||||
'Pacific/Tahiti': 'PF',
|
||||
'Pacific/Tarawa': 'KI',
|
||||
'Pacific/Tongatapu': 'TO',
|
||||
'Pacific/Truk': 'FM',
|
||||
'Pacific/Wake': 'UM',
|
||||
'Pacific/Wallis': 'WF',
|
||||
};
|
||||
@@ -1110,10 +1110,11 @@ 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).
|
||||
assert.equal(block.length, 31372, 'serialized tool schema length drifted');
|
||||
// Fire Perimeters queries add lastGrowthTime.
|
||||
assert.equal(block.length, 31387, 'serialized tool schema length drifted');
|
||||
assert.equal(
|
||||
crypto.createHash('sha256').update(block).digest('hex'),
|
||||
'7f593e78c232db972b04441f830b6a60f93916a6e5bc5a68eca7422cd1035508',
|
||||
'909bc8924e5ad6adf599406d462d325a703d18993176d96498cbb057240a58b6',
|
||||
'the first-run missions must ride EXISTING tools: no schema edit, no cache bust',
|
||||
);
|
||||
const instructions = fs.readFileSync(
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
|
||||
import { START_VIEW } from './camera.js';
|
||||
|
||||
/**
|
||||
* The visitor's country, guessed from the browser's time zone and, for a zone
|
||||
* that belongs to no country (UTC), the region of a preferred language
|
||||
* ("en-GB"). Nothing leaves the browser. Null when neither names one.
|
||||
* @param {{timeZone?: string|null, languages?: readonly string[]}} [where]
|
||||
* @returns {string|null} ISO 3166 code, e.g. 'DE'
|
||||
*/
|
||||
export function homeCountry({
|
||||
timeZone = currentTimeZone(),
|
||||
languages = globalThis.navigator?.languages ?? [],
|
||||
} = {}) {
|
||||
const byZone = ZONE_COUNTRIES[timeZone];
|
||||
if (byZone) return byZone;
|
||||
for (const language of languages) {
|
||||
const region = regionOf(language);
|
||||
if (region && COUNTRY_CENTRES[region]) return region;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The start view over the visitor's country: the planet from `base.height`,
|
||||
* looking straight down on the country's centre. `base` where the country is
|
||||
* unknown.
|
||||
* @param {{timeZone?: string|null, languages?: readonly string[],
|
||||
* base?: {lon: number, lat: number, height: number}}} [where]
|
||||
*/
|
||||
export function homeCountryView({ base = START_VIEW, ...where } = {}) {
|
||||
const centre = COUNTRY_CENTRES[homeCountry(where)];
|
||||
if (!centre) return base;
|
||||
const [lat, lon] = centre;
|
||||
return Object.freeze({ lon, lat, height: base.height });
|
||||
}
|
||||
|
||||
function currentTimeZone() {
|
||||
try {
|
||||
return new Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function regionOf(language) {
|
||||
try {
|
||||
return new Intl.Locale(language).region ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { homeCountry, homeCountryView } from './homeCountry.js';
|
||||
import { START_VIEW } from './camera.js';
|
||||
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
|
||||
|
||||
test('the time zone names the country, in its tzdata or ICU name', () => {
|
||||
assert.equal(homeCountry({ timeZone: 'Europe/Berlin', languages: [] }), 'DE');
|
||||
assert.equal(homeCountry({ timeZone: 'Asia/Kolkata', languages: [] }), 'IN');
|
||||
assert.equal(homeCountry({ timeZone: 'Asia/Calcutta', languages: [] }), 'IN');
|
||||
assert.equal(homeCountry({ timeZone: 'Europe/Kiev', languages: [] }), 'UA');
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'America/Chicago', languages: ['de-DE'] }),
|
||||
'US',
|
||||
'the zone outranks the language',
|
||||
);
|
||||
});
|
||||
|
||||
test("a zone of no country falls back to a language's region", () => {
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'UTC', languages: ['fr', 'en-GB'] }),
|
||||
'GB',
|
||||
);
|
||||
assert.equal(homeCountry({ timeZone: 'Etc/UTC', languages: ['ru'] }), null);
|
||||
assert.equal(homeCountry({ timeZone: null, languages: [] }), null);
|
||||
});
|
||||
|
||||
test('the start view looks down on the country from the planet height', () => {
|
||||
const view = homeCountryView({ timeZone: 'Asia/Tokyo', languages: [] });
|
||||
assert.deepEqual(
|
||||
[view.lat, view.lon, view.height],
|
||||
[...COUNTRY_CENTRES.JP, START_VIEW.height],
|
||||
);
|
||||
assert.equal(
|
||||
homeCountryView({ timeZone: 'UTC', languages: [] }),
|
||||
START_VIEW,
|
||||
'unknown: the default start',
|
||||
);
|
||||
});
|
||||
|
||||
test('every zone has a country with a centre on the globe', () => {
|
||||
for (const [zone, country] of Object.entries(ZONE_COUNTRIES)) {
|
||||
const centre = COUNTRY_CENTRES[country];
|
||||
assert.ok(centre, `${zone} → ${country}`);
|
||||
const [lat, lon] = centre;
|
||||
assert.ok(Math.abs(lat) <= 90 && Math.abs(lon) <= 180, country);
|
||||
}
|
||||
// Countries whose largest part is not where their centroid would be.
|
||||
const [usLat, usLon] = COUNTRY_CENTRES.US;
|
||||
assert.ok(usLat > 30 && usLat < 45 && usLon > -110 && usLon < -85);
|
||||
const [frLat, frLon] = COUNTRY_CENTRES.FR;
|
||||
assert.ok(frLat > 42 && frLat < 50 && frLon > -2 && frLon < 8);
|
||||
});
|
||||
@@ -1845,11 +1845,6 @@
|
||||
"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.": "تحديث الدليل متدهور؛ يُعرض فهرس المحطات السابق.",
|
||||
@@ -4856,5 +4851,12 @@
|
||||
"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}"
|
||||
"{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 م."
|
||||
}
|
||||
@@ -1727,11 +1727,6 @@
|
||||
"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.",
|
||||
@@ -4432,5 +4427,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1411,11 +1411,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1070,11 +1070,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -919,11 +919,6 @@
|
||||
"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": "חדשות",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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 מ׳."
|
||||
}
|
||||
@@ -1070,11 +1070,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1024,11 +1024,6 @@
|
||||
"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": "ニュース",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"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} 発表"
|
||||
"{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 に簡略化されています。"
|
||||
}
|
||||
@@ -1068,11 +1068,6 @@
|
||||
"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",
|
||||
@@ -4538,5 +4533,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1439,11 +1439,6 @@
|
||||
"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 м",
|
||||
@@ -4644,5 +4639,12 @@
|
||||
"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}"
|
||||
"{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 м."
|
||||
}
|
||||
@@ -1643,11 +1643,6 @@
|
||||
"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.",
|
||||
@@ -4432,5 +4427,12 @@
|
||||
"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}"
|
||||
"{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."
|
||||
}
|
||||
@@ -1092,11 +1092,6 @@
|
||||
"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": "Новини",
|
||||
@@ -4644,5 +4639,12 @@
|
||||
"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}"
|
||||
"{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 м."
|
||||
}
|
||||
@@ -1004,11 +1004,6 @@
|
||||
"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": "新闻",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"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}"
|
||||
"{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 米。"
|
||||
}
|
||||
@@ -1004,11 +1004,6 @@
|
||||
"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": "新聞",
|
||||
@@ -4326,5 +4321,12 @@
|
||||
"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}"
|
||||
"{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 米。"
|
||||
}
|
||||
@@ -8,13 +8,14 @@ import { buildIncidentCard } from './cards.js';
|
||||
|
||||
const now = Date.UTC(2026, 9, 14);
|
||||
const row = {
|
||||
stableId: 'x',
|
||||
id: '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',
|
||||
@@ -33,6 +34,7 @@ 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',
|
||||
]);
|
||||
@@ -44,8 +46,8 @@ for (const locale of ['es', 'ru']) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
assert.notEqual(
|
||||
t('Fully contained'),
|
||||
'Fully contained',
|
||||
t('Older or unknown'),
|
||||
'Older or unknown',
|
||||
'legend is translated',
|
||||
);
|
||||
const card = buildIncidentCard(row, now, {
|
||||
@@ -60,6 +62,7 @@ for (const locale of ['es', 'ru']) {
|
||||
'contained',
|
||||
'discovered',
|
||||
'updated',
|
||||
'last growth',
|
||||
'part of',
|
||||
'cause',
|
||||
'personnel',
|
||||
|
||||
@@ -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 (mirrors the fill). */
|
||||
/** CSS accent for a perimeter card by containment progress. */
|
||||
export function containmentAccent(containedPct) {
|
||||
if (!Number.isFinite(containedPct) || containedPct <= 0) return '#ff3b30';
|
||||
if (containedPct < 50) return '#ff7a00';
|
||||
@@ -11,55 +11,6 @@ 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.
|
||||
@@ -149,8 +100,9 @@ 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 - Normalized perimeter row (see records.js).
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @param {Object} row - A snapshot fire (see records.js).
|
||||
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
|
||||
* `at`, or now.
|
||||
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
|
||||
* @returns {Object} World-overlay entry without `position`.
|
||||
*/
|
||||
@@ -194,13 +146,17 @@ 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 = 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 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 details = [facts.join(' · ')];
|
||||
if (row.complexName)
|
||||
@@ -209,6 +165,7 @@ 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'));
|
||||
|
||||
@@ -216,7 +173,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
|
||||
name: row.name || t('Unnamed incident'),
|
||||
});
|
||||
return {
|
||||
id: `fire-perimeter-card:${row.stableId}`,
|
||||
id: `fire-perimeter-card:${row.id}`,
|
||||
// `selected` picks the paint lane and collision protection; an explicit
|
||||
// paintLane would override it in the host's lane resolver.
|
||||
selected: true,
|
||||
|
||||
@@ -1,99 +1,12 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
import { buildIncidentCard } from './cards.js';
|
||||
|
||||
test('a full incident row renders name, size, containment, and ages', () => {
|
||||
const now = 1758000000000;
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: '2026-NMGNF-000123',
|
||||
id: '2026-NMGNF-000123',
|
||||
name: 'Frijoles',
|
||||
acres: 15956.4,
|
||||
containedPct: 74,
|
||||
@@ -101,6 +14,7 @@ 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,
|
||||
@@ -116,6 +30,7 @@ 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);
|
||||
@@ -125,7 +40,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: null,
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -149,7 +64,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Timber',
|
||||
acres: 25426,
|
||||
containedPct: 44,
|
||||
@@ -177,7 +92,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Any',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -204,7 +119,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 = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Any',
|
||||
acres: null,
|
||||
containedPct: null,
|
||||
@@ -232,7 +147,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(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 342923,
|
||||
containedPct: 99,
|
||||
@@ -256,7 +171,7 @@ test('a complex member names its complex on the card', () => {
|
||||
test('a card without a link is not interactive', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Crosswhite',
|
||||
acres: 1,
|
||||
containedPct: 1,
|
||||
@@ -279,7 +194,7 @@ test('a card without a link is not interactive', () => {
|
||||
test('partial incident details render only the facts that exist', () => {
|
||||
const card = buildIncidentCard(
|
||||
{
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Whiskey',
|
||||
acres: 542,
|
||||
containedPct: 48,
|
||||
@@ -305,7 +220,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 = {
|
||||
stableId: 'x',
|
||||
id: 'x',
|
||||
name: 'Grey',
|
||||
acres: 0.25,
|
||||
containedPct: null,
|
||||
@@ -333,3 +248,22 @@ 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',
|
||||
]);
|
||||
});
|
||||
@@ -17,19 +17,8 @@ function normalizeName(name) {
|
||||
.replace(/ fire$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
function nodeCandidates(publications, { name, state }) {
|
||||
if (!Array.isArray(publications) || !name) return [];
|
||||
const wanted = normalizeName(name);
|
||||
let candidates = publications.filter(
|
||||
(row) =>
|
||||
@@ -51,20 +40,26 @@ export function resolveInciwebNodeLink(publications, { name, state }) {
|
||||
row.tau.slice(0, 2).toLowerCase() === statePrefix,
|
||||
);
|
||||
} else if (candidates.length > 1) {
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
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;
|
||||
// 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;
|
||||
}
|
||||
|
||||
/** The publication id inside a node link produced above, or null. */
|
||||
@@ -79,7 +74,8 @@ 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 recent editorial activity on the page.
|
||||
// Without a discovery date, require editorial activity on the page in the
|
||||
// 180 days up to the moment shown.
|
||||
const CHANGED_WITHIN_MS = 180 * 24 * 3600000;
|
||||
|
||||
/**
|
||||
@@ -97,7 +93,8 @@ export function isCurrentPublication(
|
||||
return createdMs >= discoveredTime - CREATED_BEFORE_DISCOVERY_MS;
|
||||
}
|
||||
if (Number.isFinite(changedMs)) {
|
||||
return nowMs - changedMs <= CHANGED_WITHIN_MS;
|
||||
const age = nowMs - changedMs;
|
||||
return age >= 0 && age <= CHANGED_WITHIN_MS;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -132,6 +129,14 @@ 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
|
||||
@@ -143,11 +148,8 @@ export function createInciwebPublicationSource({
|
||||
* - WFIGS row facts.
|
||||
* @returns {?string} InciWeb URL.
|
||||
*/
|
||||
export function findInciwebLink(publications, { name, state, complexName }) {
|
||||
return (
|
||||
resolveInciwebNodeLink(publications, { name, state }) ??
|
||||
resolveInciwebNodeLink(publications, { name: complexName, state })
|
||||
);
|
||||
export function findInciwebLink(publications, incident) {
|
||||
return findInciwebLinks(publications, incident)[0] ?? null;
|
||||
}
|
||||
|
||||
/** Fetch the full InciWeb incident catalog. */
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
resolveInciwebNodeLink,
|
||||
createInciwebIndexSource,
|
||||
createInciwebPublicationSource,
|
||||
@@ -142,6 +143,34 @@ 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, {
|
||||
@@ -214,6 +243,14 @@ 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(
|
||||
|
||||
+242
-142
@@ -1,34 +1,64 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { PERIMETER_OVERLAY_SOURCE_ID, buildIncidentCard } from './cards.js';
|
||||
import {
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
perimeterAnchorDegrees,
|
||||
buildIncidentCard,
|
||||
containmentAccent,
|
||||
} from './cards.js';
|
||||
import {
|
||||
findInciwebLink,
|
||||
findInciwebLinks,
|
||||
inciwebNodeId,
|
||||
isCurrentPublication,
|
||||
} from './inciweb.js';
|
||||
import { msg, t } from '../../i18n/index.js';
|
||||
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
|
||||
export { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
export {
|
||||
normalizeFirePerimeterSnapshot,
|
||||
perimeterAnchorDegrees,
|
||||
} from './records.js';
|
||||
export { createWfigsPerimeterSource } from './source.js';
|
||||
export * from './cards.js';
|
||||
export * from './inciweb.js';
|
||||
|
||||
const HOUR_MS = 3600000;
|
||||
|
||||
/**
|
||||
* Fill/line colour for a perimeter by containment progress (same ramp as the
|
||||
* card accent), as a renderer colour `[r, g, b, a]`.
|
||||
* 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.
|
||||
*/
|
||||
export function containmentColor(containedPct) {
|
||||
return hexColor(containmentAccent(containedPct));
|
||||
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);
|
||||
}
|
||||
|
||||
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
|
||||
const FILL_ALPHA = 0.35;
|
||||
const LINE_ALPHA = 0.9;
|
||||
const LINE_WIDTH_PX = 2;
|
||||
|
||||
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
|
||||
@@ -52,10 +82,29 @@ const INCIWEB_INDEX_TTL_MS = 6 * 3600000;
|
||||
/**
|
||||
* Own one fire-perimeter display, its refresh lifecycle, and click selection.
|
||||
*
|
||||
* 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.
|
||||
* `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.
|
||||
*/
|
||||
export function createFirePerimetersLayer({
|
||||
source,
|
||||
@@ -71,12 +120,17 @@ export function createFirePerimetersLayer({
|
||||
let _viewer = null;
|
||||
let _request = null;
|
||||
let _linkRequest = null;
|
||||
let _snapshotSignature = null;
|
||||
// What the sets show: the snapshot revision and each piece's age band.
|
||||
let _drawnKey = 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;
|
||||
@@ -88,16 +142,23 @@ export function createFirePerimetersLayer({
|
||||
let _inciwebIndex = [];
|
||||
let _indexFetchedAt = 0;
|
||||
let _indexFetchInFlight = false;
|
||||
/** @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();
|
||||
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();
|
||||
function abortLinkVerification() {
|
||||
_linkRequest?.controller.abort();
|
||||
_linkRequest = null;
|
||||
}
|
||||
|
||||
function resetSelection() {
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
}
|
||||
|
||||
const canSelect = () => overlayHost && inputFor && picking;
|
||||
|
||||
/**
|
||||
@@ -141,13 +202,8 @@ export function createFirePerimetersLayer({
|
||||
.getPublication(id, { signal })
|
||||
.then((publication) => {
|
||||
if (signal.aborted || _linkRequest !== request || !_enabled) return;
|
||||
_linkVerdicts.set(
|
||||
link,
|
||||
isCurrentPublication(publication, {
|
||||
discoveredTime: row.discoveredTime,
|
||||
}),
|
||||
);
|
||||
if (_selectedId === row.stableId) publishSelectedCard();
|
||||
_linkPublications.set(link, publication ?? {});
|
||||
if (_selectedId === row.id) publishSelectedCard();
|
||||
})
|
||||
.catch(() => {
|
||||
// Fail closed without caching: no link now, retry on reselection.
|
||||
@@ -157,13 +213,44 @@ export function createFirePerimetersLayer({
|
||||
});
|
||||
}
|
||||
|
||||
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 (!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 ? _rowById.get(_selectedId) : null;
|
||||
const row = _selectedId ? _fireById.get(_selectedId) : null;
|
||||
if (!row) {
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
resetSelection();
|
||||
overlayHost.setEntries(
|
||||
PERIMETER_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
@@ -171,12 +258,15 @@ export function createFirePerimetersLayer({
|
||||
);
|
||||
return;
|
||||
}
|
||||
const candidate = findInciwebLink(_inciwebIndex, row);
|
||||
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
|
||||
_selectedLink =
|
||||
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
|
||||
// Live, the newest same-name page stands for the incident. A past `at`
|
||||
// checks each, since the newest may postdate it.
|
||||
const links = findInciwebLinks(_inciwebIndex, row);
|
||||
const candidates = _at === null ? links.slice(0, 1) : links;
|
||||
const unverified = candidates.find((link) => !_linkPublications.has(link));
|
||||
if (unverified) verifyLink(unverified, row);
|
||||
_selectedLink = unverified ? null : chooseLink(candidates, row);
|
||||
const card = {
|
||||
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
|
||||
...buildIncidentCard(row, shownAt(), { link: _selectedLink }),
|
||||
position: fromDegrees(row.anchor.lon, row.anchor.lat),
|
||||
};
|
||||
if (!openExternal) card.interactive = false;
|
||||
@@ -201,11 +291,9 @@ export function createFirePerimetersLayer({
|
||||
* of this layer's own sets, for an incident drawn now; else null.
|
||||
*/
|
||||
function pickedIncidentId(hit) {
|
||||
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;
|
||||
if (!hit || hit.surface) return null;
|
||||
const incidentId = _fireByItem.get(`${hit.set}\n${hit.id}`);
|
||||
return incidentId != null && _fireById.has(incidentId) ? incidentId : null;
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
@@ -247,23 +335,67 @@ 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() {
|
||||
abortLinkVerification();
|
||||
_selectedId = null;
|
||||
_selectedLink = null;
|
||||
_selectedCardId = null;
|
||||
resetSelection();
|
||||
if (overlayHost) {
|
||||
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
|
||||
@@ -292,9 +424,7 @@ export function createFirePerimetersLayer({
|
||||
clampTo: 'both',
|
||||
show: false,
|
||||
});
|
||||
_setIds = new Set([_fills.id, _lines.id]);
|
||||
_viewer = viewer;
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -318,87 +448,55 @@ export function createFirePerimetersLayer({
|
||||
clearSelection();
|
||||
},
|
||||
|
||||
async update() {
|
||||
async update(_viewerArg, { signal } = {}) {
|
||||
if (!_enabled || !_fills) return false;
|
||||
_request?.abort();
|
||||
const request = new AbortController();
|
||||
_request = request;
|
||||
refreshInciwebIndex(request.signal);
|
||||
const abort = () => request.abort(signal.reason);
|
||||
if (signal?.aborted) abort();
|
||||
else signal?.addEventListener('abort', abort, { once: true });
|
||||
try {
|
||||
// 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 }) };
|
||||
refreshInciwebIndex(request.signal);
|
||||
const snapshot = await source.getSnapshot({ signal: request.signal });
|
||||
if (request.signal.aborted || _request !== request || !_enabled)
|
||||
return false;
|
||||
const { rows } = snapshot;
|
||||
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
|
||||
throw new Error(msg('Malformed perimeter 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();
|
||||
|
||||
// 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)),
|
||||
_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),
|
||||
);
|
||||
if (signature === _snapshotSignature) {
|
||||
if (_selectedId) publishSelectedCard();
|
||||
_lastUpdate = updatedAt;
|
||||
_lastError = null;
|
||||
return true;
|
||||
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;
|
||||
}
|
||||
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.
|
||||
// Refresh (or drop) the selected incident's card against the new
|
||||
// snapshot: its ages move with `at` even when nothing is redrawn.
|
||||
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)
|
||||
@@ -409,6 +507,7 @@ export function createFirePerimetersLayer({
|
||||
_stale = false;
|
||||
return false;
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', abort);
|
||||
if (_request === request) _request = null;
|
||||
}
|
||||
},
|
||||
@@ -418,18 +517,20 @@ export function createFirePerimetersLayer({
|
||||
_request = null;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
_rowById.clear();
|
||||
_snapshotSignature = null;
|
||||
_fireById = new Map();
|
||||
_fireByItem.clear();
|
||||
_drawnKey = null;
|
||||
_at = null;
|
||||
_bandsAt = null;
|
||||
_note = null;
|
||||
_inciwebIndex = [];
|
||||
_indexFetchedAt = 0;
|
||||
_linkVerdicts.clear();
|
||||
_linkPublications.clear();
|
||||
_viewer = null;
|
||||
_enabled = false;
|
||||
_fills?.dispose();
|
||||
_lines?.dispose();
|
||||
_fills = _lines = null;
|
||||
_setIds = new Set();
|
||||
_count = 0;
|
||||
_lastUpdate = null;
|
||||
_lastError = null;
|
||||
_stale = false;
|
||||
@@ -442,11 +543,11 @@ export function createFirePerimetersLayer({
|
||||
? Math.max(1, Math.floor(maxCount))
|
||||
: 2000;
|
||||
const result = [];
|
||||
for (const row of _rowById.values()) {
|
||||
for (const fire of _fireById.values()) {
|
||||
if (result.length >= limit) break;
|
||||
const { anchor, stableId, ...facts } = row;
|
||||
const { anchor, id, ...facts } = fire;
|
||||
result.push({
|
||||
id: stableId,
|
||||
id,
|
||||
...facts,
|
||||
lat: anchor.lat,
|
||||
lon: anchor.lon,
|
||||
@@ -455,34 +556,33 @@ export function createFirePerimetersLayer({
|
||||
return result;
|
||||
},
|
||||
|
||||
/** The moment the analyst records show: the snapshot's `at`, or null for now. */
|
||||
getAnalystRecordsAt() {
|
||||
return _at;
|
||||
},
|
||||
|
||||
getRowControls() {
|
||||
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) },
|
||||
];
|
||||
const atMs = _bandsAt;
|
||||
const counts = PERIMETER_AGE_BANDS.map(() => 0);
|
||||
for (const fire of _fireById.values())
|
||||
counts[perimeterAgeBand(fire.lastGrowthTime, atMs)]++;
|
||||
return {
|
||||
chips: [],
|
||||
legend: bands.map((band, index) => ({
|
||||
...band,
|
||||
count: [..._rowById.values()].filter(
|
||||
(row) => containmentAccent(row.containedPct) === band.color,
|
||||
).length,
|
||||
legend: PERIMETER_AGE_BANDS.map((band, index) => ({
|
||||
label: t(band.label),
|
||||
color: band.color,
|
||||
count: counts[index],
|
||||
...(index === 0
|
||||
? {
|
||||
blurb: t(
|
||||
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
|
||||
),
|
||||
}
|
||||
? { blurb: t('Colour shows the age of each area.') }
|
||||
: {}),
|
||||
})),
|
||||
...(_note ? { info: t(_note) } : {}),
|
||||
};
|
||||
},
|
||||
|
||||
getStats() {
|
||||
return {
|
||||
count: _count,
|
||||
count: _fireById.size,
|
||||
lastUpdate: _lastUpdate,
|
||||
error: _lastError,
|
||||
stale: _stale,
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createFirePerimetersLayer } from './index.js';
|
||||
import {
|
||||
createFirePerimetersLayer,
|
||||
perimeterAnchorDegrees,
|
||||
PERIMETER_AGE_BANDS,
|
||||
} from './index.js';
|
||||
import { firePerimeterSnapshot } from './records.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
import { LayerLifecycle } from '../../data/lifecycle.js';
|
||||
import { clickCard } from '../../data/pickRegistry.js';
|
||||
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
@@ -17,6 +25,7 @@ const liveSet = (draw, suffix) =>
|
||||
function harness(
|
||||
source,
|
||||
{
|
||||
init = true,
|
||||
pick = () => null,
|
||||
inciwebIndex = null,
|
||||
cardHit = () => null,
|
||||
@@ -72,9 +81,11 @@ function harness(
|
||||
inciwebPublications: { getPublication: publication },
|
||||
openExternal: (url) => opened.push(url),
|
||||
});
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
fillsSetId = liveSet(draw, ':fills').spec.id;
|
||||
if (init) {
|
||||
layer.init(viewer);
|
||||
layer.enable(viewer);
|
||||
fillsSetId = liveSet(draw, ':fills').spec.id;
|
||||
}
|
||||
return {
|
||||
layer,
|
||||
viewer,
|
||||
@@ -97,8 +108,9 @@ const ring = [
|
||||
[-108.0, 35.3],
|
||||
[-108.1, 35.2],
|
||||
];
|
||||
const row = {
|
||||
stableId: '2026-NMGNF-000123',
|
||||
const HOUR = 3600000;
|
||||
const fire = {
|
||||
id: '2026-NMGNF-000123',
|
||||
name: 'Fixture Fire',
|
||||
acres: 512.5,
|
||||
containedPct: 40,
|
||||
@@ -113,58 +125,105 @@ const row = {
|
||||
costToDate: 4200000,
|
||||
complexity: 'Type 3 Incident',
|
||||
complexName: 'ROWE CREEK COMPLEX',
|
||||
polygons: [[ring]],
|
||||
lastGrowthTime: 1757950000000,
|
||||
anchor: perimeterAnchorDegrees([[ring]]),
|
||||
};
|
||||
/** One piece of `fireId`'s area: one polygon, outlined by its rings. */
|
||||
const pieceOf = (fireId, { rings = [ring], born = null, ...rest } = {}) => ({
|
||||
fireId,
|
||||
born,
|
||||
polygons: [rings],
|
||||
outline: rings,
|
||||
...rest,
|
||||
});
|
||||
/** A source snapshot of `fires`, one piece each unless `pieces` is given. */
|
||||
function snap(fires, { pieces, ...rest } = {}) {
|
||||
return {
|
||||
at: null,
|
||||
fetchedAt: null,
|
||||
stale: false,
|
||||
revision: 'r1',
|
||||
note: null,
|
||||
fires,
|
||||
pieces: pieces ?? fires.map(({ id }) => pieceOf(id)),
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
const tick = () => new Promise((done) => setTimeout(done, 0));
|
||||
const rgba = (band, alpha) => hexColor(PERIMETER_AGE_BANDS[band].color, alpha);
|
||||
|
||||
test('each perimeter polygon draws as one clamped fill with its draped fire line', async () => {
|
||||
test('each piece draws as a clamped fill and its outline as draped lines, coloured by age', async () => {
|
||||
const hole = [
|
||||
[-108.08, 35.22],
|
||||
[-108.02, 35.22],
|
||||
[-108.02, 35.25],
|
||||
[-108.08, 35.22],
|
||||
];
|
||||
const at = Date.UTC(2025, 7, 1, 12);
|
||||
const other = { ...fire, id: 'other', containedPct: 100 };
|
||||
const h = harness({
|
||||
getSnapshot: async () => [
|
||||
{ ...row, polygons: [[ring, hole]] },
|
||||
{
|
||||
...row,
|
||||
stableId: 'other',
|
||||
containedPct: 100,
|
||||
polygons: [[ring], [ring]],
|
||||
},
|
||||
],
|
||||
getSnapshot: async () =>
|
||||
snap([fire, other], {
|
||||
at,
|
||||
pieces: [
|
||||
pieceOf(fire.id, { rings: [ring, hole], born: at - HOUR }),
|
||||
// A piece cut from a larger area: no line along the cut.
|
||||
{
|
||||
fireId: 'other',
|
||||
born: at - 30 * HOUR,
|
||||
polygons: [[ring]],
|
||||
outline: [ring.slice(0, 3)],
|
||||
},
|
||||
pieceOf('other', { born: null }),
|
||||
],
|
||||
}),
|
||||
});
|
||||
assert.equal(h.fills().show, true);
|
||||
assert.equal(h.lines().show, true);
|
||||
assert.equal(await h.layer.update(h.viewer), true);
|
||||
const ids = [
|
||||
'fire-perimeter:2026-NMGNF-000123:0',
|
||||
'fire-perimeter:other:0',
|
||||
'fire-perimeter:other:1',
|
||||
];
|
||||
assert.deepEqual([...h.fills().items.keys()], ids);
|
||||
assert.deepEqual([...h.lines().items.keys()], ids);
|
||||
const fill = h.fills().items.get(ids[0]);
|
||||
assert.deepEqual(
|
||||
[...h.fills().items.keys()],
|
||||
[
|
||||
'fire-perimeter:2026-NMGNF-000123:0',
|
||||
'fire-perimeter:other:0',
|
||||
'fire-perimeter:other:1',
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...h.lines().items.keys()],
|
||||
[
|
||||
'fire-perimeter:2026-NMGNF-000123:line:0',
|
||||
'fire-perimeter:2026-NMGNF-000123:line:1',
|
||||
'fire-perimeter:other:line:0',
|
||||
'fire-perimeter:other:line:1',
|
||||
],
|
||||
);
|
||||
const fill = h.fills().items.get('fire-perimeter:2026-NMGNF-000123:0');
|
||||
assert.equal(fill.height, 'clampGround');
|
||||
assert.deepEqual(fill.fill, [1, 122 / 255, 0, 0.25]);
|
||||
assert.deepEqual(fill.fill, rgba(0, 0.35));
|
||||
assert.equal(fill.geometry.kind, 'polygon');
|
||||
assert.equal(fill.geometry.rings.length, 2, 'the hole stays');
|
||||
assert.deepEqual(fill.geometry.rings[0][1], { lon: -108.0, lat: 35.2 });
|
||||
const line = h.lines().items.get(ids[0]);
|
||||
const line = h.lines().items.get('fire-perimeter:2026-NMGNF-000123:line:1');
|
||||
assert.equal(line.mode, 'draped');
|
||||
assert.equal(line.widthPx, 2);
|
||||
assert.deepEqual(line.style, {
|
||||
kind: 'solid',
|
||||
color: [1, 122 / 255, 0, 0.9],
|
||||
});
|
||||
assert.equal(line.positions.length, ring.length, 'the exterior ring only');
|
||||
assert.deepEqual(line.style, { kind: 'solid', color: rgba(0, 0.9) });
|
||||
assert.equal(line.positions.length, hole.length, 'the hole is outlined too');
|
||||
assert.ok(Number.isFinite(line.positions[0].x), 'lines take ECEF');
|
||||
assert.deepEqual(h.fills().items.get(ids[1]).fill, [
|
||||
139 / 255,
|
||||
195 / 255,
|
||||
74 / 255,
|
||||
0.25,
|
||||
]);
|
||||
assert.equal(
|
||||
h.lines().items.get('fire-perimeter:other:line:0').positions.length,
|
||||
3,
|
||||
'the outline as given, not the polygon',
|
||||
);
|
||||
// Aged at the snapshot's moment, not now: 30 h is 1–3 days; unknown is oldest.
|
||||
assert.deepEqual(
|
||||
h.fills().items.get('fire-perimeter:other:0').fill,
|
||||
rgba(2, 0.35),
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.fills().items.get('fire-perimeter:other:1').fill,
|
||||
rgba(3, 0.35),
|
||||
);
|
||||
assert.equal(h.layer.getStats().count, 2);
|
||||
h.layer.disable();
|
||||
assert.equal(h.fills().show, false);
|
||||
@@ -174,10 +233,23 @@ test('each perimeter polygon draws as one clamped fill with its draped fire line
|
||||
assert.equal(h.lines(), undefined);
|
||||
});
|
||||
|
||||
test('a piece of a fire the snapshot does not list is dropped', async () => {
|
||||
const h = harness({
|
||||
getSnapshot: async () =>
|
||||
snap([fire], { pieces: [pieceOf(fire.id), pieceOf('ghost')] }),
|
||||
});
|
||||
await h.layer.update();
|
||||
assert.deepEqual(
|
||||
[...h.fills().items.keys()],
|
||||
['fire-perimeter:2026-NMGNF-000123:0'],
|
||||
);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test("a pick selects only an item of the layer's own sets", async () => {
|
||||
let pickResult = null;
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{ pick: () => pickResult },
|
||||
);
|
||||
await h.layer.update(h.viewer);
|
||||
@@ -188,7 +260,10 @@ test("a pick selects only an item of the layer's own sets", async () => {
|
||||
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
|
||||
// The fire line picks as its perimeter, as the one entity used to.
|
||||
pickResult = {
|
||||
id: { set: h.lines().spec.id, id: 'fire-perimeter:2026-NMGNF-000123:0' },
|
||||
id: {
|
||||
set: h.lines().spec.id,
|
||||
id: 'fire-perimeter:2026-NMGNF-000123:line:0',
|
||||
},
|
||||
};
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
assert.equal(h.overlay.entries.get('fire-perimeters').length, 1);
|
||||
@@ -209,7 +284,7 @@ test('late refresh cannot publish after disable or destroy', async () => {
|
||||
h.layer[action](h.viewer);
|
||||
assert.equal(signal.aborted, true);
|
||||
if (action === 'disable') h.layer.enable(h.viewer);
|
||||
resolve([row]);
|
||||
resolve(snap([fire]));
|
||||
assert.equal(await pending, false);
|
||||
assert.equal(h.layer.getStats().count, 0);
|
||||
h.layer.destroy(h.viewer);
|
||||
@@ -219,7 +294,7 @@ test('late refresh cannot publish after disable or destroy', async () => {
|
||||
test('clicking a perimeter publishes its incident card; empty space clears it', async () => {
|
||||
let pickResult = null;
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{
|
||||
pick: () => pickResult,
|
||||
},
|
||||
@@ -259,7 +334,7 @@ test("another layer's overlay on top keeps a click off the area", async () => {
|
||||
let pickResult = null;
|
||||
let foreignOnTop = false;
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{
|
||||
pick: () => pickResult,
|
||||
// Unfiltered: the topmost entry of any source.
|
||||
@@ -292,7 +367,7 @@ test("another layer's overlay on top keeps a click off the area", async () => {
|
||||
|
||||
test('disable removes the click handler, pick ownership, and any card', async () => {
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
|
||||
);
|
||||
await h.layer.update(h.viewer);
|
||||
@@ -304,7 +379,7 @@ test('disable removes the click handler, pick ownership, and any card', async ()
|
||||
});
|
||||
|
||||
test('a refresh that drops the selected incident also drops its card', async () => {
|
||||
let rows = [row];
|
||||
let rows = snap([fire]);
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => rows },
|
||||
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
|
||||
@@ -312,11 +387,61 @@ test('a refresh that drops the selected incident also drops its card', async ()
|
||||
await h.layer.update(h.viewer);
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
assert.equal(h.overlay.entries.get('fire-perimeters').length, 1);
|
||||
rows = [{ ...row, stableId: 'different' }];
|
||||
rows = snap([{ ...fire, id: 'different' }], { revision: 'r2' });
|
||||
await h.layer.update(h.viewer);
|
||||
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
|
||||
});
|
||||
|
||||
test('a selected fire keeps its card while listed, even with no pieces left', async () => {
|
||||
let current = snap([fire]);
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => current },
|
||||
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
|
||||
);
|
||||
await h.layer.update();
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
current = snap([fire], { pieces: [] });
|
||||
await h.layer.update();
|
||||
assert.equal(h.fills().items.size, 0);
|
||||
const [card] = h.overlay.entries.get('fire-perimeters');
|
||||
assert.equal(card.id, 'fire-perimeter-card:2026-NMGNF-000123');
|
||||
assert.equal(h.layer.getStats().count, 1, 'a fire without pieces counts');
|
||||
assert.equal(
|
||||
h.layer.getRowControls().legend.reduce((sum, { count }) => sum + count, 0),
|
||||
1,
|
||||
);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('the card ages from the moment the snapshot shows', async () => {
|
||||
const at = Date.UTC(2025, 7, 1, 12);
|
||||
const h = harness(
|
||||
{
|
||||
getSnapshot: async () =>
|
||||
snap(
|
||||
[
|
||||
{
|
||||
...fire,
|
||||
discoveredTime: at - 50 * HOUR,
|
||||
updatedTime: at - 2 * HOUR,
|
||||
lastGrowthTime: at - 5 * HOUR,
|
||||
},
|
||||
],
|
||||
{ at },
|
||||
),
|
||||
},
|
||||
{ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0') },
|
||||
);
|
||||
await h.layer.update();
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
const [card] = h.overlay.entries.get('fire-perimeters');
|
||||
assert.deepEqual(card.details.slice(-2), [
|
||||
'last growth 5h ago',
|
||||
'discovered 2d ago · updated 2h ago',
|
||||
]);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('a matched incident card carries the InciWeb line and click-through', async () => {
|
||||
const inciwebIndex = [
|
||||
{
|
||||
@@ -328,7 +453,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
|
||||
let cardHitResult = null;
|
||||
let foreignOnTop = false;
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [{ ...row, name: 'Fixture' }] },
|
||||
{ getSnapshot: async () => snap([{ ...fire, name: 'Fixture' }]) },
|
||||
{
|
||||
pick: () => null,
|
||||
inciwebIndex,
|
||||
@@ -371,7 +496,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
|
||||
test('a click on a mission label over the incident card never opens its InciWeb page, and keeps the card open', async () => {
|
||||
let cardHitResult = null;
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{
|
||||
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
|
||||
inciwebIndex: [
|
||||
@@ -409,7 +534,7 @@ test('a click on a mission label over the incident card never opens its InciWeb
|
||||
test('an unmatched incident renders no InciWeb line and card clicks stay inert', async () => {
|
||||
let cardHitResult = null;
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{
|
||||
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
|
||||
inciwebIndex: [],
|
||||
@@ -432,7 +557,7 @@ test('an unmatched incident renders no InciWeb line and card clicks stay inert',
|
||||
|
||||
test('a complex member resolves to its complex page from the catalog', async () => {
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{
|
||||
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
|
||||
inciwebIndex: [
|
||||
@@ -473,7 +598,7 @@ test('a stale or unverifiable publication yields no link', async () => {
|
||||
},
|
||||
]) {
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{
|
||||
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
|
||||
inciwebIndex,
|
||||
@@ -495,17 +620,20 @@ test('a stale or unverifiable publication yields no link', async () => {
|
||||
});
|
||||
|
||||
test('a hanging InciWeb index fetch never blocks the perimeter refresh', async (t) => {
|
||||
const h = harness({ getSnapshot: async () => [row] }, { inciwebIndex: null });
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => snap([fire]) },
|
||||
{ inciwebIndex: null },
|
||||
);
|
||||
// Replace the index source with one that never resolves.
|
||||
h.layer.destroy(h.viewer);
|
||||
const hanging = harness({ getSnapshot: async () => [row] });
|
||||
const hanging = harness({ getSnapshot: async () => snap([fire]) });
|
||||
hanging.layer.destroy(hanging.viewer);
|
||||
const viewer = { scene: { pick: () => null } };
|
||||
bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
t.after(() => input.destroy());
|
||||
const layer = createFirePerimetersLayer({
|
||||
source: { getSnapshot: async () => [row] },
|
||||
source: { getSnapshot: async () => snap([fire]) },
|
||||
overlayHost: {
|
||||
setEntries() {},
|
||||
setVisible() {},
|
||||
@@ -537,9 +665,9 @@ test('a hanging InciWeb index fetch never blocks the perimeter refresh', async (
|
||||
});
|
||||
|
||||
test('an InciWeb outage never breaks the perimeter refresh', async (t) => {
|
||||
const h = harness({ getSnapshot: async () => [row] });
|
||||
const h = harness({ getSnapshot: async () => snap([fire]) });
|
||||
const failing = createFirePerimetersLayer({
|
||||
source: { getSnapshot: async () => [row] },
|
||||
source: { getSnapshot: async () => snap([fire]) },
|
||||
overlayHost: {
|
||||
setEntries() {},
|
||||
setVisible() {},
|
||||
@@ -577,7 +705,7 @@ test('an InciWeb outage never breaks the perimeter refresh', async (t) => {
|
||||
});
|
||||
|
||||
test('analyst records expose incident facts without geometry payloads', async () => {
|
||||
const h = harness({ getSnapshot: async () => [row] });
|
||||
const h = harness({ getSnapshot: async () => snap([fire]) });
|
||||
await h.layer.update(h.viewer);
|
||||
const records = h.layer.getAnalystRecords();
|
||||
assert.equal(records.length, 1);
|
||||
@@ -591,95 +719,129 @@ test('analyst records expose incident facts without geometry payloads', async ()
|
||||
assert.equal(records[0].county, 'Sandoval');
|
||||
assert.equal(records[0].costToDate, 4200000);
|
||||
assert.equal(records[0].complexity, 'Type 3 Incident');
|
||||
assert.equal(records[0].lastGrowthTime, fire.lastGrowthTime);
|
||||
assert.equal(records[0].id, fire.id);
|
||||
// Spatial scoping in the analyst engine requires coordinates.
|
||||
assert.ok(Math.abs(records[0].lat - 35.2333) < 0.01);
|
||||
assert.ok(Math.abs(records[0].lon - -108.0333) < 0.01);
|
||||
assert.equal('polygons' in records[0], false);
|
||||
assert.equal('polygons' in records[0] || 'anchor' in records[0], false);
|
||||
});
|
||||
|
||||
test('unchanged snapshots draw nothing again even if source ordering changes', async () => {
|
||||
let rows = [row, { ...row, stableId: 'other' }];
|
||||
const h = harness({ getSnapshot: async () => rows });
|
||||
await h.layer.update();
|
||||
test('the layer redraws on a new revision or a change of age band, and only then', async () => {
|
||||
const at = Date.UTC(2025, 7, 1, 12);
|
||||
const other = { ...fire, id: 'other' };
|
||||
let current = snap([fire, other], {
|
||||
at,
|
||||
pieces: [pieceOf(fire.id, { born: at - HOUR }), pieceOf('other')],
|
||||
});
|
||||
const h = harness({ getSnapshot: async () => current });
|
||||
const writes = () => [h.fills().writes, h.lines().writes];
|
||||
assert.deepEqual(writes(), [1, 1]);
|
||||
rows = [...rows].reverse();
|
||||
await h.layer.update();
|
||||
assert.deepEqual(writes(), [1, 1]);
|
||||
rows = rows.map((value) => ({
|
||||
...value,
|
||||
updatedTime: value.updatedTime + 1,
|
||||
}));
|
||||
// Same revision, feed reordered, facts changed, still in the same band.
|
||||
current = {
|
||||
...current,
|
||||
at: at + 4 * HOUR,
|
||||
fires: [{ ...other, containedPct: 100 }, fire],
|
||||
};
|
||||
await h.layer.update();
|
||||
assert.deepEqual(writes(), [1, 1]);
|
||||
// The new piece turns 6 h old.
|
||||
current = { ...current, at: at + 6 * HOUR };
|
||||
await h.layer.update();
|
||||
assert.deepEqual(writes(), [2, 2]);
|
||||
rows = rows.map((value) => ({ ...value, containedPct: 100 }));
|
||||
await h.layer.update();
|
||||
assert.deepEqual(
|
||||
writes(),
|
||||
[3, 3],
|
||||
'incident facts can change without a new polygon timestamp',
|
||||
h.fills().items.get('fire-perimeter:2026-NMGNF-000123:0').fill,
|
||||
rgba(1, 0.35),
|
||||
);
|
||||
assert.equal(h.layer.getRowControls().legend[3].count, 2);
|
||||
rows = [];
|
||||
current = { ...current, revision: 'changed' };
|
||||
await h.layer.update();
|
||||
assert.deepEqual(writes(), [3, 3]);
|
||||
// A source without a revision is drawn every time.
|
||||
current = { ...current, revision: undefined };
|
||||
await h.layer.update();
|
||||
await h.layer.update();
|
||||
assert.deepEqual(writes(), [5, 5]);
|
||||
current = snap([]);
|
||||
await h.layer.update();
|
||||
assert.equal(h.fills().items.size, 0);
|
||||
assert.equal(h.lines().items.size, 0);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('containment legend uses the existing thresholds, colours and incident counts', async () => {
|
||||
const values = [null, -1, 0, 0.5, 49.9, 50, 99.9, 100, 101];
|
||||
test('a failed read keeps the picture and reports the error', async () => {
|
||||
let fail = false;
|
||||
const h = harness({
|
||||
getSnapshot: async () => {
|
||||
if (fail) throw new Error('WFIGS HTTP 502');
|
||||
return snap([fire]);
|
||||
},
|
||||
});
|
||||
await h.layer.update();
|
||||
fail = true;
|
||||
assert.equal(await h.layer.update(), false);
|
||||
assert.equal(h.fills().items.size, 1);
|
||||
assert.equal(h.layer.getStats().error, 'WFIGS HTTP 502');
|
||||
assert.equal(h.layer.getStats().count, 1);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('a malformed snapshot is an error, not an empty map', async () => {
|
||||
const h = harness({ getSnapshot: async () => [fire] });
|
||||
assert.equal(await h.layer.update(), false);
|
||||
assert.equal(h.layer.getStats().error, 'Malformed perimeter snapshot');
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('the legend counts fires by their last growth at the moment shown, with the source note', async () => {
|
||||
const at = Date.UTC(2025, 7, 1, 12);
|
||||
const ages = [0, 5.9, 6, 23.9, 24, 71.9, 72, null, -1];
|
||||
const h = harness({
|
||||
getSnapshot: async () =>
|
||||
values.map((containedPct, index) => ({
|
||||
...row,
|
||||
stableId: String(index),
|
||||
containedPct,
|
||||
})),
|
||||
snap(
|
||||
ages.map((hours, index) => ({
|
||||
...fire,
|
||||
id: String(index),
|
||||
lastGrowthTime: hours === null ? null : at - hours * HOUR,
|
||||
})),
|
||||
{ at, note: 'Perimeters are simplified to about 100 m.' },
|
||||
),
|
||||
});
|
||||
await h.layer.update();
|
||||
const controls = h.layer.getRowControls();
|
||||
assert.deepEqual(controls.chips, []);
|
||||
assert.deepEqual(
|
||||
controls.legend.map(({ color, count }) => [color, count]),
|
||||
controls.legend.map(({ label, color, count }) => [label, color, count]),
|
||||
[
|
||||
['#ff3b30', 3],
|
||||
['#ff7a00', 2],
|
||||
['#ffb300', 2],
|
||||
['#8bc34a', 2],
|
||||
['Last 6 hours', '#ffc72e', 2],
|
||||
['6–24 hours', '#ff730d', 2],
|
||||
['1–3 days', '#d9290d', 2],
|
||||
['Older or unknown', '#730f0a', 3],
|
||||
],
|
||||
);
|
||||
assert.ok(
|
||||
controls.legend.every(
|
||||
({ label }) => typeof label === 'string' && label.length,
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
controls.legend[0].blurb,
|
||||
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
|
||||
);
|
||||
assert.equal(controls.legend[0].blurb, 'Colour shows the age of each area.');
|
||||
assert.equal(controls.info, 'Perimeters are simplified to about 100 m.');
|
||||
h.layer.destroy();
|
||||
assert.deepEqual(
|
||||
h.layer.getRowControls().legend.map(({ count }) => count),
|
||||
[0, 0, 0, 0],
|
||||
);
|
||||
assert.equal(h.layer.getRowControls().info, undefined);
|
||||
});
|
||||
|
||||
for (const action of ['disable', 'destroy', 'selection']) {
|
||||
test(`incident-link verification aborts on ${action} and ignores late completion`, async () => {
|
||||
let finish, signal;
|
||||
let pickId = `fire-perimeter:${row.stableId}:0`;
|
||||
let pickId = `fire-perimeter:${fire.id}:0`;
|
||||
const h = harness(
|
||||
{
|
||||
getSnapshot: async () => [
|
||||
row,
|
||||
{ ...row, stableId: 'other', name: 'Other Fire' },
|
||||
],
|
||||
getSnapshot: async () =>
|
||||
snap([fire, { ...fire, id: 'other', name: 'Other Fire' }]),
|
||||
},
|
||||
{
|
||||
pick: () => perimeterPick(pickId),
|
||||
inciwebIndex: [
|
||||
{ incident_id: '123', incident_title: row.name, tau: 'nm' },
|
||||
{ incident_id: '123', incident_title: fire.name, tau: 'nm' },
|
||||
],
|
||||
publication: (_id, options) => {
|
||||
signal = options.signal;
|
||||
@@ -698,7 +860,7 @@ for (const action of ['disable', 'destroy', 'selection']) {
|
||||
} else h.layer[action]();
|
||||
assert.equal(signal.aborted, true);
|
||||
const entries = h.overlay.entries.get('fire-perimeters');
|
||||
finish({ createdMs: row.discoveredTime, changedMs: row.updatedTime });
|
||||
finish({ createdMs: fire.discoveredTime, changedMs: fire.updatedTime });
|
||||
await new Promise(setImmediate);
|
||||
assert.equal(h.overlay.entries.get('fire-perimeters'), entries);
|
||||
if (action !== 'destroy') h.layer.destroy();
|
||||
@@ -707,15 +869,12 @@ for (const action of ['disable', 'destroy', 'selection']) {
|
||||
|
||||
test('a stale snapshot reads stale, dated by its own fetch, and a fresh one clears it', async () => {
|
||||
const fetchedAt = Date.now() - 3 * 60 * 60 * 1000;
|
||||
let snapshot = { rows: [row], stale: true, fetchedAt };
|
||||
const h = harness({
|
||||
getSnapshot: async () => snapshot.rows,
|
||||
getSnapshotDetail: async () => snapshot,
|
||||
});
|
||||
let snapshot = snap([fire], { stale: true, fetchedAt });
|
||||
const h = harness({ getSnapshot: async () => snapshot });
|
||||
await h.layer.update(h.viewer);
|
||||
assert.equal(h.layer.getStats().stale, true);
|
||||
assert.equal(h.layer.getStats().lastUpdate, fetchedAt);
|
||||
snapshot = { rows: [row], stale: false, fetchedAt: Date.now() };
|
||||
snapshot = snap([fire], { fetchedAt: Date.now() });
|
||||
await h.layer.update(h.viewer);
|
||||
assert.equal(h.layer.getStats().stale, false);
|
||||
assert.ok(h.layer.getStats().lastUpdate > fetchedAt);
|
||||
@@ -724,10 +883,9 @@ test('a stale snapshot reads stale, dated by its own fetch, and a fresh one clea
|
||||
test('a failed refresh after a stale snapshot reads as the failure, not stale', async () => {
|
||||
let fail = false;
|
||||
const h = harness({
|
||||
getSnapshot: async () => [row],
|
||||
getSnapshotDetail: async () => {
|
||||
getSnapshot: async () => {
|
||||
if (fail) throw new Error('WFIGS HTTP 502');
|
||||
return { rows: [row], stale: true, fetchedAt: Date.now() - 60_000 };
|
||||
return snap([fire], { stale: true, fetchedAt: Date.now() - 60_000 });
|
||||
},
|
||||
});
|
||||
await h.layer.update(h.viewer);
|
||||
@@ -737,3 +895,219 @@ test('a failed refresh after a stale snapshot reads as the failure, not stale',
|
||||
assert.equal(h.layer.getStats().stale, false);
|
||||
assert.equal(h.layer.getStats().error, 'WFIGS HTTP 502');
|
||||
});
|
||||
|
||||
test('a WFIGS fire without poly_DateCurrent redraws when its outline moves', async () => {
|
||||
const T = Date.UTC(2026, 10, 20, 12);
|
||||
const sq = (dx) => [
|
||||
[-108 + dx, 35],
|
||||
[-107.9 + dx, 35],
|
||||
[-107.9 + dx, 35.1],
|
||||
[-108 + dx, 35.1],
|
||||
[-108 + dx, 35],
|
||||
];
|
||||
const rowOf = (dx, polygonTime, acres) => ({
|
||||
stableId: 'X',
|
||||
name: 'X Fire',
|
||||
acres,
|
||||
containedPct: 0,
|
||||
discoveredTime: T - 10 * 3600000,
|
||||
updatedTime: null,
|
||||
polygonTime,
|
||||
polygons: [[sq(dx)]],
|
||||
});
|
||||
for (const [a, b] of [
|
||||
[rowOf(0, T - 2 * 3600000, 10), rowOf(1, T - 3600000, 20)],
|
||||
[rowOf(0, null, 10), rowOf(1, null, 20)],
|
||||
]) {
|
||||
const realNow = Date.now;
|
||||
Date.now = () => T;
|
||||
try {
|
||||
let cur = a;
|
||||
const h = harness({
|
||||
getSnapshot: async () => firePerimeterSnapshot([cur], { now: T }),
|
||||
});
|
||||
assert.equal(await h.layer.update(h.viewer), true);
|
||||
cur = b;
|
||||
assert.equal(await h.layer.update(h.viewer), true);
|
||||
const record = h.layer.getAnalystRecords()[0];
|
||||
const fillLon = [...h.fills().items.values()][0].geometry.rings[0][0].lon;
|
||||
const lineLon = [...h.lines().items.values()][0].positions[0];
|
||||
assert.ok(Math.abs(record.lon - -106.95) < 1e-6, 'record follows B');
|
||||
assert.equal(
|
||||
fillLon,
|
||||
-107,
|
||||
'the fill must follow B like the card anchor',
|
||||
);
|
||||
assert.deepEqual(lineLon, fromDegrees(-107, 35), 'the outline follows B');
|
||||
h.layer.destroy();
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const legendCounts = (layer) =>
|
||||
layer.getRowControls().legend.map((entry) => entry.count);
|
||||
const fillBands = (h) =>
|
||||
[...h.fills().items.values()].map((item) =>
|
||||
PERIMETER_AGE_BANDS.findIndex((_, band) =>
|
||||
rgba(band, 0.35).every((v, i) => v === item.fill[i]),
|
||||
),
|
||||
);
|
||||
|
||||
test('the live legend counts a fire in the band its drawn piece shows', async () => {
|
||||
const T = Date.UTC(2026, 10, 20, 12);
|
||||
const realNow = Date.now;
|
||||
let now = T;
|
||||
Date.now = () => now;
|
||||
try {
|
||||
const born = T - (5 * 60 + 59) * 60000;
|
||||
const f = { ...fire, lastGrowthTime: born };
|
||||
let fail = false;
|
||||
const h = harness({
|
||||
getSnapshot: async () => {
|
||||
if (fail) throw new Error('down');
|
||||
return snap([f], { pieces: [pieceOf(f.id, { born })] });
|
||||
},
|
||||
});
|
||||
assert.equal(await h.layer.update(h.viewer), true);
|
||||
assert.deepEqual(fillBands(h), [0]);
|
||||
assert.deepEqual(legendCounts(h.layer), [1, 0, 0, 0]);
|
||||
// Two minutes later the panel repaints (another layer toggled): no refresh.
|
||||
now = T + 2 * 60000;
|
||||
assert.deepEqual(fillBands(h), [0], 'the piece is still drawn yellow');
|
||||
assert.deepEqual(
|
||||
legendCounts(h.layer),
|
||||
[1, 0, 0, 0],
|
||||
'the legend must count the fire where the map shows it',
|
||||
);
|
||||
// A failed refresh keeps the yellow picture; the legend must agree.
|
||||
fail = true;
|
||||
assert.equal(await h.layer.update(h.viewer), false);
|
||||
assert.deepEqual(fillBands(h), [0]);
|
||||
assert.deepEqual(legendCounts(h.layer), [1, 0, 0, 0]);
|
||||
// A successful refresh moves both to orange.
|
||||
fail = false;
|
||||
assert.equal(await h.layer.update(h.viewer), true);
|
||||
assert.deepEqual(fillBands(h), [1]);
|
||||
assert.deepEqual(legendCounts(h.layer), [0, 1, 0, 0]);
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
}
|
||||
});
|
||||
|
||||
test('a refresh the host cancelled through refreshLayer publishes nothing', async (t) => {
|
||||
const ringAt = (lon) => [
|
||||
[lon, 35.2],
|
||||
[lon + 0.1, 35.2],
|
||||
[lon + 0.1, 35.3],
|
||||
[lon, 35.2],
|
||||
];
|
||||
const snapshotAt = (revision, lon) =>
|
||||
snap([{ ...fire, anchor: { lon: lon + 0.05, lat: 35.25 } }], {
|
||||
revision,
|
||||
pieces: [pieceOf(fire.id, { rings: [ringAt(lon)] })],
|
||||
});
|
||||
let next = async () => snapshotAt('S', -108);
|
||||
const seen = [];
|
||||
const h = harness(
|
||||
{
|
||||
getSnapshot: (options) => {
|
||||
seen.push(options.signal);
|
||||
return next(options);
|
||||
},
|
||||
},
|
||||
{ init: false },
|
||||
);
|
||||
const manager = new LayerLifecycle(h.viewer);
|
||||
manager.register(h.layer);
|
||||
let releaseA;
|
||||
t.after(async () => {
|
||||
releaseA?.();
|
||||
await manager.destroyAll();
|
||||
});
|
||||
assert.equal(await manager.setEnabled(h.layer.id, true), true);
|
||||
const firstLon = () =>
|
||||
h.fills().items.get(`fire-perimeter:${fire.id}:0`).geometry.rings[0][0].lon;
|
||||
assert.equal(firstLon(), -108);
|
||||
|
||||
next = () =>
|
||||
new Promise((resolve) => {
|
||||
releaseA = () => resolve(snapshotAt('A', -100));
|
||||
});
|
||||
const host = new AbortController();
|
||||
const refreshA = manager.refreshLayer(h.layer.id, { signal: host.signal });
|
||||
await tick();
|
||||
host.abort();
|
||||
await tick();
|
||||
assert.equal(seen.at(-1).aborted, true, 'the source hears the host abort');
|
||||
|
||||
next = async () => {
|
||||
throw new Error('B failed');
|
||||
};
|
||||
const refreshB = manager.refreshLayer(h.layer.id);
|
||||
releaseA?.();
|
||||
assert.equal(await refreshA, false);
|
||||
assert.equal(firstLon(), -108, 'cancelled A is never drawn');
|
||||
assert.equal(await refreshB, false);
|
||||
assert.equal(firstLon(), -108, 'S stays after B fails');
|
||||
});
|
||||
|
||||
// Pine, US-NM, discovered 2024-07-01. The InciWeb catalog holds two Pine
|
||||
// pages in NM: 101 (began 2024) and 202 (began 2026).
|
||||
test('a historical card links the same-name page of its own fire, whatever the snapshot time', async () => {
|
||||
const pine = {
|
||||
...fire,
|
||||
name: 'Pine',
|
||||
discoveredTime: Date.UTC(2024, 6, 1),
|
||||
updatedTime: Date.UTC(2024, 6, 2),
|
||||
lastGrowthTime: Date.UTC(2024, 6, 2),
|
||||
};
|
||||
let at = Date.UTC(2024, 6, 3);
|
||||
const asked = [];
|
||||
const h = harness(
|
||||
{ getSnapshot: async () => snap([pine], { at }) },
|
||||
{
|
||||
pick: () => perimeterPick(`fire-perimeter:${fire.id}:0`),
|
||||
inciwebIndex: [
|
||||
{ incident_id: '101', tau: 'NMGNF', incident_title: 'Pine Fire' },
|
||||
{ incident_id: '202', tau: 'NMGNF', incident_title: '2026 Pine' },
|
||||
],
|
||||
publication: async (id) => {
|
||||
asked.push(id);
|
||||
return id === '202'
|
||||
? {
|
||||
createdMs: Date.UTC(2026, 6, 1),
|
||||
changedMs: Date.UTC(2026, 6, 5),
|
||||
}
|
||||
: {
|
||||
createdMs: Date.UTC(2024, 6, 1),
|
||||
changedMs: Date.UTC(2024, 7, 1),
|
||||
};
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(await h.layer.update(), true);
|
||||
await tick();
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
await tick();
|
||||
await tick();
|
||||
const [card] = h.overlay.entries.get('fire-perimeters');
|
||||
card.activate();
|
||||
assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/101']);
|
||||
assert.deepEqual(asked, ['202', '101']);
|
||||
at = Date.UTC(2026, 6, 6);
|
||||
assert.equal(await h.layer.update(), true);
|
||||
const [laterCard] = h.overlay.entries.get('fire-perimeters');
|
||||
laterCard.activate();
|
||||
assert.deepEqual(h.opened, [
|
||||
'https://inciweb.wildfire.gov/node/101',
|
||||
'https://inciweb.wildfire.gov/node/101',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
asked,
|
||||
['202', '101'],
|
||||
'changing the snapshot time reuses the publications',
|
||||
);
|
||||
h.layer.destroy();
|
||||
});
|
||||
@@ -1,3 +1,14 @@
|
||||
/**
|
||||
* 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
|
||||
@@ -80,6 +91,7 @@ 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),
|
||||
@@ -92,3 +104,114 @@ 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,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeFirePerimeterSnapshot } from './records.js';
|
||||
import {
|
||||
perimeterAnchorDegrees,
|
||||
normalizeFirePerimeterSnapshot,
|
||||
firePerimeterSnapshot,
|
||||
} from './records.js';
|
||||
|
||||
const ring = [
|
||||
[-108.1, 35.2],
|
||||
@@ -22,6 +26,7 @@ function feature(overrides = {}) {
|
||||
attr_IncidentTypeCategory: 'WF',
|
||||
attr_FireDiscoveryDateTime: 1757900000000,
|
||||
poly_DateCurrent: 1757950000000,
|
||||
poly_PolygonDateTime: 1757940000000,
|
||||
attr_FireCause: 'Natural',
|
||||
attr_FireBehaviorGeneral: 'Active',
|
||||
attr_TotalIncidentPersonnel: 380,
|
||||
@@ -59,6 +64,7 @@ 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,
|
||||
@@ -90,6 +96,7 @@ 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,
|
||||
@@ -110,6 +117,7 @@ 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,
|
||||
@@ -126,6 +134,7 @@ test('optional attributes normalize to null rather than leaking undefined', () =
|
||||
category: null,
|
||||
discoveredTime: null,
|
||||
updatedTime: null,
|
||||
polygonTime: null,
|
||||
cause: null,
|
||||
behavior: null,
|
||||
personnel: null,
|
||||
@@ -199,3 +208,223 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,42 +1,35 @@
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import { readResponseJsonCapped } from '../../sources/httpBody.js';
|
||||
import { firePerimeterSnapshot } from './records.js';
|
||||
|
||||
// A portable export (package.json): no i18n here. Failures stay English data;
|
||||
// the Layers panel shows them translated.
|
||||
const msg = (text) => text;
|
||||
// Failures stay English data. The Layers panel shows them translated.
|
||||
|
||||
/** Request a normalized snapshot through the bounded, same-origin WFIGS proxy. */
|
||||
/** Request a 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 {
|
||||
/** The perimeter rows (see getSnapshotDetail for staleness). */
|
||||
async getSnapshot(options = {}) {
|
||||
return (await getSnapshotDetail(options)).rows;
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
},
|
||||
getSnapshotDetail,
|
||||
};
|
||||
}
|
||||
@@ -20,7 +20,7 @@ const validPayload = {
|
||||
],
|
||||
};
|
||||
|
||||
test('a successful response yields normalized perimeter rows', async () => {
|
||||
test('a successful response yields the snapshot of fires and pieces', async () => {
|
||||
let requested;
|
||||
const source = createWfigsPerimeterSource({
|
||||
fetchImpl: async (url) => {
|
||||
@@ -30,9 +30,13 @@ test('a successful response yields normalized perimeter rows', async () => {
|
||||
});
|
||||
},
|
||||
});
|
||||
const rows = await source.getSnapshot();
|
||||
assert.equal(rows.length, 1);
|
||||
assert.equal(rows[0].stableId, '2026-NMGNF-000123');
|
||||
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);
|
||||
assert.equal(requested, '/api/fire-perimeters');
|
||||
});
|
||||
|
||||
@@ -160,22 +164,20 @@ 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 detail carries the proxy staleness and fetch time', async () => {
|
||||
test('the snapshot 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 }),
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshotDetail(), {
|
||||
rows: [],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
});
|
||||
assert.deepEqual(await source.getSnapshot(), []);
|
||||
const snapshot = await source.getSnapshot();
|
||||
assert.equal(snapshot.stale, true);
|
||||
assert.equal(snapshot.fetchedAt, fetchedAt);
|
||||
assert.deepEqual([snapshot.fires, snapshot.pieces], [[], []]);
|
||||
});
|
||||
|
||||
test('getSnapshot works when taken off its source object', async () => {
|
||||
const { getSnapshot } = createWfigsPerimeterSource({
|
||||
fetchImpl: async () => Response.json({ rows: [] }),
|
||||
});
|
||||
assert.deepEqual(await getSnapshot(), []);
|
||||
assert.deepEqual((await getSnapshot()).fires, []);
|
||||
});
|
||||
@@ -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}` }));
|
||||
|
||||
@@ -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,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],
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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),
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -16,13 +16,6 @@ export const BOX = Object.freeze({
|
||||
north: 30.3,
|
||||
});
|
||||
|
||||
export const FIJI_BOX = Object.freeze({
|
||||
west: 179,
|
||||
south: -18,
|
||||
east: -177,
|
||||
north: -17,
|
||||
});
|
||||
|
||||
export const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
/** Timers that fire only when the test says so. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per
|
||||
* candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that
|
||||
* candidate day. The response's `Data-Present` header is the only proof that
|
||||
* a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and
|
||||
* `Acquisition-Time` carries the sensing time. Fetches are bounded, and so
|
||||
* are decoded images: residency is least-recently-USED, where a request or a
|
||||
@@ -8,28 +8,16 @@
|
||||
* card on every render, so a read that counted would evict the visible cards
|
||||
* first). Eviction revokes the image only; what the probe proved is kept.
|
||||
*/
|
||||
import { boxKey, thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource, dataPresent } from './source.js';
|
||||
import { thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
|
||||
const EMPTY = Object.freeze({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */
|
||||
function keepProvenHalves(previous, next, opposite) {
|
||||
if (!Array.isArray(next) || !Array.isArray(opposite)) return previous;
|
||||
const drop = new Set([...next, ...opposite].map(boxKey));
|
||||
return [
|
||||
...next,
|
||||
...(previous ?? []).filter((half) => !drop.has(boxKey(half))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options]
|
||||
*/
|
||||
@@ -102,22 +90,18 @@ export function createThumbnailLoader({
|
||||
let status = 'error';
|
||||
let objectUrl = null;
|
||||
let acquisitionTime = null;
|
||||
// Per-half evidence (see withHalves in source.js), or null without it.
|
||||
let availableBoxes = null;
|
||||
let emptyBoxes = null;
|
||||
let cancelled = false;
|
||||
try {
|
||||
const response = await requestThumbnail(entry.candidate, entry.box, {
|
||||
size,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Each half's explicit answer counts even when the shown response fails.
|
||||
availableBoxes = response?.presentBoxes ?? null;
|
||||
emptyBoxes = response?.emptyBoxes ?? null;
|
||||
if (controller.signal.aborted) {
|
||||
cancelled = true;
|
||||
} else if (response?.ok) {
|
||||
const present = dataPresent(response);
|
||||
const present = String(
|
||||
response.headers?.get?.('Data-Present') ?? '',
|
||||
).toLowerCase();
|
||||
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
|
||||
if (present === 'false') {
|
||||
status = 'empty';
|
||||
@@ -133,11 +117,7 @@ export function createThumbnailLoader({
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || error?.name === 'AbortError')
|
||||
cancelled = true;
|
||||
else {
|
||||
status = 'error';
|
||||
availableBoxes = error?.presentBoxes ?? availableBoxes;
|
||||
emptyBoxes = error?.emptyBoxes ?? emptyBoxes;
|
||||
}
|
||||
else status = 'error';
|
||||
} finally {
|
||||
inFlight -= 1;
|
||||
entry.loading = false;
|
||||
@@ -149,17 +129,6 @@ export function createThumbnailLoader({
|
||||
pump();
|
||||
return;
|
||||
}
|
||||
// Each half keeps its latest explicit answer.
|
||||
entry.availableBoxes = keepProvenHalves(
|
||||
entry.availableBoxes,
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
);
|
||||
entry.emptyBoxes = keepProvenHalves(
|
||||
entry.emptyBoxes,
|
||||
emptyBoxes,
|
||||
availableBoxes,
|
||||
);
|
||||
// A failed re-fetch of an evicted image keeps what the day proved.
|
||||
if (status !== 'error' || entry.status !== 'present') {
|
||||
entry.status = status;
|
||||
@@ -227,8 +196,6 @@ export function createThumbnailLoader({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
controller: null,
|
||||
touched: 0,
|
||||
@@ -305,7 +272,7 @@ export function createThumbnailLoader({
|
||||
/**
|
||||
* Read a day's state. A read is not a use: it never changes residency.
|
||||
* @param {string} key Candidate key.
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array<object> | null, emptyBoxes: Array<object> | null, loading: boolean }}
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}
|
||||
*/
|
||||
get(key) {
|
||||
const entry = entries.get(key);
|
||||
@@ -314,8 +281,6 @@ export function createThumbnailLoader({
|
||||
status: entry.status,
|
||||
objectUrl: entry.objectUrl,
|
||||
acquisitionTime: entry.acquisitionTime,
|
||||
availableBoxes: entry.availableBoxes,
|
||||
emptyBoxes: entry.emptyBoxes,
|
||||
loading: entry.loading,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs';
|
||||
import { BOX, response, settle } from './testDoubles.mjs';
|
||||
|
||||
const candidate = (product, day) => ({
|
||||
key: `${product}:${day}`,
|
||||
product,
|
||||
day,
|
||||
});
|
||||
|
||||
/** A fetch whose responses the test releases, in any order. */
|
||||
function fakeFetch() {
|
||||
@@ -64,8 +68,6 @@ test('Data-Present decides the day: present with an object URL and sensing time,
|
||||
status: 'present',
|
||||
objectUrl: 'blob:1',
|
||||
acquisitionTime: '2026-09-18T17:12:00Z',
|
||||
availableBoxes: [BOX],
|
||||
emptyBoxes: [],
|
||||
loading: false,
|
||||
});
|
||||
assert.equal(loader.get('L30:2026-09-16').status, 'empty');
|
||||
@@ -335,75 +337,6 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
|
||||
assert.deepEqual(revoked, ['blob:1']);
|
||||
});
|
||||
|
||||
test('the loader proves a dateline day present from one half and hands that half on', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const time = day.day + 'T22:10:00Z';
|
||||
const { loader } = fixture({
|
||||
fetchImpl: async (url) => {
|
||||
const east =
|
||||
new URL(url).searchParams.get('BBOX').split(',')[1] === '-180';
|
||||
return response({
|
||||
headers: east
|
||||
? { 'Data-Present': 'true', 'Acquisition-Time': time }
|
||||
: { 'Data-Present': 'false' },
|
||||
});
|
||||
},
|
||||
});
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settle();
|
||||
const entry = loader.get(day.key);
|
||||
assert.equal(entry.status, 'present');
|
||||
assert.equal(entry.acquisitionTime, time);
|
||||
assert.ok(entry.objectUrl);
|
||||
assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a dateline day whose halves both hang is an error, not "checking" forever', async () => {
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl: () => new Promise(() => {}),
|
||||
halfDeadlineMs: 20,
|
||||
});
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
});
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const settled = new Promise((resolve) => loader.subscribe(resolve));
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settled;
|
||||
assert.equal(loader.get(day.key).status, 'error');
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present day drops a half only when it is confirmed empty', async () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
const answers = [
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west], emptyBoxes: [east] },
|
||||
];
|
||||
const { loader } = fixture({
|
||||
maxDecoded: 1,
|
||||
requestThumbnail: async () =>
|
||||
Object.assign(
|
||||
response({ headers: { 'Data-Present': 'true' } }),
|
||||
answers.shift(),
|
||||
),
|
||||
});
|
||||
const day1 = candidate('VIIRS', '2026-11-04');
|
||||
const day2 = candidate('VIIRS', '2026-11-05');
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
loader.request(day2, box);
|
||||
await settle();
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
|
||||
const { loader, fetch } = fixture({ maxInFlight: 1 });
|
||||
const stale = candidate('S30', '2026-09-10');
|
||||
|
||||
@@ -2294,7 +2294,7 @@ test('points show only within their display range', () => {
|
||||
set.dispose();
|
||||
});
|
||||
|
||||
test('the fire perimeters layer draws holed ground fills and draped fire lines on a viewer of its own', async () => {
|
||||
test('the fire perimeters layer draws holed ground fills and draped outlines on a viewer of its own', async () => {
|
||||
const { createFirePerimetersLayer } =
|
||||
await import('../../layers/perimeters/index.js');
|
||||
const scene = fakeScene();
|
||||
@@ -2313,9 +2313,19 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
|
||||
];
|
||||
const layer = createFirePerimetersLayer({
|
||||
source: {
|
||||
getSnapshot: async () => [
|
||||
{ stableId: 'a', containedPct: 0, polygons: [[outer, hole]] },
|
||||
],
|
||||
getSnapshot: async () => ({
|
||||
at: null,
|
||||
revision: 'r',
|
||||
fires: [{ id: 'a', containedPct: 0, anchor: { lon: -108, lat: 35.2 } }],
|
||||
pieces: [
|
||||
{
|
||||
fireId: 'a',
|
||||
born: null,
|
||||
polygons: [[outer, hole]],
|
||||
outline: [outer, hole],
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
});
|
||||
layer.init(viewer);
|
||||
@@ -2336,9 +2346,9 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
|
||||
assert.equal(instance.geometry._polygonHierarchy.holes.length, 1);
|
||||
const [line] = of(Cesium.GroundPolylinePrimitive);
|
||||
assert.equal(line.classificationType, Cesium.ClassificationType.BOTH);
|
||||
assert.equal(line.geometryInstances.length, 1, 'the exterior ring only');
|
||||
assert.equal(line.geometryInstances.length, 2, 'the hole is outlined too');
|
||||
assert.equal(line.geometryInstances[0].geometry.width, 2);
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:0');
|
||||
assert.equal(line.geometryInstances[0].id.id, 'fire-perimeter:a:line:0');
|
||||
layer.destroy();
|
||||
assert.equal(scene.added.length, 0);
|
||||
});
|
||||
|
||||
Vendored
-3
@@ -1,11 +1,8 @@
|
||||
import { createApplicationControls } from '../app/controls.js';
|
||||
import { getStandaloneCatalog } from './catalog.js';
|
||||
import { homeCountryView } from '../homeCountry.js';
|
||||
export function createStandaloneControls(options) {
|
||||
return createApplicationControls({
|
||||
catalog: options?.catalog ?? getStandaloneCatalog(),
|
||||
// The planet over the visitor's country; the title's logo goes back here.
|
||||
startView: homeCountryView(),
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
import { startApplicationChrome } from '../app/startupChrome.js';
|
||||
import { playOpeningIntro } from '../app/openingIntro.js';
|
||||
import { initKeySetup } from '../keySetup.js';
|
||||
export function startStandaloneChrome(options) {
|
||||
return startApplicationChrome({
|
||||
initializeSettings: initKeySetup,
|
||||
playOpening: playOpeningIntro,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,7 @@ const source = readFileSync(
|
||||
.replace(/^import .*;\n/gm, '')
|
||||
.replace('export function', 'function');
|
||||
|
||||
function fixture({ playOpening, hasShareState = false } = {}) {
|
||||
function fixture() {
|
||||
const timers = new Map();
|
||||
const listeners = new Map();
|
||||
const events = [];
|
||||
@@ -44,10 +44,7 @@ function fixture({ playOpening, hasShareState = false } = {}) {
|
||||
addEventListener: (type, listener) => listeners.set(type, listener),
|
||||
removeEventListener: (type) => listeners.delete(type),
|
||||
},
|
||||
playOpening,
|
||||
styleManager: {
|
||||
hasShareState,
|
||||
viewer: 'viewer',
|
||||
initialRestorePromise: new Promise((resolve) => {
|
||||
restored = resolve;
|
||||
}),
|
||||
@@ -127,59 +124,3 @@ test('shutdown during the cover transition cancels the listener and fallback', a
|
||||
f.fire(900);
|
||||
assert.deepEqual(f.events, ['hidden', 'settings:destroy']);
|
||||
});
|
||||
|
||||
function openingStub(events) {
|
||||
let land;
|
||||
const calls = [];
|
||||
const play = (options) => {
|
||||
calls.push(options);
|
||||
events.push('opening');
|
||||
return {
|
||||
done: new Promise((resolve) => {
|
||||
land = resolve;
|
||||
}),
|
||||
cancel: () => events.push('opening:cancel'),
|
||||
};
|
||||
};
|
||||
return { play, calls, land: () => land() };
|
||||
}
|
||||
|
||||
test('a bare address plays the opening, and welcome waits for its end', async () => {
|
||||
const events = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({ playOpening: opening.play });
|
||||
f.events.push = (value) => events.push(value);
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(events, ['opening']);
|
||||
assert.equal(opening.calls[0].viewer, 'viewer');
|
||||
f.fire(900);
|
||||
assert.deepEqual(events, ['opening'], 'no fallback timer while it plays');
|
||||
opening.land();
|
||||
await flush();
|
||||
assert.deepEqual(events, ['opening', 'welcome']);
|
||||
await f.stop();
|
||||
assert.ok(events.includes('opening:cancel'));
|
||||
});
|
||||
|
||||
test('a shared view opens without the opening', async () => {
|
||||
const events = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({ playOpening: opening.play, hasShareState: true });
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, 0);
|
||||
assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
test('without an opening to play the cover hides as before', async () => {
|
||||
const f = fixture({ playOpening: () => null });
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
@@ -250,7 +250,8 @@ export const getFirePerimeters = defineTool({
|
||||
title: 'Wildfire perimeters',
|
||||
description:
|
||||
'Mapped wildfire perimeters from the US WFIGS service in an area, ' +
|
||||
'largest first, with size, containment, cause and personnel.',
|
||||
'largest first, with size, containment, cause, personnel, and ' +
|
||||
"`last_growth`: when each was last mapped (WFIGS mapping time, else the record's last edit).",
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
properties: { area: AREA_SCHEMA, limit: LIMIT_SCHEMA },
|
||||
@@ -260,19 +261,33 @@ export const getFirePerimeters = defineTool({
|
||||
requires: ['perimeters'],
|
||||
async run(args, { services, signal }) {
|
||||
const area = await resolveArea(args.area, { services, signal });
|
||||
const snapshot =
|
||||
typeof services.perimeters.getSnapshotDetail === 'function'
|
||||
? await services.perimeters.getSnapshotDetail({ signal })
|
||||
: { rows: await services.perimeters.getSnapshot({ signal }) };
|
||||
const snapshot = await services.perimeters.getSnapshot({ signal });
|
||||
if (!Array.isArray(snapshot?.fires) || !Array.isArray(snapshot.pieces))
|
||||
throw new ToolError('malformed', 'The perimeter snapshot is malformed');
|
||||
const at = isoTime(snapshot.at);
|
||||
// A time after the moment shown is not known at it.
|
||||
const timeAt = (ms) =>
|
||||
at !== null && ms > snapshot.at ? null : isoTime(ms);
|
||||
// The proxy answers from its last snapshot, marked stale, while WFIGS is
|
||||
// unreachable.
|
||||
const stale = snapshot.stale === true;
|
||||
const rows = snapshot.rows
|
||||
.filter((fire) => polygonsTouchArea(fire.polygons, area))
|
||||
.map((fire) => ({ fire, point: polygonCenter(fire.polygons) }))
|
||||
.filter(({ point }) => point)
|
||||
.map(({ fire, point }) => ({
|
||||
id: fire.stableId,
|
||||
// A fire is in the area when a piece of its burned area is.
|
||||
const touching = new Set();
|
||||
for (const piece of snapshot.pieces)
|
||||
if (
|
||||
!touching.has(piece.fireId) &&
|
||||
polygonsTouchArea(piece.polygons, area)
|
||||
)
|
||||
touching.add(piece.fireId);
|
||||
const rows = snapshot.fires
|
||||
.filter(
|
||||
(fire) =>
|
||||
touching.has(fire.id) &&
|
||||
Number.isFinite(fire.anchor?.lat) &&
|
||||
Number.isFinite(fire.anchor?.lon),
|
||||
)
|
||||
.map((fire) => ({
|
||||
id: fire.id,
|
||||
name: fire.name,
|
||||
acres: round(fire.acres, 0),
|
||||
contained_pct: fire.containedPct,
|
||||
@@ -282,47 +297,29 @@ export const getFirePerimeters = defineTool({
|
||||
cause: fire.cause,
|
||||
behavior: fire.behavior,
|
||||
personnel: fire.personnel,
|
||||
discovered: isoTime(fire.discoveredTime),
|
||||
updated: isoTime(fire.updatedTime),
|
||||
lat: round(point.lat, 5),
|
||||
lon: round(point.lon, 5),
|
||||
discovered: timeAt(fire.discoveredTime),
|
||||
updated: timeAt(fire.updatedTime),
|
||||
last_growth: timeAt(fire.lastGrowthTime),
|
||||
lat: round(fire.anchor.lat, 5),
|
||||
lon: round(fire.anchor.lon, 5),
|
||||
}))
|
||||
.sort((a, b) => (b.acres ?? 0) - (a.acres ?? 0));
|
||||
return {
|
||||
summary:
|
||||
`${countNoun(rows.length, 'mapped wildfire perimeter')} in ${area.label}` +
|
||||
(at ? ` as of ${at}` : '') +
|
||||
(stale ? ' (data may be stale).' : '.'),
|
||||
data: {
|
||||
view: suggestView(services, { area, layers: ['fire-perimeters'] }),
|
||||
stale,
|
||||
retrieved_at: isoTime(snapshot.fetchedAt),
|
||||
...(at && { snapshot_at: at }),
|
||||
...capRows(rows, args.limit),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
/** Average outer-ring vertices, using a circular longitude mean at the dateline. */
|
||||
function polygonCenter(polygons) {
|
||||
let lat = 0;
|
||||
let sinLon = 0;
|
||||
let cosLon = 0;
|
||||
let count = 0;
|
||||
const toRad = Math.PI / 180;
|
||||
for (const polygon of polygons || []) {
|
||||
for (const [x, y] of polygon?.[0] || []) {
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
|
||||
sinLon += Math.sin(x * toRad);
|
||||
cosLon += Math.cos(x * toRad);
|
||||
lat += y;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count
|
||||
? { lat: lat / count, lon: Math.atan2(sinLon, cosLon) / toRad }
|
||||
: null;
|
||||
}
|
||||
|
||||
export const getTerrainHeight = defineTool({
|
||||
name: 'get_terrain_height',
|
||||
title: 'Terrain height',
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
defineTool,
|
||||
ToolError,
|
||||
} from '../index.js';
|
||||
import { firePerimeterSnapshot } from '../../layers/perimeters/records.js';
|
||||
|
||||
const conditions = {
|
||||
observedAt: '2026-10-01T19:15:00.000Z',
|
||||
@@ -154,6 +155,57 @@ test('cyclones are listed strongest first and can be limited to an area', async
|
||||
);
|
||||
});
|
||||
|
||||
test('get_fire_perimeters rejects a snapshot that breaks the contract', async () => {
|
||||
const square = [
|
||||
[-118.5, 35.2],
|
||||
[-118.4, 35.2],
|
||||
[-118.4, 35.3],
|
||||
[-118.5, 35.3],
|
||||
[-118.5, 35.2],
|
||||
];
|
||||
const area = { bbox: [-119, 35, -118, 36] };
|
||||
const legacyRow = {
|
||||
stableId: 'legacy',
|
||||
name: 'Legacy',
|
||||
acres: 100,
|
||||
polygons: [[square]],
|
||||
};
|
||||
const fire = {
|
||||
id: 'f1',
|
||||
name: 'Fire One',
|
||||
acres: 10,
|
||||
anchor: { lon: -118.45, lat: 35.25 },
|
||||
};
|
||||
const piece = {
|
||||
fireId: 'f1',
|
||||
born: null,
|
||||
polygons: [[square]],
|
||||
outline: [square],
|
||||
};
|
||||
const query = (snapshot) =>
|
||||
composeCatalog({
|
||||
tools: coreTools,
|
||||
services: { perimeters: { getSnapshot: async () => snapshot } },
|
||||
}).call('get_fire_perimeters', { area });
|
||||
for (const malformed of [
|
||||
[legacyRow],
|
||||
{ rows: [legacyRow], stale: false, fetchedAt: 1 },
|
||||
{ fires: [fire] },
|
||||
{ pieces: [piece] },
|
||||
])
|
||||
await assert.rejects(
|
||||
query(malformed),
|
||||
(error) => error.code === 'malformed',
|
||||
);
|
||||
const live = await query({ fires: [], pieces: [] });
|
||||
assert.equal(live.data.rows.length, 0);
|
||||
assert.equal('snapshot_at' in live.data, false);
|
||||
assert.equal(
|
||||
(await query({ fires: [fire], pieces: [piece] })).data.rows.length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('fire perimeters are placed by their outline and sorted by size', async () => {
|
||||
const ring = (lon, lat) => [
|
||||
[
|
||||
@@ -161,11 +213,12 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
[lon + 0.1, lat],
|
||||
[lon + 0.1, lat + 0.1],
|
||||
[lon, lat + 0.1],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
const perimeters = {
|
||||
async getSnapshot() {
|
||||
return [
|
||||
return firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'small',
|
||||
name: 'Small Fire',
|
||||
@@ -179,6 +232,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
personnel: 20,
|
||||
discoveredTime: Date.UTC(2026, 8, 1),
|
||||
updatedTime: null,
|
||||
polygonTime: Date.UTC(2026, 8, 2, 6),
|
||||
polygons: [ring(-118.5, 35.2)],
|
||||
},
|
||||
{
|
||||
@@ -194,8 +248,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
acres: 9000,
|
||||
polygons: [ring(-80, 30)],
|
||||
},
|
||||
{ stableId: 'empty', name: 'No Outline', acres: 1, polygons: [] },
|
||||
];
|
||||
]);
|
||||
},
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
@@ -222,6 +275,7 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
personnel: 20,
|
||||
discovered: '2026-09-01T00:00:00.000Z',
|
||||
updated: null,
|
||||
last_growth: '2026-09-02T06:00:00.000Z',
|
||||
lat: 35.25,
|
||||
lon: -118.45,
|
||||
});
|
||||
@@ -229,24 +283,25 @@ test('fire perimeters are placed by their outline and sorted by size', async ()
|
||||
|
||||
test('fire perimeter queries include dateline interiors and exclude the opposite meridian', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'dateline',
|
||||
name: 'Dateline Fire',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
};
|
||||
const catalog = catalogWith({ perimeters });
|
||||
for (const area of [
|
||||
@@ -268,45 +323,46 @@ test('fire perimeter queries include dateline interiors and exclude the opposite
|
||||
|
||||
test('fire perimeter coordinates stay at the dateline for closed and multipart outlines', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'closed',
|
||||
acres: 100,
|
||||
polygons: [
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
[
|
||||
[179, -2],
|
||||
[-179, -2],
|
||||
[-179, 2],
|
||||
[179, 2],
|
||||
[179, -2],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
[
|
||||
},
|
||||
{
|
||||
stableId: 'multipart',
|
||||
acres: 50,
|
||||
polygons: [
|
||||
[
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
[
|
||||
[179, -1],
|
||||
[179.5, -1],
|
||||
[179.5, 1],
|
||||
[179, 1],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
[
|
||||
[-179.5, -1],
|
||||
[-179, -1],
|
||||
[-179, 1],
|
||||
[-179.5, 1],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [178, -3, -178, 3] },
|
||||
@@ -759,23 +815,24 @@ test('brief sections use a named place at its own point', async () => {
|
||||
|
||||
test('a fire perimeter enclosing the whole area is found', async () => {
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [
|
||||
{
|
||||
stableId: 'big',
|
||||
name: 'Big Fire',
|
||||
acres: 250000,
|
||||
polygons: [
|
||||
[
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot([
|
||||
{
|
||||
stableId: 'big',
|
||||
name: 'Big Fire',
|
||||
acres: 250000,
|
||||
polygons: [
|
||||
[
|
||||
[-122, 38],
|
||||
[-120, 38],
|
||||
[-120, 40],
|
||||
[-122, 40],
|
||||
[
|
||||
[-122, 38],
|
||||
[-120, 38],
|
||||
[-120, 40],
|
||||
[-122, 40],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-121.2, 38.9, -120.8, 39.1] },
|
||||
@@ -883,19 +940,11 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
|
||||
],
|
||||
];
|
||||
const perimeters = {
|
||||
getSnapshot: async () => [],
|
||||
getSnapshotDetail: async () => ({
|
||||
rows: [
|
||||
{
|
||||
stableId: 'held',
|
||||
name: 'Held Fire',
|
||||
acres: 300,
|
||||
polygons: [ring],
|
||||
},
|
||||
],
|
||||
stale: true,
|
||||
fetchedAt,
|
||||
}),
|
||||
getSnapshot: async () =>
|
||||
firePerimeterSnapshot(
|
||||
[{ stableId: 'held', name: 'Held Fire', acres: 300, polygons: [ring] }],
|
||||
{ stale: true, fetchedAt },
|
||||
),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-120, 34, -117, 36] },
|
||||
@@ -907,3 +956,62 @@ test('stale fire perimeters say so, with when they were fetched', async () => {
|
||||
assert.equal(result.data.stale, true);
|
||||
assert.equal(result.data.retrieved_at, new Date(fetchedAt).toISOString());
|
||||
});
|
||||
|
||||
test('a fire is in the area when one of its pieces is', async () => {
|
||||
const square = (lon, lat) => [
|
||||
[
|
||||
[lon, lat],
|
||||
[lon + 0.1, lat],
|
||||
[lon + 0.1, lat + 0.1],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
const fire = (id, lon, lat) => ({
|
||||
id,
|
||||
name: id,
|
||||
acres: 10,
|
||||
lastGrowthTime: null,
|
||||
anchor: { lon, lat },
|
||||
});
|
||||
const perimeters = {
|
||||
getSnapshot: async () => ({
|
||||
at: Date.UTC(2024, 6, 3),
|
||||
stale: false,
|
||||
fetchedAt: null,
|
||||
revision: '',
|
||||
note: null,
|
||||
fires: [
|
||||
{
|
||||
...fire('split', -80, 30),
|
||||
discoveredTime: Date.UTC(2024, 6, 1),
|
||||
updatedTime: Date.UTC(2024, 6, 4),
|
||||
lastGrowthTime: Date.UTC(2024, 6, 4),
|
||||
},
|
||||
fire('unmapped', -118.5, 35.2),
|
||||
],
|
||||
pieces: [
|
||||
{ fireId: 'split', born: null, polygons: [square(-80, 30)] },
|
||||
{ fireId: 'split', born: null, polygons: [square(-118.5, 35.2)] },
|
||||
],
|
||||
}),
|
||||
};
|
||||
const result = await catalogWith({ perimeters }).call('get_fire_perimeters', {
|
||||
area: { bbox: [-120, 34, -117, 36] },
|
||||
});
|
||||
const [row] = result.data.rows;
|
||||
assert.deepEqual(
|
||||
[row.discovered, row.updated, row.last_growth],
|
||||
['2024-07-01T00:00:00.000Z', null, null],
|
||||
'times after the snapshot are unknown at it',
|
||||
);
|
||||
assert.equal(result.data.snapshot_at, '2024-07-03T00:00:00.000Z');
|
||||
assert.equal(
|
||||
result.summary,
|
||||
'1 mapped wildfire perimeter in the requested box as of 2024-07-03T00:00:00.000Z.',
|
||||
);
|
||||
assert.deepEqual(
|
||||
result.data.rows.map(({ id, lat, lon }) => [id, lat, lon]),
|
||||
[['split', 30, -80]],
|
||||
'placed at its card anchor; a fire with no pieces is not mapped',
|
||||
);
|
||||
});
|
||||
@@ -31,6 +31,11 @@ export const getRecentImagery = defineTool({
|
||||
requires: ['imagery'],
|
||||
async run(args, { services, signal }) {
|
||||
const area = await resolveArea(args.area, { services, signal });
|
||||
if (area.west > area.east)
|
||||
throw new ToolError(
|
||||
'invalid_arguments',
|
||||
'The area must not cross the antimeridian',
|
||||
);
|
||||
if (
|
||||
Math.abs(area.south) > MAX_LATITUDE ||
|
||||
Math.abs(area.north) > MAX_LATITUDE
|
||||
@@ -50,13 +55,6 @@ export const getRecentImagery = defineTool({
|
||||
east: area.east,
|
||||
north: area.north,
|
||||
};
|
||||
// Worldview Snapshots rejects a west > east BBOX, so a dateline area can
|
||||
// never produce the image this tool returns: refuse before searching.
|
||||
if (box.west > box.east)
|
||||
throw new ToolError(
|
||||
'invalid_arguments',
|
||||
'The area must not cross the antimeridian',
|
||||
);
|
||||
let latest;
|
||||
try {
|
||||
latest = await services.imagery.latest({ box, signal });
|
||||
|
||||
@@ -82,30 +82,8 @@ test('overview fallback, empty results and invalid areas are reported', async ()
|
||||
);
|
||||
await assert.rejects(
|
||||
none.call('get_recent_imagery', { area: { bbox: [170, 0, -170, 5] } }),
|
||||
/too large for imagery/,
|
||||
/antimeridian/,
|
||||
);
|
||||
const crossing = imagery({
|
||||
candidate: {
|
||||
product: 'S30',
|
||||
day: '2026-10-01',
|
||||
cloud: { min: 1, max: 2 },
|
||||
coverage: 'full',
|
||||
},
|
||||
reason: 'clear',
|
||||
errors: [],
|
||||
});
|
||||
const wrapped = composeCatalog({
|
||||
tools: coreTools,
|
||||
services: { imagery: crossing },
|
||||
});
|
||||
await assert.rejects(
|
||||
wrapped.call('get_recent_imagery', {
|
||||
area: { bbox: [179, 0, -179, 1] },
|
||||
}),
|
||||
/must not cross the antimeridian/,
|
||||
);
|
||||
assert.equal(crossing.snapshots.length, 0);
|
||||
assert.equal(crossing.boxes.length, 0);
|
||||
await assert.rejects(
|
||||
none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }),
|
||||
/±85° latitude/,
|
||||
|
||||
@@ -48,20 +48,13 @@ export function initImageryBoxTool({
|
||||
let lease = null;
|
||||
let releaseCamera = null;
|
||||
|
||||
const dragBox = () => {
|
||||
if (!anchor) return null;
|
||||
const lo = Math.min(anchor.lon, corner.lon);
|
||||
const hi = Math.max(anchor.lon, corner.lon);
|
||||
// Corners more than half the globe apart are the short way round, over
|
||||
// the dateline: west gets the larger longitude, east the smaller.
|
||||
const crosses = hi - lo > 180;
|
||||
return {
|
||||
west: crosses ? hi : lo,
|
||||
const dragBox = () =>
|
||||
anchor && {
|
||||
west: Math.min(anchor.lon, corner.lon),
|
||||
south: Math.min(anchor.lat, corner.lat),
|
||||
east: crosses ? lo : hi,
|
||||
east: Math.max(anchor.lon, corner.lon),
|
||||
north: Math.max(anchor.lat, corner.lat),
|
||||
};
|
||||
};
|
||||
|
||||
const preview = createPreview(viewer, dragBox);
|
||||
const setPreview = (visible) => preview.setVisible(visible);
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
IMAGERY_BOX_POINTER_OWNER,
|
||||
initImageryBoxTool,
|
||||
} from './imageryBoxTool.js';
|
||||
import { lonSpanDeg, validateBox } from '../layers/recentImagery/model.js';
|
||||
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
|
||||
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
@@ -210,40 +209,3 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the
|
||||
assert.equal(f.tool.start(), false);
|
||||
assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);
|
||||
});
|
||||
|
||||
test('a drag across the dateline is the short box, not a box round the world', async () => {
|
||||
const pickWorld = (_viewer, nx, ny) =>
|
||||
ny < 0.05 ? null : { lon: nx < 0.5 ? 179.99 : -179.99, lat: ny };
|
||||
const f = fixture({ pickWorld });
|
||||
f.tool.start();
|
||||
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
|
||||
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
|
||||
assert.deepEqual(f.cancels, []);
|
||||
assert.equal(f.boxes.length, 1);
|
||||
const { west, east } = f.boxes[0];
|
||||
assert.ok(west > east, `west ${west} is east of east ${east}`);
|
||||
assert.ok(Math.abs(east + 360 - west - 0.02) < 1e-9, 'a 0.02 degree span');
|
||||
await f.tool.destroy();
|
||||
});
|
||||
|
||||
test('a drag whose short arc is still over the size limit is refused as too large', async () => {
|
||||
const pickWorld = (_viewer, nx, ny) => ({
|
||||
lon: nx < 0.5 ? 100 : -100,
|
||||
lat: ny,
|
||||
});
|
||||
const refused = [];
|
||||
const f = fixture({
|
||||
pickWorld,
|
||||
onCancel: (reason, message, box) => refused.push({ reason, message, box }),
|
||||
});
|
||||
f.tool.start();
|
||||
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
|
||||
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
|
||||
assert.equal(f.boxes.length, 0);
|
||||
const { reason, message, box } = refused.at(-1);
|
||||
assert.equal(reason, 'too-large');
|
||||
assert.deepEqual([box.west, box.east], [100, -100], 'the short arc');
|
||||
assert.equal(lonSpanDeg(box.west, box.east), 160);
|
||||
assert.equal(message, validateBox(box).message);
|
||||
await f.tool.destroy();
|
||||
});
|
||||
+5
-27
@@ -22,7 +22,6 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
|
||||
import {
|
||||
PRODUCTS,
|
||||
hhmm,
|
||||
nonCrossingBoxes,
|
||||
wvsSnapshotUrl,
|
||||
} from '../layers/recentImagery/model.js';
|
||||
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
|
||||
@@ -136,20 +135,6 @@ function coverageText(coverage) {
|
||||
return t('unknown');
|
||||
}
|
||||
|
||||
/** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */
|
||||
function shownCoverage(candidate, box) {
|
||||
const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {};
|
||||
const halves = nonCrossingBoxes(box).length;
|
||||
if (emptyBoxes?.length && emptyBoxes.length < halves) return 'partial';
|
||||
if (
|
||||
status !== 'present' ||
|
||||
!Array.isArray(availableBoxes) ||
|
||||
availableBoxes.length >= halves
|
||||
)
|
||||
return candidate.coverage;
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function cloudText(candidate) {
|
||||
if (candidate.thumbnail?.status === 'empty') return t('no imagery');
|
||||
if (!candidate.cloud) return t('cloud unknown');
|
||||
@@ -531,9 +516,6 @@ export function createRecentImageryPanel({
|
||||
|
||||
function exportsView() {
|
||||
const ab = snapshot.mode === 'ab';
|
||||
const crossing = Boolean(
|
||||
snapshot.box && snapshot.box.west > snapshot.box.east,
|
||||
);
|
||||
return [
|
||||
{
|
||||
id: 'export',
|
||||
@@ -543,12 +525,10 @@ export function createRecentImageryPanel({
|
||||
label: ab
|
||||
? t('EXPORT {slot}', { slot: slotId.toUpperCase() })
|
||||
: t('EXPORT'),
|
||||
title: crossing
|
||||
? t('Select one side of the dateline')
|
||||
: ab
|
||||
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
|
||||
: t('Download the image as a PNG'),
|
||||
disabled: crossing || !exportTarget(slotId) || exporting.has(slotId),
|
||||
title: ab
|
||||
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
|
||||
: t('Download the image as a PNG'),
|
||||
disabled: !exportTarget(slotId) || exporting.has(slotId),
|
||||
reserved: slotId === 'b' ? !ab : undefined,
|
||||
onClick: () => void exportImage(slotId),
|
||||
})),
|
||||
@@ -586,9 +566,7 @@ export function createRecentImageryPanel({
|
||||
}),
|
||||
);
|
||||
times.push(
|
||||
t('Coverage {coverage}', {
|
||||
coverage: coverageText(shownCoverage(focus, snapshot.box)),
|
||||
}),
|
||||
t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }),
|
||||
);
|
||||
lines.push({ id: 'acquired', text: times.join(' · ') });
|
||||
(focus.granules || []).forEach((granule, index) => {
|
||||
|
||||
@@ -5,11 +5,9 @@ import assert from 'node:assert/strict';
|
||||
import { assertSameNode } from '../testSupport/domAssert.mjs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRecentImageryPanel } from './recentImagery.js';
|
||||
import { nonCrossingBoxes } from '../layers/recentImagery/model.js';
|
||||
import { createRecentImageryLayer } from '../layers/recentImagery/index.js';
|
||||
import {
|
||||
BOX,
|
||||
FIJI_BOX,
|
||||
fakeCatalog,
|
||||
fakeController,
|
||||
fakeRenderer,
|
||||
@@ -979,29 +977,6 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX
|
||||
await settle();
|
||||
assert.equal(await f.readout.exportImage('a'), true);
|
||||
assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/);
|
||||
// A dateline box is drawn on the map, but Worldview rejects a crossing BBOX.
|
||||
const before = f.fetches.length;
|
||||
f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 });
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.notEqual(
|
||||
f.byId('ri-notice-text').textContent,
|
||||
'Select one side of the dateline',
|
||||
'the drawn box is not a warning until an export is tried',
|
||||
);
|
||||
const crossingExport = f.byAction('export-a');
|
||||
assert.equal(crossingExport.disabled, true, 'EXPORT is off up front');
|
||||
assert.equal(crossingExport.title, 'Select one side of the dateline');
|
||||
assert.equal(await f.readout.exportImage('a'), false);
|
||||
assert.equal(
|
||||
f.byId('ri-notice-text').textContent,
|
||||
'Export failed · A snapshot cannot cross the dateline',
|
||||
);
|
||||
assert.equal(
|
||||
f.fetches.length,
|
||||
before,
|
||||
'export does not request a crossing BBOX',
|
||||
);
|
||||
f.layer.setMode('ab');
|
||||
assert.deepEqual(
|
||||
[
|
||||
@@ -1065,31 +1040,6 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to
|
||||
assert.equal(article.dataset.open, 'false');
|
||||
});
|
||||
|
||||
test('DETAILS shows partial coverage for a dateline day with one side empty, unknown when a side did not answer', async () => {
|
||||
const f = fixture();
|
||||
f.layer.enable();
|
||||
f.layer.setBox(FIJI_BOX);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.match(f.byId('ri-details').textContent, /Coverage full/);
|
||||
const get = f.thumbnails.get;
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
f.thumbnails.get = (key) => ({
|
||||
...get(key),
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [east],
|
||||
});
|
||||
f.thumbnails.probe(f.snap().focus.key, 'present');
|
||||
assert.match(f.byId('ri-details').textContent, /Coverage partial/);
|
||||
f.thumbnails.get = (key) => ({
|
||||
...get(key),
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
f.thumbnails.probe(f.snap().focus.key, 'present');
|
||||
assert.match(f.byId('ri-details').textContent, /Coverage unknown/);
|
||||
});
|
||||
|
||||
test('the body scroll position survives renders even when DOM mutations reset it', async () => {
|
||||
const f = fixture();
|
||||
await f.ready();
|
||||
|
||||
@@ -13,11 +13,11 @@ const REFUSALS = [
|
||||
'Point the camera at the ground to use the view', // layers/recentImagery/index.js
|
||||
'That point cannot anchor a box', // layers/recentImagery/index.js
|
||||
...[
|
||||
{ west: 170, south: 10, east: -170, north: 20 }, // dateline, over the size cap
|
||||
{ west: 10, south: 80, east: 20, north: 89 },
|
||||
{ west: 10, south: 10, east: 10, north: 20 },
|
||||
{ west: 10, south: 10, east: 200, north: 20 },
|
||||
{ west: Number.NaN, south: 10, east: 20, north: 20 },
|
||||
{ west: 170, south: 10, east: -170, north: 20 }, // dateline
|
||||
{ west: 10, south: 80, east: 20, north: 89 }, // polar
|
||||
{ west: 10, south: 10, east: 10, north: 20 }, // degenerate
|
||||
{ west: 10, south: 10, east: 200, north: 20 }, // longitude range
|
||||
{ west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite
|
||||
].map((box) => {
|
||||
const result = validateBox(box);
|
||||
assert.equal(result.ok, false);
|
||||
@@ -27,14 +27,7 @@ const REFUSALS = [
|
||||
|
||||
test('en: refusals stay English', () => {
|
||||
setLocale('en');
|
||||
for (const text of REFUSALS) {
|
||||
const shown = localizeNotice(text);
|
||||
// Size refusals are rewritten with a non-breaking space before the unit.
|
||||
const expected = / km wide/.test(text)
|
||||
? text.replaceAll(' km', '\u00a0km')
|
||||
: text;
|
||||
assert.equal(shown, expected);
|
||||
}
|
||||
for (const text of REFUSALS) assert.equal(localizeNotice(text), text);
|
||||
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
|
||||
});
|
||||
|
||||
|
||||
@@ -92,19 +92,6 @@ export function compassName(deg) {
|
||||
return COMPASS[Math.round((((deg % 360) + 360) % 360) / 45) % 8];
|
||||
}
|
||||
|
||||
// The middle of a perimeter's first ring, close enough for "how far".
|
||||
function perimeterMiddle(row) {
|
||||
const ring = row?.polygons?.[0]?.[0];
|
||||
if (!Array.isArray(ring) || !ring.length) return null;
|
||||
let lat = 0;
|
||||
let lon = 0;
|
||||
for (const [x, y] of ring) {
|
||||
lon += x;
|
||||
lat += y;
|
||||
}
|
||||
return { lat: lat / ring.length, lon: lon / ring.length };
|
||||
}
|
||||
|
||||
/** A storm as "Hurricane Melissa": its class in words when the code has them. */
|
||||
function stormTitle(storm) {
|
||||
const word = codeWord('classification', storm.classification);
|
||||
@@ -129,7 +116,7 @@ export async function hazardsNear(
|
||||
{ fires: withFires = false, force = false } = {},
|
||||
) {
|
||||
const here = { lat, lon };
|
||||
const [quakeRows, stormSnap, perimeterRows, fireSnap] = await Promise.all([
|
||||
const [quakeRows, stormSnap, perimeterSnap, fireSnap] = await Promise.all([
|
||||
quakes(force),
|
||||
storms(force),
|
||||
perimeters(force),
|
||||
@@ -171,8 +158,9 @@ export async function hazardsNear(
|
||||
at,
|
||||
});
|
||||
}
|
||||
for (const fire of Array.isArray(perimeterRows) ? perimeterRows : []) {
|
||||
const at = perimeterMiddle(fire);
|
||||
for (const fire of perimeterSnap?.fires || []) {
|
||||
// The point the fire's card stands on, close enough for "how far".
|
||||
const at = fire.anchor;
|
||||
if (!at || !(distanceKm(here, at) <= radiusKm)) continue;
|
||||
const acres = Number(fire.acres);
|
||||
add({
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { hazardsNear } from './spotConditions.js';
|
||||
|
||||
test('a wildfire is placed at its card anchor, not its first ring', async (t) => {
|
||||
// Two polygons: the larger one, far from the first, carries the anchor.
|
||||
const square = (lon, lat, size) => [
|
||||
[
|
||||
[lon, lat],
|
||||
[lon + size, lat],
|
||||
[lon + size, lat + size],
|
||||
[lon, lat + size],
|
||||
[lon, lat],
|
||||
],
|
||||
];
|
||||
t.mock.method(globalThis, 'fetch', async (url) =>
|
||||
String(url) === '/api/fire-perimeters'
|
||||
? Response.json({
|
||||
rows: [
|
||||
{
|
||||
stableId: 'fire',
|
||||
name: 'Fixture Fire',
|
||||
acres: 1200,
|
||||
containedPct: 30,
|
||||
updatedTime: Date.now() - 3600000,
|
||||
polygons: [square(-110, 35, 0.01), square(-108, 35, 0.2)],
|
||||
},
|
||||
],
|
||||
})
|
||||
: new Response('down', { status: 503 }),
|
||||
);
|
||||
const near = await hazardsNear(35.1, -107.9, 30, { force: true });
|
||||
const fires = near.filter(({ kind }) => kind === 'wildfire');
|
||||
assert.equal(fires.length, 1);
|
||||
assert.equal(fires[0].title, 'Fixture Fire');
|
||||
assert.ok(fires[0].distanceKm < 5, `${fires[0].distanceKm} km`);
|
||||
});
|
||||
@@ -431,35 +431,6 @@ html:not([lang='en']):not(:lang(zh)):not(:lang(ja))
|
||||
}
|
||||
}
|
||||
|
||||
/* The opening (src/app/openingIntro.js) sets these each frame. */
|
||||
#loading-screen.opening {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--bg-dark) calc(var(--opening-veil, 1) * 100%),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
#loading-screen.opening .loader-logo {
|
||||
animation: none;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
#loading-screen.opening .loader-logo svg {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
#loading-screen.opening .loader-logo svg > path {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
#loading-screen.opening h2,
|
||||
#loading-screen.opening .loader-status {
|
||||
animation: none;
|
||||
opacity: var(--opening-text, 1);
|
||||
}
|
||||
|
||||
.loader-content h2 {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 18px;
|
||||
|
||||
@@ -63,7 +63,8 @@ test('the complete Realtime tool payload pins the manifest-generated layer relea
|
||||
// The Cyber HUD layout leaves set_hud's layout enum (its sonar is a
|
||||
// visual style; set_cyber_sonar is excluded above).
|
||||
// The Space Missions panel adds one panel target.
|
||||
'09abe70ef3a1fc4320e25cff997dd3b04db7e78ff31b8530e17bbbbb8156b4c6',
|
||||
// Fire Perimeters queries add lastGrowthTime.
|
||||
'2be49b7634a7b74b756a68cf80835ee36411e087edb549eb39f1ce7310afe60f',
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
+18
-4
@@ -5990,6 +5990,14 @@ function analystProviders(
|
||||
truncated: true,
|
||||
};
|
||||
},
|
||||
/** The moment a layer's records show when it is not now (a past snapshot), else null. */
|
||||
getRecordsAt(layerKey) {
|
||||
if (!dataManager.isEnabled(layerKey)) return null;
|
||||
const at = dataManager.layers
|
||||
.get(layerKey)
|
||||
?.module?.getAnalystRecordsAt?.();
|
||||
return Number.isFinite(at) ? at : null;
|
||||
},
|
||||
isWarming,
|
||||
/** The layer's own status text for an empty result, e.g. "Fly below 400 km". */
|
||||
getEmptyNote(layerKey) {
|
||||
@@ -6076,8 +6084,11 @@ const ANALYST_CANONICAL_FIELDS = new Set([
|
||||
|
||||
/**
|
||||
* Compact one analyst record for the voice payload: identity, position (so a
|
||||
* follow-up can fly to it), distance, and that layer's manifest fields with
|
||||
* times as ISO text. The full record set stays engine-side for follow-ups.
|
||||
* follow-up can fly to it), distance, and that layer's manifest fields. The layer's
|
||||
* `timeField` (on a layer without one, any time field) comes back as ISO `time`.
|
||||
* Other timestamps keep their own keys,
|
||||
* as ISO text except for numeric `lastContactAtMs`. The full record set
|
||||
* stays engine-side for follow-ups.
|
||||
*
|
||||
* `icao24`/`vesselId`/`mmsi` ride along because the tool instructions tell the model to
|
||||
* hand this result straight to track_entity, and `id` is a DISPLAY label
|
||||
@@ -6097,7 +6108,8 @@ function compactAnalystItem(r) {
|
||||
compact.lon = Math.round(r.lon * 1e4) / 1e4;
|
||||
}
|
||||
if (present(r.distanceKm)) compact.distanceKm = r.distanceKm;
|
||||
const fields = voiceLayer(r.layerKey)?.query?.fields || {};
|
||||
const query = voiceLayer(r.layerKey)?.query;
|
||||
const fields = query?.fields || {};
|
||||
for (const [key, spec] of Object.entries(fields)) {
|
||||
if (!present(r[key]) || key in compact) continue;
|
||||
if (spec.type === 'time') {
|
||||
@@ -6106,7 +6118,9 @@ function compactAnalystItem(r) {
|
||||
const time = new Date(ms);
|
||||
if (Number.isFinite(time.getTime())) {
|
||||
if (key === 'lastContactAtMs') compact.lastContactAtMs = ms;
|
||||
else compact.time = time.toISOString();
|
||||
else if (key === (query.timeField ?? key))
|
||||
compact.time = time.toISOString();
|
||||
else compact[key] = time.toISOString();
|
||||
}
|
||||
} else compact[key] = r[key];
|
||||
}
|
||||
|
||||
@@ -6016,6 +6016,54 @@ test('analyst_query keeps its answer when one record has an out-of-range time',
|
||||
assert.equal(r.time, undefined, 'an unrepresentable time is omitted');
|
||||
});
|
||||
|
||||
test("analyst_query keeps a fire's discovery time apart from its last growth", async (t) => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
setTimeout,
|
||||
requestIdleCallback: null,
|
||||
};
|
||||
const T = Date.parse('2026-09-04T00:00:00Z');
|
||||
t.mock.method(Date, 'now', () => T);
|
||||
const records = [
|
||||
{
|
||||
id: 'fire-a',
|
||||
name: 'Alpha Fire',
|
||||
lat: 35.2,
|
||||
lon: -108.1,
|
||||
discoveredTime: Date.parse('2026-09-01T00:00:00Z'),
|
||||
lastGrowthTime: Date.parse('2026-09-02T00:00:00Z'),
|
||||
},
|
||||
{
|
||||
id: 'fire-b',
|
||||
name: 'Bravo Fire',
|
||||
lat: 35.3,
|
||||
lon: -108.2,
|
||||
discoveredTime: Date.parse('2026-09-01T00:00:00Z'),
|
||||
lastGrowthTime: null,
|
||||
},
|
||||
];
|
||||
const module = {
|
||||
getStats: () => ({ count: records.length, lastUpdate: T }),
|
||||
getAnalystRecords: () => records,
|
||||
};
|
||||
const { runner } = manifestRunner(
|
||||
{ 'fire-perimeters': module },
|
||||
{ enabled: ['fire-perimeters'] },
|
||||
);
|
||||
const result = await runner('analyst_query', {
|
||||
layers: ['fire-perimeters'],
|
||||
scope: { kind: 'anywhere' },
|
||||
limit: 5,
|
||||
});
|
||||
assert.equal(result.ok, true, JSON.stringify(result));
|
||||
const a = result.items.find((item) => item.id === 'fire-a');
|
||||
const b = result.items.find((item) => item.id === 'fire-b');
|
||||
assert.equal(a.time, '2026-09-01T00:00:00.000Z');
|
||||
assert.equal(a.lastGrowthTime, '2026-09-02T00:00:00.000Z');
|
||||
assert.equal(b.time, '2026-09-01T00:00:00.000Z');
|
||||
assert.equal('lastGrowthTime' in b, false);
|
||||
});
|
||||
|
||||
test('spoken layer names from the manifest reach the newer layers', async () => {
|
||||
globalThis.window = globalThis.window || {
|
||||
clearTimeout,
|
||||
|
||||
+11
-11
@@ -17,12 +17,7 @@
|
||||
* @module voice/imageryActions
|
||||
*/
|
||||
|
||||
import {
|
||||
PRODUCTS,
|
||||
boxCentre,
|
||||
boxSideKm,
|
||||
rankLatest,
|
||||
} from '../layers/recentImagery/model.js';
|
||||
import { PRODUCTS, rankLatest } from '../layers/recentImagery/model.js';
|
||||
import {
|
||||
displacedLayerResult,
|
||||
watchExplicitLayerOff,
|
||||
@@ -208,14 +203,19 @@ export async function findImagery(
|
||||
`No area "${args.areaId}" on this page — call resolve_area again.`,
|
||||
);
|
||||
const [west, south, east, north] = record.bbox;
|
||||
if (west > east)
|
||||
return fail(
|
||||
'DATELINE',
|
||||
`${record.name} crosses the date line; the imagery box needs one side of it.`,
|
||||
);
|
||||
// 30 m pixels over a landmark-sized area show a handful of blobs: a small
|
||||
// area gets the layer's own 10 km box around its centre instead.
|
||||
// west > east is the short arc across the date line. The layer's helpers
|
||||
// measure and centre it.
|
||||
const { width, height } = boxSideKm({ west, south, east, north });
|
||||
const small = width < 5 && height < 5;
|
||||
const small =
|
||||
(north - south) * 111 < 5 &&
|
||||
(east - west) * 111 * Math.cos((((north + south) / 2) * Math.PI) / 180) <
|
||||
5;
|
||||
box = small
|
||||
? { pin: boxCentre({ west, south, east, north }) }
|
||||
? { pin: { lon: (west + east) / 2, lat: (south + north) / 2 } }
|
||||
: { west, south, east, north };
|
||||
areaName = record.name;
|
||||
} else if (where === 'point') {
|
||||
|
||||
@@ -236,7 +236,7 @@ test('an area handle searches its bounding box; the view and pointer have their
|
||||
assert.equal(unknown.code, 'AREA_UNKNOWN');
|
||||
});
|
||||
|
||||
test('a mixed antimeridian area is searched as its short-arc box', async () => {
|
||||
test('a mixed antimeridian area gets the deliberate imagery date-line refusal', async () => {
|
||||
const square = (w, s, e, n) => [
|
||||
[w, s],
|
||||
[e, s],
|
||||
@@ -251,7 +251,6 @@ test('a mixed antimeridian area is searched as its short-arc box', async () => {
|
||||
[178, 1],
|
||||
[178, 0],
|
||||
];
|
||||
const layer = fakeLayer();
|
||||
const store = createAreaStore();
|
||||
const area = store.put({
|
||||
geometry: [[crossing], [square(-176, 0.2, -174, 0.8)]],
|
||||
@@ -259,33 +258,11 @@ test('a mixed antimeridian area is searched as its short-arc box', async () => {
|
||||
source: 'osm',
|
||||
});
|
||||
assert.deepEqual(area.bbox, [178, 0, -174, 1]);
|
||||
const result = await findImagery(deps(layer, { area }).value, {
|
||||
const result = await findImagery(deps(fakeLayer(), { area }).value, {
|
||||
areaId: area.areaId,
|
||||
});
|
||||
assert.equal(result.ok, true, 'the guard is lifted');
|
||||
assert.deepEqual(layer.calls.find((c) => c[0] === 'setBox')[1], {
|
||||
west: 178,
|
||||
south: 0,
|
||||
east: -174,
|
||||
north: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test('a small area across the date line is pinned at its short-arc centre', async () => {
|
||||
const layer = fakeLayer();
|
||||
await findImagery(
|
||||
deps(layer, {
|
||||
area: {
|
||||
areaId: 'd',
|
||||
name: 'Dateline Islet',
|
||||
bbox: [179.998, 0, -179.998, 0.01],
|
||||
},
|
||||
}).value,
|
||||
{ areaId: 'd' },
|
||||
);
|
||||
const [, lon, lat] = layer.calls.find((c) => c[0] === 'boxFromPinAt');
|
||||
assert.ok(Math.abs(Math.abs(lon) - 180) < 1e-9, `pin lon ${lon}, not 0`);
|
||||
assert.equal(lat, 0.005);
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.code, 'DATELINE');
|
||||
});
|
||||
|
||||
test('a box the layer refuses is refused with its reason, and the layer is turned on first', async () => {
|
||||
|
||||
@@ -234,6 +234,7 @@ const layers = [
|
||||
behavior: ['t'],
|
||||
complexity: ['t'],
|
||||
discoveredTime: ['ms'],
|
||||
lastGrowthTime: ['ms'],
|
||||
},
|
||||
timeField: 'discoveredTime',
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user