Merge main (e4708a81, #1745) into the renderer branch

Main brings the reviewed one-time-control and timeline-mark changes. They
keep this branch's renderer work: earthquakes draw through the draw port and
register their strong quakes as marks; the weather clock keeps `follows` beside
`world`; the weather layer measures ages and delays from the timeline time;
the Visual panel keeps its sky and weather groups under Effects. Tests that
moved time through the weather clock now move it on the world clock.
This commit is contained in:
Sameh Khamis committed 2026-11-14 22:08:39 -08:00
commit 0ecbfbecd0
123 files changed
+5917 -1471

No files matched your search

+27 -2
View File
@@ -1,5 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
@@ -9,6 +10,7 @@ import {
createEarthquakeOverlayEntry,
selectEarthquakeOverlayCohort,
mapAnalystRecord,
earthquakeCoverage,
} from './model.js';
export * from './model.js';
export { createUsgsEarthquakeSource } from './source.js';
@@ -39,12 +41,25 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
let _viewer = null;
let _request = null;
let _discs = null;
// What the discs were drawn from, so analyst reads come from the app, not the drawing.
let _events = [];
let _count = 0;
let _lastUpdate = null;
let _lastError = null;
let _enabled = false;
// What the discs were drawn from, so analyst reads come from the layer, not the
// drawing, and the timeline reads its marks ({ mag, time, place, usgsId }).
let _events = [];
let _uncover = null;
// The marks last told to the clock, so a refresh with the same strong
// quakes does not tell it again.
let _marksKey = null;
const coverage = () => (_enabled ? earthquakeCoverage(_events) : null);
const coverageChanged = () => {
const covered = coverage();
const key = covered ? JSON.stringify(covered.marks) : null;
if (key === _marksKey) return;
_marksKey = key;
worldClock.coverageChanged();
};
const layer = {
id: 'earthquakes',
@@ -60,6 +75,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
show: false,
});
_viewer = viewer;
// While on, the strong quakes are marks on the world clock's timeline.
// Registered once; off, the layer has no time to show.
_marksKey = null;
_uncover = worldClock.register({ id: 'earthquakes', coverage });
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -74,6 +93,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
// layer has no per-frame animator to keep the render loop alive for.
if (_discs) _discs.show = true;
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
coverageChanged();
},
disable(viewer) {
@@ -83,6 +103,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
if (_discs) _discs.show = false;
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
coverageChanged();
},
async update(viewer) {
@@ -146,6 +167,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_discs.set(nextDiscs);
_events = nextEvents;
coverageChanged();
if (_enabled) {
overlayHost.setEntries(
EARTHQUAKE_OVERLAY_SOURCE_ID,
@@ -184,6 +206,9 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_discs?.dispose();
_discs = null;
_events = [];
_uncover?.();
_uncover = null;
_marksKey = null;
_count = 0;
_lastUpdate = null;
_lastError = null;
+59 -1
View File
@@ -14,6 +14,64 @@ const DEEP = Object.freeze({ rgba: [1, 1, 0, 1], css: 'rgb(255,255,0)' });
const depthBand = (depthKm) =>
depthKm < 70 ? SHALLOW : depthKm < 300 ? INTERMEDIATE : DEEP;
/**
* The smallest magnitude the timeline marks. Most quakes are small shakes;
* M6 and up come about once every two days worldwide, so each is an event
* worth stepping to. The map still draws every quake.
*/
export const EARTHQUAKE_MARK_MAGNITUDE = 6;
/** The longest place a timeline mark's label carries, ellipsis and all. */
const MARK_PLACE_LENGTH = 40;
/** A magnitude as the map's labels show it: `M6.4`. */
export const earthquakeMagnitudeTitle = (magnitude) =>
`M${Number(magnitude).toFixed(1)}`;
/**
* A strong quake's timeline label: its magnitude and, where the feed names
* one, its place, cut short (`M6.4 · 113 km SSE of Lata, Solomon Islands`).
* @param {{mag: number, place?: string | null}} event
* @returns {string}
*/
export function earthquakeMarkLabel({ mag, place }) {
const title = earthquakeMagnitudeTitle(mag);
const where =
typeof place === 'string' ? place.replace(/\s+/g, ' ').trim() : '';
if (!where) return title;
const short =
where.length > MARK_PLACE_LENGTH
? `${where.slice(0, MARK_PLACE_LENGTH - 1).trimEnd()}…`
: where;
return `${title} · ${short}`;
}
/**
* The time a world clock's timeline can show for `events` (`{mag, time,
* place?, usgsId?}`, time in ms): the span of the quakes of
* EARTHQUAKE_MARK_MAGNITUDE and up, each one a mark labelled with its
* magnitude and place, or null with none, so the layer never stretches the
* timeline past what its feed covers.
* @returns {{start: number, end: number, marks: Array<{time: number, label: string, id?: string, kind: string}>} | null}
*/
export function earthquakeCoverage(events) {
const marks = events
.filter(
({ mag, time }) =>
mag >= EARTHQUAKE_MARK_MAGNITUDE && Number.isFinite(time),
)
.map((event) => ({
time: event.time,
label: earthquakeMarkLabel(event),
...(event.usgsId ? { id: String(event.usgsId) } : {}),
kind: 'earthquake',
}))
.sort((a, b) => a.time - b.time);
return marks.length
? { start: marks[0].time, end: marks.at(-1).time, marks }
: null;
}
/**
* Color by depth, as a renderer colour `[r, g, b, a]` (0..1):
* - Shallow (<70km): Red
@@ -50,7 +108,7 @@ export function createEarthquakeOverlayEntry({
id: String(id),
position,
variant: 'label',
title: `M${mag.toFixed(1)}`,
title: earthquakeMagnitudeTitle(mag),
accent,
priority: Math.round(mag * 1000),
collisionGroup: 'ambient-label',
+71
View File
@@ -3,6 +3,8 @@ import test from 'node:test';
import { createEarthquakesLayer } from './index.js';
import { createUsgsEarthquakeSource } from './source.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { EARTHQUAKE_MARK_MAGNITUDE, earthquakeMarkLabel } from './model.js';
import { worldClock } from '../../time/worldClock.js';
function harness(source) {
const events = [];
const viewer = {};
@@ -168,3 +170,72 @@ test('a viewer with nothing to draw with is refused at init, and init can be ret
layer.destroy();
unbind();
});
test('the timeline marks only strong quakes, while the layer is on', async () => {
assert.equal(EARTHQUAKE_MARK_MAGNITUDE, 6);
const rows = [
{ ...row, stableId: 'small', mag: 4.5, time: 1_000 },
{ ...row, stableId: 'strong', usgsId: 'us-strong', mag: 6, time: 5_000 },
{
...row,
stableId: 'great',
usgsId: 'us-great',
mag: 7.2,
place: ' 113 km SSE of Lata, Solomon Islands region of the Pacific ',
time: 3_000,
},
{ ...row, stableId: 'untimed', mag: 6.5, time: null },
];
let snapshot = rows;
const h = harness({ getSnapshot: async () => snapshot });
assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show');
let changes = 0;
const unsubscribe = worldClock.subscribe(() => changes++);
await h.layer.update(h.viewer);
// Every quake is drawn; only M6 and up are marks, spanning their own time.
assert.equal(h.draw.find('earthquakes:').items.size, 4);
// Each labelled with its magnitude and, cut short, its place.
assert.deepEqual(worldClock.coverage(), {
start: 3_000,
end: 5_000,
marks: [3_000, 5_000],
markDetails: [
{
time: 3_000,
label: 'M7.2 · 113 km SSE of Lata, Solomon Islands reg…',
id: 'us-great',
kind: 'earthquake',
},
{
time: 5_000,
label: 'M6.0 · Fixture',
id: 'us-strong',
kind: 'earthquake',
},
],
});
const told = changes;
await h.layer.update(h.viewer);
assert.equal(changes, told, 'the same strong quakes are not told again');
snapshot = rows.slice(0, 1);
await h.layer.update(h.viewer);
assert.equal(worldClock.coverage(), null, 'small shakes alone cover no time');
snapshot = rows;
await h.layer.update(h.viewer);
h.layer.disable(h.viewer);
assert.equal(worldClock.coverage(), null, 'off, no time to show');
h.layer.enable(h.viewer);
assert.deepEqual(worldClock.coverage().marks, [3_000, 5_000]);
h.layer.destroy();
assert.equal(worldClock.coverage(), null);
unsubscribe();
});
test('a strong quake with no place is labelled with its magnitude alone', () => {
assert.equal(earthquakeMarkLabel({ mag: 6.44, place: null }), 'M6.4');
assert.equal(earthquakeMarkLabel({ mag: 6, place: ' ' }), 'M6.0');
assert.equal(
earthquakeMarkLabel({ mag: 8.1, place: 'Off the coast' }),
'M8.1 · Off the coast',
);
});
+21 -6
View File
@@ -147,6 +147,9 @@ function restoreCameraView(viewer, view, landedView) {
camera.setView(view);
}
/** The longest name a timeline mark carries, as in the mission index. */
const MARK_LABEL_LENGTH = 27;
export function createLifecycle({
state: layerState,
services,
@@ -156,18 +159,30 @@ export function createLifecycle({
const { holdContinuousRender, releaseContinuousRender } = services.render;
let hover = null;
// While on, the launches loaded span the time from the first to the last,
// each one a mark. Registered once; off, the layer has no time to show, and
// each step tells the clock once it has settled.
// each one a mark labelled with its mission's name (the launch's where it
// has none), cut short and in capitals as the mission index shows names.
// Registered once; off, the layer has no time to show, and each step tells
// the clock once it has settled.
worldClock.register({
id: 'rocket-launches',
coverage: () => {
if (!layerState._enabled) return null;
const marks = layerState._launches
.map((launch) => Date.parse(launch.launchTime))
.filter(Number.isFinite)
.sort((a, b) => a - b);
.map((launch) => ({
time: Date.parse(launch.launchTime),
label: parts.overlays
.shortMissionLabel(
launch.missionName || launch.name,
MARK_LABEL_LENGTH,
)
.toUpperCase(),
...(launch.id != null ? { id: String(launch.id) } : {}),
kind: 'launch',
}))
.filter(({ time }) => Number.isFinite(time))
.sort((a, b) => a.time - b.time);
if (!marks.length) return null;
return { start: marks[0], end: marks.at(-1), marks };
return { start: marks[0].time, end: marks.at(-1).time, marks };
},
});
+45 -155
View File
@@ -59,34 +59,36 @@ export const PLAY_WAIT_MS = 8_000;
// costs play nothing.
let clocks = 0;
// How many weather clocks follow each world clock.
const followers = new WeakMap();
/**
* Transient observed time. Products must honor the signal before installing a
* frame. Its time is the world clock's: latest while the world is live,
* history at the world's time otherwise. Replay steps the observed frames and
* moves the world clock as it goes, as the world clock's driver.
* history at the world's time otherwise. It never moves the world clock
* itself; the world's own controls (its timeline) move time, and while the
* world plays it stops at each next frame until that frame loads.
*
* `shared` (the default) is a clock several layers share, such as the
* catalog's: the last shared clock destroyed leaves the world live. A clock
* one layer keeps for itself (`shared: false`) leaves the world's time where
* it is.
*/
export function createWeatherClock({
now = Date.now,
setTimeout = globalThis.setTimeout,
clearTimeout = globalThis.clearTimeout,
world = createWorldClock({ now }),
shared = true,
} = {}) {
const registry = new Map();
const listeners = new Set();
let mode = 'latest';
let target = null;
let playing = false;
// The world time last applied; while this clock moves the world, the
// transition its move started.
// The world time last applied.
let seen = 'latest';
let moving = false;
let moved = null;
const releases = new Map();
// Attached at the end, once the API exists.
let driver = null;
let generation = 0;
let timer = null;
let pending = null;
// This clock's name on the world, for its holds and its gate.
const holdId = `weather:${++clocks}`;
@@ -147,10 +149,9 @@ export function createWeatherClock({
const getState = () => ({
mode,
target,
playing,
// Frames come on one after another: this clock replays them, or the world
// plays on through them, so the next is worth loading ahead.
advancing: playing || worldPlaysOn(),
// Frames come on one after another as the world plays on through them,
// so the next is worth loading ahead.
advancing: worldPlaysOn(),
timeline: getTimeline(),
products: [...registry.values()].map(({ product }) => ({
id: product.id,
@@ -162,60 +163,12 @@ export function createWeatherClock({
const notify = () => {
if (!destroyed) for (const listener of listeners) listener(getState());
};
const cancelTimer = () => {
if (timer !== null) clearTimeout(timer);
timer = null;
};
const canPlay = () => getTimeline().length >= 2;
const stopPlaying = () => {
if (!playing) return;
playing = false;
driver?.driven(false);
};
// Move the world clock; the change comes back through followWorld. Returns
// the transition the move started, if it started one.
const move = (fn) => {
const outer = [moving, moved];
moving = true;
moved = null;
try {
fn();
return moved;
} finally {
[moving, moved] = outer;
}
};
const selections = () =>
[...registry.values()].map(({ product }) => selectedFor(product)).join();
let applied = null;
function schedule() {
cancelTimer();
if (!playing || destroyed || pending) return;
if (!canPlay()) {
stopPlaying();
notify();
return;
}
const owner = generation;
timer = setTimeout(() => {
timer = null;
if (destroyed || !playing || owner !== generation) return;
const timeline = getTimeline();
if (timeline.length < 2) {
api.pause();
return;
}
const next = timeline.find(
(time) => Date.parse(time) > Date.parse(target),
);
void api.setTarget(next ?? timeline[0]);
}, 2000);
}
function transition() {
if (destroyed) return Promise.resolve(false);
cancelTimer();
const owner = ++generation;
if (!canPlay()) stopPlaying();
// A scrub drops what loads and moves on; play goes on as this loads.
applied = selections();
deferred = false;
@@ -235,15 +188,12 @@ export function createWeatherClock({
if (destroyed || owner !== generation) return false;
stopWaiting();
pending = null;
if (!canPlay()) stopPlaying();
notify();
schedule();
// Play held at the next frame for this one goes on to it.
if (deferred) void transition();
return true;
});
pending = result;
if (moving) moved ??= result;
notify();
return result;
}
@@ -254,11 +204,13 @@ export function createWeatherClock({
throw new Error(`Duplicate weather product: ${product.id}`);
const entry = { product, controller: null };
registry.set(product.id, entry);
// The product moves with the world clock, and its frames are time the
// world clock's timeline can show while it is on, suspended or not, so
// the way back to live stays on screen. Both calls notify the world's
// listeners, which may destroy this clock: the release is in place
// first, and anything acquired after a destroy is let go at once.
// The product moves with the world clock, and the span of its frames is
// time the world clock's timeline can show while it is on, suspended or
// not, so the way back to live stays on screen. The frames are not
// marks: they come every few minutes, and the timeline marks only
// events. Both calls notify the world's listeners, which may destroy
// this clock: the release is in place first, and anything acquired
// after a destroy is let go at once.
let unhold = null;
let uncover = null;
const release = () => {
@@ -272,9 +224,12 @@ export function createWeatherClock({
uncover = world.register({
id: product.id,
coverage: () => {
const marks = timesFor(product).map((time) => Date.parse(time));
return marks.length
? { start: marks[0], end: marks.at(-1), marks }
const times = timesFor(product);
return times.length
? {
start: Date.parse(times[0]),
end: Date.parse(times.at(-1)),
}
: null;
},
});
@@ -300,81 +255,17 @@ export function createWeatherClock({
* wind, gives that layer the timeline time rather than the live edge.
*/
follows: (id) => world.follows(id),
setTarget(time) {
if (destroyed) return Promise.resolve(false);
if (!Number.isFinite(Date.parse(time)))
throw new TypeError('Weather target must be a UTC time');
const normalized = new Date(time).toISOString();
if (mode === 'history' && target === normalized)
return pending ?? Promise.resolve(true);
return (
move(() => world.seek(Date.parse(normalized))) ??
pending ??
Promise.resolve(true)
);
},
step(direction) {
if (destroyed || ![-1, 1].includes(direction))
return Promise.resolve(false);
api.pause();
const timeline = getTimeline();
if (!timeline.length) return Promise.resolve(false);
const at = Date.parse(target ?? timeline.at(-1));
const next =
direction < 0
? (timeline.findLast((time) => Date.parse(time) < at) ?? timeline[0])
: (timeline.find((time) => Date.parse(time) > at) ?? timeline.at(-1));
return api.setTarget(next);
},
latest() {
if (destroyed) return Promise.resolve(false);
stopPlaying();
if (mode === 'latest') return transition();
return move(() => world.goLive()) ?? pending ?? Promise.resolve(true);
},
play() {
if (destroyed || playing || !canPlay())
return pending ?? Promise.resolve(false);
playing = true;
if (mode === 'latest') {
const timeline = getTimeline();
const start =
timeline.findLast((time) => Date.parse(time) <= now()) ?? timeline[0];
// Playing and at the first frame in one move of the world.
return (
move(() => driver.driven(true, Date.parse(start))) ??
pending ??
Promise.resolve(true)
);
}
driver.driven(true);
notify();
schedule();
return pending ?? Promise.resolve(true);
},
pause() {
cancelTimer();
if (!playing) {
// The world may be playing on its own; a pause or step here holds it.
if (world.isPlaying()) world.pause();
return;
}
stopPlaying();
notify();
},
togglePlay() {
return playing ? api.pause() : api.play();
},
/**
* The world clock this clock follows. Time moves there, through the same
* seek, play and live the world's timeline uses, never through this clock.
*/
world,
refresh() {
if (destroyed) return Promise.resolve(false);
// New frames, or products added or dropped, and with them the next.
world.coverageChanged();
gated = undefined;
gateNext(world.getState());
if (!canPlay()) {
stopPlaying();
cancelTimer();
}
if (mode === 'history') return transition();
notify();
return Promise.resolve(true);
@@ -386,15 +277,18 @@ export function createWeatherClock({
},
destroy() {
if (destroyed) return;
stopPlaying();
destroyed = true;
++generation;
stopWaiting();
world.gate(holdId, null);
cancelTimer();
unfollowWorld();
// The last weather clock leaves the world live, as a new one expects.
if (driver.detach() === 0) world.goLive();
// The last shared weather clock leaves the world live, as a new one
// expects.
if (shared) {
const left = followers.get(world) - 1;
followers.set(world, left);
if (left === 0) world.goLive();
}
for (const release of releases.values()) release();
releases.clear();
for (const entry of registry.values()) entry.controller?.abort();
@@ -403,9 +297,8 @@ export function createWeatherClock({
pending = null;
},
};
// Follow the world clock. A move of this clock's own always applies; one
// from elsewhere (a host's seek, continuous play) applies only when it
// changes the mode or a product's frame.
// Follow the world clock. A move (a seek, play going on) applies only when
// it changes the mode or a product's frame.
function followWorld(state) {
if (destroyed) return;
gateNext(state);
@@ -426,7 +319,7 @@ export function createWeatherClock({
const modeChanged = nextMode !== mode;
mode = nextMode;
target = nextTarget;
if (!moving && !modeChanged && selections() === applied) {
if (!modeChanged && selections() === applied) {
// Back at the frame that loads, play need not hold for it.
if (deferred) {
deferred = false;
@@ -439,7 +332,7 @@ export function createWeatherClock({
}
// Playing on into the next frame while the one before it loads, the
// world holds here until that one shows.
if (!moving && !modeChanged && pending && playsOn) {
if (!modeChanged && pending && playsOn) {
deferred = true;
startWaiting();
notify();
@@ -462,10 +355,7 @@ export function createWeatherClock({
world.gate(holdId, next);
}
const unfollowWorld = world.subscribe(followWorld);
driver = world.attachDriver({
play: () => (canPlay() ? void api.play() : false),
pause: () => api.pause(),
});
if (shared) followers.set(world, (followers.get(world) ?? 0) + 1);
followWorld(world.getState());
return api;
}
+74 -200
View File
@@ -158,13 +158,16 @@ test('a product’s gap is at least one and a half of its feed’s frame spacing
assert.equal(clock.selectFor('clouds', time(211)), null);
});
test('history applies per-product selections, including null; latest restores unequal newest times', async (t) => {
const { clock } = harness(t);
const at = (minutes) => Date.parse(time(minutes));
test('history applies per-product selections, including null; live restores unequal newest times', async (t) => {
const { clock, world } = harness(t);
const radar = product('radar', [0, 10, 20]);
const satellite = product('satellite', [5, 15]);
const lightning = product('lightning', [15]);
for (const p of [radar, satellite, lightning]) clock.register(p);
await clock.setTarget(time(10));
world.seek(at(10));
await flush();
assert.deepEqual(
[radar.shown, satellite.shown, lightning.shown],
[time(10), time(5), null],
@@ -173,18 +176,19 @@ test('history applies per-product selections, including null; latest restores un
clock.getState().products.map(({ selected }) => selected),
[time(10), time(5), null],
);
await clock.latest();
world.goLive();
await flush();
assert.deepEqual(
[radar.shown, satellite.shown, lightning.shown],
[time(20), time(15), time(15)],
);
assert.equal(clock.getState().mode, 'latest');
assert.equal(clock.getState().target, null);
assert.equal(clock.getState().playing, false);
assert.equal(clock.getState().advancing, false);
});
test('superseded completions cannot commit, notify or schedule a new playback advance', async (t) => {
const { clock, timers } = harness(t);
test('superseded completions cannot commit or notify', async (t) => {
const { clock, world, timers } = harness(t);
const p = product('radar', [0, 10, 20]);
const loads = [];
p.apply = (selected, { signal }) =>
@@ -201,113 +205,44 @@ test('superseded completions cannot commit, notify or schedule a new playback ad
clock.register(p);
let notifications = 0;
clock.subscribe(() => notifications++);
const old = clock.setTarget(time(0));
world.seek(at(0));
await flush();
const current = clock.setTarget(time(10));
world.seek(at(10));
await flush();
assert.equal(loads[0].signal.aborted, true);
loads[1].finish();
assert.equal(await current, true);
await flush();
const count = notifications;
loads[0].finish();
assert.equal(await old, false);
await flush();
assert.equal(notifications, count);
assert.equal(p.shown, time(10));
assert.equal(clock.getState().target, time(10));
assert.equal(timers.size, 0);
});
test('steps use strict union neighbours from arbitrary targets and clamp at endpoints', async (t) => {
const { clock } = harness(t);
clock.register(product('radar', [0, 10, 20]));
clock.register(product('satellite', [5, 15]));
await clock.step(-1);
assert.equal(clock.getState().target, time(15));
await clock.setTarget(time(12));
await clock.step(-1);
assert.equal(clock.getState().target, time(10));
await clock.setTarget(time(12));
await clock.step(1);
assert.equal(clock.getState().target, time(15));
await clock.setTarget(time(0));
await clock.step(-1);
assert.equal(clock.getState().target, time(0));
await clock.setTarget(time(20));
await clock.step(1);
assert.equal(clock.getState().target, time(20));
});
test('playback waits for every product to settle, including rejection, then waits 2000 ms and wraps', async (t) => {
const { clock, tick, timers } = harness(t);
const a = product('radar', [0, 10]);
const b = product('satellite', [5]);
const loads = [];
b.apply = () =>
new Promise((resolve, reject) => loads.push({ resolve, reject }));
clock.register(a);
clock.register(b);
const start = clock.play();
await flush();
assert.equal(clock.getState().target, time(10));
tick(10_000);
assert.equal(timers.size, 0);
assert.equal(a.calls.length, 1);
loads[0].reject(new Error('unavailable'));
await start;
assert.equal(timers.size, 1);
tick(1999);
assert.equal(clock.getState().target, time(10));
tick(1);
await flush();
assert.equal(clock.getState().target, time(0));
assert.equal(timers.size, 0);
tick(10_000);
assert.equal(clock.getState().target, time(0));
loads[1].resolve(true);
await flush();
tick(2000);
await flush();
assert.equal(clock.getState().target, time(5));
clock.pause();
loads[2].resolve(false);
await flush();
assert.equal(timers.size, 0, 'pausing during a load prevents rescheduling');
});
test('pause cancels a pending advance; playback stops with one time or all products suspended', async (t) => {
const { clock, tick, timers } = harness(t);
const p = product('radar', [0, 10]);
clock.register(p);
await clock.play();
await clock.play();
assert.equal(timers.size, 1);
clock.pause();
tick(2000);
assert.equal(clock.getState().target, time(10));
assert.equal(timers.size, 0);
await clock.togglePlay();
p.times = [time(0)];
await clock.refresh();
assert.equal(clock.getState().playing, false);
await clock.play();
assert.equal(clock.getState().playing, false);
p.times = [time(0), time(10)];
await clock.refresh();
await clock.play();
p.suspended = true;
await clock.refresh();
assert.equal(clock.getState().playing, false);
assert.deepEqual(clock.getTimeline(), []);
assert.equal(timers.size, 0);
test('the clock has no time controls of its own; the world clock moves time', (t) => {
const { clock, world } = harness(t);
for (const name of [
'setTarget',
'step',
'latest',
'play',
'pause',
'togglePlay',
])
assert.equal(clock[name], undefined, name);
assert.equal(clock.world, world);
});
test('refresh does not apply in latest; history retains its target as expired frames disappear', async (t) => {
const { clock } = harness(t);
const { clock, world } = harness(t);
const p = product('radar', [0, 10]);
clock.register(p);
await clock.refresh();
assert.equal(p.calls.length, 0);
await clock.setTarget(time(10));
world.seek(at(10));
await flush();
p.times = [time(0), time(20)];
await clock.refresh();
assert.equal(p.shown, time(0));
@@ -318,15 +253,16 @@ test('refresh does not apply in latest; history retains its target as expired fr
});
test('registration joins history; unregister and destroy abort work and release subscriptions/timers', async (t) => {
const { clock, timers, tick } = harness(t);
const { clock, world, timers } = harness(t);
const p = product('radar', [0, 10]);
const unregister = clock.register(p);
await clock.setTarget(time(0));
world.seek(at(0));
await flush();
const b = product('satellite', [0, 5]);
clock.register(b);
await flush();
assert.equal(b.shown, time(0));
await clock.play();
world.seek(at(5));
unregister();
unregister();
await flush();
@@ -337,31 +273,27 @@ test('registration joins history; unregister and destroy abort work and release
);
let notifications = 0;
const off = clock.subscribe(() => notifications++);
clock.pause();
off();
const before = notifications;
await clock.play();
assert.equal(notifications, before);
world.seek(at(0));
await flush();
assert.equal(notifications, 0);
world.seek(at(5));
clock.destroy();
clock.destroy();
tick(2000);
await flush();
assert.equal(timers.size, 0);
assert.equal(b.calls.at(-1).signal.aborted, true);
assert.equal(clock.getState().playing, false);
assert.deepEqual(clock.getTimeline(), []);
assert.equal(await clock.setTarget(time(5)), false);
});
test('the weather time is the world time, both ways', async (t) => {
test('the weather time is the world time', async (t) => {
const { clock, world } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
assert.equal(world.follows('radar'), true);
await clock.setTarget(time(10));
assert.equal(world.isLive(), false);
assert.equal(world.now(), Date.parse(time(10)));
world.seek(Date.parse(time(3)));
world.seek(at(3));
await flush();
assert.equal(clock.getState().mode, 'history');
assert.equal(clock.getState().target, time(3));
assert.equal(radar.shown, time(0));
world.goLive();
@@ -370,30 +302,22 @@ test('the weather time is the world time, both ways', async (t) => {
assert.equal(radar.shown, time(20));
});
test('world play and pause drive the weather replay', async (t) => {
test('world play runs the world on its own at its rate; weather does not drive it', async (t) => {
const { clock, world, tick } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(0)));
world.seek(at(0));
await flush();
world.play();
assert.equal(clock.getState().playing, true);
assert.equal(world.isPlaying(), true);
tick(2000);
world.play({ rate: 60 });
assert.equal(world.getState().stepping, false);
assert.equal(clock.getState().advancing, true);
tick(5_000);
assert.equal(world.now(), at(5), 'five minutes on at a minute a second');
tick(10_000);
await flush();
assert.equal(radar.shown, time(10));
assert.equal(world.now(), Date.parse(time(10)));
assert.equal(world.now(), at(10), 'held at the next frame');
world.pause();
assert.equal(clock.getState().playing, false);
clock.play();
assert.equal(world.isPlaying(), true);
clock.pause();
assert.equal(world.isPlaying(), false);
clock.play();
world.goLive();
await flush();
assert.equal(clock.getState().playing, false);
assert.equal(clock.getState().mode, 'latest');
assert.equal(clock.getState().advancing, false);
});
test('a moving world re-applies frames only when a product changes frame', async (t) => {
@@ -416,15 +340,6 @@ test('a moving world re-applies frames only when a product changes frame', async
assert.equal(radar.shown, time(10));
});
test('a world without frames to step plays on its own', async (t) => {
const { clock, world, tick } = harness(t);
world.seek(Date.parse(time(0)));
world.play();
assert.equal(clock.getState().playing, false);
tick(1000);
assert.equal(world.now(), Date.parse(time(0)) + 1000);
});
function worldAt(at) {
return createWorldClock({
now: () => at,
@@ -434,74 +349,25 @@ function worldAt(at) {
});
}
test('weather clocks sharing a world hand play over, and the last leaves it live', async () => {
test('weather clocks sharing a world: the last one destroyed leaves it live', () => {
const world = worldAt(Date.parse(time(20)));
const a = createWeatherClock({ world, now: () => Date.parse(time(20)) });
const b = createWeatherClock({ world, now: () => Date.parse(time(20)) });
const radarA = product('radar', [0, 10, 20]);
const radarB = product('radar', [0, 10, 20]);
a.register(radarA);
b.register(radarB);
await a.play();
assert.equal(world.isPlaying(), true);
world.pause();
assert.equal(a.getState().playing, false);
assert.equal(world.isPlaying(), false);
await a.play();
world.goLive();
assert.equal(a.getState().playing, false);
b.destroy();
assert.equal(world.follows('radar'), true);
a.register(product('radar', [0, 10, 20]));
b.register(product('radar', [0, 10, 20]));
world.seek(Date.parse(time(0)));
world.play();
assert.equal(a.getState().playing, true);
b.destroy();
assert.equal(world.follows('radar'), true);
assert.equal(world.isLive(), false);
assert.equal(world.isPlaying(), true);
a.destroy();
assert.equal(world.follows('radar'), false);
assert.equal(world.isLive(), true);
assert.equal(world.isPlaying(), false);
});
test('pausing from inside the first playing notice stops the world too', async (t) => {
const { clock, world } = harness(t);
clock.register(product('radar', [0, 10, 20]));
const off = clock.subscribe((state) => {
if (state.playing) {
off();
clock.pause();
}
});
await clock.play();
assert.equal(clock.getState().playing, false);
assert.equal(world.isPlaying(), false);
});
test('a step holds a world that was playing on its own', async (t) => {
const { clock, world } = harness(t);
world.seek(Date.parse(time(0)));
world.play();
clock.register(product('radar', [0, 10, 20]));
await clock.step(1);
assert.equal(world.isPlaying(), false);
assert.equal(world.now(), Date.parse(time(10)));
});
test('a target superseded from a listener resolves false', async (t) => {
const { clock } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
await flush();
let redirected = false;
clock.subscribe((state) => {
if (state.target === time(0) && !redirected) {
redirected = true;
void clock.setTarget(time(10));
}
});
assert.equal(await clock.setTarget(time(0)), false);
assert.equal(radar.shown, time(10));
});
test('each product’s frames are world clock coverage, and support the timeline while shown', (t) => {
test('each product’s frames span world clock coverage, with no marks, and support the timeline while shown', (t) => {
const { clock, world } = harness(t);
assert.equal(world.coverage(), null);
assert.equal(world.getState().supported, false);
@@ -511,11 +377,17 @@ test('each product’s frames are world clock coverage, and support the timeline
assert.deepEqual(world.coverage(), {
start: Date.parse(time(0)),
end: Date.parse(time(10)),
marks: [0, 5, 10].map((m) => Date.parse(time(m))),
marks: [],
markDetails: [],
});
assert.equal(world.getState().supported, true);
unregister();
assert.deepEqual(world.coverage().marks, [Date.parse(time(5))]);
assert.deepEqual(world.coverage(), {
start: Date.parse(time(5)),
end: Date.parse(time(5)),
marks: [],
markDetails: [],
});
clock.destroy();
assert.equal(world.coverage(), null);
assert.equal(world.getState().supported, false);
@@ -528,10 +400,12 @@ test('a suspended product keeps its coverage, so the way back to live stays', (t
radar.suspended = true;
void clock.refresh();
assert.equal(world.getState().supported, true);
assert.deepEqual(
world.coverage().marks,
[0, 10].map((m) => Date.parse(time(m))),
);
assert.deepEqual(world.coverage(), {
start: Date.parse(time(0)),
end: Date.parse(time(10)),
marks: [],
markDetails: [],
});
});
test('new frames reach the world clock through refresh', (t) => {
+9
View File
@@ -39,6 +39,15 @@ function text(value, max) {
: undefined;
}
/**
* A source name a weather feed supplies itself (`sourceName` on the feed),
* held to the same rule as a manifest's `display.source`; undefined when it
* is not a fit name.
*/
export function weatherSourceName(value) {
return text(value, TEXT_LIMITS.source);
}
/**
* Whether a label the legend formats as a number reads back exactly as given:
* within the safe integer range and with no digits lost to rounding, so
+145 -162
View File
@@ -2,14 +2,16 @@ import { createWeatherRendering } from './rendering.js';
import { createWeatherShell, globeImageryHost } from './shellRendering.js';
import { weatherFrameSource } from './source.js';
import { imageryHostStatus } from './imageryHost.js';
import { weatherDisplay, insideExtent } from './display.js';
import { weatherDisplay, weatherSourceName, insideExtent } from './display.js';
import {
RADAR_MAX_GAP_MS,
REGIONAL_INFRARED_MAX_GAP_MS,
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
atLeastFrameSpacing,
createWeatherClock,
} from './clock.js';
import { worldClock } from '../../time/worldClock.js';
import { formatUtcDayMonth, t, msg } from '../../i18n/index.js';
import { formatScaleLabel } from '../../ui/unitLabels.js';
import { toLonLatH } from '../../geo/ellipsoid.js';
@@ -60,12 +62,68 @@ const utc = (value) =>
? `${formatUtcDayMonth(value)} ${value.slice(11, 16)} UTC`
: t('Unavailable');
/**
* Move `world`, the world clock, as its timeline does: `play` toggles play at
* the world clock's rate (the speed the timeline chose), from the start of the
* covered time when live or at its end, unless `canPlay` is false or there
* is no covered time (no timeline to play); `latest` goes live. `step` (-1 or 1) goes to the previous or next of `frames`, the
* weather frames; the timeline does not mark them, so this is the row's own
* way to step through them.
*/
function moveWorldTime(world, frames, { play, latest, step }, canPlay) {
if (!world) return;
if (play === true) {
const state = world.getState();
if (state.playing) world.pause();
else {
// With no time to show there is no timeline, and nothing to play.
const covered = canPlay && state.supported ? world.coverage() : null;
if (covered) {
// The covered time reaches to now, as the timeline's track does.
const end = Math.max(covered.end, world.wallNow());
if (state.live || state.timeMs >= end)
world.seek(Math.min(covered.start, state.timeMs));
world.play({ continuous: true });
}
}
}
if (latest === true) world.goLive();
if (step === -1 || step === 1) {
const at = world.getState().timeMs;
const times = frames
.map((time) => Date.parse(time))
.filter(Number.isFinite)
.sort((a, b) => a - b);
const to =
step < 0
? times.findLast((frame) => frame < at)
: times.find((frame) => frame > at);
if (to === undefined) return;
world.pause();
world.seek(to);
}
}
// What a layer that has not built its own clock yet reads: live, no frames.
const IDLE_CLOCK = Object.freeze({
mode: 'latest',
target: null,
advancing: false,
timeline: [],
products: [],
});
/** A per-application observation layer, using the existing layer lifecycle and
* row controls. Its time is the world clock's, so a link made away from live
* opens its imagery at that time; one made live opens the latest. */
* opens its imagery at that time; one made live opens the latest. Its frames
* follow `clock`, a weather clock several layers share; without one the layer
* builds its own on the page's world clock when first enabled and keeps it
* for its lifetime; that clock never sends the world live. The feed may also
* name its source with `sourceName(kind)`, `kind` being 'radar', 'lightning'
* or 'satellite'; NOAA nowCOAST is named otherwise. */
export function createWeatherLayer({
feed,
clock,
clock: sharedClock,
id = 'weather-radar',
createRendering = createWeatherRendering,
documentRef = globalThis.document,
@@ -74,10 +132,28 @@ export function createWeatherLayer({
} = {}) {
if (typeof feed?.getSnapshot !== 'function')
throw new TypeError('Weather requires a snapshot source');
// Without a shared clock the layer builds its own when first enabled, so a
// layer never turned on leaves the world clock alone.
let ownClock = null;
let clock = sharedClock ?? null;
// A feed may also supply decoded frames; see weatherFrameSource.
const radar = id === 'weather-radar';
const lightning = id === 'weather-lightning';
const satellite = !radar && !lightning;
// A feed may name the source behind each product ('radar', 'lightning' or
// 'satellite'); its row then says so before a manifest names it. A name
// that fails, like a manifest's, leaves the built-in one.
let sourceName = null;
try {
sourceName =
weatherSourceName(
feed.sourceName?.(
radar ? 'radar' : lightning ? 'lightning' : 'satellite',
),
) ?? null;
} catch (cause) {
console.warn('[weather] source name unavailable:', cause);
}
let product = radar ? 'radar' : lightning ? 'lightning' : 'clouds-regional';
let opacity = 'strong';
let infrared = 100;
@@ -86,12 +162,10 @@ export function createWeatherLayer({
manifest = null,
request = null,
listener = null;
let destroyed = false;
let enabled = false,
loading = false,
playing = false,
followLatest = true;
loading = false;
let generation = 0,
timer = null,
error = null,
removeCamera = null;
let motion = null;
@@ -131,39 +205,38 @@ export function createWeatherLayer({
return spaced;
};
const maxGap = () => spacedTimes().gap;
const isLatest = () =>
clock ? clock.getState().mode === 'latest' : followLatest;
const clockState = () => clock?.getState() ?? IDLE_CLOCK;
const isLatest = () => clockState().mode === 'latest';
const getHost = () => imageryHost?.() ?? globeImageryHost(viewer);
const notify = () => listener?.();
const shownTime = () => (noFrame ? null : rendering?.getDiagnostics().time);
const unsubscribeClock = clock?.subscribe(() => {
const onClock = () => {
if (!clock.getState().advancing || suspended())
rendering?.cancelPrefetch?.();
notify();
});
};
let unsubscribeClock = clock?.subscribe(onClock) ?? null;
const ensureClock = () => {
if (clock) return;
ownClock = createWeatherClock({ world: worldClock, shared: false });
clock = ownClock;
unsubscribeClock = clock.subscribe(onClock);
};
// Ages and delays are measured from the time the layer shows: the world
// clock's time at a past time, the wall clock while live.
const worldNow = () => {
const shared = clock?.getState();
return shared?.mode === 'history' && shared.target
const shared = clockState();
return shared.mode === 'history' && shared.target
? Date.parse(shared.target)
: Date.now();
};
const observationDelayed = () =>
manifest?.latest &&
worldNow() - Date.parse(manifest.latest) > spacedTimes().delay;
const stop = () => {
if (clock) return;
playing = false;
rendering?.cancelPrefetch?.();
clearTimeout(timer);
timer = null;
};
const suspended = () => hostHidden || documentRef?.hidden || motion?.matches;
const onVisibility = () => {
if (suspended()) rendering?.cancelPrefetch?.();
if (clock) void clock.refresh();
else if (suspended()) stop();
void clock?.refresh();
notify();
};
@@ -178,46 +251,15 @@ export function createWeatherLayer({
if (!changed || !rendering) return;
++generation;
rendering.rehome?.();
clearTimeout(timer);
timer = null;
loading = Boolean(request && !request.signal.aborted);
if (clock && enabled) {
if (resume) {
void clock.refresh();
if (!hostHidden && manifest && isLatest()) void show(manifest.latest);
}
notify();
return;
}
if (resume && enabled && !hostHidden && manifest) {
const time =
followLatest || !manifest.times.includes(shownTime())
? manifest.latest
: shownTime();
if (
time !== shownTime() ||
(satellite && rendering.getDiagnostics().infrared !== infrared)
)
void show(time);
else schedule();
if (enabled && resume) {
void clock.refresh();
if (!hostHidden && manifest && isLatest()) void show(manifest.latest);
}
notify();
}
const onMapStackChanged = () => checkHost();
function schedule() {
if (clock) return;
clearTimeout(timer);
timer = null;
if (!enabled || !playing || suspended()) return;
timer = setTimeout(() => {
timer = null;
const times = manifest?.times || [];
const next = (times.indexOf(shownTime()) + 1) % times.length;
if (times[next]) void show(times[next]);
else stop();
}, 2000);
}
async function applyClockTime(time, { signal }) {
if (!enabled || signal.aborted) return false;
if (time !== null) return show(time, signal);
@@ -231,7 +273,7 @@ export function createWeatherLayer({
return true;
}
function registerClock() {
if (!clock || unregisterClock || !rendering || !enabled) return;
if (unregisterClock || !rendering || !enabled || !clock) return;
unregisterClock = clock.register({
id,
get maxGapMs() {
@@ -244,15 +286,11 @@ export function createWeatherLayer({
});
}
async function warmNext(time) {
if (
!enabled ||
suspended() ||
!(clock ? clock.getState().advancing : playing)
)
return;
if (!enabled || suspended() || !clockState().advancing) return;
// The world plays on past the newest frame, never round to the first.
const times = manifest?.times ?? [];
const next = times[(times.indexOf(time) + 1) % times.length];
if (!next || next === time) return;
const next = times[times.indexOf(time) + 1];
if (!next) return;
try {
await rendering.prefetch?.(manifest, next, { infrared });
} catch {
@@ -287,13 +325,10 @@ export function createWeatherLayer({
error = ok
? null
: msg('Frame unavailable; previous observation retained');
if (!ok) stop();
return ok;
} catch {
if (owner === generation && !controller.signal.aborted) {
if (owner === generation && !controller.signal.aborted)
error = msg('Weather imagery unavailable');
stop();
}
return false;
} finally {
signal?.removeEventListener('abort', abort);
@@ -301,8 +336,7 @@ export function createWeatherLayer({
if (owner === generation) {
loading = Boolean(request && !request.signal.aborted);
notify();
if (clock && isLatest()) void clock.refresh();
schedule();
if (isLatest()) void clock?.refresh();
}
}
}
@@ -314,7 +348,7 @@ export function createWeatherLayer({
? 'Lightning density'
: 'Satellite clouds',
icon: radar ? '◉' : lightning ? 'ϟ' : '☁',
source: 'NOAA nowCOAST · OBSERVED',
source: sourceName ?? 'NOAA nowCOAST · OBSERVED',
updateInterval: lightning ? 600_000 : 120_000,
init(nextViewer) {
viewer = nextViewer;
@@ -349,7 +383,10 @@ export function createWeatherLayer({
notify();
},
enable() {
// Destroyed, the layer stays off: no clock is built for it again.
if (destroyed) return;
enabled = true;
ensureClock();
if (!removeCamera) {
removeCamera =
findCamera(viewer)?.on('moveEnd', () => {
@@ -371,26 +408,20 @@ export function createWeatherLayer({
noFrame = false;
request?.abort();
request = null;
stop();
rendering?.cancelPrefetch?.();
rendering?.clear();
manifest = null;
loading = false;
error = null;
followLatest = true;
},
async update(_viewer, { signal } = {}) {
if (!enabled) return false;
checkHost(false);
clearTimeout(timer);
timer = null;
request?.abort();
const controller = new AbortController();
if (signal?.aborted) controller.abort(signal.reason);
request = controller;
const abort = () => {
controller.abort(signal.reason);
stop();
};
const abort = () => controller.abort(signal.reason);
signal?.addEventListener('abort', abort, { once: true });
loading = true;
notify();
@@ -406,36 +437,15 @@ export function createWeatherLayer({
error = msg(
'Weather source unavailable; previous observation retained',
);
stop();
return true;
}
manifest = snapshot;
error = null;
// The shown frame may stay; its credit follows the refreshed manifest.
rendering?.updateSnapshot?.(snapshot);
if (clock) {
await clock.refresh();
if (
isLatest() &&
request === controller &&
!controller.signal.aborted
)
await show(snapshot.latest, controller.signal);
return (
enabled &&
!signal?.aborted &&
(!controller.signal.aborted || request !== controller)
);
}
const time =
followLatest || !snapshot.times.includes(shownTime())
? snapshot.latest
: shownTime();
if (
shownTime() !== time ||
(satellite && rendering.getDiagnostics().infrared !== infrared)
)
await show(time, controller.signal);
await clock.refresh();
if (isLatest() && request === controller && !controller.signal.aborted)
await show(snapshot.latest, controller.signal);
return (
enabled &&
!signal?.aborted &&
@@ -445,7 +455,6 @@ export function createWeatherLayer({
if (controller.signal.aborted || request !== controller)
return enabled && !signal?.aborted && request !== controller;
error = cause?.message || msg('Weather unavailable');
stop();
return true;
} finally {
signal?.removeEventListener('abort', abort);
@@ -453,7 +462,6 @@ export function createWeatherLayer({
request = null;
loading = Boolean(rendering?.getDiagnostics().loading);
notify();
schedule();
}
}
},
@@ -488,19 +496,16 @@ export function createWeatherLayer({
noFrame = false;
request?.abort();
request = null;
stop();
rendering?.cancelPrefetch?.();
manifest = null;
error = null;
loading = false;
followLatest = true;
rendering?.clear();
if (clock) void clock.refresh();
void clock?.refresh();
if (enabled) void layer.update(viewer);
}
if (infraredChanged && enabled && manifest) {
clearTimeout(timer);
timer = null;
if (clock && !isLatest()) void clock.refresh();
if (!isLatest()) void clock.refresh();
else void show(shownTime() || manifest.latest);
}
if (
@@ -528,38 +533,19 @@ export function createWeatherLayer({
);
});
}
if (clock && enabled) {
if (params.play === true) void clock.togglePlay();
if (params.latest === true) void clock.latest();
if ([-1, 1].includes(params.step)) void clock.step(params.step);
}
if (
!clock &&
params.play === true &&
enabled &&
manifest?.times?.length > 1 &&
!suspended()
) {
playing = !playing;
followLatest = false;
if (playing) schedule();
else stop();
}
if (!clock && params.latest === true && manifest) {
stop();
followLatest = true;
void show(manifest.latest);
}
if (!clock && [-1, 1].includes(params.step) && manifest && !loading) {
stop();
followLatest = false;
const at = manifest.times.indexOf(shownTime());
const next = Math.max(
0,
Math.min(manifest.times.length - 1, at + params.step),
// Time is the world's: these move the world clock as its timeline
// does, and every layer that follows it moves along. A step goes
// through every shown observation's frames, and this row's own even
// while it is suspended.
// Play does nothing while every observation it would show is suspended
// (reduced motion, a hidden page, no imagery host), as the row says.
if (enabled)
moveWorldTime(
clock.world,
[...clock.getTimeline(), ...(manifest?.times ?? [])],
params,
clock.getState().products.some(({ suspended }) => !suspended),
);
void show(manifest.times[next]);
}
notify();
},
getParams() {
@@ -570,13 +556,13 @@ export function createWeatherLayer({
: { product, opacity };
},
getRowControls() {
const shared = clock?.getState();
const shared = clockState();
const followLatest = isLatest();
// Source-described text is data: shown as is, never translated.
const display = weatherDisplay(manifest);
const missing =
noFrame &&
shared?.mode === 'history' &&
shared.mode === 'history' &&
shared.products.find((entry) => entry.id === id)?.selected === null
? maxGap() / 60_000 < 60
? t('No frame within {gap} min of {time}', {
@@ -697,9 +683,7 @@ export function createWeatherLayer({
const stops =
display.legend ?? (radar ? STOPS : lightning ? LIGHTNING_STOPS : []);
const infoMotion = motion?.matches
? clock
? t('Reduced motion · history playback unavailable')
: t('Reduced motion · manual history available')
? t('Reduced motion · history playback unavailable')
: '';
const controls = {
readout: true,
@@ -881,35 +865,34 @@ export function createWeatherLayer({
loading,
error: error || rendering?.getDiagnostics().error || null,
stale: Boolean(manifest?.stale || observationDelayed()),
...(source === undefined
...(source === undefined && sourceName === null
? { source: 'NOAA nowCOAST' }
: // Source text is data: the panel shows it untranslated.
{ source, sourceVerbatim: true }),
{ source: source ?? sourceName, sourceVerbatim: true }),
observedAt: shownTime(),
};
},
getDiagnostics() {
const shared = clock?.getState();
const shared = clockState();
return {
...rendering?.getDiagnostics(),
playing: shared ? shared.playing : playing && !hostHidden,
playing: shared.advancing,
followLatest: isLatest(),
...(shared
? {
clock: {
mode: shared.mode,
target: shared.target,
playing: shared.playing,
},
}
: {}),
clock: {
mode: shared.mode,
target: shared.target,
playing: shared.advancing,
},
historyFrames: manifest?.times?.length || 0,
timerActive: timer !== null,
};
},
destroy() {
destroyed = true;
layer.disable();
unsubscribeClock?.();
unsubscribeClock = null;
ownClock?.destroy();
if (ownClock) clock = ownClock = null;
removeCamera?.();
removeCamera = null;
motion?.removeEventListener?.('change', onVisibility);
+311 -106
View File
@@ -1,8 +1,9 @@
import test from 'node:test';
import test, { afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createWeatherRendering, READY_WAKE_MS } from './rendering.js';
import { createWeatherLayer } from './index.js';
import { createWeatherClock } from './clock.js';
import { worldClock } from '../../time/worldClock.js';
import * as Cesium from 'cesium';
import { Color, ImageryLayerCollection, GeographicTilingScheme } from 'cesium';
import { NO_IMAGERY_HOST } from './imageryHost.js';
@@ -41,6 +42,16 @@ const deferred = () => {
const flush = async () => {
for (let i = 0; i < 30; i++) await Promise.resolve();
};
// Time moves on the world clock the weather clock follows, as the timeline
// moves it.
const seekTo = (clock, time) => {
clock.world.seek(Date.parse(time));
return flush();
};
const goLive = (clock) => {
clock.world.goLive();
return flush();
};
function event() {
const listeners = new Set();
return {
@@ -557,12 +568,22 @@ test('failed and timed-out stages retain the previous observation; a healthy rep
h.rendering.clear();
});
// A layer built without a clock keeps its own on the page's world clock:
// each test leaves that clock live, with no layer of its own on it.
const harnessed = new Set();
afterEach(() => {
for (const layer of harnessed) layer.destroy();
harnessed.clear();
worldClock.goLive();
worldClock.setRate(1);
});
function layerHarness({
clock,
reducedMotion = false,
feed,
id,
eventTarget = target(),
enable = true,
} = {}) {
const stages = [];
const motion = target({ matches: reducedMotion });
@@ -637,7 +658,8 @@ function layerHarness({
createRendering: () => rendering,
});
layer.init(viewer);
layer.enable();
if (enable) layer.enable();
harnessed.add(layer);
return {
layer,
rendering,
@@ -651,72 +673,189 @@ function layerHarness({
};
}
test('history has one owned timer, stops while hidden, and releases all work on disable/destroy', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
test('without a clock the layer keeps one of its own on the world clock and lets it go on destroy', async () => {
const h = layerHarness();
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
assert.equal(worldClock.follows('weather-radar'), true);
// The frames span the timeline's time; they are not marks on it.
assert.deepEqual(worldClock.coverage(), {
start: Date.parse(times[0]),
end: Date.parse(times.at(-1)),
marks: [],
markDetails: [],
});
h.layer.setParams({ play: true });
assert.equal(h.layer.getDiagnostics().timerActive, true);
t.mock.timers.tick(2000);
assert.equal(h.stages.length, 2);
assert.equal(
h.layer.getDiagnostics().timerActive,
false,
'next timer waits for stage settlement',
);
h.stages[1].finish();
await flush();
assert.equal(h.layer.getDiagnostics().timerActive, true);
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getState().stepping, false);
assert.equal(h.layer.getDiagnostics().playing, true);
h.documentRef.hidden = true;
h.documentRef.emit('visibilitychange');
assert.equal(h.layer.getDiagnostics().playing, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
t.mock.timers.tick(20_000);
assert.equal(h.stages.length, 2);
await flush();
assert.equal(worldClock.isPlaying(), true, 'hiding suspends the layer only');
h.documentRef.hidden = false;
h.documentRef.emit('visibilitychange');
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), false);
h.layer.disable();
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(h.layer.getDiagnostics().historyFrames, 0);
t.mock.timers.tick(20_000);
assert.equal(h.stages.length, 2);
h.layer.destroy();
assert.equal(worldClock.follows('weather-radar'), false);
assert.equal(h.documentRef.size, 0);
assert.equal(h.motion.size, 0);
assert.equal(h.moveEnd.size, 0);
assert.ok(h.clears() >= 1);
});
test('reduced motion blocks autoplay but permits manual history and stops newly suspended playback', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
test('a layer without a clock leaves the world clock alone until enabled, and never sends it live', async (t) => {
const past = Date.parse(times[0]) - 3_600_000;
worldClock.seek(past);
const subscribe = t.mock.method(worldClock, 'subscribe');
const gate = t.mock.method(worldClock, 'gate');
const h = layerHarness({ enable: false });
h.layer.getRowControls();
h.layer.getDiagnostics();
h.layer.setParams({ play: true, step: -1 });
assert.equal(subscribe.mock.callCount(), 0, 'off, no clock is built');
assert.equal(gate.mock.callCount(), 0);
assert.equal(worldClock.isPlaying(), false);
h.layer.destroy();
harnessed.delete(h.layer);
assert.equal(worldClock.now(), past, 'never on, the world is where it was');
assert.equal(worldClock.isLive(), false);
const on = layerHarness({ enable: false });
on.layer.enable();
assert.equal(subscribe.mock.callCount(), 1, 'built on first enable');
const update = on.layer.update();
await flush();
on.stages.at(-1)?.finish();
await update;
on.layer.disable();
on.layer.enable();
assert.equal(subscribe.mock.callCount(), 1, 'built once');
on.layer.destroy();
harnessed.delete(on.layer);
assert.equal(
worldClock.isLive(),
false,
'its own clock does not send it live',
);
assert.equal(worldClock.now(), past);
});
test('destroyed, a layer without a clock stays off: enabling it builds no clock', (t) => {
const subscribe = t.mock.method(worldClock, 'subscribe');
const h = layerHarness();
assert.equal(subscribe.mock.callCount(), 1, 'its clock, built on enable');
h.layer.destroy();
harnessed.delete(h.layer);
h.layer.enable();
assert.equal(subscribe.mock.callCount(), 1, 'no clock built after destroy');
assert.equal(worldClock.follows('weather-radar'), false);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), false);
});
test('with no frames yet there is no timeline, and a row plays nothing', () => {
worldClock.setRate(604_800);
const h = layerHarness({
feed: { getSnapshot: () => new Promise(() => {}) },
});
void h.layer.update();
assert.equal(worldClock.coverage(), null);
h.layer.setParams({ play: true });
assert.equal(worldClock.isLive(), true);
assert.equal(worldClock.isPlaying(), false);
});
test('a row plays at the speed the world clock keeps, from the start at the end of the covered time', async () => {
const h = layerHarness();
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
// A speed chosen on the timeline, while live.
worldClock.setRate(3_600);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getRate(), 3_600, 'played at the speed chosen');
assert.ok(
worldClock.now() - Date.parse(times[0]) < 3_600_000,
'live, play starts at the start of the covered time',
);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), false);
// Paused at the end of the covered time (it reaches to now), play starts
// again from the start, as the timeline's does.
worldClock.seek(worldClock.wallNow() + 1_000);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), true);
assert.ok(worldClock.now() - Date.parse(times[0]) < 3_600_000);
assert.equal(worldClock.getRate(), 3_600);
worldClock.pause();
});
test('reduced motion offers no play; steps still move the world clock from frame to frame', async () => {
const h = layerHarness({ reducedMotion: true });
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
h.layer.setParams({ play: true });
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(
h.layer.getRowControls().chips.some((chip) => chip.id === 'play'),
false,
);
h.layer.setParams({ step: -1 });
assert.equal(h.stages[1].time, times[1]);
h.stages[1].finish();
await flush();
h.motion.matches = false;
h.motion.emit('change');
// Play, which the row does not offer, does nothing while it is suspended.
h.layer.setParams({ play: true });
assert.equal(h.layer.getDiagnostics().playing, true);
h.motion.matches = true;
h.motion.emit('change');
assert.equal(h.layer.getDiagnostics().playing, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
h.layer.destroy();
assert.equal(worldClock.isPlaying(), false);
assert.equal(worldClock.isLive(), true);
// A step back from live goes to the newest frame, and the next one back
// to the frame before it.
h.layer.setParams({ step: -1 });
await flush();
assert.equal(worldClock.now(), Date.parse(times[2]));
h.layer.setParams({ step: -1 });
await flush();
assert.equal(worldClock.now(), Date.parse(times[1]));
assert.equal(h.stages.at(-1).time, times[1]);
});
test('a row steps forward and plays from a past time through the world clock', async () => {
const h = layerHarness();
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
worldClock.seek(Date.parse(times[0]));
await flush();
h.layer.setParams({ step: 1 });
assert.equal(worldClock.now(), Date.parse(times[1]));
assert.equal(worldClock.isPlaying(), false);
await flush();
assert.equal(h.stages.at(-1).time, times[1]);
h.layer.setParams({ step: 1 });
assert.equal(worldClock.now(), Date.parse(times[2]));
h.layer.setParams({ step: 1 });
assert.equal(
worldClock.now(),
Date.parse(times[2]),
'no frame after the newest',
);
worldClock.seek(Date.parse(times[1]));
await flush();
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getState().stepping, false);
assert.ok(
worldClock.now() - Date.parse(times[1]) < 1_000,
'away from live, play goes on from the time shown',
);
h.layer.setParams({ step: 1 });
assert.equal(worldClock.isPlaying(), false, 'a step holds play');
assert.equal(worldClock.now(), Date.parse(times[2]));
});
test('disable invalidates an abort-insensitive source result and an already staged frame', async (t) => {
@@ -745,7 +884,6 @@ test('disable invalidates an abort-insensitive source result and an already stag
await next;
await flush();
assert.equal(h.layer.getStats().count, 0);
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(h.layer.getStats().loading, false);
h.layer.destroy();
});
@@ -804,7 +942,6 @@ test('update cancellation reaches imagery after source acquisition has completed
assert.equal(h.stages[0].signal.aborted, true);
assert.equal(h.layer.getStats().count, 0);
assert.equal(h.layer.getStats().loading, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
h.layer.destroy();
});
@@ -912,21 +1049,22 @@ test('coverage navigation requires the shared shell handoff and detaches cleanly
h.layer.destroy();
});
test('manifest refresh during a manual history stage does not strand loading controls', async () => {
test('manifest refresh during a history stage restages the same time and does not strand loading controls', async () => {
const h = layerHarness();
const first = h.layer.update();
await flush();
h.stages[0].finish();
await first;
h.layer.setParams({ step: -1 });
worldClock.seek(Date.parse(times[1]));
await flush();
assert.equal(h.layer.getStats().loading, true);
await h.layer.update();
assert.equal(
h.stages.length,
2,
'metadata refresh preserves the staged manual selection',
);
h.stages[1].finish();
const refreshed = h.layer.update();
await flush();
assert.equal(h.stages.length, 3);
assert.equal(h.stages[1].signal.aborted, true);
assert.equal(h.stages[2].time, times[1], 'the refresh keeps the time');
h.stages[2].finish();
await refreshed;
await flush();
assert.equal(h.layer.getStats().loading, false);
assert.equal(h.layer.getStats().observedAt, times[1]);
@@ -956,7 +1094,8 @@ test('historical observations do not relabel a fresh lightning feed as stale', a
await flush();
h.stages[0].finish();
await first;
h.layer.setParams({ step: -1 });
worldClock.seek(Date.parse(old));
await flush();
h.stages[1].finish();
await flush();
assert.equal(h.layer.getStats().stale, false);
@@ -1313,8 +1452,7 @@ test('404 fails a frame without retry', async () => {
h.rendering.clear();
});
test('no host pauses history, refreshes metadata, and restores retained time and playback', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
test('no host holds the shown history frame, refreshes metadata, and restores the retained time', async () => {
let refreshes = 0;
const h = layerHarness({
feed: {
@@ -1330,28 +1468,23 @@ test('no host pauses history, refreshes metadata, and restores retained time and
await flush();
h.stages[0].finish();
await update;
h.layer.setParams({ play: true });
t.mock.timers.tick(2000);
worldClock.seek(Date.parse(times[0]));
await flush();
assert.equal(h.stages.length, 2);
h.stages[1].finish();
await flush();
host = { collection: null, kind: 'none' };
h.eventTarget.emit('gev:map-stack-changed');
await flush();
assert.equal(h.layer.getDiagnostics().playing, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(h.layer.getRowControls().summary.status, NO_IMAGERY_HOST);
assert.equal(h.layer.getRowControls().info, NO_IMAGERY_HOST);
await h.layer.update();
assert.equal(refreshes, 2);
t.mock.timers.tick(10_000);
assert.equal(h.stages.length, 2);
assert.equal(h.layer.getDiagnostics().time, times[2]);
assert.equal(h.stages.length, 2, 'nothing stages without a host');
host = { collection: {}, kind: 'globe' };
h.eventTarget.emit('gev:map-stack-changed');
assert.equal(h.layer.getDiagnostics().playing, true);
assert.equal(h.layer.getDiagnostics().timerActive, true);
t.mock.timers.tick(2000);
assert.equal(h.stages.length, 3);
assert.equal(h.stages[2].time, times[0]);
await flush();
assert.equal(h.stages.at(-1).time, times[0], 'the retained time restages');
h.layer.destroy();
assert.equal(h.eventTarget.size, 0);
});
@@ -1465,25 +1598,21 @@ for (const [id, product] of [
const [shell] = h.shells();
assert.equal(shell.show, true);
layer.setParams({ play: true });
t.mock.timers.tick(2000);
worldClock.seek(Date.parse(times[0]));
await flush();
assert.equal(
layer.getDiagnostics().time,
times[0],
'history advances at street level',
'history moves at street level',
);
camera.positionCartographic.height = 59_999;
camera.moveEnd.emit();
assert.equal(shell.show, true, 'no height gate');
assert.equal(layer.getDiagnostics().playing, true);
assert.equal(layer.getDiagnostics().timerActive, true);
host = { collection: null, kind: 'none' };
events.emit('gev:map-stack-changed');
assert.equal(shell.show, false);
assert.equal(layer.getRowControls().summary.status, NO_IMAGERY_HOST);
assert.equal(layer.getDiagnostics().timerActive, false);
host = { collection: h.viewer.imageryLayers, kind: 'globe' };
events.emit('gev:map-stack-changed');
assert.equal(shell.destroyed, true);
@@ -1675,10 +1804,12 @@ test('satellite mode chips restage history without changing time or latest-follo
await flush();
h.stages[0].finish();
await update;
h.layer.setParams({ step: -1 });
worldClock.seek(Date.parse(times[1]));
await flush();
h.stages[1].finish();
await flush();
h.layer.setParams({ infrared: 'full' });
await flush();
assert.equal(h.stages[2].time, times[1]);
assert.equal(h.stages[2].infrared, 0);
assert.equal(h.layer.getParams().infrared, 0);
@@ -1802,7 +1933,7 @@ test('a delayed installation failure retains the replacement and does not throw
h.rendering.clear();
});
test('one row steps every registered observation; missing frames hide and latest restores each product', async (t) => {
test('a row steps the world clock through every registered observation; missing frames hide and latest goes live', async (t) => {
const clock = createWeatherClock();
const radar = layerHarness({ clock });
const satellite = layerHarness({
@@ -1835,6 +1966,14 @@ test('one row steps every registered observation; missing frames hide and latest
.chips.filter(({ id }) =>
['previous', 'play', 'next', 'latest'].includes(id),
);
// A step back from live goes to the newest frame, and the next one back
// to the frame before it.
radar.layer.setParams({ step: -1 });
await flush();
assert.equal(clock.getState().target, times[2]);
assert.equal(clock.world.isPlaying(), false);
for (const h of [radar, satellite]) h.stages.at(-1)?.finish();
await flush();
radar.layer.setParams({ step: -1 });
await flush();
assert.equal(clock.getState().target, times[1]);
@@ -1886,6 +2025,33 @@ test('one row steps every registered observation; missing frames hide and latest
assert.equal(clock.getState().products.length, 1);
});
test('a row’s play and latest move the world clock as its timeline does', async (t) => {
const clock = createWeatherClock();
const { world } = clock;
const h = layerHarness({ clock });
t.after(() => {
h.layer.destroy();
clock.destroy();
});
const update = h.layer.update();
await flush();
h.stages.at(-1).finish();
await update;
h.layer.setParams({ play: true });
assert.equal(world.isPlaying(), true);
assert.equal(world.getState().stepping, false, 'the world plays on its own');
assert.ok(
world.now() - Date.parse(times[0]) < 1_000,
'from the start when live',
);
h.layer.setParams({ play: true });
assert.equal(world.isPlaying(), false);
h.layer.setParams({ latest: true });
assert.equal(world.isLive(), true);
await flush();
assert.equal(clock.getState().mode, 'latest');
});
test('history manifest expiry hides imagery without jumping to latest; host resume keeps the target', async (t) => {
const clock = createWeatherClock();
let value = snapshot;
@@ -1898,7 +2064,7 @@ test('history manifest expiry hides imagery without jumping to latest; host resu
await flush();
h.stages.at(-1).finish();
await update;
const history = clock.setTarget(times[0]);
const history = seekTo(clock, times[0]);
await flush();
h.stages.at(-1).finish();
await history;
@@ -1967,7 +2133,7 @@ test('satellite global selection uses the three-hour gap and preserves the share
await flush();
h.stages.at(-1).finish();
await update;
await clock.setTarget(times[0]);
await seekTo(clock, times[0]);
assert.equal(
h.layer.getDiagnostics().hidden,
true,
@@ -2026,7 +2192,8 @@ test('satellite clouds from an hourly feed draw all through each hour and read l
);
// Forty-five minutes past a frame, between it and the next, it still shows.
const between = clock.setTarget(
const between = seekTo(
clock,
new Date(Date.parse(hourly[0]) + 45 * 60_000).toISOString(),
);
await flush();
@@ -2037,7 +2204,7 @@ test('satellite clouds from an hourly feed draw all through each hour and read l
// Live again (a past time judges delay from the timeline's time), past
// one and a half hours it reads late.
const live = clock.latest();
const live = goLive(clock);
await flush();
h.stages.at(-1).finish();
await live;
@@ -2059,11 +2226,11 @@ test('switching to history cancels a still-loading latest refresh and a later ta
const update = h.layer.update();
await flush();
const latest = h.stages.at(-1);
const oldHistory = clock.setTarget(times[0]);
const oldHistory = seekTo(clock, times[0]);
await flush();
assert.equal(latest.signal.aborted, true);
const oldStage = h.stages.at(-1);
const current = clock.setTarget(times[1]);
const current = seekTo(clock, times[1]);
await flush();
assert.equal(oldStage.signal.aborted, true);
h.stages.at(-1).finish();
@@ -2373,8 +2540,9 @@ test('failed prefetch leaves the current frame and errors unchanged and releases
assert.deepEqual(h.rendering.getDiagnostics(), before);
});
test('layer warms the next advertised observation only after a successful playing frame, wrapping at the end', async (t) => {
test('as the world plays, the layer warms the next advertised observation after each frame that shows', async (t) => {
const clock = createWeatherClock();
const { world } = clock;
const h = layerHarness({ clock });
const warmed = [];
let cancels = 0;
@@ -2392,45 +2560,45 @@ test('layer warms the next advertised observation only after a successful playin
await flush();
h.stages.at(-1).finish();
await updated;
assert.equal(warmed.length, 0);
const play = clock.play();
await seekTo(clock, times[0]);
h.stages.at(-1).finish();
await flush();
assert.equal(warmed.length, 0, 'paused, nothing is warmed');
world.play({ rate: 1e-9, continuous: true });
assert.equal(clock.getState().advancing, true);
await seekTo(clock, times[1]);
assert.equal(warmed.length, 0, 'still staging');
h.stages.at(-1).finish();
await play;
await flush();
assert.deepEqual(
warmed.map(({ time }) => time),
[times[0]],
[times[2]],
);
assert.deepEqual(warmed[0].options, { infrared: 100 });
const next = clock.setTarget(times[0]);
await flush();
h.stages.at(-1).finish();
await next;
assert.deepEqual(
warmed.map(({ time }) => time),
[times[0], times[1]],
);
const failed = clock.setTarget(times[1]);
await flush();
await seekTo(clock, times[0]);
h.stages.at(-1).finish(false);
await failed;
assert.equal(warmed.length, 2);
const priorCancels = cancels;
clock.pause();
assert.ok(cancels > priorCancels);
const paused = clock.setTarget(times[2]);
await flush();
assert.equal(warmed.length, 1, 'a failed frame warms nothing');
await seekTo(clock, times[2]);
h.stages.at(-1).finish();
await paused;
assert.equal(warmed.length, 2);
await clock.play();
await flush();
assert.equal(warmed.length, 1, 'the world plays on past the newest frame');
const priorCancels = cancels;
world.pause();
await flush();
assert.ok(cancels > priorCancels);
await seekTo(clock, times[1]);
h.stages.at(-1).finish();
await flush();
assert.equal(warmed.length, 1);
world.play({ rate: 1e-9, continuous: true });
h.documentRef.hidden = true;
h.documentRef.emit('visibilitychange');
await flush();
h.stages.at(-1).finish();
h.stages.at(-1)?.finish();
await flush();
assert.equal(warmed.length, 2, 'hidden products do not prefetch');
assert.equal(warmed.length, 1, 'hidden products do not prefetch');
world.goLive();
});
for (const product of ['radar', 'clouds-regional', 'lightning']) {
@@ -2767,7 +2935,7 @@ test('at a past time a frame is aged and its source judged delayed from the time
// Years later, the world clock is moved back to the newest frame.
Date.now.mock.mockImplementation(() => Date.parse('2032-01-01T00:00:00Z'));
void clock.setTarget(times[2]);
void seekTo(clock, times[2]);
await flush();
h.stages.at(-1)?.finish();
await flush();
@@ -2778,10 +2946,47 @@ test('at a past time a frame is aged and its source judged delayed from the time
assert.equal(h.layer.getStats().stale, false);
// Ten minutes after the newest frame, the frame is ten minutes old.
void clock.setTarget('2026-09-15T20:20:00.000Z');
void seekTo(clock, '2026-09-15T20:20:00.000Z');
await flush();
h.stages.at(-1)?.finish();
await flush();
assert.match(h.layer.getRowControls().summary.detail, /10m ago · nearest/);
assert.equal(h.layer.getRowControls().summary.status, null);
});
test('a feed names the source behind each product, before any manifest does', (t) => {
t.mock.method(console, 'warn', () => {});
const quiet = {
documentRef: target({ hidden: false }),
eventTarget: target(),
matchMedia: () => target({ matches: false }),
};
const asked = [];
const feed = {
getSnapshot: async () => snapshot,
sourceName(kind) {
asked.push(kind);
if (kind === 'satellite') throw new Error('no name');
return kind === 'radar' ? ' NOAA MRMS ' : 'NOAA\u200b GLM';
},
};
const radar = createWeatherLayer({ ...quiet, feed, id: 'weather-radar' });
assert.equal(radar.source, 'NOAA MRMS');
const stats = radar.getStats();
assert.equal(stats.source, 'NOAA MRMS');
assert.equal(stats.sourceVerbatim, true);
// A name a manifest could not carry, or a failing call, leaves nowCOAST, as
// does a feed with no names.
for (const id of ['weather-lightning', 'weather-satellite']) {
const layer = createWeatherLayer({ ...quiet, feed, id });
assert.equal(layer.source, 'NOAA nowCOAST · OBSERVED', id);
assert.equal(layer.getStats().source, 'NOAA nowCOAST', id);
assert.equal(layer.getStats().sourceVerbatim, undefined, id);
}
assert.deepEqual(asked, ['radar', 'lightning', 'satellite']);
const unnamed = createWeatherLayer({
...quiet,
feed: { getSnapshot: async () => snapshot },
});
assert.equal(unnamed.source, 'NOAA nowCOAST · OBSERVED');
});
+9 -4
View File
@@ -390,20 +390,24 @@ test('sample stays fixed across model, field and unit changes; dismissal and dis
test('observed history labels wind as a forecast without changing its data or parameters', async () => {
const { createWeatherClock } = await import('../weather/clock.js');
const clock = createWeatherClock();
const { world } = clock;
const layer = createWindLayer({ feed: { getSnapshot: async () => snapshot('gfs') }, clock });
let changes = 0;
layer.setRowControlsListener(() => changes++);
const params = layer.getParams();
await clock.setTarget('2026-09-14T12:00:00.000Z');
world.seek(Date.parse('2026-09-14T12:00:00.000Z'));
await Promise.resolve();
assert.equal(layer.getRowControls().summary.status, null, 'history does not mask source status');
assert.ok(changes > 0);
assert.match(layer.getRowControls().info, /Forecast · does not follow history/);
assert.deepEqual(layer.getParams(), params);
await clock.latest();
world.goLive();
await Promise.resolve();
assert.equal(layer.getRowControls().summary.status, null);
layer.destroy();
const before = changes;
await clock.setTarget('2026-09-14T12:00:00.000Z');
world.seek(Date.parse('2026-09-14T12:00:00.000Z'));
await Promise.resolve();
assert.equal(changes, before);
clock.destroy();
});
@@ -462,7 +466,8 @@ test('wind whose source follows the timeline drops the note that it does not fol
const clock = createWeatherClock({ world });
const layer = createWindLayer({ feed: { getSnapshot: async () => snapshot('gfs') }, clock });
world.follow('wind');
await clock.setTarget('2026-09-14T12:00:00.000Z');
world.seek(Date.parse('2026-09-14T12:00:00.000Z'));
for (let i = 0; i < 10; i++) await Promise.resolve();
assert.equal(clock.getState().mode, 'history');
assert.doesNotMatch(layer.getRowControls().info, /does not follow history/);
world.follow('wind', false);