Merge origin/main into fix/earthquake-click-details

This commit is contained in:
manjunath22466 committed 2026-11-17 11:49:17 +05:30
commit 4804097ca1
204 files changed
+34669 -680

No files matched your search

+4
View File
@@ -641,6 +641,8 @@ export function placeCard(card, leader, anchor) {
function createRoot(documentRef, viewer) {
const root = documentRef.createElement('div');
root.id = 'bhote-koshi-embedded-media-root';
// Drawn over the globe for the scene: Stories keeps it while one plays.
root.setAttribute('data-globe-overlay', '');
root.setAttribute('aria-live', 'polite');
(viewer?.container || documentRef.body)?.append(root);
return root;
@@ -1120,6 +1122,8 @@ export function createBhoteKoshiEmbeddedMedia({
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
+131 -51
View File
@@ -1088,6 +1088,10 @@ export function createBhoteKoshiEventLayer({
let _sceneRevealAnimationFrame = null;
let _sceneRevealHoldActive = false;
let _sceneRevealProgress = 1;
// How far a timeline seek's settled-camera reveal had come (0..1, linear).
let _sceneSeekRevealLinear = 1;
// The beat whose clip a run going on from a seek in its hold started again.
let _sceneMediaRestartBeatId = null;
let _cinematicKeyframes = [];
let _cinematicActive = false;
let _cinematicReplayArmed = false;
@@ -1411,6 +1415,16 @@ export function createBhoteKoshiEventLayer({
: null;
}
/** Whether a seek's moment in the hold comes after the shot's clip. */
function sceneSeekPassedMedia(seek) {
if (_sceneControls.evidenceMediaAutoplay !== true) return false;
const mediaDurationSec = Math.max(
SCENE_MEDIA_MIN_PLAYBACK_SECONDS,
Number(_sceneControls.mediaPlaybackHoldSec) || 0,
);
return Math.max(0, Number(seek?.holdElapsedSec) || 0) >= mediaDurationSec;
}
function sceneTimelineMediaVisible() {
const seek = sceneTimelineSeek();
if (!seek || _sceneControls.evidenceMediaAutoplay !== true) return true;
@@ -1540,6 +1554,19 @@ export function createBhoteKoshiEventLayer({
);
}
/**
* Whether a run going on from a seek in this beat's hold started its clip
* again, so the hold has to play out as from its start.
*/
function sceneShotRestartsMedia(beatId) {
return (
_enabled &&
_sceneBeatId === beatId &&
_sceneMediaRestartBeatId === beatId &&
sceneEvidenceMediaAutoplays()
);
}
function getSceneShotMediaHold(beatId) {
if (
!_enabled ||
@@ -1821,6 +1848,7 @@ export function createBhoteKoshiEventLayer({
function applySceneTimelineSeek() {
const seek = sceneTimelineSeek();
if (!seek) return false;
_sceneSeekRevealLinear = 1;
stopScenePathReveal();
stopSceneEvidenceReveal();
stopSceneMediaPlayback();
@@ -1845,6 +1873,43 @@ export function createBhoteKoshiEventLayer({
return true;
}
// The settled-camera reveal waits out the shot's clip and its exit
// (unless the path runs during the clip), then runs for its duration.
const mediaDurationSec =
_sceneControls.evidenceMediaAutoplay === true
? Math.max(
SCENE_MEDIA_MIN_PLAYBACK_SECONDS,
Number(_sceneControls.mediaPlaybackHoldSec) || 0,
)
: 0;
const exitDurationSec =
_sceneControls.evidenceMediaAutoplay === true
? Math.max(
SCENE_MEDIA_EXIT_SECONDS,
Number(_sceneControls.mediaExitDurationSec) || 0,
)
: 0;
const settledDurationSec = Math.max(
0.25,
Number(
sceneUsesSourcePath()
? _sceneControls.evidencePathDurationSec
: sceneEvidenceSequenceAnimates()
? _sceneControls.evidenceSequenceDurationSec
: _sceneControls.evidenceRevealDurationSec,
) || 0.9,
);
const settledStartSec = Math.max(
0,
Number(_sceneControls.evidencePathStartDelaySec) || 0,
_sceneControls.evidencePathDuringMedia === true
? 0
: mediaDurationSec + exitDurationSec,
);
const settledLinear = clampUnit(
(holdElapsedSec - settledStartSec) / settledDurationSec,
);
if (scenePathMovesDuringCamera()) {
const authoredDurationSec = Number(
_sceneControls.evidencePathTravelDurationSec,
@@ -1870,41 +1935,25 @@ export function createBhoteKoshiEventLayer({
Number(_sceneControls.evidenceRevealDurationSec) || 0.9,
),
);
// In the hold, an animated evidence sequence runs on its own clock
// after the camera's path; it stands where that clock has it.
const sequenceWindow =
cameraProgress >= 1 && sceneEvidenceSequenceAnimates()
? evidenceSequenceWindow(_sceneBeatId, _evidenceTimeline)
: null;
if (sequenceWindow) {
_sceneSeekRevealLinear = settledLinear;
_sceneRevealProgress = smoothstep(0, 1, settledLinear);
_progress =
sequenceWindow.startProgress +
(sequenceWindow.targetProgress - sequenceWindow.startProgress) *
_sceneRevealProgress;
}
return true;
}
const mediaDurationSec =
_sceneControls.evidenceMediaAutoplay === true
? Math.max(
SCENE_MEDIA_MIN_PLAYBACK_SECONDS,
Number(_sceneControls.mediaPlaybackHoldSec) || 0,
)
: 0;
const exitDurationSec =
_sceneControls.evidenceMediaAutoplay === true
? Math.max(
SCENE_MEDIA_EXIT_SECONDS,
Number(_sceneControls.mediaExitDurationSec) || 0,
)
: 0;
const pathDurationSec = Math.max(
0.25,
Number(
sceneUsesSourcePath()
? _sceneControls.evidencePathDurationSec
: sceneEvidenceSequenceAnimates()
? _sceneControls.evidenceSequenceDurationSec
: _sceneControls.evidenceRevealDurationSec,
) || 0.9,
);
const pathStartSec = Math.max(
0,
Number(_sceneControls.evidencePathStartDelaySec) || 0,
_sceneControls.evidencePathDuringMedia === true
? 0
: mediaDurationSec + exitDurationSec,
);
const linear = clampUnit((holdElapsedSec - pathStartSec) / pathDurationSec);
const linear = settledLinear;
_sceneSeekRevealLinear = linear;
_sceneRevealProgress = smoothstep(0, 1, linear);
_scenePathRevealProgress =
startProgress + (targetProgress - startProgress) * _sceneRevealProgress;
@@ -2025,7 +2074,11 @@ export function createBhoteKoshiEventLayer({
_scenePathAnimationFrame = requestAnimationFrame(step);
}
function startSceneEvidenceReveal() {
/**
* Start the settled-camera reveal, from `fromLinear` of its way when a run
* goes on from a timeline seek that had already brought it that far.
*/
function startSceneEvidenceReveal(fromLinear = 0) {
stopSceneEvidenceReveal();
const sequenceAnimates = sceneEvidenceSequenceAnimates();
if (
@@ -2069,7 +2122,25 @@ export function createBhoteKoshiEventLayer({
);
if (sequenceWindow) updateProgress(sequenceWindow.startProgress);
let lastTickAt = performance.now();
let activeElapsedMs = 0;
let activeElapsedMs = clampUnit(fromLinear) * durationMs;
const applyReveal = (linear) => {
_sceneRevealProgress = smoothstep(0, 1, linear);
if (sequenceWindow) {
updateProgress(
sequenceWindow.startProgress +
(sequenceWindow.targetProgress - sequenceWindow.startProgress) *
_sceneRevealProgress,
);
} else if (!scenePathMovesDuringCamera()) {
const floodProgress = sourceWindow
? sourceWindow.start +
(sourceWindow.target - sourceWindow.start) * _sceneRevealProgress
: targetFloodProgress * _sceneRevealProgress;
updateFloodTrace(floodProgress);
updateSurgeFront(floodProgress);
}
};
if (activeElapsedMs > 0) applyReveal(activeElapsedMs / durationMs);
renderHost.hold(SCENE_REVEAL_RENDER_HOLD);
_sceneRevealHoldActive = true;
const step = (now) => {
@@ -2086,21 +2157,7 @@ export function createBhoteKoshiEventLayer({
activeElapsedMs += tickAt - lastTickAt;
lastTickAt = tickAt;
const linear = clampUnit(activeElapsedMs / durationMs);
_sceneRevealProgress = smoothstep(0, 1, linear);
if (sequenceWindow) {
updateProgress(
sequenceWindow.startProgress +
(sequenceWindow.targetProgress - sequenceWindow.startProgress) *
_sceneRevealProgress,
);
} else if (!scenePathMovesDuringCamera()) {
const floodProgress = sourceWindow
? sourceWindow.start +
(sourceWindow.target - sourceWindow.start) * _sceneRevealProgress
: targetFloodProgress * _sceneRevealProgress;
updateFloodTrace(floodProgress);
updateSurgeFront(floodProgress);
}
applyReveal(linear);
renderHost.request('bhote-koshi-scene-beat-reveal');
if (linear < 1) {
_sceneRevealAnimationFrame = requestAnimationFrame(step);
@@ -3786,6 +3843,7 @@ export function createBhoteKoshiEventLayer({
_sceneControls.cameraTravel?.completed === true;
const previousTravelCancelled =
_sceneControls.cameraTravel?.cancelled === true;
const previousSeek = sceneTimelineSeek();
if (params.presentation === BHOTE_KOSHI_SCENE_PRESENTATION) {
_presentation = BHOTE_KOSHI_SCENE_PRESENTATION;
_sceneSurface =
@@ -3840,6 +3898,27 @@ export function createBhoteKoshiEventLayer({
stopSceneMediaPlayback();
_sceneMediaPlaybackCompletedBeatId = null;
}
// A run going on from a seek inside the settled hold plays on from that
// moment: the reveal continues from where the seek put it, and the clip
// starts again unless the seek was already past it.
const resumesSeek =
previousSeek != null &&
!sceneTimelineSeek() &&
!beatChanged &&
cameraIsSettled &&
cameraWasSettled &&
previouslyDeferred &&
nowDeferred;
if (resumesSeek && sceneSeekPassedMedia(previousSeek))
_sceneMediaPlaybackCompletedBeatId = _sceneBeatId;
if (
resumesSeek &&
sceneEvidenceMediaAutoplays() &&
!sceneSeekPassedMedia(previousSeek)
)
_sceneMediaRestartBeatId = _sceneBeatId;
else if (beatChanged || sceneTimelineSeek())
_sceneMediaRestartBeatId = null;
if (!nowDeferred) {
stopSceneEvidenceReveal();
_sceneRevealProgress = 1;
@@ -3906,9 +3985,9 @@ export function createBhoteKoshiEventLayer({
!timelineSeekActive &&
cameraIsSettled &&
(nowDeferred || sceneEvidenceSequenceAnimates()) &&
(beatChanged || !previouslyDeferred || !cameraWasSettled)
(beatChanged || !previouslyDeferred || !cameraWasSettled || resumesSeek)
) {
startSceneEvidenceReveal();
startSceneEvidenceReveal(resumesSeek ? _sceneSeekRevealLinear : 0);
}
if (!sceneDirected && params.cinematic === true)
startCinematic({ play: params.autoPlay !== false });
@@ -3954,6 +4033,7 @@ export function createBhoteKoshiEventLayer({
setParams,
getParams,
getSceneShotMediaHold,
sceneShotRestartsMedia,
setSceneMediaPlayback,
getStats() {
return {
+175 -1
View File
@@ -34,7 +34,7 @@ import {
usesProviderEmbeddedEvidence,
visibleSegmentCount,
} from './bhoteKoshiEvent.js';
import { SCENE_RECIPES } from '../scenes/recipes.js';
import { SCENE_RECIPES, getSceneAppendRecipeById } from '../scenes/recipes.js';
import { LayerLifecycle } from './lifecycle.js';
import { createBhoteKoshiEmbeddedMedia } from './bhoteKoshiEmbeddedMedia.js';
import { SceneDirector } from '../scenes/director.js';
@@ -415,6 +415,180 @@ test('trimmed scene media holds through provider startup, playback and fade, the
}
});
test('scene media plays again when a run goes on from a seek inside its hold, unless the seek was past the clip', async () => {
const previous = { document: globalThis.document, window: globalThis.window,
requestAnimationFrame: globalThis.requestAnimationFrame,
cancelAnimationFrame: globalThis.cancelAnimationFrame };
installEventDom();
globalThis.window = { setTimeout: () => 1, clearTimeout() {} };
// The reveal's frames are not driven here; only that it starts.
let frames = 0;
globalThis.requestAnimationFrame = () => ++frames;
globalThis.cancelAnimationFrame = () => {};
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
let plays = 0;
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
embeddedMediaFactory: () => ({ warm: () => true, show: () => true, play() { plays++; }, pause() {},
getPlaybackState: () => ({ phase: 'playing' }), hide() {}, destroy() {} }),
});
const controls = { evidenceMediaAutoplay: true, mediaPlaybackHoldSec: 4, cameraSettled: true,
deferEvidenceUntilCameraSettled: true };
const params = (sceneControls) => ({ presentation: 'scene-beat', sceneSurface: 'evidence-beat',
beatId: 'mailung-bazzar', sceneContext: { sceneId: 'scene', shotId: 'shot', holdSec: 7.65 }, sceneControls });
const seek = (holdElapsedSec) => ({ ...controls,
timelineSeek: { cameraProgress: 1, holdElapsedSec, holdDurationSec: 7.65, flightDurationSec: 2 } });
try {
const viewer = eventViewer();
await layer.init(viewer);
layer.setSceneMediaPlayback({ sceneId: 'scene', shotId: 'shot', token: { cancelled: false } });
// A seek 1 s into the hold shows that moment and plays nothing.
layer.setParams(params(seek(1)), { origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
assert.equal(plays, 0);
assert.equal(layer.getSceneShotMediaHold('mailung-bazzar'), null);
// The run goes on from there: the clip starts again and holds the shot.
const framesBefore = frames;
layer.setParams(params(controls), { origin: 'scene' });
assert.ok(frames > framesBefore, 'the reveal runs again');
assert.ok(plays > 0, 'the clip plays');
assert.equal(layer.getSceneShotMediaHold('mailung-bazzar').pending, true);
// A seek after the clip goes on without it.
layer.setParams(params(seek(6)), { origin: 'scene' });
const before = plays;
layer.setParams(params(controls), { origin: 'scene' });
assert.equal(plays, before, 'the clip already played');
assert.equal(layer.getSceneShotMediaHold('mailung-bazzar').pending, false);
} finally { await layer.destroy(); Object.assign(globalThis, previous); }
});
test('a run going on from a seek in Timure’s hold resumes its evidence sequence from that point', async () => {
const keys = ['document', 'window', 'performance', 'requestAnimationFrame', 'cancelAnimationFrame'];
const previous = Object.fromEntries(keys.map((key) => [key, globalThis[key]]));
installEventDom();
let now = 1000;
let nextFrame = 0;
const frames = new Map();
globalThis.window = { setTimeout: () => 1, clearTimeout() {} };
globalThis.performance = { now: () => now };
globalThis.requestAnimationFrame = (callback) => { frames.set(++nextFrame, callback); return nextFrame; };
globalThis.cancelAnimationFrame = (id) => frames.delete(id);
const frame = (ms) => {
now += ms;
const callback = frames.get(nextFrame);
frames.delete(nextFrame);
callback?.(now);
};
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async () => null,
mediaLoader: async () => { throw Object.assign(new Error('fixture'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
embeddedMediaFactory: () => ({ warm: () => true, show: () => true, play() {}, pause() {},
getPlaybackState: () => ({ phase: 'completed' }), hide() {}, destroy() {} }),
});
const recipe = getSceneAppendRecipeById('bhote-koshi-nepal-evidence-pack');
const controls = { ...recipe.runtimeControlsByBeat['timure-cluster'], cameraSettled: true };
assert.equal(controls.evidenceSequence, true);
assert.equal(controls.evidencePathDuringCamera, true);
const params = (sceneControls) => ({ presentation: 'scene-beat', sceneSurface: 'evidence-beat',
beatId: 'timure-cluster', sceneControls });
// The sequence waits out the 6 s clip and its 0.65 s exit, then runs 12 s:
// 8 s into the hold it is 1.35 s along.
const seek = { ...controls,
timelineSeek: { cameraProgress: 1, holdElapsedSec: 8, holdDurationSec: 12, flightDurationSec: 2 } };
const at = (holdElapsedSec) => {
layer.setParams(params({ ...seek, timelineSeek: { ...seek.timelineSeek, holdElapsedSec } }),
{ origin: 'scene' });
return layer.getPlaybackState().progress;
};
try {
const viewer = eventViewer();
await layer.init(viewer);
layer.setParams(params(seek), { origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
// Where the sequence starts and ends, and where the seek puts it.
const start = at(0);
const end = at(30);
const atSeek = at(8);
assert.ok(start < atSeek && atSeek < end, `the seek shows the sequence partway (${start} < ${atSeek} < ${end})`);
// The run goes on: the sequence carries on from that point, not 0 or its end.
layer.setParams(params(controls), { origin: 'scene' });
assert.ok(Math.abs(layer.getPlaybackState().progress - atSeek) < 1e-9, 'it starts where the seek stood');
frame(1000);
const later = layer.getPlaybackState().progress;
assert.ok(atSeek < later && later < end, `and moves on from there (${atSeek} < ${later} < ${end})`);
} finally { await layer.destroy(); Object.assign(globalThis, previous); }
});
test('a run going on from a seek in Gyirong’s hold plays its restarted clip out before the next shot', async () => {
const previous = { document: globalThis.document, window: globalThis.window,
requestAnimationFrame: globalThis.requestAnimationFrame, cancelAnimationFrame: globalThis.cancelAnimationFrame };
installEventDom();
globalThis.window = { setTimeout: () => 1, clearTimeout() {} };
globalThis.requestAnimationFrame = () => 1;
globalThis.cancelAnimationFrame = () => {};
const event = JSON.parse(await readFile(eventUrl, 'utf8'));
let plays = 0;
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
terrainSampler: async (_viewer, observations) => observations.map(() => ({ height: 800 })),
mediaLoader: async () => { throw Object.assign(new Error('No bundled clip'), { name: 'AbortError' }); },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
renderHost: { request() {}, hold() {}, release() {} },
embeddedMediaFactory: () => ({ warm: () => true, show: () => true, play() { plays++; }, pause() {},
getPlaybackState: () => ({ phase: 'playing' }), hide() {}, destroy() {} }),
});
const recipe = getSceneAppendRecipeById('bhote-koshi-nepal-evidence-pack');
const controls = { ...recipe.runtimeControlsByBeat['gyirong-border-gate'], cameraSettled: true };
const params = (sceneControls) => ({ presentation: 'scene-beat', sceneSurface: 'evidence-beat',
beatId: 'gyirong-border-gate', sceneContext: { sceneId: 'scene', shotId: 'shot', holdSec: 9.15 }, sceneControls });
const token = { cancelled: false, signal: new AbortController().signal };
const hold = async (resume) => {
const waits = [];
await SceneDirector.prototype._holdShot.call({
_layerStatesForShot: () => ({ [layer.id]: { enabled: true, params: params(controls) } }),
dataManager: { layers: new Map([[layer.id, { module: layer }]]) },
_effectiveShotHoldSec: () => 9.15,
_sleep: async (ms) => waits.push(ms),
stopScene: () => assert.fail('no timeout'),
}, { id: 'scene' }, { id: 'shot' }, token, resume);
return waits;
};
try {
const viewer = eventViewer();
await layer.init(viewer);
layer.setSceneMediaPlayback({ sceneId: 'scene', shotId: 'shot', token });
// 5 s into the 9.15 s hold, inside the 6 s clip, which has no media gate.
const resume = { holdElapsedSec: 5, holdDurationSec: 9.15 };
layer.setParams(params({ ...controls, timelineSeek: { cameraProgress: 1, ...resume, flightDurationSec: 2 } }),
{ origin: 'scene' });
await layer.enable(viewer, { origin: 'scene' });
assert.equal(layer.getSceneShotMediaHold('gyirong-border-gate'), null, 'the clip is not trimmed');
layer.setParams(params(controls), { origin: 'scene' });
assert.ok(plays > 0, 'the clip starts again');
assert.equal(layer.sceneShotRestartsMedia('gyirong-border-gate'), true);
assert.deepEqual(await hold(resume), [9150], 'the hold plays out as from its start, not 4.15 s');
// A seek after the clip: only the rest of the hold.
const late = { holdElapsedSec: 8, holdDurationSec: 9.15 };
layer.setParams(params({ ...controls, timelineSeek: { cameraProgress: 1, ...late, flightDurationSec: 2 } }),
{ origin: 'scene' });
layer.setParams(params(controls), { origin: 'scene' });
assert.equal(layer.sceneShotRestartsMedia('gyirong-border-gate'), false);
const [rest] = await hold(late);
assert.ok(Math.abs(rest - 1150) < 1e-6, String(rest));
} finally { await layer.destroy(); Object.assign(globalThis, previous); }
});
test('Pinokio source-card fallback selects authored Director dwell, not an impossible player hold', async () => {
const previous = { document: globalThis.document, window: globalThis.window };
installEventDom();
File diff suppressed because it is too large. Load diff
+506
View File
@@ -0,0 +1,506 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
aircraftInsights,
describeEntity,
findRecord,
formatFact,
layerBreakdown,
nearbyEntities,
recordTitle,
recordWarnings,
searchEntities,
viewSummary,
} from './entityContext.js';
/** A data manager over fixed layer records. */
function manager(layers) {
const map = new Map(
Object.entries(layers).map(([id, { name, records }]) => [
id,
{ id, name, enabled: true, module: { getAnalystRecords: () => records } },
]),
);
return {
layers: map,
isEnabled: (id) => map.get(id)?.enabled === true,
getAll: () => [...map.values()],
};
}
const flights = Array.from({ length: 2500 }, (_, i) => ({
id: `FLT${i}`,
icao24: `a${String(i).padStart(5, '0')}`,
callsign: `FLT${i}`,
lat: 34 + i * 0.001,
lon: -118,
altitudeM: 10000,
}));
const dams = [
{
id: 'Grand Coulee Dam',
name: 'Grand Coulee Dam',
lat: 47.957,
lon: -118.981,
operator: 'Bureau of Reclamation',
},
{
id: '123456',
name: null,
lat: 47.9,
lon: -118.9,
operator: 'Some Utility',
},
];
const dm = manager({
flights: { name: 'Live Flights', records: flights },
'local-dams': { name: 'Dams', records: dams },
});
test('a click identity finds its record by key, past the first 2000 records', () => {
const record = findRecord(dm, {
layerId: 'flights',
id: 'a02400',
lat: 0,
lon: 0,
});
assert.equal(record?.callsign, 'FLT2400');
});
test('a transit click finds its vehicle by the layer key and reads its state', () => {
const buses = manager({
transit: {
name: 'Transit',
records: [
{
id: 'M634',
key: 'capmetro-austin:M634',
route: '801',
operator: 'CapMetro',
status: 'IN_TRANSIT_TO',
lat: 30.2,
lon: -97.7,
},
],
},
});
const card = describeEntity(buses, {
layerId: 'transit',
id: 'capmetro-austin:M634',
lat: 30.21,
lon: -97.71,
});
assert.equal(card?.title, 'M634');
const facts = Object.fromEntries(
card.facts.map((fact) => [fact.label, fact.value]),
);
assert.equal(facts.Operator, 'CapMetro');
assert.equal(facts.Status, 'Heading to next stop');
assert.equal(facts.Key, undefined, 'the layer key is not shown');
});
test('transit vehicles break down by motion, mode and reported state', () => {
const at = { lat: 30.2, lon: -97.7 };
const buses = manager({
transit: {
name: 'Transit',
records: [
{
id: '1',
mode: 'bus',
motion: 'moving',
status: 'IN_TRANSIT_TO',
...at,
},
{
id: '2',
mode: 'bus',
motion: 'stopped',
status: 'STOPPED_AT',
...at,
},
{ id: '3', mode: 'rail', motion: 'moving', occupancy: 'FULL', ...at },
],
},
});
const breakdown = layerBreakdown(buses, 'transit');
assert.equal(breakdown.total, 3);
const split = (title) =>
Object.fromEntries(
breakdown.splits
.find((item) => item.title === title)
.parts.map((part) => [part.label, part.count]),
);
assert.deepEqual(split('Motion'), { Moving: 2, Stopped: 1 });
assert.deepEqual(split('Mode'), { Bus: 2, Rail: 1 });
assert.deepEqual(split('Last reported'), {
'Heading to next stop': 1,
'Stopped at a stop': 1,
});
assert.deepEqual(split('Crowding'), { Full: 1 });
});
test('a moving item never borrows a nearby craft when its key is unknown', () => {
const record = findRecord(dm, {
layerId: 'flights',
id: 'zzzzzz',
label: 'NOPE',
lat: 34.0004,
lon: -118.05,
});
assert.equal(record, null);
});
test('an unnamed site goes by its operator, not its database number', () => {
assert.equal(recordTitle(dams[1]), 'Some Utility');
});
test('a card lists facts with units and keeps the title out of them', () => {
const card = describeEntity(dm, { layerId: 'flights', id: 'a00001' });
assert.equal(card.title, 'FLT1');
assert.equal(card.kind, 'aircraft');
assert.ok(
card.facts.some(
(fact) => fact.label === 'Altitude' && fact.value === '32,808 ft',
),
);
assert.ok(!card.facts.some((fact) => fact.value === 'FLT1'));
});
test('nearby lists the closest of the same kind and one of each other layer', () => {
const card = describeEntity(dm, {
layerId: 'local-dams',
id: 'Grand Coulee Dam',
});
const { same, other } = nearbyEntities(dm, card, { radiusKm: 2000 });
assert.equal(same[0].title, 'Some Utility');
assert.equal(other.length, 1);
assert.equal(other[0].layerId, 'flights');
});
test('search ranks an exact name first and needs two characters', () => {
assert.deepEqual(searchEntities(dm, 'f'), []);
const [first] = searchEntities(dm, 'FLT12');
assert.equal(first.title, 'FLT12');
assert.equal(searchEntities(dm, 'coulee')[0]?.title, 'Grand Coulee Dam');
});
test('fact formatting follows the field suffix', () => {
assert.equal(formatFact('speedMps', 100).value, '194 kt');
// Orbital speeds read in km/s, road and rail in km/h.
assert.equal(formatFact('speedMps', 7670).value, '7.67 km/s');
assert.equal(
formatFact('speedMps', 10, { kind: 'vehicle' }).value,
'36 km/h',
);
// Units follow the field's suffix; feed codes and bare words read as words.
assert.equal(formatFact('containedPct', 96).value, '96%');
assert.equal(formatFact('windKt', 30).value, '30 kt');
assert.equal(formatFact('pressureHpa', 1009).value, '1,009 hPa');
assert.equal(formatFact('classification', 'TD').value, 'Tropical depression');
assert.equal(formatFact('telecom', 'data_center').value, 'Data center');
assert.equal(formatFact('icao24', 'abcdef').value, 'abcdef');
assert.equal(formatFact('shipType', 70).value, 'Cargo');
assert.equal(formatFact('shipType', 'Tanker').value, 'Tanker');
assert.equal(
formatFact('discoveredTime', Date.UTC(2026, 5, 29)).value,
'29 Jun 2026',
);
assert.equal(
formatFact('updatedTime', 1_700_000_000_000, { nowMs: 1_700_000_060_000 })
.age,
60_000,
);
assert.equal(formatFact('altitudeM', 420000).value, '420 km');
assert.equal(formatFact('confidence', 0.82).value, '82%');
assert.equal(formatFact('onGround', false), null);
assert.equal(
formatFact('lastContactAtMs', 1_700_000_000_000, {
nowMs: 1_700_000_060_000,
}).age,
60_000,
);
});
test('warnings lead with an emergency, then the squawk code, and stay out of the facts', () => {
assert.deepEqual(
recordWarnings({ emergency: true, emergencyKind: 'medical' }),
['Emergency: medical'],
);
assert.deepEqual(recordWarnings({ squawk: '7600' }), [
'Radio failure (squawk 7600)',
]);
assert.deepEqual(
recordWarnings({ squawk: '1200', emergencyKind: 'none' }),
[],
);
assert.deepEqual(recordWarnings({ tsunami: 1 }), ['Tsunami warning issued']);
const urgent = manager({
flights: {
name: 'Live Flights',
records: [
{
id: 'X1',
icao24: 'x00001',
callsign: 'X1',
lat: 1,
lon: 1,
emergency: true,
emergencyKind: 'fuel',
},
],
},
});
const card = describeEntity(urgent, { layerId: 'flights', id: 'x00001' });
assert.deepEqual(card.warnings, ['Emergency: fuel']);
assert.ok(!card.facts.some((fact) => /emergency/i.test(fact.label)));
});
test('the view summary counts each layer inside the view, closest to the middle first', () => {
const groups = viewSummary(
dm,
{ west: -119, south: 34, east: -117, north: 34.5 },
{ lat: 34.1, lon: -118 },
{ perLayer: 2 },
);
assert.equal(groups.length, 1);
assert.equal(groups[0].layerId, 'flights');
assert.equal(groups[0].count, 501);
assert.equal(groups[0].items[0].title, 'FLT100');
});
test('flight insights work out phase, flight level, Mach, squawk meaning and signal age', () => {
const insights = aircraftInsights(
{
altitudeM: 10668,
verticalRateMps: 0,
speedMps: 230,
squawk: '7000',
lastContactAtMs: 1_000_000,
},
{ nowMs: 1_012_000 },
);
const value = (label) => insights.find((item) => item.label === label)?.value;
assert.equal(value('Phase'), 'Cruising, level');
assert.equal(value('Flight level'), 'FL350');
assert.equal(value('Mach'), 'M 0.78');
assert.equal(value('Squawk {code}'), 'VFR conspicuity');
assert.deepEqual(
insights.find((item) => item.label === 'Squawk {code}').labelValues,
{ code: '7000' },
);
assert.equal(value('Signal'), '12 s ago');
assert.equal(aircraftInsights({ onGround: true })[0].value, 'On the ground');
assert.match(
aircraftInsights({ verticalRateMps: -8 })[0].value,
/^Descending 1600 ft\/min$/,
);
});
test('a layer breakdown splits aircraft by status and type, inside a view when given', () => {
const craft = [
{
id: 'A',
lat: 10,
lon: 10,
onGround: false,
military: false,
aircraftClass: 'airliner',
},
{
id: 'B',
lat: 10,
lon: 11,
onGround: false,
military: true,
aircraftClass: 'fastjet',
},
{
id: 'C',
lat: 10,
lon: 12,
onGround: true,
military: true,
aircraftClass: 'airliner',
},
{
id: 'D',
lat: 60,
lon: 12,
onGround: false,
military: false,
aircraftClass: 'airliner',
},
];
const data = manager({
flights: { name: 'Live Flights', records: craft },
'local-dams': { name: 'Dams', records: dams },
});
const all = layerBreakdown(data, 'flights');
assert.equal(all.total, 4);
assert.deepEqual(all.splits[0].parts, [
{ label: 'Civilian, in the air', count: 2 },
{ label: 'Military, in the air', count: 1 },
{ label: 'On the ground', count: 1 },
]);
assert.deepEqual(all.splits[1].parts, [
{ label: 'Airliners', count: 3 },
{ label: 'Fast jets', count: 1 },
]);
const near = layerBreakdown(data, 'flights', {
rect: { west: 9, east: 13, south: 9, north: 11 },
});
assert.equal(near.total, 3);
assert.equal(layerBreakdown(data, 'local-dams'), null);
});
test('a moving item with an unknown key is not matched to a craft right beside it', () => {
// About 110 m from FLT0: well inside any nearest-item reach.
assert.equal(
findRecord(dm, {
layerId: 'flights',
id: 'zzzzzz',
label: 'NOPE',
lat: 34.001,
lon: -118,
}),
null,
);
});
test('sites that share a key are told apart by where the identity says they are', () => {
const sites = [
{
id: 'Amazon Web Services',
name: 'Amazon Web Services',
lat: -52.942,
lon: -70.849,
},
{
id: 'Amazon Web Services',
name: 'Amazon Web Services',
lat: -33.557,
lon: -70.813,
},
];
const data = manager({
'local-datacenters': { name: 'Datacenters', records: sites },
});
const identity = {
layerId: 'local-datacenters',
id: 'Amazon Web Services',
label: 'Amazon Web Services',
lat: -33.557,
lon: -70.813,
};
assert.equal(findRecord(data, identity), sites[1]);
const card = describeEntity(data, identity);
assert.equal(card.lat, -33.557);
// The card's own identity finds the same site again, as its refresh does.
assert.equal(findRecord(data, card.identity), sites[1]);
});
test('a link is built only from a language code, and a level is not a warning', () => {
const site = {
id: 'X',
name: 'X',
lat: 1,
lon: 1,
wikipedia: 'evil.example/a#:Y',
};
const data = manager({ 'local-dams': { name: 'Dams', records: [site] } });
assert.deepEqual(
describeEntity(data, { layerId: 'local-dams', id: 'X', lat: 1, lon: 1 })
.links,
[],
);
assert.deepEqual(recordWarnings({ alert: 'green' }), []);
});
test('a breakdown names "Other" once', () => {
const ships = [30, 30, 70, 70, 70, 80, 80, 60, 37, 52, 52, 90, 90, 90].map(
(shipType, i) => ({
id: `S${i}`,
mmsi: String(i),
lat: 1,
lon: 1 + i * 0.01,
shipType,
}),
);
const data = manager({
'ais-live-vessels': { name: 'Vessels', records: ships },
});
const labels = layerBreakdown(data, 'ais-live-vessels').splits[0].parts.map(
(part) => part.label,
);
assert.equal(labels.filter((label) => label === 'Other').length <= 1, true);
assert.equal(new Set(labels).size, labels.length);
});
test('a card shows the photo its layer looked up: the tracked airliner, the selected vessel', () => {
const photo = {
src: 'https://cdn.example/p.jpg',
link: 'https://example/p',
photographer: 'A. Spotter',
width: 640,
};
const planes = manager({
flights: {
name: 'Live Flights',
records: [
{
id: 'DAL1',
icao24: 'aa0001',
callsign: 'DAL1',
lat: 34,
lon: -118,
typeCode: 'B739',
category: 'A3',
},
{ id: 'DAL2', icao24: 'aa0002', callsign: 'DAL2', lat: 35, lon: -118 },
],
},
'ais-live-vessels': {
name: 'Vessels',
records: [
{
id: 'EVER GIVEN',
vesselId: 'v1',
mmsi: '353136000',
lat: 30,
lon: 32,
},
],
},
});
planes.layers.get('flights').module.getTrackedSubject = () => ({
id: 'aa0001',
photo,
});
planes.layers.get('ais-live-vessels').module.getVesselPhoto = (id) =>
id === 'v1' ? { ...photo, licence: 'CC BY 4.0' } : null;
const tracked = describeEntity(planes, { layerId: 'flights', id: 'aa0001' });
assert.deepEqual(tracked.photo, {
src: photo.src,
link: photo.link,
photographer: 'A. Spotter',
licence: '',
});
// What picks the globe's fleet model for it.
assert.deepEqual(tracked.aircraftModel, {
typeCode: 'B739',
category: 'A3',
callsign: 'DAL1',
});
// Photos are looked up for the tracked plane only.
assert.equal(
describeEntity(planes, { layerId: 'flights', id: 'aa0002' }).photo,
null,
);
assert.equal(
describeEntity(planes, { layerId: 'ais-live-vessels', id: 'EVER GIVEN' })
.photo.licence,
'CC BY 4.0',
);
});
+9
View File
@@ -538,6 +538,15 @@ export function fleetModelSet() {
return loaded;
}
/**
* The load a layer has started (resolving to the set), or null when none
* has: for a view that needs the set but does not fetch it itself.
* @returns {Promise<object>|null}
*/
export function fleetModelSetLoading() {
return loading;
}
/**
* Fetch the model set once for every layer: `catalog.json`, `types.json` and
* every GLB the catalog names, all up front, so no model is fetched while a
+7
View File
@@ -91,6 +91,8 @@ const FULL_INFO = {
verticalRate: -4.5,
onGround: false,
klass: 'airliner',
typeCode: 'B738',
category: 'A3',
originCountry: 'United States',
airline: 'Southwest Airlines',
route: { origin: { code: 'AUS' }, destination: { code: 'LAX' } },
@@ -114,6 +116,8 @@ test('flights analyst record: full record maps every contract field', () => {
onGround: false,
military: false,
aircraftClass: 'airliner',
typeCode: 'B738',
category: 'A3',
originCountry: 'United States',
operator: 'Southwest Airlines',
squawk: null,
@@ -124,6 +128,9 @@ test('flights analyst record: full record maps every contract field', () => {
lastContactAtMs: null,
routeOrigin: 'AUS',
routeDestination: 'LAX',
routeFrom: null,
routeTo: null,
routeScheduled: null,
});
});
+4 -2
View File
@@ -167,8 +167,10 @@ test('pointer input, camera holds and the stock clicks go through the one dispat
[
/\.enableInputs\s*=(?!=)/,
'writes enableInputs instead of suspendCamera()',
// The scene's camera-input holds, which own the flag.
['src/render/cesium/cameraInput.js'],
// The scene's camera-input holds, which own the flag; the Context
// card's previews turn it off in their own small scenes, which take
// no input at all.
['src/render/cesium/cameraInput.js', 'src/render/cesium/cardPreviews.js'],
],
[
/(?:screenSpaceEventHandler|stockHandler)\??\.removeInputAction\(/,
+2 -1
View File
@@ -1370,8 +1370,9 @@ test('a cached Context subject re-reads its label when enrichment lands after se
/N123AB/,
'the rendered Context panel must show the registration without a position change',
);
// `subjectIdentity` is the subject's id for matching, never shown.
assert.doesNotMatch(
JSON.stringify(repainted.view),
JSON.stringify({ ...repainted.view, subjectIdentity: undefined }),
/ae1fa4/,
'the hex must be gone from the panel',
);