From bc77f265a88b2f93abdc00ccdcf008821a422c85 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Fri, 20 Nov 2026 19:41:13 +0400 Subject: [PATCH] feat(perimeters): colour fire perimeters by age The Fire Perimeters layer now draws a snapshot of fires and the pieces of their burned area, each piece coloured by its age at the snapshot's moment (under 6 h, 6-24 h, 1-3 days, older or unknown). Containment stays on the card; the legend counts fires by last growth and shows the source's note. - One source method, getSnapshot, returning {at, fetchedAt, stale, revision, note, fires, pieces}; getSnapshotDetail is removed. - WFIGS: one piece per polygon, born at poly_PolygonDateTime, else poly_DateCurrent; a time more than 10 minutes ahead is unknown. - Outlines are drawn apart from fills, so cut pieces have no line along the cut; redraws happen only on a new revision or a change of age band. - The card ages from `at` and adds "last growth ... ago"; a past `at` links only to InciWeb pages created by then. - perimeterOptions: { inciweb: false } creates no InciWeb sources. - get_fire_perimeters filters by pieces, places fires at their anchor and returns last_growth; analyst items carry lastGrowthTime; spot conditions use the anchor. --- DATA_SOURCES.md | 2 +- README.md | 2 +- docs/CURRENT-STATE.md | 29 +- docs/TOOLS.md | 2 +- scripts/format-scope.json | 2 + scripts/package-boundaries.json | 2 + server/providers/firePerimeters.js | 1 + src/app/constructCatalog.js | 4 + src/app/constructCatalog.test.mjs | 47 ++ src/app/layers/perimeters.js | 18 +- src/app/layers/perimeters.test.mjs | 54 ++ src/data/analystEngine.js | 14 +- src/data/analystEngine.test.mjs | 18 + src/data/firePerimetersProxy.test.mjs | 28 + src/firstRunExperience.test.mjs | 5 +- src/i18n/locales/ar.json | 14 +- src/i18n/locales/de.json | 14 +- src/i18n/locales/es.json | 14 +- src/i18n/locales/fr.json | 14 +- src/i18n/locales/he.json | 14 +- src/i18n/locales/it.json | 14 +- src/i18n/locales/ja.json | 14 +- src/i18n/locales/pt.json | 14 +- src/i18n/locales/ru.json | 14 +- src/i18n/locales/sv.json | 14 +- src/i18n/locales/uk.json | 14 +- src/i18n/locales/zh-CN.json | 14 +- src/i18n/locales/zh-Hant.json | 14 +- src/layers/perimeters/cards.i18n.test.mjs | 9 +- src/layers/perimeters/cards.js | 75 +-- src/layers/perimeters/cards.test.mjs | 128 ++--- src/layers/perimeters/inciweb.js | 68 +-- src/layers/perimeters/inciweb.test.mjs | 37 ++ src/layers/perimeters/index.js | 384 +++++++++----- src/layers/perimeters/ownership.test.mjs | 598 ++++++++++++++++++---- src/layers/perimeters/records.js | 123 +++++ src/layers/perimeters/records.test.mjs | 231 ++++++++- src/layers/perimeters/source.js | 57 +-- src/layers/perimeters/source.test.mjs | 26 +- src/render/cesium/draw.test.mjs | 22 +- src/tools/queries/environment.js | 69 ++- src/tools/queries/environment.test.mjs | 264 +++++++--- src/ui/spotConditions.js | 20 +- src/ui/spotConditions.test.mjs | 37 ++ src/voice/actionSchemas.test.mjs | 3 +- src/voice/gevActions.js | 22 +- src/voice/gevActions.test.mjs | 48 ++ src/voice/layerManifest.js | 1 + 48 files changed, 1899 insertions(+), 733 deletions(-) create mode 100644 src/app/layers/perimeters.test.mjs create mode 100644 src/ui/spotConditions.test.mjs diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 7f7cadd939..d0ba3260e4 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -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 | diff --git a/README.md b/README.md index c26d8094cb..88153ae0d4 100644 --- a/README.md +++ b/README.md @@ -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 | 🟢 | diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ada8897b97..f17b58c038 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -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 diff --git a/docs/TOOLS.md b/docs/TOOLS.md index a6d501c8c5..ca17311c36 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -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) | diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 1704338109..6d032d05a1 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -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", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 0e29f23de1..0c2b77ae5c 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -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", @@ -8190,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", diff --git a/server/providers/firePerimeters.js b/server/providers/firePerimeters.js index 4a364fa6da..74d5a0a0c1 100644 --- a/server/providers/firePerimeters.js +++ b/server/providers/firePerimeters.js @@ -23,6 +23,7 @@ const API_URL = 'attr_IncidentTypeCategory', 'attr_FireDiscoveryDateTime', 'poly_DateCurrent', + 'poly_PolygonDateTime', 'attr_FireCause', 'attr_FireBehaviorGeneral', 'attr_TotalIncidentPersonnel', diff --git a/src/app/constructCatalog.js b/src/app/constructCatalog.js index 204d5653c6..0600e62ac2 100644 --- a/src/app/constructCatalog.js +++ b/src/app/constructCatalog.js @@ -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({ diff --git a/src/app/constructCatalog.test.mjs b/src/app/constructCatalog.test.mjs index ea6b46cd66..5b8995ca98 100644 --- a/src/app/constructCatalog.test.mjs +++ b/src/app/constructCatalog.test.mjs @@ -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')), + [], + ); +}); diff --git a/src/app/layers/perimeters.js b/src/app/layers/perimeters.js index dd1230ce46..e4ae09a40d 100644 --- a/src/app/layers/perimeters.js +++ b/src/app/layers/perimeters.js @@ -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, + }), }); } diff --git a/src/app/layers/perimeters.test.mjs b/src/app/layers/perimeters.test.mjs new file mode 100644 index 0000000000..eda67aedfc --- /dev/null +++ b/src/app/layers/perimeters.test.mjs @@ -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); + }); +} diff --git a/src/data/analystEngine.js b/src/data/analystEngine.js index cc85195219..e6649ca5e0 100644 --- a/src/data/analystEngine.js +++ b/src/data/analystEngine.js @@ -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} [options.recordsAt] Per-layer snapshot times in epoch ms. + * Ages count from the layer’s snapshot time when given, otherwise from now. * @returns {Promise} 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, diff --git a/src/data/analystEngine.test.mjs b/src/data/analystEngine.test.mjs index 7bf20defa6..34e22f82db 100644 --- a/src/data/analystEngine.test.mjs +++ b/src/data/analystEngine.test.mjs @@ -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({ diff --git a/src/data/firePerimetersProxy.test.mjs b/src/data/firePerimetersProxy.test.mjs index 6c559c0d71..6cabf5a98e 100644 --- a/src/data/firePerimetersProxy.test.mjs +++ b/src/data/firePerimetersProxy.test.mjs @@ -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 = []; diff --git a/src/firstRunExperience.test.mjs b/src/firstRunExperience.test.mjs index 96982fb02d..a2d5b31396 100644 --- a/src/firstRunExperience.test.mjs +++ b/src/firstRunExperience.test.mjs @@ -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( diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 5f3d6501b0..15734b7c25 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -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 م." } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 4dd017bee0..4ede4d56c7 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -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." } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index acdc0be5f6..9aac4dd3b3 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -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." } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index bf9ceedada..b673fbce73 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -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." } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 95c51c7cbc..dc602802eb 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -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 מ׳." } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 15716131df..547c6baad6 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -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." } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 6b92ec40e9..944ca61b0b 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -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 に簡略化されています。" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index c08294e421..4f42435cb5 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -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." } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 6bf754dbe1..eb8aca4a22 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -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 м." } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 0720881a1d..0d8dfca041 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -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." } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 5eab3f5f8d..7d6deb0dba 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -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 м." } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index f798c8a328..6559001340 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -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 米。" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index ff677f2572..0e01112e1b 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -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 米。" } diff --git a/src/layers/perimeters/cards.i18n.test.mjs b/src/layers/perimeters/cards.i18n.test.mjs index 95fa090a14..520b958df4 100644 --- a/src/layers/perimeters/cards.i18n.test.mjs +++ b/src/layers/perimeters/cards.i18n.test.mjs @@ -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', diff --git a/src/layers/perimeters/cards.js b/src/layers/perimeters/cards.js index 4c73d5733a..6c823ad208 100644 --- a/src/layers/perimeters/cards.js +++ b/src/layers/perimeters/cards.js @@ -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>>} 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, diff --git a/src/layers/perimeters/cards.test.mjs b/src/layers/perimeters/cards.test.mjs index fe4aac06ba..f7211c91bd 100644 --- a/src/layers/perimeters/cards.test.mjs +++ b/src/layers/perimeters/cards.test.mjs @@ -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', + ]); +}); diff --git a/src/layers/perimeters/inciweb.js b/src/layers/perimeters/inciweb.js index 3cc3ae5385..9206bf2591 100644 --- a/src/layers/perimeters/inciweb.js +++ b/src/layers/perimeters/inciweb.js @@ -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. */ diff --git a/src/layers/perimeters/inciweb.test.mjs b/src/layers/perimeters/inciweb.test.mjs index 70d4e147c4..6de3a29ef9 100644 --- a/src/layers/perimeters/inciweb.test.mjs +++ b/src/layers/perimeters/inciweb.test.mjs @@ -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( diff --git a/src/layers/perimeters/index.js b/src/layers/perimeters/index.js index 8d0e1ab7ed..b1481332e8 100644 --- a/src/layers/perimeters/index.js +++ b/src/layers/perimeters/index.js @@ -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} */ - 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(); + /** `\n` → 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::` for fills, `…::line:` 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, diff --git a/src/layers/perimeters/ownership.test.mjs b/src/layers/perimeters/ownership.test.mjs index d0dd6075ee..9914993cde 100644 --- a/src/layers/perimeters/ownership.test.mjs +++ b/src/layers/perimeters/ownership.test.mjs @@ -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(); +}); diff --git a/src/layers/perimeters/records.js b/src/layers/perimeters/records.js index faed5ba641..d918777224 100644 --- a/src/layers/perimeters/records.js +++ b/src/layers/perimeters/records.js @@ -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>>} 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, + }; +} diff --git a/src/layers/perimeters/records.test.mjs b/src/layers/perimeters/records.test.mjs index fb11193ed1..a289f7a775 100644 --- a/src/layers/perimeters/records.test.mjs +++ b/src/layers/perimeters/records.test.mjs @@ -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); + } + } + } + } +}); diff --git a/src/layers/perimeters/source.js b/src/layers/perimeters/source.js index 5691917818..f01dd5782e 100644 --- a/src/layers/perimeters/source.js +++ b/src/layers/perimeters/source.js @@ -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, }; } diff --git a/src/layers/perimeters/source.test.mjs b/src/layers/perimeters/source.test.mjs index bb6d6b305e..f64e3f5ec2 100644 --- a/src/layers/perimeters/source.test.mjs +++ b/src/layers/perimeters/source.test.mjs @@ -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, []); }); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 3c359ba2e7..aa08058180 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -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); }); diff --git a/src/tools/queries/environment.js b/src/tools/queries/environment.js index 01fe3624a5..e5ae27b069 100644 --- a/src/tools/queries/environment.js +++ b/src/tools/queries/environment.js @@ -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', diff --git a/src/tools/queries/environment.test.mjs b/src/tools/queries/environment.test.mjs index b7107f49eb..7dd9664fc4 100644 --- a/src/tools/queries/environment.test.mjs +++ b/src/tools/queries/environment.test.mjs @@ -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', + ); +}); diff --git a/src/ui/spotConditions.js b/src/ui/spotConditions.js index 963b65cf2f..c85d3dc47d 100644 --- a/src/ui/spotConditions.js +++ b/src/ui/spotConditions.js @@ -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({ diff --git a/src/ui/spotConditions.test.mjs b/src/ui/spotConditions.test.mjs new file mode 100644 index 0000000000..bb3acea219 --- /dev/null +++ b/src/ui/spotConditions.test.mjs @@ -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`); +}); diff --git a/src/voice/actionSchemas.test.mjs b/src/voice/actionSchemas.test.mjs index cfd4ec0a3a..81a1a08aaf 100644 --- a/src/voice/actionSchemas.test.mjs +++ b/src/voice/actionSchemas.test.mjs @@ -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', ); }); diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 5d32fde90f..13dde36721 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -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]; } diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index 4c9d7a84aa..a97e72aea0 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -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, diff --git a/src/voice/layerManifest.js b/src/voice/layerManifest.js index 52cb0f90fc..e72fdc6996 100644 --- a/src/voice/layerManifest.js +++ b/src/voice/layerManifest.js @@ -234,6 +234,7 @@ const layers = [ behavior: ['t'], complexity: ['t'], discoveredTime: ['ms'], + lastGrowthTime: ['ms'], }, timeField: 'discoveredTime', },