fix(cyclones): reconcile explicit shared selection with current main

Carry reviewer-verified stale A-to-B record eviction, explicit selection
and refresh semantics over latest i18n/cyclone source ownership.
This commit is contained in:
Kevin Rajan committed 2026-10-17 03:31:28 -05:00
commit abaaf0c254
1066 files changed
+148075 -8596

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCyclonesLayer } from './index.js';
import { setLocale, t } from '../../i18n/index.js';
// The exact string the server sends (COVERAGE in server/providers/cyclones.js).
const SERVER_COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
const time = '2026-09-16T03:00:00.000Z';
const storm = {
id: 'ep152026',
name: 'Fifteen-E',
classification: 'PTC',
basin: 'EP',
position: { longitude: -125.8, latitude: 15.5 },
positionAt: time,
issuedAt: time,
advisoryNumber: '10',
windKt: 25,
pressureHpa: 1006,
geometryStatus: 'pending',
geometryAdvisoryNumber: null,
forecastPoints: [],
track: null,
cone: null,
advisoryUrl: 'https://www.nhc.noaa.gov/text/MIATCMEP5.shtml',
};
const snapshot = (storms, extra = {}) => ({
schemaVersion: 1,
storms,
unavailable: false,
stale: false,
fetchedAt: Date.parse(time),
coverage: SERVER_COVERAGE,
reason: null,
...extra,
});
function harness(feed) {
const rendering = {
async setSnapshot() {
return true;
},
setSelection() {},
getFocusSphere: () => ({ radius: 500000 }),
clear() {},
destroy() {},
getDiagnostics: () => ({ entities: 0, timerActive: false }),
};
const layer = createCyclonesLayer({
feed,
createRendering: () => rendering,
matchMedia: () => ({ matches: false }),
openLink: () => {},
});
layer.init({ camera: { flyToBoundingSphere() {} } });
layer.attachShellServices({ runNavigation: (fn) => fn() });
return layer;
}
const translated = () => t(SERVER_COVERAGE);
test('es: server snapshot without storms -> coverage line in Spanish', async () => {
setLocale('es');
try {
assert.notEqual(translated(), SERVER_COVERAGE, 'es.json has a translation');
const layer = harness({ getSnapshot: async () => snapshot([]) });
layer.enable();
await layer.update();
const info = layer.getRowControls().info;
assert.ok(
info.endsWith(translated()),
`expected Spanish coverage, got:\n${info}`,
);
layer.destroy();
} finally {
setLocale('en');
}
});
test('es: server snapshot with a storm -> coverage line in Spanish', async () => {
setLocale('es');
try {
const layer = harness({ getSnapshot: async () => snapshot([storm]) });
layer.enable();
await layer.update();
const info = layer.getRowControls().info;
assert.ok(
info.endsWith(translated()),
`expected Spanish coverage, got:\n${info}`,
);
layer.destroy();
} finally {
setLocale('en');
}
});
test('es: unavailable without reason -> fallback status not the English literal', async () => {
setLocale('es');
try {
const layer = harness({
getSnapshot: async () =>
snapshot([], { unavailable: true, reason: null }),
});
layer.enable();
await layer.update();
const status = layer.getRowControls().summary.status;
assert.notEqual(
status,
'Cyclone advisories unavailable',
`fallback shown in English: ${status}`,
);
layer.destroy();
} finally {
setLocale('en');
}
});
test('en: coverage and fallback status read as before', async () => {
const layer = harness({ getSnapshot: async () => snapshot([]) });
layer.enable();
await layer.update();
assert.ok(layer.getRowControls().info.endsWith(SERVER_COVERAGE));
layer.destroy();
const down = harness({
getSnapshot: async () => snapshot([], { unavailable: true, reason: null }),
});
down.enable();
await down.update();
assert.equal(
down.getRowControls().summary.status,
'Cyclone advisories unavailable',
);
down.destroy();
});
+127 -40
View File
@@ -14,23 +14,47 @@ import {
CYCLONE_OVERLAY_SOURCE_ID,
cycloneStormIdFromEntryId,
} from './labels.js';
import {
formatUtcDayMonth,
t,
tn,
msg,
translateKnown,
} from '../../i18n/index.js';
import { formatQuantity } from '../../ui/unitLabels.js';
// "10-12 15:00 UTC" never breaks across lines: no-break spaces, and a word
// joiner after the hyphen (JetBrains Mono has no U+2011 non-breaking hyphen).
const utc = (value) =>
value ? `${value.slice(5, 16).replace('T', ' ')} UTC` : 'Unavailable';
const COVERAGE =
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.';
value
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${value.slice(11, 16)}\u00a0UTC`
: t('Unavailable');
const COVERAGE = msg(
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
);
// The server sends the same English coverage (server/providers/cyclones.js);
// data stays English and is translated here, where it is shown.
const coverageText = (coverage) =>
!coverage || coverage === COVERAGE ? t(COVERAGE) : translateKnown(coverage);
const ADVISORIES_UNAVAILABLE = msg('Cyclone advisories unavailable');
// Reason the server gives with an unavailable snapshot, translated when shown.
const SERVER_REASONS = new Set([msg('Cyclone data unavailable')]);
const errorText = (error) =>
error && (SERVER_REASONS.has(error) ? t(error) : translateKnown(error));
const CLASSIFICATION_NAMES = Object.freeze({
PTC: 'Potential tropical cyclone',
HU: 'Hurricane',
TS: 'Tropical storm',
TD: 'Tropical depression',
SS: 'Subtropical storm',
SD: 'Subtropical depression',
PTC: msg('Potential tropical cyclone'),
HU: msg('Hurricane'),
TS: msg('Tropical storm'),
TD: msg('Tropical depression'),
SS: msg('Subtropical storm'),
SD: msg('Subtropical depression'),
});
const classificationName = (code) =>
Object.hasOwn(CLASSIFICATION_NAMES, code) ? CLASSIFICATION_NAMES[code] : code;
Object.hasOwn(CLASSIFICATION_NAMES, code)
? t(CLASSIFICATION_NAMES[code])
: code;
const number = (value, unit) =>
value === null ? 'Unavailable' : `${value} ${unit}`;
value === null ? t('Unavailable') : formatQuantity(value, unit);
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
export function createCyclonesLayer({
@@ -65,7 +89,6 @@ export function createCyclonesLayer({
const notify = () => listener?.();
const selected = () =>
snapshot?.storms.find((storm) => storm.id === selectedId) || null;
function clearSelectedContext() {
context?.removeEntityContextsForLayer?.('weather-cyclones');
selectedContextStormId = null;
@@ -278,7 +301,7 @@ export function createCyclonesLayer({
selectedId = null;
++navigationGeneration;
clearSelectedContext();
error = next.reason || 'Cyclone advisories unavailable';
error = next.reason || ADVISORIES_UNAVAILABLE;
return true;
}
const applied = await rendering.setSnapshot(next, {
@@ -307,7 +330,7 @@ export function createCyclonesLayer({
return true;
} catch (cause) {
if (controller.signal.aborted || request !== controller) return false;
error = cause?.message || 'Cyclone advisories unavailable';
error = cause?.message || ADVISORIES_UNAVAILABLE;
// Failed acquisition has no bounded last-good age guarantee at this layer.
rendering?.clear();
snapshot = null;
@@ -372,41 +395,68 @@ export function createCyclonesLayer({
const geometry =
storm &&
(coherentCycloneGeometry(storm)
? 'Track and cone match this advisory'
? t('Track and cone match this advisory')
: storm.geometryStatus === 'pending'
? `Track/cone awaiting advisory ${storm.advisoryNumber}`
: 'Track/cone unavailable');
? t('Track/cone awaiting advisory {number}', {
number: storm.advisoryNumber,
})
: t('Track/cone unavailable'));
const status =
error ||
errorText(error) ||
(snapshot?.stale
? 'Cached advisory · stale source'
? t('Cached advisory · stale source')
: loading
? 'Loading advisories…'
? t('Loading advisories…')
: storm && !coherentCycloneGeometry(storm)
? geometry
: null);
const stormCount = snapshot?.storms.length || 0;
const activeStorms = tn(
stormCount,
'{count} active storm',
'{count} active storms',
);
const position = storm
? t('Position as of {time}', { time: utc(storm.positionAt) })
: '';
const intensity = storm
? t('Maximum sustained wind: {wind} · Pressure: {pressure}', {
wind: number(storm.windKt, 'kt'),
pressure: number(storm.pressureHpa, 'hPa'),
})
: '';
const detail = storm
? `${storm.name} · ${classificationName(storm.classification)} · Advisory ${storm.advisoryNumber} · issued ${utc(storm.issuedAt)}`
? t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
classification: classificationName(storm.classification),
number: storm.advisoryNumber,
time: utc(storm.issuedAt),
})
: empty
? 'No active NHC/CPHC systems'
: snapshot?.storms.length
? `${snapshot.storms.length} active storm${snapshot.storms.length === 1 ? '' : 's'}`
? t('No active NHC/CPHC systems')
: stormCount
? activeStorms
: loading
? 'Loading advisories…'
: 'Advisories unavailable';
? t('Loading advisories…')
: t('Advisories unavailable');
const controls = {
readout: true,
summary: {
label: 'Cyclones · NHC / CPHC',
coverage: 'Atlantic · E/C Pacific',
compact: snapshot?.storms.length
? `${snapshot.storms.length} active storm${snapshot.storms.length === 1 ? '' : 's'}${storm ? ` · ${storm.name} selected` : ''}`
label: t('Cyclones · NHC / CPHC'),
coverage: t('Atlantic · E/C Pacific'),
compact: stormCount
? storm
? t('{storms} · {name} selected', {
storms: activeStorms,
name: storm.name,
})
: activeStorms
: detail,
actions: storm?.advisoryUrl
? [
{
id: 'advisory',
label: 'Official advisory ↗',
label: t('Official advisory ↗'),
href: storm.advisoryUrl,
},
]
@@ -416,12 +466,12 @@ export function createCyclonesLayer({
? [
{
id: 'position',
text: `Position as of ${utc(storm.positionAt)}`,
text: position,
muted: true,
},
{
id: 'intensity',
text: `Maximum sustained wind: ${number(storm.windKt, 'kt')} · Pressure: ${number(storm.pressureHpa, 'hPa')}`,
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
]
@@ -431,34 +481,71 @@ export function createCyclonesLayer({
units: 'kt',
},
list: {
ariaLabel: 'Active NHC and CPHC cyclone advisories',
ariaLabel: t('Active NHC and CPHC cyclone advisories'),
items: (snapshot?.storms || []).map((item, index) => ({
id: item.id,
ordinal: index + 1,
lead: item.basin,
text: `${item.name} · ${classificationName(item.classification)} · ${item.windKt === null ? 'Wind unavailable' : `${item.windKt} kt`}`,
text: `${item.name} · ${classificationName(item.classification)} · ${item.windKt === null ? t('Wind unavailable') : formatQuantity(item.windKt, 'kt')}`,
active: item.id === selectedId,
params: { stormId: item.id, focus: true },
})),
},
chips: [],
legendCategorical: true,
legend: storm
? [
{ label: 'Advisory center / forecast track', color: '#7fe6ed' },
{ label: 'Center-track uncertainty cone', color: '#7fe6ed44' },
{
label: t('Advisory center / forecast track'),
color: '#7fe6ed',
},
{
label: t('Center-track uncertainty cone'),
color: '#7fe6ed44',
},
]
: [],
info: storm
? `${detail}\nPosition as of ${utc(storm.positionAt)}\nMaximum sustained wind: ${number(storm.windKt, 'kt')} · Pressure: ${number(storm.pressureHpa, 'hPa')}\n${geometry}${status && status !== geometry ? '\n' + status : ''}\n${snapshot.coverage}`
: `${detail}${status ? '\n' + status : ''}\n${snapshot?.coverage || COVERAGE}`,
infoTitle:
? `${detail}\n${position}\n${intensity}\n${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
: `${detail}${status ? '\n' + status : ''}\n${coverageText(snapshot?.coverage)}`,
infoTitle: t(
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.',
),
};
return controls;
},
setRowControlsListener(value) {
listener = typeof value === 'function' ? value : null;
},
/**
* Snapshot loaded active storms as plain JSON-safe records for the analyst
* query engine. On demand only (once per spoken query); [] while the
* layer is off.
* @param {number} [maxCount=Infinity] Most records to return.
* @returns {Array<Object>} {id, name, classification, basin, lat, lon, windKt, pressureHpa}.
*/
getAnalystRecords(maxCount = Infinity) {
if (!enabled || destroyed) return [];
const num = (v) => (Number.isFinite(v) ? v : null);
const result = [];
for (const storm of snapshot?.storms || []) {
if (result.length >= maxCount) break;
const lat = storm.position?.latitude;
const lon = storm.position?.longitude;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
result.push({
id: storm.name || storm.id,
name: storm.name || null,
classification: storm.classification || null,
basin: storm.basin || null,
lat,
lon,
windKt: num(storm.windKt),
pressureHpa: num(storm.pressureHpa),
});
}
return result;
},
getStats() {
const storm = selected();
return {
+3 -1
View File
@@ -645,7 +645,9 @@ test('advisory selection uses accessible row descriptors and shared camera hando
1,
);
assert.equal(controls.summary.status, 'Track/cone awaiting advisory 10');
assert.match(controls.info, /09-16 03:00 UTC/);
// No line break inside the date: a word joiner holds the hyphen.
assert.match(controls.info, /issued 09-\u206016\u00a003:00\u00a0UTC/);
assert.match(controls.info, /: 25\u00a0kt · .*: 1006\u00a0hPa/);
assert.match(controls.infoTitle, /not storm size/);
assert.match(controls.infoTitle, /follows the surface/);
assert.equal(controls.list.items[1].params.focus, true);