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"; with a past
  `at` it links only to an InciWeb incident that began 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.
This commit is contained in:
German Khokhlov committed 2026-11-23 15:48:54 +04:00
1 parent e51853de3d
commit d303d48693
48 files changed
+2127 -734

No files matched your search

+6 -3
View File
@@ -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',
+16 -59
View File
@@ -3,7 +3,7 @@ import { formatNumber, t, tn } from '../../i18n/index.js';
export const PERIMETER_OVERLAY_SOURCE_ID = 'fire-perimeters';
/** CSS accent for a perimeter card by containment progress (mirrors the fill). */
/** CSS accent for a perimeter card by containment progress. */
export function containmentAccent(containedPct) {
if (!Number.isFinite(containedPct) || containedPct <= 0) return '#ff3b30';
if (containedPct < 50) return '#ff7a00';
@@ -11,55 +11,6 @@ export function containmentAccent(containedPct) {
return '#8bc34a';
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/**
* Compact USD in the UI language: en "$85K / $4.2M / $1.3B", ru "4,2 млн $",
* es "4,2 M$". Null under $1,000.
@@ -149,8 +100,9 @@ function formatAge(deltaMs) {
/**
* Build the overlay-host entry for one selected incident. The caller supplies
* `position` (Cartesian) separately — this model stays JSON-safe for tests.
* @param {Object} row - Normalized perimeter row (see records.js).
* @param {number} nowMs - Current epoch milliseconds.
* @param {Object} row - A snapshot fire (see records.js).
* @param {number} nowMs - The moment shown, epoch milliseconds: the snapshot's
* `at`, or now.
* @param {{link: ?string}} [extras] - Optional InciWeb page for this incident.
* @returns {Object} World-overlay entry without `position`.
*/
@@ -194,13 +146,17 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
if (cost) response.push(t('{cost} to date', { cost }));
}
const ago = (time) => (time == null ? null : formatAge(nowMs - time));
const growth = ago(row.lastGrowthTime);
const lastGrowth = growth
? t('last growth {age} ago', { age: growth })
: null;
const ages = [];
const discovered = formatAge(nowMs - row.discoveredTime);
if (row.discoveredTime != null && discovered)
ages.push(t('discovered {age} ago', { age: discovered }));
const updated = formatAge(nowMs - row.updatedTime);
if (row.updatedTime != null && updated)
ages.push(t('updated {age} ago', { age: updated }));
const discovered = ago(row.discoveredTime);
if (discovered) ages.push(t('discovered {age} ago', { age: discovered }));
const updated = ago(row.updatedTime);
if (updated) ages.push(t('updated {age} ago', { age: updated }));
const details = [facts.join(' · ')];
if (row.complexName)
@@ -209,6 +165,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
);
if (situation.length) details.push(situation.join(' · '));
if (response.length) details.push(response.join(' · '));
if (lastGrowth) details.push(lastGrowth);
if (ages.length) details.push(ages.join(' · '));
if (link) details.push(t('InciWeb ↗ · click card to open'));
@@ -216,7 +173,7 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
name: row.name || t('Unnamed incident'),
});
return {
id: `fire-perimeter-card:${row.stableId}`,
id: `fire-perimeter-card:${row.id}`,
// `selected` picks the paint lane and collision protection; an explicit
// paintLane would override it in the host's lane resolver.
selected: true,
+31 -97
View File
@@ -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',
]);
});
+35 -33
View File
@@ -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. */
+37
View File
@@ -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(
+277 -143
View File
@@ -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,26 @@ export function createFirePerimetersLayer({
let _inciwebIndex = [];
let _indexFetchedAt = 0;
let _indexFetchInFlight = false;
/** @type {Map<string, {stableId: string, anchor: {lon: number, lat: number}}>} */
const _rowById = new Map();
// Link → currency verdict from the publication check; unknown links are
// absent. Failed checks are not cached so a transient outage retries.
const _linkVerdicts = new Map();
let _fireById = new Map();
/** `<set id>\n<item id>` → the fire that item belongs to. */
const _fireByItem = new Map();
const shownAt = () => _at ?? Date.now();
const _linkPublications = new Map();
// Retry failed pages on reselection or when a read finds the card linkless.
const _linkFailures = new Set();
function abortLinkVerification() {
_linkRequest?.controller.abort();
_linkRequest = null;
}
function resetSelection() {
abortLinkVerification();
_linkFailures.clear();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
}
const canSelect = () => overlayHost && inputFor && picking;
/**
@@ -141,29 +205,57 @@ 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.
if (signal.aborted || _linkRequest !== request || !_enabled) return;
_linkFailures.add(link);
if (_selectedId === row.id) publishSelectedCard();
})
.finally(() => {
if (_linkRequest === request) _linkRequest = null;
});
}
function isCurrentLink(publication, row) {
if (
_at !== null &&
!(Number.isFinite(publication.createdMs) && publication.createdMs <= _at)
)
return false;
return isCurrentPublication(publication, {
discoveredTime: row.discoveredTime,
nowMs: shownAt(),
});
}
/**
* The current page among verified candidates: the one whose incident began
* nearest the fire's discovery, else (no discovery date) the newest.
*/
function chooseLink(links, row) {
let best = null;
let bestGap = Infinity;
for (const link of links) {
const publication = _linkPublications.get(link);
if (!publication || !isCurrentLink(publication, row)) continue;
const gap = Number.isFinite(row.discoveredTime)
? Math.abs(publication.createdMs - row.discoveredTime)
: 0;
if (best === null || gap < bestGap) {
best = link;
bestGap = gap;
}
}
return best;
}
function publishSelectedCard() {
if (!canSelect()) return;
const row = _selectedId ? _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 +263,36 @@ 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 own-name page, since the newest may postdate it, and the
// complex's pages only when none of those is current.
const groups =
_at === null
? [findInciwebLinks(_inciwebIndex, row).slice(0, 1)]
: [
findInciwebLinks(_inciwebIndex, {
name: row.name,
state: row.state,
}),
findInciwebLinks(_inciwebIndex, {
name: row.complexName,
state: row.state,
}),
];
_selectedLink = null;
for (const links of groups) {
const unverified = links.find(
(link) => !_linkPublications.has(link) && !_linkFailures.has(link),
);
if (unverified) {
verifyLink(unverified, row);
break;
}
_selectedLink = chooseLink(links, row);
if (_selectedLink) break;
}
const 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 +317,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() {
@@ -236,6 +350,7 @@ export function createFirePerimetersLayer({
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
if (incidentId) {
abortLinkVerification();
_linkFailures.clear();
_selectedId = incidentId;
publishSelectedCard();
return;
@@ -247,23 +362,67 @@ export function createFirePerimetersLayer({
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
}
if (_selectedId) {
abortLinkVerification();
_selectedId = null;
publishSelectedCard();
}
});
}
function drawPieces(pieces, bands) {
const nextFills = [];
const nextLines = [];
const counts = new Map();
_fireByItem.clear();
// `fire-perimeter:<fire>:<n>` for fills, `…:<fire>:line:<n>` for lines.
const itemId = (fireId, kind) => {
const key = `${kind}${fireId}`;
const n = counts.get(key) ?? 0;
counts.set(key, n + 1);
const id = `${PICK_PREFIX}${fireId}:${kind}${n}`;
_fireByItem.set(`${kind ? _lines.id : _fills.id}\n${id}`, fireId);
return id;
};
for (const [index, piece] of pieces.entries()) {
const { color } = PERIMETER_AGE_BANDS[bands[index]];
// Each exterior keeps its own holes.
for (const rings of Array.isArray(piece.polygons) ? piece.polygons : []) {
if (!Array.isArray(rings) || !rings.every((ring) => validLine(ring, 3)))
continue;
nextFills.push({
id: itemId(piece.fireId, ''),
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: hexColor(color, FILL_ALPHA),
height: 'clampGround',
});
}
// The fire line: the piece's outline draped on the ground, apart from
// its fill, so a piece cut from a larger area has no line along the
// cut (lines take ECEF, draw.d.ts `LineItem`).
for (const line of Array.isArray(piece.outline) ? piece.outline : []) {
if (!validLine(line, 2)) continue;
nextLines.push({
id: itemId(piece.fireId, 'line:'),
positions: line.map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: LINE_WIDTH_PX,
mode: 'draped',
style: { kind: 'solid', color: hexColor(color, LINE_ALPHA) },
});
}
}
_fills.set(nextFills);
_lines.set(nextLines);
console.log(
`[Data:FirePerimeters] Drew ${pieces.length} pieces of ${_fireById.size} fires`,
);
}
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
}
function clearSelection() {
abortLinkVerification();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
resetSelection();
if (overlayHost) {
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
@@ -292,9 +451,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 +475,58 @@ 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),
});
// Refresh (or drop) the selected incident's card against the new
// snapshot: its ages move with `at` even when nothing is redrawn.
if (_selectedId) {
if (_selectedLink === null && !_linkRequest) _linkFailures.clear();
publishSelectedCard();
}
_fills.set(nextFills);
_lines.set(nextLines);
_snapshotSignature = signature;
// Refresh (or drop) the selected incident's card against the new feed.
if (_selectedId) publishSelectedCard();
_count = rows.length;
_lastUpdate = updatedAt;
_lastError = null;
console.log(
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
);
return true;
} catch (e) {
if (request.signal.aborted || _request !== request || !_enabled)
@@ -409,6 +537,7 @@ export function createFirePerimetersLayer({
_stale = false;
return false;
} finally {
signal?.removeEventListener('abort', abort);
if (_request === request) _request = null;
}
},
@@ -418,18 +547,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 +573,15 @@ 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;
// A time after the moment shown is unknown in this snapshot.
if (_at !== null)
for (const key of ['discoveredTime', 'updatedTime', 'lastGrowthTime'])
if (facts[key] > _at) facts[key] = null;
result.push({
id: stableId,
id,
...facts,
lat: anchor.lat,
lon: anchor.lon,
@@ -455,34 +590,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,
File diff suppressed because it is too large. Load diff
+123
View File
@@ -1,3 +1,14 @@
/**
* WFIGS perimeters: the proxy's rows (normalizeFirePerimeterSnapshot) and
* the snapshot the layer draws (firePerimeterSnapshot).
*
* The server and the package's `./layers/perimeters/source` export import
* this module, so it marks text with msg() only. The layer translates `note`
* when it shows it.
*/
import { msg } from '../../i18n/marker.js';
/**
* Normalize a WFIGS feed, skipping individually invalid features.
* Only a payload that is not a feature collection at all rejects the whole
@@ -80,6 +91,7 @@ export function normalizeFirePerimeterSnapshot(geojson) {
: null,
discoveredTime: finiteOrNull(properties.attr_FireDiscoveryDateTime),
updatedTime: finiteOrNull(properties.poly_DateCurrent),
polygonTime: finiteOrNull(properties.poly_PolygonDateTime),
cause: textOrNull(properties.attr_FireCause),
behavior: textOrNull(properties.attr_FireBehaviorGeneral),
personnel: finiteOrNull(properties.attr_TotalIncidentPersonnel),
@@ -92,3 +104,114 @@ export function normalizeFirePerimeterSnapshot(geojson) {
}
return rows;
}
/** Shoelace area along short longitude edges (degree², relative sizes only). */
function ringArea(ring) {
let sum = 0;
let [x1, y1] = ring[0];
for (let i = 1; i < ring.length; i++) {
let delta = ring[i][0] - ring[i - 1][0];
if (delta > 180) delta -= 360;
else if (delta < -180) delta += 360;
const x2 = x1 + delta;
const y2 = ring[i][1];
sum += x1 * y2 - x2 * y1;
x1 = x2;
y1 = y2;
}
return Math.abs(sum / 2);
}
/**
* Anchor point for the incident card: the vertex mean of the largest polygon's
* outer ring, with circular longitude. Callers own the Cartesian conversion.
* @param {Array<Array<Array<[number, number]>>>} polygons - Normalized rows' polygons.
* @returns {{lon: number, lat: number}}
*/
export function perimeterAnchorDegrees(polygons) {
let best = null;
let bestArea = -1;
for (const rings of polygons) {
const outer = rings[0];
const area = ringArea(outer);
if (area > bestArea) {
bestArea = area;
best = outer;
}
}
// Vertex mean over the closed ring (first == last point dropped): perimeters
// are compact enough that this stays inside or near the polygon.
let sinLon = 0;
let cosLon = 0;
let lat = 0;
const count = best.length - 1;
const toRad = Math.PI / 180;
for (let i = 0; i < count; i++) {
sinLon += Math.sin(best[i][0] * toRad);
cosLon += Math.cos(best[i][0] * toRad);
lat += best[i][1];
}
return { lon: Math.atan2(sinLon, cosLon) / toRad, lat: lat / count };
}
/** WFIGS times up to this far ahead of our clock (clock skew) are taken as now; later ones are unknown. */
const CLOCK_SKEW_MS = 10 * 60 * 1000;
/**
* The WFIGS snapshot for the Fire Perimeters layer (contract:
* `createFirePerimetersLayer`), from the proxy's rows.
*
* WFIGS keeps one perimeter per fire, so each of its polygons is one piece,
* born when the perimeter was mapped (`poly_PolygonDateTime`, else the
* record's last edit `poly_DateCurrent`).
* @param {object[]} rows - normalizeFirePerimeterSnapshot rows.
* @param {{fetchedAt?: number|null, stale?: boolean, now?: number}} [options]
* @returns {{at: null, fetchedAt: number|null, stale: boolean,
* revision: string, note: string, fires: object[], pieces: object[]}}
*/
export function firePerimeterSnapshot(
rows,
{ fetchedAt = null, stale = false, now = Date.now() } = {},
) {
const fires = [];
const pieces = [];
const versions = [];
for (const row of rows) {
const { stableId, polygons, polygonTime, ...facts } = row;
const mapped = polygonTime ?? facts.updatedTime;
const grown =
Number.isFinite(mapped) && mapped <= now + CLOCK_SKEW_MS
? Math.min(mapped, now)
: null;
fires.push({
...facts,
id: stableId,
lastGrowthTime: grown,
anchor: perimeterAnchorDegrees(polygons),
});
for (const rings of polygons)
pieces.push({
fireId: stableId,
born: grown,
polygons: [rings],
outline: rings,
});
// Without poly_DateCurrent, the mapping time and outline stand in for it.
versions.push(
Number.isFinite(facts.updatedTime)
? `${stableId}@${facts.updatedTime}`
: `${stableId}@${polygonTime ?? ''}:${JSON.stringify(polygons)}`,
);
}
return {
at: null,
fetchedAt: Number.isFinite(fetchedAt) ? fetchedAt : null,
stale: stale === true,
revision: versions.sort().join('|'),
note: msg(
"Age counts from WFIGS mapping time, else the record's last edit. Perimeters simplified to ~100 m.",
),
fires,
pieces,
};
}
+230 -1
View File
@@ -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);
}
}
}
}
});
+25 -32
View File
@@ -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,
};
}
+14 -12
View File
@@ -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, []);
});