Files
gods-eye-view/src/layers/perimeters/index.js
T
Sameh Khamis bb3bf9858b fix(click): the card or label on top takes the click in every layer
Review fixes for #1781:

- One rule for cards: the world-overlay host hands its hit test to the
  pick registry, and every click handler reads the topmost interactive
  card or label once per click (`clickCard`, `isUnderOtherCard` in
  src/data/pickRegistry.js), so all handlers agree in any listener order.
  A layer whose own card or label is on top acts on it whatever is drawn
  under it; a layer under another layer's card neither acts nor treats
  the click as empty space (a tracked aircraft stays tracked, a selection
  stays selected); Context names nothing under a card. A selected news
  card over a vessel no longer opens the link and selects the vessel.
- With one rule, the per-owner arbitration options are no longer read
  and are removed: `passive`, `expanded` and `declinesClick` pick owners,
  `rememberClickPickActions`, `isActedOnByOtherLayer`, card backgrounds
  and `cardKeepsClick`. The dispatcher is unchanged from main.
- A drag that ends on a quake disc, label or card does nothing; opening
  the USGS page or clearing the selection needs a clean click.
- A click on the map under another layer's card opens no Street Level
  ground image.
- A CCTV card that is going away is still not the scene under it.
- Docs and changelog describe the new rule.
2026-11-18 18:23:41 -08:00

494 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { hexColor } from '../../render/color.js';
import {
PERIMETER_OVERLAY_SOURCE_ID,
perimeterAnchorDegrees,
buildIncidentCard,
containmentAccent,
} from './cards.js';
import {
findInciwebLink,
inciwebNodeId,
isCurrentPublication,
} from './inciweb.js';
import { msg, t } from '../../i18n/index.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
export { normalizeFirePerimeterSnapshot } from './records.js';
export { createWfigsPerimeterSource } from './source.js';
export * from './cards.js';
export * from './inciweb.js';
/**
* Fill/line colour for a perimeter by containment progress (same ramp as the
* card accent), as a renderer colour `[r, g, b, a]`.
*/
export function containmentColor(containedPct) {
return hexColor(containmentAccent(containedPct));
}
const withAlpha = ([r, g, b], alpha) => [r, g, b, alpha];
const ringDegrees = (ring) => ring.map(([lon, lat]) => ({ lon, lat }));
/**
* The draw sets the perimeters are drawn in start with this; each layer has
* its own (`fire-perimeters:1:fills`, …), so several can share a renderer.
* Picks name them as `Hit.set`.
*/
export const PERIMETER_SET_PREFIX = 'fire-perimeters';
let instances = 0;
const PICK_PREFIX = 'fire-perimeter:';
const CARD_HOST_OPTIONS = Object.freeze({
cohortLimit: 1,
collisionCapacity: 1,
moving: false,
});
// The InciWeb catalog changes on the order of days; refreshing it on the
// 5-minute perimeter cadence would hammer a public .gov endpoint for ~200 KB
// of near-identical bytes.
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.
*/
export function createFirePerimetersLayer({
source,
overlayHost = null,
inputFor = defaultInputFor,
picking = null,
inciwebSource = null,
inciwebPublications = null,
openExternal = null,
} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Fire perimeters require a snapshot source');
let _viewer = null;
let _request = null;
let _linkRequest = null;
let _snapshotSignature = null;
let _fills = null;
let _lines = null;
let _setIds = new Set();
let _count = 0;
let _lastUpdate = null;
// The proxy's last snapshot, served while WFIGS is unreachable.
let _stale = false;
let _lastError = null;
let _enabled = false;
let _clickSubscription = null;
let _selectedId = null;
let _selectedLink = null;
let _selectedCardId = null;
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();
function abortLinkVerification() {
_linkRequest?.controller.abort();
_linkRequest = null;
}
const canSelect = () => overlayHost && inputFor && picking;
/**
* Refresh the InciWeb catalog off the render path: a hanging or failed
* fetch only costs the link line, never the perimeter refresh — the
* catalog is consumed solely by the selected card.
*/
function refreshInciwebIndex(signal) {
if (!inciwebSource || _indexFetchInFlight) return;
if (Date.now() - _indexFetchedAt < INCIWEB_INDEX_TTL_MS) return;
_indexFetchInFlight = true;
inciwebSource
.getIndex({ signal })
.then((rows) => {
if (signal.aborted || !_enabled || !Array.isArray(rows)) return;
_inciwebIndex = rows;
_indexFetchedAt = Date.now();
if (_selectedId) publishSelectedCard();
})
.catch(() => {
// Catalog unavailable — cards stay linkless until the next attempt.
})
.finally(() => {
_indexFetchInFlight = false;
});
}
/**
* Verify that a matched publication describes the current incident, not
* an archived same-name fire — the catalog is all-time. Async: the card
* republishes with the link once (and only if) the check passes.
*/
function verifyLink(link, row) {
const id = inciwebNodeId(link);
if (!id || !inciwebPublications || _linkRequest?.link === link) return;
abortLinkVerification();
const request = { link, controller: new AbortController() };
_linkRequest = request;
const { signal } = request.controller;
inciwebPublications
.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();
})
.catch(() => {
// Fail closed without caching: no link now, retry on reselection.
})
.finally(() => {
if (_linkRequest === request) _linkRequest = null;
});
}
function publishSelectedCard() {
if (!canSelect()) return;
const row = _selectedId ? _rowById.get(_selectedId) : null;
if (!row) {
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
overlayHost.setEntries(
PERIMETER_OVERLAY_SOURCE_ID,
[],
CARD_HOST_OPTIONS,
);
return;
}
const candidate = findInciwebLink(_inciwebIndex, row);
if (candidate && !_linkVerdicts.has(candidate)) verifyLink(candidate, row);
_selectedLink =
candidate && _linkVerdicts.get(candidate) === true ? candidate : null;
const card = {
...buildIncidentCard(row, Date.now(), { link: _selectedLink }),
position: fromDegrees(row.anchor.lon, row.anchor.lat),
};
if (!openExternal) card.interactive = false;
if (_selectedLink && openExternal) {
const link = _selectedLink;
// Keyboard/assistive activation mirrors the pointer click-through.
card.activate = () => {
openExternal(link);
return true;
};
}
_selectedCardId = card.id;
overlayHost.setEntries(
PERIMETER_OVERLAY_SOURCE_ID,
[card],
CARD_HOST_OPTIONS,
);
}
/**
* The incident a click's draw hit (`Hit`, query.d.ts) belongs to: an item
* 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;
}
function installClickHandler() {
if (!canSelect() || _clickSubscription || !_viewer) return;
// Deliberately NOT registered in the pick-ownership registry: sibling
// layers yield to owned picks before their own overlay-card hit-tests,
// so claiming these large ground polygons would make FIRMS/vessel/CCTV
// cards inert anywhere over a perimeter. Unowned, our picks read as
// "empty space" to siblings — the pre-existing behavior for the globe.
_clickSubscription = inputFor(_viewer).onClick((event) => {
// A click on the incident card itself opens its InciWeb page (when the
// incident has one) and never disturbs the selection.
// The card or label painted on top takes the click, read once per
// click so every layer agrees: this area's shapes are background to
// another layer's card or label painted over them.
const cardHit = picking.clickCard?.(event) ?? null;
if (cardHit) {
if (
cardHit.sourceId === PERIMETER_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId &&
_selectedLink &&
openExternal
)
openExternal(_selectedLink);
return;
}
const picked = event.topHit;
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
if (incidentId) {
abortLinkVerification();
_selectedId = incidentId;
publishSelectedCard();
return;
}
// A pick that belongs to a sibling layer (e.g. an aircraft) is not
// "empty space" — leave the selection alone and let that layer handle it.
if (picked) {
const pickId = picking.resolvePickId(picked);
if (pickId && picking.isOwnedByOtherLayer(layer.id, pickId)) return;
}
if (_selectedId) {
abortLinkVerification();
_selectedId = null;
publishSelectedCard();
}
});
}
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
}
function clearSelection() {
abortLinkVerification();
_selectedId = null;
_selectedLink = null;
_selectedCardId = null;
if (overlayHost) {
overlayHost.clearSource(PERIMETER_OVERLAY_SOURCE_ID);
overlayHost.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, false);
}
}
const layer = {
id: 'fire-perimeters',
name: 'Fire Perimeters',
icon: '🔥',
source: 'NIFC WFIGS',
updateInterval: 300000,
init(viewer) {
if (_viewer)
throw new Error('Fire perimeter layer is already initialized');
const draw = drawOf(viewer);
const prefix = `${PERIMETER_SET_PREFIX}:${++instances}`;
_fills = draw.shapes({
id: `${prefix}:fills`,
clampTo: 'both',
show: false,
});
_lines = draw.lines({
id: `${prefix}:lines`,
clampTo: 'both',
show: false,
});
_setIds = new Set([_fills.id, _lines.id]);
_viewer = viewer;
_count = 0;
_lastUpdate = null;
_lastError = null;
_stale = false;
_enabled = false;
console.log('[Data:FirePerimeters] Initialized');
},
enable() {
_enabled = true;
if (_fills) _fills.show = _lines.show = true;
overlayHost?.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, true);
installClickHandler();
},
disable() {
_request?.abort();
_request = null;
_enabled = false;
if (_fills) _fills.show = _lines.show = false;
removeClickHandler();
clearSelection();
},
async update() {
if (!_enabled || !_fills) return false;
_request?.abort();
const request = new AbortController();
_request = request;
refreshInciwebIndex(request.signal);
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 }) };
if (request.signal.aborted || _request !== request || !_enabled)
return false;
const { rows } = snapshot;
_stale = snapshot.stale === true;
// A stale snapshot is as old as its fetch, not this poll.
const updatedAt =
_stale && Number.isFinite(snapshot.fetchedAt)
? snapshot.fetchedAt
: Date.now();
// 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)),
);
if (signature === _snapshotSignature) {
if (_selectedId) publishSelectedCard();
_lastUpdate = updatedAt;
_lastError = null;
return true;
}
abortLinkVerification();
const nextFills = [];
const nextLines = [];
_rowById.clear();
for (const row of rows) {
const color = containmentColor(row.containedPct);
for (const [index, rings] of row.polygons.entries()) {
const id = `${PICK_PREFIX}${row.stableId}:${index}`;
// Each exterior keeps its own holes.
nextFills.push({
id,
geometry: { kind: 'polygon', rings: rings.map(ringDegrees) },
fill: withAlpha(color, 0.25),
height: 'clampGround',
});
// The fire line: the exterior ring draped on the ground (lines
// take ECEF, draw.d.ts `LineItem`).
nextLines.push({
id,
positions: rings[0].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
style: { kind: 'solid', color: withAlpha(color, 0.9) },
});
}
// Keep a geometry-free projection: the coordinate arrays would
// otherwise be retained for the layer's lifetime while only the
// anchor is ever read again.
const { polygons, ...facts } = row;
_rowById.set(row.stableId, {
...facts,
anchor: perimeterAnchorDegrees(polygons),
});
}
_fills.set(nextFills);
_lines.set(nextLines);
_snapshotSignature = signature;
// Refresh (or drop) the selected incident's card against the new feed.
if (_selectedId) publishSelectedCard();
_count = rows.length;
_lastUpdate = updatedAt;
_lastError = null;
console.log(
`[Data:FirePerimeters] Updated: ${_count} incidents, ${nextFills.length} polygons`,
);
return true;
} catch (e) {
if (request.signal.aborted || _request !== request || !_enabled)
return false;
console.warn('[Data:FirePerimeters] Fetch error:', e);
_lastError = e?.message || msg('Perimeter source unavailable');
// A failure now outranks the stale snapshot still drawn.
_stale = false;
return false;
} finally {
if (_request === request) _request = null;
}
},
destroy() {
_request?.abort();
_request = null;
removeClickHandler();
clearSelection();
_rowById.clear();
_snapshotSignature = null;
_inciwebIndex = [];
_indexFetchedAt = 0;
_linkVerdicts.clear();
_viewer = null;
_enabled = false;
_fills?.dispose();
_lines?.dispose();
_fills = _lines = null;
_setIds = new Set();
_count = 0;
_lastUpdate = null;
_lastError = null;
_stale = false;
},
/** Snapshot incident facts (with card-anchor coordinates) for the analyst query engine. */
getAnalystRecords(maxCount = 2000) {
if (!_fills || !_fills.show) return [];
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 2000;
const result = [];
for (const row of _rowById.values()) {
if (result.length >= limit) break;
const { anchor, stableId, ...facts } = row;
result.push({
id: stableId,
...facts,
lat: anchor.lat,
lon: anchor.lon,
});
}
return result;
},
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) },
];
return {
chips: [],
legend: bands.map((band, index) => ({
...band,
count: [..._rowById.values()].filter(
(row) => containmentAccent(row.containedPct) === band.color,
).length,
...(index === 0
? {
blurb: t(
'Colour shows reported containment. Perimeters are simplified to about 100 m.',
),
}
: {}),
})),
};
},
getStats() {
return {
count: _count,
lastUpdate: _lastUpdate,
error: _lastError,
stale: _stale,
};
},
};
return layer;
}