From 0a0c6a0e5ba345e1cda68eaa10282fc48f666e3f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sun, 15 Nov 2026 23:56:03 -0800 Subject: [PATCH 01/70] Vessel playback moves icons on the renderer's clock While the timeline plays or is scrubbed, each vessel icon is handed to the renderer as a motion segment along its track (a straight piece of at most 10 km between two fixes, on the scene clock), as aircraft already are. The layer writes an icon again only when its segment runs out or the time moves back before it, instead of moving every icon on the CPU every frame. Behaviour is kept: - Icons follow the same great-circle track between fixes (a 10 km chord stays within 2 m of it) with the same course. - A vessel still appears TIMELINE_UNSEEN_MS before its first fix and hides again when the time moves back before that. - Cards, the selected vessel, ship models and the vessel the bridge camera rides are read where they are every frame; the rest within HIDDEN_FOLLOW_MS, as before. - Position reads (getAllPositions, getNearby, the focus pass, the detection overlay, single-vessel lookups) return where the icon is drawn at the world time. - Going live, each icon holds where its segment last drew it, unless a live update has drawn it since. - Trails are unchanged: they are built from the feed's fixes, not from the per-frame position. - Live mode and renderers without the motionSegments capability take the previous path unchanged. --- src/layers/vessels/motion.js | 86 ++++++- src/layers/vessels/motion.test.mjs | 80 +++++- src/layers/vessels/motionSegments.test.mjs | 284 +++++++++++++++++++++ src/layers/vessels/queries.js | 5 +- src/layers/vessels/rendering.js | 279 +++++++++++++++++++- src/layers/vessels/testing.js | 23 +- src/testSupport/fakeCesiumScene.mjs | 10 +- 7 files changed, 746 insertions(+), 21 deletions(-) create mode 100644 src/layers/vessels/motionSegments.test.mjs diff --git a/src/layers/vessels/motion.js b/src/layers/vessels/motion.js index 60c8038b15..564b0aa058 100644 --- a/src/layers/vessels/motion.js +++ b/src/layers/vessels/motion.js @@ -54,10 +54,94 @@ export function vesselPositionAt(record, tMs) { } const RAD = Math.PI / 180; +/** The mean Earth radius (metres) a span's length is judged on. */ +const EARTH_RADIUS_M = 6371008.8; + +/** + * The stretch of a vessel's track around world time `tMs`, as + * vesselPositionAt draws it: between the last fix at or before the time and + * the next one (`move`, which always ends after `tMs`), or where it holds + * still (`hold`) before its first fix, after its last, or around a record's + * one move; from when (`fromMs`) until when (`untilMs`) the answer holds. + * Null for a vessel the clock never moves (no fixes and no move). + * @param {object} record + * @param {number} tMs + * @returns {{kind: 'move', lat0: number, lon0: number, t0: number, + * lat1: number, lon1: number, t1: number, metres: number}| + * {kind: 'hold', lat: number, lon: number, fromMs: number, + * untilMs: number}|null} + */ +export function vesselSpanAt(record, tMs) { + if (!Number.isFinite(tMs)) return null; + const fixes = record?.fixes; + if (fixes?.length >= 2) { + const first = fixes[0]; + const last = fixes[fixes.length - 1]; + if (tMs < first.atMs) + return hold(first.lat, first.lon, -Infinity, first.atMs); + if (tMs >= last.atMs) return hold(last.lat, last.lon, last.atMs, Infinity); + // The first fix after the time: the one before it is at or before it. + let low = 1; + let high = fixes.length - 1; + while (low < high) { + const mid = (low + high) >> 1; + if (fixes[mid].atMs <= tMs) low = mid + 1; + else high = mid; + } + const a = fixes[low - 1]; + const b = fixes[low]; + return move(a.lat, a.lon, a.atMs, b.lat, b.lon, b.atMs); + } + const motion = record?.motion; + if (!motion || !(motion.toMs > motion.fromMs)) return null; + if (tMs < motion.fromMs) + return hold(motion.fromLat, motion.fromLon, -Infinity, motion.fromMs); + if (tMs >= motion.toMs) + return hold(record.lat, record.lon, motion.toMs, Infinity); + return move( + motion.fromLat, + motion.fromLon, + motion.fromMs, + motion.toLat, + motion.toLon, + motion.toMs, + ); +} + +const hold = (lat, lon, fromMs, untilMs) => ({ + kind: 'hold', + lat, + lon, + fromMs, + untilMs, +}); + +function move(lat0, lon0, t0, lat1, lon1, t1) { + return { + kind: 'move', + lat0, + lon0, + t0, + lat1, + lon1, + t1, + metres: greatCircleAngle(lat0, lon0, lat1, lon1) * EARTH_RADIUS_M, + }; +} + +/** The angle (radians) between two positions, seen from the Earth's centre. */ +function greatCircleAngle(lat1, lon1, lat2, lon2) { + const phi1 = lat1 * RAD; + const phi2 = lat2 * RAD; + const s = + Math.sin((phi2 - phi1) / 2) ** 2 + + Math.cos(phi1) * Math.cos(phi2) * Math.sin(((lon2 - lon1) * RAD) / 2) ** 2; + return 2 * Math.asin(Math.min(1, Math.sqrt(s))); +} /** The point `fraction` of the way from one position to another. It runs * for every drawn vessel as the clock plays, so it builds no arrays. */ -function greatCircleAt(lat1, lon1, lat2, lon2, fraction) { +export function greatCircleAt(lat1, lon1, lat2, lon2, fraction) { const phi1 = lat1 * RAD; const lambda1 = lon1 * RAD; const phi2 = lat2 * RAD; diff --git a/src/layers/vessels/motion.test.mjs b/src/layers/vessels/motion.test.mjs index 79378853f5..58d2509c4e 100644 --- a/src/layers/vessels/motion.test.mjs +++ b/src/layers/vessels/motion.test.mjs @@ -1,6 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { fixesMove, vesselPositionAt } from './motion.js'; +import { + fixesMove, + greatCircleAt, + vesselPositionAt, + vesselSpanAt, +} from './motion.js'; const record = { lat: 1, @@ -61,3 +66,76 @@ test('fixes that stay in one place do not move a vessel', () => { ); assert.equal(fixesMove(null), false); }); + +const fixes = [ + { atMs: 1_000, lat: 0, lon: 0 }, + { atMs: 2_000, lat: 0, lon: 1 }, + { atMs: 3_000, lat: 1, lon: 1 }, +]; + +test('vesselSpanAt holds at the first fix before it, until it', () => { + assert.deepEqual(vesselSpanAt({ fixes }, 500), { + kind: 'hold', + lat: 0, + lon: 0, + fromMs: -Infinity, + untilMs: 1_000, + }); +}); + +test('vesselSpanAt runs from the fix at or before the time to the next, ending after it', () => { + for (const [atMs, t0, t1] of [ + [1_000, 1_000, 2_000], + [1_999, 1_000, 2_000], + [2_000, 2_000, 3_000], + [2_500, 2_000, 3_000], + ]) { + const span = vesselSpanAt({ fixes }, atMs); + assert.equal(span.kind, 'move'); + assert.deepEqual([span.t0, span.t1], [t0, t1], `at ${atMs}`); + assert.ok(span.t1 > atMs); + } + // A degree of longitude on the equator. + assert.ok(Math.abs(vesselSpanAt({ fixes }, 1_500).metres - 111_195) < 10); +}); + +test('vesselSpanAt holds at the last fix from it on', () => { + assert.deepEqual(vesselSpanAt({ fixes }, 3_000), { + kind: 'hold', + lat: 1, + lon: 1, + fromMs: 3_000, + untilMs: Infinity, + }); +}); + +test("vesselSpanAt follows a record's one move, and nothing for none", () => { + assert.equal(vesselSpanAt(record, 500).untilMs, 1_000); + const span = vesselSpanAt(record, 1_500); + assert.equal(span.kind, 'move'); + assert.deepEqual([span.lat0, span.lat1], [0, 1]); + assert.deepEqual(vesselSpanAt(record, 9_000), { + kind: 'hold', + lat: 1, + lon: 1, + fromMs: record.motion.toMs, + untilMs: Infinity, + }); + assert.equal(vesselSpanAt({ lat: 1, lon: 1 }, 1_500), null); +}); + +test('vesselSpanAt agrees with vesselPositionAt along the span', () => { + for (const atMs of [1_000, 1_250, 2_000, 2_750]) { + const span = vesselSpanAt({ fixes }, atMs); + const at = greatCircleAt( + span.lat0, + span.lon0, + span.lat1, + span.lon1, + (atMs - span.t0) / (span.t1 - span.t0), + ); + const expected = vesselPositionAt({ fixes }, atMs); + assert.ok(Math.abs(at.lat - expected.lat) < 1e-9); + assert.ok(Math.abs(at.lon - expected.lon) < 1e-9); + } +}); diff --git a/src/layers/vessels/motionSegments.test.mjs b/src/layers/vessels/motionSegments.test.mjs new file mode 100644 index 0000000000..bc199a4f4a --- /dev/null +++ b/src/layers/vessels/motionSegments.test.mjs @@ -0,0 +1,284 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { createVesselLayer } from './index.js'; +import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; + +// Following the world clock on a renderer that moves icons along motion +// segments on its own clock, each vessel's icon is drawn along its track +// between two fixes, and the layer draws it again only when that runs out. + +const noop = () => {}; + +function setup(t, { capabilities = new Set(['motionSegments']) } = {}) { + const originalDocument = globalThis.document; + globalThis.document = { getElementById: () => null }; + t.after(() => { + if (originalDocument === undefined) delete globalThis.document; + else globalThis.document = originalDocument; + }); + const layer = createVesselLayer({ + source: { getSnapshot: async () => ({ records: [] }) }, + services: { + context: { + clearSelectedEntityContextForLayer: noop, + registerEntityContext: () => null, + }, + trails: { + createTrail: () => ({ setPositions: noop, clear: noop, destroy: noop }), + }, + labels: { formatKnots: (knots) => `${knots} kt` }, + picking: { unregisterPickOwner: noop }, + overlay: { + setOverlayEntries: noop, + setOverlaySourceVisible: noop, + clearOverlaySource: noop, + }, + geoid: {}, + sprites: {}, + focus: { + focusNowMs: () => 0, + getFocusTarget: () => null, + focusPassIsNeeded: () => false, + forgetSpriteFocus: noop, + }, + worldFocus: {}, + render: { + holdContinuousRender: noop, + releaseContinuousRender: noop, + governorRequestRender: noop, + }, + }, + }); + const camera = { + positionWC: { x: 0, y: 0, z: 7_000_000 }, + heading: 0, + pitch: -1.2, + roll: 0, + }; + const viewer = { camera, scene: {} }; + const { draw } = bindFakeCesiumScene(viewer, { capabilities }); + layer.testing._setVesselStateForTest({ viewer, icons: null }); + layer.testing._setAisRuntimeForTest({ + now: () => 0, + setTimeout: () => 0, + clearTimeout: noop, + }); + const icons = () => + [...draw.sets.values()].find( + (record) => record.kind === 'icons' && !record.disposed, + ); + return { layer, viewer, icons }; +} + +const T = 1_000_000; +/** Northbound off Rotterdam, a fix a minute (about 1.1 km apart). */ +const row = (fixes) => ({ + mmsi: '111', + lat: fixes.at(-1).lat, + lon: fixes.at(-1).lon, + last_position_epoch: fixes.at(-1).atMs / 1000, + fixes, +}); +const minuteFixes = [ + { atMs: T, lat: 51.93, lon: 4.05 }, + { atMs: T + 60_000, lat: 51.94, lon: 4.05 }, + { atMs: T + 120_000, lat: 51.95, lon: 4.05 }, +]; + +test('following the clock, an icon moves along its fixes on the scene clock and is drawn again only when that runs out', (t) => { + const { layer, viewer, icons } = setup(t); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]); + layer.testing._runClockPassForTest(T + 10_000); + const set = icons(); + assert.deepEqual(set.spec.motionClock, { kind: 'scene' }); + let item = set.items.get('111'); + assert.equal(item.motion.kind, 'lerp'); + assert.deepEqual([item.motion.t0, item.motion.t1], [T, T + 60_000]); + const writes = set.writes; + // Within the stretch: the renderer moves it, the layer writes nothing. + for (let atMs = T + 11_000; atMs < T + 60_000; atMs += 1_000) + layer.testing._runClockPassForTest(atMs); + assert.equal(set.writes, writes); + // The stretch runs out: the next one is drawn, once. + layer.testing._runClockPassForTest(T + 60_000); + item = set.items.get('111'); + assert.deepEqual([item.motion.t0, item.motion.t1], [T + 60_000, T + 120_000]); + assert.equal(set.writes, writes + 1); + // Past the last fix, it holds there for good. + layer.testing._runClockPassForTest(T + 200_000); + assert.equal(set.items.get('111').motion.kind, 'hold'); + const held = set.writes; + layer.testing._runClockPassForTest(T + 900_000); + assert.equal(set.writes, held); +}); + +test('a time moved back before the stretch drawn draws the one it is in', (t) => { + const { layer, viewer, icons } = setup(t); + layer.testing._followClockForTest(T + 90_000); + layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]); + layer.testing._runClockPassForTest(T + 90_000); + assert.equal(icons().items.get('111').motion.t0, T + 60_000); + layer.testing._runClockPassForTest(T + 30_000); + const item = icons().items.get('111'); + assert.deepEqual([item.motion.t0, item.motion.t1], [T, T + 60_000]); +}); + +test('a long stretch between fixes is drawn a piece of at most 10 km at a time', (t) => { + const { layer, viewer, icons } = setup(t); + // About 55.6 km in an hour: six pieces of ten minutes. + const fixes = [ + { atMs: T, lat: 51.5, lon: 4.05 }, + { atMs: T + 3_600_000, lat: 52.0, lon: 4.05 }, + ]; + layer.testing._followClockForTest(T + 700_000); + layer.testing._reconcileVesselsForTest(viewer, [row(fixes)]); + layer.testing._runClockPassForTest(T + 700_000); + const { motion } = icons().items.get('111'); + assert.deepEqual([motion.t0, motion.t1], [T + 600_000, T + 1_200_000]); +}); + +test('going live, every icon holds again on the live clock', (t) => { + const { layer, viewer, icons } = setup(t); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]); + layer.testing._runClockPassForTest(T + 10_000); + assert.equal(icons().items.get('111').motion.kind, 'lerp'); + layer.testing._followClockForTest(null); + layer.testing._runLiveFrameForTest(); + assert.equal(icons().items.get('111').motion.kind, 'hold'); + assert.equal(icons().spec.motionClock.kind, 'live'); +}); + +test('a renderer without motion segments has the layer move each icon, as before', (t) => { + const { layer, viewer, icons } = setup(t, { capabilities: new Set() }); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]); + layer.testing._runClockPassForTest(T + 10_000); + assert.equal(icons().items.get('111').motion.kind, 'hold'); + assert.equal(icons().spec.motionClock, undefined); +}); + +test('a vessel shows a minute before its first fix, and hides again when the time moves back before that', (t) => { + const { layer, viewer, icons } = setup(t); + layer.testing._followClockForTest(T - 120_000); + layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]); + layer.testing._runClockPassForTest(T - 120_000); + assert.equal(icons().items.get('111').show, false); + layer.testing._runClockPassForTest(T - 60_000); + assert.equal(icons().items.get('111').show, true); + layer.testing._runClockPassForTest(T - 30_000); + assert.equal(icons().items.get('111').show, true); + layer.testing._runClockPassForTest(T - 90_000); + assert.equal(icons().items.get('111').show, false); +}); + +test('the detection overlay reads a vessel where it is at the time drawn', (t) => { + const { layer, viewer } = setup(t); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, [row(minuteFixes)]); + layer.testing._runClockPassForTest(T + 10_000); + const record = layer.testing._vesselRecordForTest('111'); + const visual = layer.testing._vesselVisualForTest(record); + visual.visible = true; + // Mid-stretch, with no pass reading this vessel since. + layer.testing._followClockForTest(T + 40_000); + const [object] = layer.getDetectableObjects(); + assert.equal(object.sourceId, '111'); + assert.ok(Math.abs(visual.drawnLat - (51.93 + 0.01 * (40 / 60))) < 1e-6); +}); + +/** Three vessels a little apart, each on the minute fixes. */ +const fleet = () => + ['111', '222', '333'].map((mmsi, i) => ({ + ...row(minuteFixes.map((fix) => ({ ...fix, lon: fix.lon + i * 0.01 }))), + mmsi, + })); +const latAt = (atMs) => 51.93 + (0.01 * (atMs - T)) / 60_000; + +test('positions asked of the layer are where the vessels are drawn at the time drawn', (t) => { + const { layer, viewer } = setup(t); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, fleet()); + layer.testing._runClockPassForTest(T + 10_000); + // Mid-stretch, with no pass since. + layer.testing._followClockForTest(T + 40_000); + const latOf = (position) => + Cesium.Math.toDegrees( + Cesium.Cartographic.fromCartesian( + new Cesium.Cartesian3(position.x, position.y, position.z), + ).latitude, + ); + const rows = layer.getAllPositions(); + assert.equal(rows.length, 3); + for (const { id, position } of rows) + assert.ok(Math.abs(latOf(position) - latAt(T + 40_000)) < 1e-5, id); + // One vessel asked of by itself is brought there too. + const record = layer.testing._vesselRecordForTest('222'); + const visual = layer.testing._vesselVisualForTest(record); + layer.findByQuery('222'); + assert.ok(Math.abs(visual.drawnLat - latAt(T + 40_000)) < 1e-6); +}); + +test('going live, every icon holds where its segment last drew it', (t) => { + const { layer, viewer, icons } = setup(t); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, fleet()); + layer.testing._runClockPassForTest(T + 10_000); + layer.testing._runClockPassForTest(T + 40_000); + layer.testing._followClockForTest(null); + layer.testing._runLiveFrameForTest(); + for (const id of ['111', '222', '333']) { + const record = layer.testing._vesselRecordForTest(id); + const visual = layer.testing._vesselVisualForTest(record); + assert.ok(Math.abs(visual.drawnLat - latAt(T + 40_000)) < 1e-6, id); + assert.deepEqual(icons().items.get(id).pos, visual.position); + assert.equal(icons().items.get(id).motion.kind, 'hold'); + } +}); + +test('a time on the end of a piece draws the next piece', (t) => { + const { layer, viewer, icons } = setup(t); + // About 55.6 km in a little under an hour: six pieces, the first of whose + // ends rounds into the piece before it. + const fixes = [ + { atMs: T, lat: 51.5, lon: 4.05 }, + { atMs: T + 3_599_002, lat: 52.0, lon: 4.05 }, + ]; + layer.testing._followClockForTest(T); + layer.testing._reconcileVesselsForTest(viewer, [row(fixes)]); + for (let k = 1; k < 6; k += 1) { + const atMs = T + (3_599_002 * k) / 6; + layer.testing._runClockPassForTest(atMs); + const { motion } = icons().items.get('111'); + assert.ok(motion.t0 <= atMs && atMs < motion.t1, `piece ${k}`); + } +}); + +test('going live, a vessel a live update has drawn since stays where that drew it', (t) => { + const { layer, viewer, icons } = setup(t); + layer.testing._followClockForTest(T + 10_000); + layer.testing._reconcileVesselsForTest(viewer, fleet()); + // A later fix while following: each record keeps the move to it. + const later = { atMs: T + 180_000, lat: 51.96, lon: 4.05 }; + layer.testing._reconcileVesselsForTest( + viewer, + fleet() + .map((r) => row([...r.fixes, { ...later, lon: r.lon }])) + .map((r, i) => ({ ...r, mmsi: ['111', '222', '333'][i] })), + ); + layer.testing._runClockPassForTest(T + 10_000); + layer.testing._runClockPassForTest(T + 40_000); + layer.testing._followClockForTest(null); + // The live feed lands before the next frame, the ship further north. + const live = fleet().map((row) => ({ ...row, lat: 52.1 })); + layer.testing._reconcileVesselsForTest(viewer, live); + layer.testing._runLiveFrameForTest(); + for (const id of ['111', '222', '333']) { + const record = layer.testing._vesselRecordForTest(id); + const visual = layer.testing._vesselVisualForTest(record); + assert.equal(visual.drawnLat, 52.1, id); + assert.deepEqual(icons().items.get(id).pos, visual.position); + } +}); diff --git a/src/layers/vessels/queries.js b/src/layers/vessels/queries.js index 0e98e8c2b9..38bf0f5b7b 100644 --- a/src/layers/vessels/queries.js +++ b/src/layers/vessels/queries.js @@ -366,7 +366,7 @@ export function createQueries({ for (const record of records) { if (!Number.isFinite(record.lat) || !Number.isFinite(record.lon)) continue; - const position = components.rendering.iconPosition(record); + const position = components.rendering.drawnPositionNow(record); if (!position) continue; const distanceM = distance(centerCartesian, position); if (!Number.isFinite(distanceM) || distanceM > range) continue; @@ -471,7 +471,7 @@ export function createQueries({ for (const record of records) { if (result.length >= cap) break; - const position = components.rendering.iconPosition(record); + const position = components.rendering.drawnPositionNow(record); if (!position) continue; result.push({ id: record.id, @@ -664,6 +664,7 @@ export function createQueries({ !visual.modelOwnsVisual ) continue; + components.rendering.readVesselNow(record); const position = visual.position; if (!position) continue; result.push({ diff --git a/src/layers/vessels/rendering.js b/src/layers/vessels/rendering.js index f3b4025e80..221306c835 100644 --- a/src/layers/vessels/rendering.js +++ b/src/layers/vessels/rendering.js @@ -16,6 +16,7 @@ import { findCamera, findFrame, findQuery, + rendererOf, } from '../../render/rendererOf.js'; import { poseSignature } from '../../render/camera/poseSignature.js'; import { createVesselIconBook } from './iconBook.js'; @@ -29,7 +30,12 @@ import { CARD_MIN_SEP_PX, followsClock, } from './policy.js'; -import { fixesMove, vesselPositionAt } from './motion.js'; +import { + fixesMove, + greatCircleAt, + vesselPositionAt, + vesselSpanAt, +} from './motion.js'; import { TIMELINE_UNSEEN_MS } from '../../time/timelineFixes.js'; import { fleetModelSet, @@ -68,6 +74,11 @@ const CAMERA_STEP_FLOOR_M = 100; /** Scratch for where a moved vessel was drawn. */ const _movedFrom = vec(); +/** The longest piece (metres) of the track between two fixes an icon is + * drawn along as one straight line on the renderer's clock: at 10 km the + * line runs under 2 m inside the great circle the layer reads it on. */ +const SEGMENT_PIECE_M = 10000; + export function createRendering({ vesselState, services, @@ -83,11 +94,27 @@ export function createRendering({ return visualRecords.get(record) || record; } - /** Where a record's icon is drawn: its row holds at the visual position. */ + /** Where a record's icon is drawn: its row holds at the visual position + * (brought up to the time drawn while the renderer moves the icons). */ function iconPosition(record) { + readVesselNow(record); return getVisual(record).position; } + /** + * Where a record's icon is drawn now, for a reader of many vessels at + * once: while the renderer moves the icons, its segment at the world time + * (a new position each call); else the visual position, as iconPosition. + */ + function drawnPositionNow(record) { + const visual = getVisual(record); + if (!segmentsOn() || !visual.position) return visual.position; + return ( + state.icons?.position(visual.iconId, vesselState.worldNow()) ?? + visual.position + ); + } + function prepareRecordVisual(record) { let visual = visualRecords.get(record); if (!visual) { @@ -172,7 +199,9 @@ export function createRendering({ fromDegreesInto(lon, lat, heightM - VESSEL_LIFT_M, visual.waterline); visual.drawnLat = lat; visual.drawnLon = lon; - syncRecordIcon(record); + // Moving on the renderer's clock, its icon is where it is already. + if (segmentsOn()) visual.cullPosition = liftedForHorizon(visual.position); + else syncRecordIcon(record); } // Reused projection buffers for the card pass, grown to the candidates. @@ -226,6 +255,9 @@ export function createRendering({ function ensureCollections(viewer) { ensureModels(viewer); if (!viewer || state.icons) return; + const capabilities = rendererOf(viewer)?.capabilities ?? null; + iconMotion = capabilities?.has('motionSegments') === true; + segmentsWere = segmentsOn(); const set = drawOf(viewer).icons({ id: `ais-vessels:${++instances}`, // Translucent, as its billboards were: overlapping chevrons keep @@ -233,18 +265,118 @@ export function createRendering({ blend: 'translucent', horizonCull: true, drawOrder: spriteDrawOrder?.('ais') ?? 0, + ...(iconMotion ? { motionClock: motionClock(segmentsWere) } : null), }); // Columns of no rows put the set's host in the scene now, rather than // with its first vessel. set.setColumns?.({ ids: [] }); - state.icons = createVesselIconBook(set); + iconSet = set; + state.icons = createVesselIconBook(set, { capabilities }); state.icons.show = state.feed.enabled; } + // The icon draw set, and whether its renderer moves icons along motion + // segments on its own clock. + let iconSet = null; + let iconMotion = false; + // Whether the icons last moved on the renderer's clock. + let segmentsWere = false; + // The record drawn under each icon id, for replanning an id. + const iconRecords = new Map(); + // From when (world ms) each planned icon's motion holds: one planned + // after the time drawn is planned again when the time moves back. + const planFrom = new Map(); + // The world time the icons were last checked against. + let replannedAtMs = -Infinity; + + /** + * Whether vessel icons move on the renderer's clock: following the world + * clock, each is drawn along its track between two fixes as a segment the + * renderer moves every frame on the scene's time, and the layer writes an + * icon only when its segment runs out, rather than moving every drawn + * icon each frame. Live, a host placement moves them as before. + */ + function segmentsOn() { + return iconMotion && followsClock(vesselState); + } + + /** The set's motion clock: the scene's time while following the clock. */ + const motionClock = (scene) => + scene ? { kind: 'scene' } : { kind: 'live', delayMs: 0 }; + + /** + * The segment a vessel's icon moves along at world time `atMs`: the piece + * of its track between two fixes the time is in (at most SEGMENT_PIECE_M + * long), or where it holds; with when it runs out and from when it holds. + * Null for a vessel the clock does not move: it holds where it is drawn. + */ + function planMotion(record, atMs) { + if (!record.motion && !fixesMove(record.fixes)) return null; + const span = vesselSpanAt(record, atMs); + if (!span) return null; + if (span.kind === 'hold') { + // Before its first fix it is drawn from TIMELINE_UNSEEN_MS ahead of + // it (seenYet): drawn again when the time crosses that. + let { fromMs, untilMs } = span; + const shownFromMs = record.fixes?.[0]?.atMs - TIMELINE_UNSEEN_MS; + if (fromMs === -Infinity && shownFromMs < untilMs) { + if (atMs < shownFromMs) untilMs = shownFromMs; + else fromMs = shownFromMs; + } + return { + motion: null, + pos: anchorAt(span.lat, span.lon), + expiresAt: untilMs, + validFrom: fromMs, + }; + } + const n = Math.max(1, Math.ceil(span.metres / SEGMENT_PIECE_M)); + const spanMs = span.t1 - span.t0; + const pieceEnd = (i) => (i === n ? span.t1 : span.t0 + (spanMs * i) / n); + let k = Math.min( + n - 1, + Math.max(0, Math.floor(((atMs - span.t0) / spanMs) * n)), + ); + // A time on a piece's end belongs to the next piece, whatever rounding + // says, so a segment is never drawn already run out. + while (k < n - 1 && pieceEnd(k + 1) <= atMs) k += 1; + while (k > 0 && pieceEnd(k) > atMs) k -= 1; + const t0 = pieceEnd(k); + const t1 = pieceEnd(k + 1); + const at = (i) => + i === 0 + ? { lat: span.lat0, lon: span.lon0 } + : i === n + ? { lat: span.lat1, lon: span.lon1 } + : greatCircleAt(span.lat0, span.lon0, span.lat1, span.lon1, i / n); + const a = at(k); + const b = at(k + 1); + const to = anchorAt(b.lat, b.lon); + const courseDeg = vesselCourseDeg(record); + return { + motion: { + kind: 'lerp', + from: anchorAt(a.lat, a.lon), + to, + t0, + t1, + course0Deg: courseDeg, + courseSlopeDeg: 0, + }, + pos: to, + expiresAt: t1, + validFrom: t0, + }; + } + /** Let the icon draw set go (the layer is destroyed). */ function disposeCollections() { state.icons?.dispose(); state.icons = null; + iconSet = null; + iconRecords.clear(); + planFrom.clear(); + replannedAtMs = -Infinity; } /** Whether the Cockpit's bridge camera rides this record's ship. */ @@ -276,20 +408,25 @@ export function createRendering({ const courseDeg = vesselCourseDeg(record); // Following the clock, not there yet at the time drawn. visual.seen = seenYet(record); + const plan = segmentsOn() + ? planMotion(record, vesselState.worldNow()) + : null; + visual.plan = plan; return { id: visual.iconId, // Hidden while the bridge camera rides it, its model draws it, or it // is not there yet. show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen, - pos: visual.position, + pos: plan?.pos ?? visual.position, image: shipIcon(record, selected), size: [SHIP_ICON_PX, SHIP_ICON_PX], // Selection changes the colour only, never the size. scale: shipScale(record), rotationMode: 'course', - // Held on course; `course` for renderers without motion segments. + // Held on course, or along its track on the renderer's clock; + // `course` for renderers without motion segments. course: courseDeg, - motion: { kind: 'hold', courseDeg }, + motion: plan?.motion ?? { kind: 'hold', courseDeg }, focus: state.icons?.focus(visual.iconId) ?? 1, disableDepthTest: Infinity, meta: visual.meta, @@ -308,7 +445,8 @@ export function createRendering({ const visual = getVisual(record); // The pick meta, and the key of the vessel's focus emphasis. visual.meta = { layer: 'ais-live-vessels', id: visual.iconId }; - state.icons.put({ ...iconItem(record, visual), focus: 1 }); + iconRecords.set(visual.iconId, record); + putIcon(visual, { ...iconItem(record, visual), focus: 1 }); if (visual.position) visual.cullPosition = liftedForHorizon(visual.position); visual.visible = isVisible(visual.cullPosition, occluder, record); @@ -325,10 +463,23 @@ export function createRendering({ function syncRecordIcon(record) { const visual = getVisual(record); if (!state.icons?.has(visual.iconId) || !visual.position) return; - state.icons.put(iconItem(record, visual)); + putIcon(visual, iconItem(record, visual)); visual.cullPosition = liftedForHorizon(visual.position); } + /** Draw a vessel's icon item, with when its segment runs out while the + * icons move on the renderer's clock. */ + function putIcon(visual, item) { + if (!segmentsOn()) { + planFrom.delete(item.id); + state.icons.put(item, { expiresAt: null }); + return; + } + const plan = visual.plan; + planFrom.set(item.id, plan?.validFrom ?? -Infinity); + state.icons.put(item, { expiresAt: plan?.expiresAt ?? Infinity }); + } + /** * Remove a record's icon row. * @param {Object} record - Vessel record to tear down. @@ -341,6 +492,8 @@ export function createRendering({ if (!icons?.has(visual.iconId)) return; forgetSpriteFocus(icons.item(visual.iconId).meta); icons.remove(visual.iconId); + iconRecords.delete(visual.iconId); + planFrom.delete(visual.iconId); } function shipScale(record) { @@ -548,7 +701,8 @@ export function createRendering({ state.preRenderRemover = findFrame(viewer)?.on('preRender', () => { if (state.feed.enabled) { - if (followsClock(vesselState)) followClockPositions(); + syncSegments(); + if (followsClock(vesselState)) followClock(); else if (services.placement) followPlacements(); } updateVisibility(); @@ -569,6 +723,102 @@ export function createRendering({ let clockPassAtMs = null; // Whether the last pass left drawn vessels short of its world time. let drawnBehind = false; + /** One world-clock pass: icons on the renderer's clock when it moves + * them, else moved by the layer. */ + function followClock() { + syncSegments(); + if (segmentsOn()) followClockSegments(); + else followClockPositions(); + } + + /** + * Once a frame: when the icons start or stop moving on the renderer's + * clock (the layer starts or stops following the world clock), put the + * set on that clock and draw every icon again, along its segment or held. + */ + function syncSegments() { + const on = segmentsOn(); + if (on === segmentsWere) return; + segmentsWere = on; + iconSet?.setOptions?.({ motionClock: motionClock(on) }); + // Leaving the clock, each icon holds where its segment last drew it; + // one a live update has drawn since (no world time drawn) stays there. + const lastAtMs = on ? -Infinity : replannedAtMs; + replannedAtMs = -Infinity; + for (const record of state.records.all) { + const drawnAtMs = visualRecords.get(record)?.drawnAtMs; + if ( + lastAtMs > -Infinity && + Number.isFinite(drawnAtMs) && + catchUpVisual(record, lastAtMs) + ) + continue; + syncRecordIcon(record); + } + } + + // The vessels drawn with a card (and the selected one): their cards are + // anchored at where the layer reads them, so it reads them every frame. + const carded = new Set(); + + /** + * As the world clock plays with the icons on the renderer's clock: the + * renderer moves each icon along its segment, and the layer draws again + * only those whose segment ran out (or, the time moved back, started after + * it). Where the layer reads a vessel (its cards, picks, the horizon, its + * model) moves on by itself: every frame for the vessels drawn with a + * card or a model and the one the bridge camera rides, and for the rest a + * share of them each pass, so each moves at least every HIDDEN_FOLLOW_MS. + */ + function followClockSegments() { + const atMs = vesselState.worldNow(); + if (atMs < replannedAtMs) + for (const [id, from] of planFrom) if (from > atMs) replanIcon(id, atMs); + replannedAtMs = atMs; + for (const id of state.icons?.due(atMs) ?? []) replanIcon(id, atMs); + for (const record of carded) catchUpVisual(record, atMs); + for (const item of modelItems.values()) catchUpVisual(item.record, atMs); + const ridden = state.cockpitSubjectId + ? state.records.byId.get(state.cockpitSubjectId) + : null; + if (ridden) catchUpVisual(ridden, atMs); + const all = state.records.all; + const wallMs = performance.now(); + const sinceMs = + hiddenFollowedAtWallMs === null + ? HIDDEN_FOLLOW_MS + : wallMs - hiddenFollowedAtWallMs; + const share = Math.min( + all.length, + Math.ceil((all.length * Math.max(0, sinceMs)) / HIDDEN_FOLLOW_MS), + ); + if (share > 0) hiddenFollowedAtWallMs = wallMs; + for (let k = 0; k < share; k += 1) { + if (hiddenCursor >= all.length) hiddenCursor = 0; + const record = all[hiddenCursor]; + if (visualRecords.get(record)?.position) catchUpVisual(record, atMs); + else followRecord(record, atMs, false, motionPass); + hiddenCursor += 1; + } + } + + /** + * Bring where the layer reads a vessel up to the world time, for a reader + * that needs it where it is drawn now (the detection overlay): while the + * icons move on the renderer's clock, only some are read every frame. + */ + function readVesselNow(record) { + if (segmentsOn()) catchUpVisual(record, vesselState.worldNow()); + } + + /** Draw an icon's vessel again where it is at `atMs`. */ + function replanIcon(id, atMs) { + const record = iconRecords.get(id); + if (!record) return; + catchUpVisual(record, atMs); + syncRecordIcon(record); + } + function followClockPositions() { const atMs = vesselState.worldNow(); const wallMs = performance.now(); @@ -1039,7 +1289,7 @@ export function createRendering({ const visual = getVisual(record); const id = visual?.iconId; const item = icons?.item(id); - const position = visual?.position; + const position = item ? drawnPositionNow(record) : visual?.position; if (!item || !position) continue; const sprite = item.meta; // Most of a worldwide feed sits behind the horizon. A hidden icon with @@ -1121,6 +1371,8 @@ export function createRendering({ ? [components.cards.buildSelectedVesselCard(selected)] : []; const maxLabels = labelRowLimit(); + carded.clear(); + if (selectedCarded) carded.add(selected); if (!query || !records.length || maxLabels <= 0) { state.activeLabelCount = entries.length; @@ -1183,6 +1435,7 @@ export function createRendering({ continue; accepted.push({ x: candidate.x, y: candidate.y }); entries.push(components.cards.buildVesselCard(candidate.record)); + carded.add(candidate.record); } state.activeLabelCount = entries.length; publishVesselOverlayEntries(entries); @@ -1273,6 +1526,7 @@ export function createRendering({ return { getVisual, iconPosition, + drawnPositionNow, forgetClockStep, prepareRecordVisual, anchorPosition, @@ -1292,7 +1546,10 @@ export function createRendering({ cancelTrailingVisibilityPass, cancelPlacementFrame, followPlacements, + followClock, followClockPositions, + readVesselNow, + syncSegments, applyVesselFocusDeemphasis, makeOccluder, isVisible, diff --git a/src/layers/vessels/testing.js b/src/layers/vessels/testing.js index 531554dfd2..fcfff1dc0f 100644 --- a/src/layers/vessels/testing.js +++ b/src/layers/vessels/testing.js @@ -182,18 +182,32 @@ export function createTesting({ components.rendering.followPlacements(); } + /** + * Run what one live frame runs (not following the clock): settle whether + * icons move on the renderer's clock, then the placement pass. Test-only + * seam. + */ + + function _runLiveFrameForTest() { + components.rendering.syncSegments(); + components.rendering.followPlacements(); + } + /** Run one world-clock pass at world time `atMs`. Test-only seam. */ function _runClockPassForTest(atMs) { vesselState.worldNow = () => atMs; - components.rendering.followClockPositions(); + components.rendering.followClock(); } - /** Follow the world clock, standing at world time `atMs`. Test-only seam. */ + /** + * Follow the world clock, standing at world time `atMs`; `null` goes back + * to live. Test-only seam. + */ function _followClockForTest(atMs) { - vesselState.timeline = { active: () => true }; - vesselState.worldNow = () => atMs; + vesselState.timeline = { active: () => atMs !== null }; + vesselState.worldNow = () => atMs ?? 0; } /** True while a trailing visibility frame is scheduled. Test-only seam. */ @@ -240,6 +254,7 @@ export function createTesting({ _vesselVisualForTest, _runPlacementPassForTest, _runClockPassForTest, + _runLiveFrameForTest, _hasTrailingVisibilityPassForTest, }; } diff --git a/src/testSupport/fakeCesiumScene.mjs b/src/testSupport/fakeCesiumScene.mjs index 77fd2f80b9..35f7e605f0 100644 --- a/src/testSupport/fakeCesiumScene.mjs +++ b/src/testSupport/fakeCesiumScene.mjs @@ -208,10 +208,14 @@ export function fakeScenePorts(viewer) { /** * Bind the ports to `viewer`. * @param {object} viewer - * @param {{draw?: object}} [options] + * @param {{draw?: object, capabilities?: ReadonlySet}} [options] + * `capabilities`: what the renderer reports it can draw (none by default). * @returns {{draw: object, camera: object, query: object, frame: object, unbind: () => void}} */ -export function bindFakeCesiumScene(viewer, { draw = fakeDrawPort() } = {}) { +export function bindFakeCesiumScene( + viewer, + { draw = fakeDrawPort(), capabilities } = {}, +) { const cam = () => cameraOfDouble(viewer); const camera = { pose() { @@ -277,6 +281,8 @@ export function bindFakeCesiumScene(viewer, { draw = fakeDrawPort() } = {}) { camera, query, frame, + // What the renderer can draw, when a test gives it (none otherwise). + ...(capabilities ? { capabilities } : null), }); return { draw, camera, query, frame, unbind }; } From 541843833921a98e9862c12a79fc1688370740cb Mon Sep 17 00:00:00 2001 From: Manjunath <301209272+manjunath22466@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:08:55 +0530 Subject: [PATCH 02/70] Stories: GEV scenes as stories on the live globe A Stories button (top right) opens Explore: a feed of GEV scenes over GEV's own Cesium globe, with a pin per story. Explore opens at country level over the first story and, while idle, flies on from story to story for a minute. A picked story is framed in the middle of the view; a pin plays its story on a second click. The Story page plays the scene through SceneDirector with a timeline, chapters, key moments, sources and background, then Close (or Back) puts the person's camera, clock, layers, style and AUTHORING selection back. Open in GEV hands the scene to the Scenes panel at its current shot. Stories lists the scenes GEV ships with a camera path (while they are in the project), the scenes saved with SAVE TO STORIES in AUTHORING, and the person's other scenes as drafts. The person's own stories live in the project on this device, so they have no Share; a link to a story that is not here opens Explore and says so. Each shipped story's context comes from what GEV knows: what it shows, the place each shot goes, and each layer's data sources as DATA_SOURCES.md lists them; the Nepal story carries the event pack's facts and CC BY-NC sources. Card images are a captured THUMBNAIL or drawn from the keyless Esri World Imagery. AUTHORING has no scene picker: it starts with no scene, NEW SCENE (or CAPTURE SHOT) makes one, and Stories' Open in GEV selects one. Before SAVE TO STORIES it offers topic tags and THUMBNAIL. A scene's stories flag, storyThumb and storyTags are saved with the project and kept through export and import. Only the closed state loads with the page; the screens, styles, story data and controller load on first open. Stories keeps its place in the query (one history entry per screen) and holds the share link's hash writes while open. Keyboard input and voice tools stay with Stories while it is open. Explore's pins move on every drawn frame without asking for frames; the idle tour and tile settling are bounded. All strings are translated in the 13 locales. --- docs/CURRENT-STATE.md | 162 +- docs/VUE-MIGRATION.md | 2 +- index.html | 1 + scripts/format-scope.json | 27 + scripts/package-boundaries.json | 51 +- scripts/qa-form-fields.mjs | 86 +- scripts/qa-scene-controls.mjs | 9 +- src/app/tools.js | 17 + src/creditAttribution.test.mjs | 3 + src/data/bhoteKoshiEmbeddedMedia.js | 4 + src/director/document.js | 31 +- src/director/documentFields.js | 5 +- src/i18n/locales/ar.json | 189 +- src/i18n/locales/de.json | 177 +- src/i18n/locales/es.json | 180 +- src/i18n/locales/fr.json | 180 +- src/i18n/locales/he.json | 180 +- src/i18n/locales/it.json | 180 +- src/i18n/locales/ja.json | 174 +- src/i18n/locales/pt.json | 180 +- src/i18n/locales/ru.json | 183 +- src/i18n/locales/sv.json | 177 +- src/i18n/locales/uk.json | 183 +- src/i18n/locales/zh-CN.json | 174 +- src/i18n/locales/zh-Hant.json | 174 +- src/i18n/same-as-english.json | 30 +- src/navigationPolicy.js | 2 + src/scenes/director.js | 322 +- src/scenes/director.test.mjs | 569 ++- src/scenes/project.js | 11 + src/scenes/storyTags.js | 37 + src/scenes/storyThumb.js | 139 + src/scenes/storyThumb.test.mjs | 173 + src/sharelink.js | 46 +- src/sharelink.navigation.test.mjs | 47 + src/stories/boot.js | 119 + src/stories/boot.test.mjs | 142 + src/stories/catalog.js | 340 ++ src/stories/controller.js | 953 +++++ src/stories/controller.test.mjs | 787 ++++ src/stories/format.js | 46 + src/stories/gevLogo.js | 3 + src/stories/gevPlayer.js | 143 + src/stories/gevPlayer.test.mjs | 95 + src/stories/keyboard.js | 38 + src/stories/keyboard.test.mjs | 76 + src/stories/storyMeta.js | 150 + src/stories/thumbs.js | 102 + src/stories/thumbs.test.mjs | 68 + src/tooling/applicationHtml.test.mjs | 2 +- src/ui/sceneControls.js | 37 +- src/ui/sceneControls.test.mjs | 309 +- src/ui/scenePresentation.js | 32 +- src/ui/stores/scenes.js | 35 +- src/ui/stores/stories.js | 83 + src/ui/storiesCredit.test.mjs | 136 + src/ui/styles/english-css-parity.test.mjs | 4 +- src/ui/styles/scenes.css | 75 +- src/ui/styles/stories-entry.css | 243 ++ src/ui/styles/stories.css | 4031 +++++++++++++++++++++ src/ui/surfaceKeyboard.js | 2 + src/ui/views/LayerPanelsView.vue | 26 +- src/ui/views/SceneOptions.vue | 31 - src/ui/views/StoriesView.vue | 337 ++ src/ui/views/index.js | 2 + src/ui/views/panels/ImagerySplitView.vue | 2 +- src/ui/views/stories/ExploreScreen.vue | 782 ++++ src/ui/views/stories/StoriesHeader.vue | 181 + src/ui/views/stories/StoryContext.vue | 414 +++ src/ui/views/stories/StoryRail.vue | 53 + src/ui/views/stories/StoryScreen.vue | 631 ++++ src/ui/views/stories/StoryTimeline.vue | 560 +++ src/ui/wildlifeSightingCard.js | 2 + src/voice/gevActions.js | 11 + src/voice/gevActions.test.mjs | 42 + src/voice/realtimeInput.js | 4 +- style.css | 1 + 77 files changed, 14975 insertions(+), 260 deletions(-) create mode 100644 src/scenes/storyTags.js create mode 100644 src/scenes/storyThumb.js create mode 100644 src/scenes/storyThumb.test.mjs create mode 100644 src/stories/boot.js create mode 100644 src/stories/boot.test.mjs create mode 100644 src/stories/catalog.js create mode 100644 src/stories/controller.js create mode 100644 src/stories/controller.test.mjs create mode 100644 src/stories/format.js create mode 100644 src/stories/gevLogo.js create mode 100644 src/stories/gevPlayer.js create mode 100644 src/stories/gevPlayer.test.mjs create mode 100644 src/stories/keyboard.js create mode 100644 src/stories/keyboard.test.mjs create mode 100644 src/stories/storyMeta.js create mode 100644 src/stories/thumbs.js create mode 100644 src/stories/thumbs.test.mjs create mode 100644 src/ui/stores/stories.js create mode 100644 src/ui/storiesCredit.test.mjs create mode 100644 src/ui/styles/stories-entry.css create mode 100644 src/ui/styles/stories.css delete mode 100644 src/ui/views/SceneOptions.vue create mode 100644 src/ui/views/StoriesView.vue create mode 100644 src/ui/views/stories/ExploreScreen.vue create mode 100644 src/ui/views/stories/StoriesHeader.vue create mode 100644 src/ui/views/stories/StoryContext.vue create mode 100644 src/ui/views/stories/StoryRail.vue create mode 100644 src/ui/views/stories/StoryScreen.vue create mode 100644 src/ui/views/stories/StoryTimeline.vue diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 811e2a1fd6..87d00f49af 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -658,6 +658,106 @@ owner (open state, filters, the rows they show, Remove all) and the text helpers the view renders, so every label follows the locale. Only the modal open/close and focus moves are imperative. +## Stories — November 13, 2026 + +A Stories button (top right, `#hStories`) opens Explore: a feed of stories +over GEV's own Cesium globe with their pins, then a Story screen with a +timeline, chapters and context. Every GEV page loads only what the +closed state needs: the boot shell (`src/stories/boot.js`), the store, +`StoriesView.vue` with the Stories button, first-visit popup and +back-to-story toast, and their styles (`stories-entry.css`). The screens +(`ExploreScreen.vue`, `StoryScreen.vue` and their parts), their styles +(`stories.css`), the story data (`storyMeta.js`, `catalog.js`) and the +controller are separate chunks fetched together on first open, on a +`?stories=` / `?story=` link, or on Back or Forward into Stories; a failed +fetch is reported and the next attempt tries again. Stories keeps its place +in the query, not the share-state hash, with one history entry per screen; +Close steps back over those entries, so Back afterwards does not reopen it, +and share links carry only the Stories place (`stories` / `story`), not the +sender's camera, layers or other settings. GEV's share link keeps +`history.state` when it rewrites the hash, so Stories' entries survive. + +Every story is a GEV scene, played on the person's own Cesium globe through +`SceneDirector`, with its labels, embedded media, A/B imagery split (marked +`data-globe-overlay`) and data-pack cards kept while the rest of GEV is +hidden. Explore lists the scenes the person saved to Stories from AUTHORING +first (`SceneDirector.storyScenes()`, refreshed on every `stories-changed`), +then the person's other scenes with a shot as drafts +(`SceneDirector.draftScenes()`, marked DRAFT), then the +scenes GEV ships with a camera path while they are in the project +(`SceneDirector.hasScene`). A saved scene brings the card image and topics +picked for it in AUTHORING; the topic chips use AUTHORING's tag names and +order. Explore opens at country level +(2,500 km) over the first story and, while idle, flies on to the next story +every few seconds, for a minute after the last touch (never with a story +picked or with reduced motion). A picked story's place is framed in the +middle of the view at an angle. After each landing the globe keeps drawing +only until its tiles have loaded (at most 10 s). Each story's pin, in the +world overlay's label style (`src/overlays/worldOverlayTokens.js`), is placed +from Cesium's own projection on every drawn frame, written straight to the +pin's transform, and hidden behind the globe; the pins ask for no frames of +their own. Card images are drawn from the keyless Esri World Imagery tiles +around the story's place (`src/stories/thumbs.js`) unless the scene has its +own; with any other base imagery the card shows its placeholder, and a card +drawn from Esri earlier is dropped. A shot +tied to an anchor rather than a place pins the whole-globe view. + +A shipped story's context comes from what GEV knows about it +(`src/stories/catalog.js`): what it shows, the place each shot goes, and, +for each layer it turns on, what the layer shows and the data sources +DATA_SOURCES.md lists for it. The Nepal story carries the event pack's own +facts and sources (Vantor imagery and the GeoPera reconstruction, CC BY-NC +4.0), and its key moments are the chapters that show them. Topic chips and +region choices are the ones the listed stories carry. Closing Stories after +a story played puts AUTHORING's own selection back (usually none); +Open in GEV leaves the story's scene selected there. + +Opening Stories claims the camera through the shared navigation policy, so +orbit, a tracked contact or a flight end, and Cockpit refuses with the +policy's own toast ("Exit cockpit to open Stories"). Those owners are not +started again on Close: the camera and clock come back, a follow or orbit +does not. While Stories is open it owns the keyboard (`src/stories/keyboard.js`): +a key pressed in Stories stops at its root, and a key pressed anywhere else +stops at the window, so none of GEV's document-level shortcuts act behind it, +except on a playing GEV scene's own on-globe controls (`data-globe-overlay`); +the capture-phase listeners (hold Space to talk, a surface's Tab trap, the +wildlife card's Escape) check `body.stories-mode` themselves. Voice tool calls +are refused while `stories-mode` is set ("Close Stories first"). + +The address bar names only the story while Stories is open: the share link +holds its hash writes (`ShareLinkManager.holdWrites`, which first writes a +change still waiting for its debounce, so the view Stories saves is current). +Close works in this order. Stories' screens go and GEV is back on screen, but +`stories-mode` (keyboard guard, voice refusal) stays. The director is waited +on until idle (`SceneDirector.whenIdle`: no run and no pending LOAD, seek or +interaction; at most 15 s). The camera and clock are put back, unless a +camera owner took over during the wait (a drag on the globe, a layer's +focus). History steps back over Stories' entries; once that lands (or after +2 s if it never does), the saved share state is re-applied directly +(`ShareLinkManager.restore`, since the share link skips a hash it already +knows) and the share link writes the live view again. Back out of Stories +re-applies it the same way, and Back to Explore from a story re-applies it +once the scene has torn down, with the address still naming only Stories. +"Open in GEV" (GEV scene stories only) closes the +same way but keeps the place and look: nothing is put back, the scene and its +current shot are selected (`SceneDirector.selectShot`) and the Scenes panel +opens for authoring; Back then goes to the page before Stories. A Close or +open made while a traversal is landing runs once it has landed; a second Back +to Explore is ignored. Reopening Stories while a closed GEV scene is still +tearing down keeps the view from before Stories as the one Close restores. +Inside an inline embed Stories is not offered: the URL and history are the +host's. + +The Stories button sits left of whatever holds GEV's top-right corner: the +ACTIVE STYLE readout, or GEV Hosted's account avatar. The first-visit popup +is a labelled region that does not take focus. The story page's rail offers +Open in GEV and Share only. A scene of the person's own (saved or draft) +shows as theirs ("You") and has no Share: the project lives on this device, +so a link to it would open nothing elsewhere; a link to a story that is not +here opens Explore and says so. GEV's own credit line stays on screen throughout, inside the +Stories map while a scene plays (`creditPlacement` in +`src/stories/format.js`). + ## Utilities panel — October 29, 2026 UTILITIES is its own left-side panel, between Data Layers and Scenes, with @@ -1271,7 +1371,7 @@ Native `
- {{ t('EDIT DETAILS') }} - {{ t('SHARE SCENE') }} + {{ t('EDIT DETAILS') }} + {{ t('SHARE SCENE') }}
{{ scene?.progress ?? 0 }}%
diff --git a/src/ui/views/SceneOptions.vue b/src/ui/views/SceneOptions.vue deleted file mode 100644 index 4cc6bbe775..0000000000 --- a/src/ui/views/SceneOptions.vue +++ /dev/null @@ -1,31 +0,0 @@ - - - diff --git a/src/ui/views/StoriesView.vue b/src/ui/views/StoriesView.vue new file mode 100644 index 0000000000..4e3944e64c --- /dev/null +++ b/src/ui/views/StoriesView.vue @@ -0,0 +1,337 @@ + + + diff --git a/src/ui/views/index.js b/src/ui/views/index.js index a85224912a..522a8d0c91 100644 --- a/src/ui/views/index.js +++ b/src/ui/views/index.js @@ -10,6 +10,7 @@ import CockpitView from './CockpitView.vue'; import SceneChromeView from './SceneChromeView.vue'; import ProviderSettingsView from './ProviderSettingsView.vue'; import IntelHudView from './IntelHudView.vue'; +import StoriesView from './StoriesView.vue'; /** * Application views by name. A page places each one with a host element, @@ -26,6 +27,7 @@ export const APPLICATION_VIEWS = Object.freeze({ context: ContextView, welcome: WelcomeView, 'intel-hud': IntelHudView, + stories: StoriesView, }); const mounted = new WeakMap(); diff --git a/src/ui/views/panels/ImagerySplitView.vue b/src/ui/views/panels/ImagerySplitView.vue index b25c7cf467..1c2a34e054 100644 --- a/src/ui/views/panels/ImagerySplitView.vue +++ b/src/ui/views/panels/ImagerySplitView.vue @@ -11,6 +11,6 @@ const optional = (value) => value ?? undefined; diff --git a/src/ui/views/stories/ExploreScreen.vue b/src/ui/views/stories/ExploreScreen.vue new file mode 100644 index 0000000000..04babc0542 --- /dev/null +++ b/src/ui/views/stories/ExploreScreen.vue @@ -0,0 +1,782 @@ + + + diff --git a/src/ui/views/stories/StoriesHeader.vue b/src/ui/views/stories/StoriesHeader.vue new file mode 100644 index 0000000000..e53d35b3b3 --- /dev/null +++ b/src/ui/views/stories/StoriesHeader.vue @@ -0,0 +1,181 @@ + + + diff --git a/src/ui/views/stories/StoryContext.vue b/src/ui/views/stories/StoryContext.vue new file mode 100644 index 0000000000..2556c6405a --- /dev/null +++ b/src/ui/views/stories/StoryContext.vue @@ -0,0 +1,414 @@ + + + diff --git a/src/ui/views/stories/StoryRail.vue b/src/ui/views/stories/StoryRail.vue new file mode 100644 index 0000000000..5687a61c94 --- /dev/null +++ b/src/ui/views/stories/StoryRail.vue @@ -0,0 +1,53 @@ + + + diff --git a/src/ui/views/stories/StoryScreen.vue b/src/ui/views/stories/StoryScreen.vue new file mode 100644 index 0000000000..8eeff9c15c --- /dev/null +++ b/src/ui/views/stories/StoryScreen.vue @@ -0,0 +1,631 @@ + + + diff --git a/src/ui/views/stories/StoryTimeline.vue b/src/ui/views/stories/StoryTimeline.vue new file mode 100644 index 0000000000..de0bd99722 --- /dev/null +++ b/src/ui/views/stories/StoryTimeline.vue @@ -0,0 +1,560 @@ + + + diff --git a/src/ui/wildlifeSightingCard.js b/src/ui/wildlifeSightingCard.js index ce6a245889..7a01b110df 100644 --- a/src/ui/wildlifeSightingCard.js +++ b/src/ui/wildlifeSightingCard.js @@ -203,6 +203,8 @@ export function createWildlifeSightingCard({ const keydown = (event) => { if (!selected.value || event.key !== 'Escape') return; + // Stories owns Escape while it is open (the card is behind it). + if (documentRef.body?.classList?.contains?.('stories-mode')) return; event.preventDefault(); event.stopImmediatePropagation(); layer.clearSightingSelection(); diff --git a/src/voice/gevActions.js b/src/voice/gevActions.js index 3343cd243c..45279baa90 100644 --- a/src/voice/gevActions.js +++ b/src/voice/gevActions.js @@ -444,6 +444,17 @@ export function createGevActionRunner({ runOptions = {}, ) { const args = rawArgs && typeof rawArgs === 'object' ? rawArgs : {}; + // Stories covers GEV and owns its camera and scenes: an open-mic session + // must not fly, load or change what is behind it. + if (globalThis.document?.body?.classList?.contains?.('stories-mode')) + return { + ok: false, + action: name, + applied: false, + refused: 'stories-open', + error: 'Stories is open. Close Stories first.', + say: 'Stories is open. Close Stories first to control the globe.', + }; const current = () => !runOptions.signal?.aborted && (typeof runOptions.isCurrent !== 'function' || runOptions.isCurrent()); diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index 123bbd8e4b..0a26b4b363 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -258,6 +258,48 @@ test('zoom to globe adopts the shared visible reset route and returns its result assert.equal(calls, 1); }); +test('voice changes nothing behind Stories while it is open', async () => { + globalThis.window = globalThis.window || { + clearTimeout, + setTimeout, + requestIdleCallback: null, + }; + const viewer = { + clock: { onTick: { addEventListener: () => () => {} } }, + scene: { canvas: { addEventListener() {}, removeEventListener() {} } }, + camera: { moveEnd: { addEventListener() {} } }, + }; + let calls = 0; + const styleManager = { + async resetToGlobeView() { + calls += 1; + return { ok: true }; + }, + }; + const runner = createGevActionRunner({ + viewer, + styleManager, + dataManager: { layers: new Map(), getAll: () => [] }, + }); + const classes = new Set(['stories-mode']); + const priorDocument = globalThis.document; + globalThis.document = { + ...(priorDocument ?? {}), + body: { classList: { contains: (c) => classes.has(c) } }, + }; + try { + const refused = await runner('zoom_to_globe'); + assert.equal(refused.ok, false); + assert.equal(refused.refused, 'stories-open'); + assert.equal(calls, 0); + classes.clear(); + await runner('zoom_to_globe'); + assert.equal(calls, 1, 'works again once Stories has closed'); + } finally { + globalThis.document = priorDocument; + } +}); + test('dependent voice navigation waits for the destination viewport to arrive', async () => { globalThis.window = globalThis.window || { clearTimeout, diff --git a/src/voice/realtimeInput.js b/src/voice/realtimeInput.js index 0a43fa6ec9..e759e14d85 100644 --- a/src/voice/realtimeInput.js +++ b/src/voice/realtimeInput.js @@ -55,9 +55,11 @@ export class RealtimeInput { bindPushToTalkShortcut() { if (this.shortcutKeyDownHandler) return; this.shortcutKeyDownHandler = (event) => { - // Space types in chat; it never talks while chat is open. + // Space types in chat; it never talks while chat is open, nor while + // Stories owns the keyboard (body.stories-mode). if ( this.ui.state?.chat?.open === true || + globalThis.document?.body?.classList?.contains?.('stories-mode') || !shouldHandlePushToTalkKeyDown(event) ) return; diff --git a/style.css b/style.css index 7e218d7f8d..6d3591643f 100644 --- a/style.css +++ b/style.css @@ -55,4 +55,5 @@ @import './src/ui/styles/cockpit-panels.css'; @import './src/ui/styles/ai-chat.css'; @import './src/ui/styles/scope-off-shadows.css'; +@import './src/ui/styles/stories-entry.css'; @import './src/ui/styles/cyber.css'; From 9e9ce1db22c46de52d14b7ffb48a25dab04ad1b5 Mon Sep 17 00:00:00 2001 From: Manjunath <301209272+manjunath22466@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:23:07 +0530 Subject: [PATCH 03/70] Fix Stories navigation, sharing, and voice entry --- docs/CURRENT-STATE.md | 20 +- scripts/qa-director-sharing.mjs | 29 ++- scripts/qa-scene-controls.mjs | 16 +- server/providers/openai/instructions.js | 2 +- server/providers/openai/toolDescriptions.js | 5 + src/app/tools.js | 23 +- src/firstRunExperience.test.mjs | 1 + src/i18n/locales/ar.json | 1 + src/i18n/locales/de.json | 1 + src/i18n/locales/es.json | 1 + src/i18n/locales/fr.json | 1 + src/i18n/locales/he.json | 1 + src/i18n/locales/it.json | 1 + src/i18n/locales/ja.json | 1 + src/i18n/locales/pt.json | 1 + src/i18n/locales/ru.json | 1 + src/i18n/locales/sv.json | 1 + src/i18n/locales/uk.json | 1 + src/i18n/locales/zh-CN.json | 1 + src/i18n/locales/zh-Hant.json | 1 + src/radioMarkup.test.mjs | 9 +- src/sharelink.js | 5 + src/sharelink.navigation.test.mjs | 6 + src/stories/boot.js | 3 + src/stories/boot.test.mjs | 22 +- src/stories/controller.js | 185 +++++++++++--- src/stories/controller.test.mjs | 267 +++++++++++++++++--- src/stories/gevPlayer.js | 15 +- src/stories/gevPlayer.test.mjs | 39 ++- src/ui/views/stories/StoriesHeader.vue | 12 +- src/voice/actionSchemas.js | 8 + src/voice/actionSchemas.test.mjs | 4 +- src/voice/geminiSession.js | 9 +- src/voice/gevActions.js | 53 +++- src/voice/gevActions.test.mjs | 52 ++++ src/voice/gevRealtime.test.mjs | 28 ++ src/voice/realtimeConnection.js | 4 +- src/voice/realtimeInput.js | 7 +- src/voice/realtimeInputPolicy.js | 7 + src/voice/session.js | 14 +- src/voice/session.test.mjs | 18 +- src/voice/sessionCommands.js | 4 +- src/voice/speech.js | 1 + 43 files changed, 744 insertions(+), 137 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 87d00f49af..ce30c92172 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -721,14 +721,18 @@ a key pressed in Stories stops at its root, and a key pressed anywhere else stops at the window, so none of GEV's document-level shortcuts act behind it, except on a playing GEV scene's own on-globe controls (`data-globe-overlay`); the capture-phase listeners (hold Space to talk, a surface's Tab trap, the -wildlife card's Escape) check `body.stories-mode` themselves. Voice tool calls +wildlife card's Escape) check `body.stories-mode` themselves. "Open Stories" +works from voice or typed AI chat. Entering Stories ends active or pending +microphone capture and blocks microphone starts while Stories owns the +globe. Stories shows a notice when it turns off an active or connecting +voice session. A typed reply can finish after opening Stories. Globe tool calls are refused while `stories-mode` is set ("Close Stories first"). -The address bar names only the story while Stories is open: the share link -holds its hash writes (`ShareLinkManager.holdWrites`, which first writes a -change still waiting for its debounce, so the view Stories saves is current). -Close works in this order. Stories' screens go and GEV is back on screen, but -`stories-mode` (keyboard guard, voice refusal) stays. The director is waited +The address bar names only the story while Stories is open. Stories holds +hash writes (`ShareLinkManager.holdWrites`) and saves a snapshot of the live +globe, including when it opens from a story link without a hash. +Close dismisses the Stories screens and keeps the keyboard and microphone +guards until the previous view is back. The director is waited on until idle (`SceneDirector.whenIdle`: no run and no pending LOAD, seek or interaction; at most 15 s). The camera and clock are put back, unless a camera owner took over during the wait (a drag on the globe, a layer's @@ -751,7 +755,9 @@ host's. The Stories button sits left of whatever holds GEV's top-right corner: the ACTIVE STYLE readout, or GEV Hosted's account avatar. The first-visit popup is a labelled region that does not take focus. The story page's rail offers -Open in GEV and Share only. A scene of the person's own (saved or draft) +Open in GEV and Share only. Share on Explore reopens the list with the same +shipped story selected. A story link opens paused at the shared +point on its timeline. A scene of the person's own (saved or draft) shows as theirs ("You") and has no Share: the project lives on this device, so a link to it would open nothing elsewhere; a link to a story that is not here opens Explore and says so. GEV's own credit line stays on screen throughout, inside the diff --git a/scripts/qa-director-sharing.mjs b/scripts/qa-director-sharing.mjs index 4a4a93d48a..ef31e2e686 100644 --- a/scripts/qa-director-sharing.mjs +++ b/scripts/qa-director-sharing.mjs @@ -116,7 +116,7 @@ try { document.getElementById('loading-screen')?.classList.contains('hidden'), { timeout: 60000 }, ); - await page.click('[data-collapse-target="scene-panel"]'); + await page.click('[data-rail-item="scene-panel"]'); const before = await page.evaluate(() => JSON.stringify(window.__godsEyeView.sceneDirector._project), ); @@ -304,18 +304,17 @@ try { window.__godsEyeView.sceneDirector.getInteractionState().count === 1, )), ); - await page.waitForFunction( - () => window.__godsEyeView.tileset?.tilesLoaded === true, - { timeout: 60000 }, - ); + const activeMapReady = () => { + const { viewer, mapStackController } = window.__godsEyeView; + const tileset = mapStackController.getImageryHostTileset(); + if (tileset) return tileset.tilesLoaded; + return viewer.scene.globe.show && viewer.scene.globe.tilesLoaded; + }; + await page.waitForFunction(activeMapReady, { timeout: 60000 }); await page.screenshot({ path: path.join(output, 'rendered.png') }); fs.writeFileSync( path.join(output, 'report.json'), - JSON.stringify( - await page.evaluate(() => ({ - tilesSettled: window.__godsEyeView.tileset?.tilesLoaded === true, - })), - ), + JSON.stringify({ tilesSettled: await page.evaluate(activeMapReady) }), ); await page.evaluate(() => window.__godsEyeView.sceneDirector.stopScene()); check( @@ -368,6 +367,16 @@ try { ); await page.screenshot({ path: path.join(output, 'narrow.png') }); await page.keyboard.press('Escape'); + await page.setViewport({ width: 1440, height: 900 }); + await page.waitForSelector('[data-rail-item="scene-panel"]', { + visible: true, + }); + if ( + await page.$eval('#scene-panel', (panel) => + panel.classList.contains('collapsed'), + ) + ) + await page.click('[data-rail-item="scene-panel"]'); const pending = await page.evaluate(async () => { const d = window.__godsEyeView.sceneDirector; let finish; diff --git a/scripts/qa-scene-controls.mjs b/scripts/qa-scene-controls.mjs index 5171da6846..fc9bf16062 100644 --- a/scripts/qa-scene-controls.mjs +++ b/scripts/qa-scene-controls.mjs @@ -45,7 +45,7 @@ try { window.__qaSceneState.push(notification), ); }); - await page.click('[data-collapse-target="scene-panel"]'); + await page.click('[data-rail-item="scene-panel"]'); await page.click('#scene-new-btn'); await page.waitForFunction( () => document.querySelector('#scene-name')?.textContent === 'QA Scene', @@ -276,7 +276,7 @@ try { panel.classList.contains('collapsed'), ) ) - await page.click('[data-collapse-target="scene-panel"]'); + await page.click('[data-rail-item="scene-panel"]'); await page.waitForSelector('#scene-download-btn', { visible: true }); await page.click('#scene-download-btn'); const metadata = await page.evaluate(async () => @@ -389,15 +389,15 @@ try { () => !window.__godsEyeView.sceneDirector._project.scenes.some( (item) => item.title === 'QA Scene', - ), + ) && document.querySelector('#scene-name.scene-name-empty'), ); check( - 'Deleting the final scene restores the built-in recipes', + 'Deleting the final scene restores the built-in recipes and clears Authoring', await page.evaluate( () => window.__godsEyeView.sceneDirector._project.scenes.length > 0 && - document.querySelector('#scene-name')?.textContent === - window.__godsEyeView.sceneDirector._getSelectedScene()?.title, + window.__godsEyeView.sceneDirector._getSelectedScene() === null && + document.querySelector('#scene-name.scene-name-empty') !== null, ), ); check( @@ -425,6 +425,10 @@ try { ); }), ); + promptValue = 'Disposal scene'; + await page.click('#scene-new-btn'); + await page.click('#scene-capture-btn'); + await page.waitForSelector('.scene-shot-label', { visible: true }); const teardown = await page.evaluate(async () => { const director = window.__godsEyeView.sceneDirector; const controls = director._controls; diff --git a/server/providers/openai/instructions.js b/server/providers/openai/instructions.js index f9ac492440..f9125df607 100644 --- a/server/providers/openai/instructions.js +++ b/server/providers/openai/instructions.js @@ -26,7 +26,7 @@ function realtimeDirectives( 'analyst_query ANSWERS questions; it never moves the camera or starts tracking. For requests to FOLLOW or TRACK a specific aircraft/ship, call track_entity (get_entity_context first when the target is ambiguous), never analyst_query as the final or only action. For "follow/track the nearest aircraft", first call analyst_query with the aircraft layer(s), sortBy=distance, and limit=1, then call track_entity with the returned aircraft identity in the same turn. The lookup alone does not fulfill a follow/track command.', 'For a request to enable an aircraft layer and SELECT or FIND the nearest/closest aircraft near a named place — for example, "Turn on flights and select the closest aircraft to Austin" — call select_nearest_aircraft once. It atomically turns on the requested aircraft layer first, waits for location arrival, refreshes that layer for the destination viewport, filters out landed/on-ground records, and selects the nearest airborne result. A healthy fallback feed is valid data, never an enable failure. Do not also call fly_to_location, set_layer_visibility, analyst_query, track_entity, set_context_mode, or control_cockpit for the same request.', 'For ANALYTICAL questions about loaded layer data — how many / which / fastest / highest / biggest / nearest / next flights, ships, fires, earthquakes, satellites, launches, storms, transit, bikes, bases, datacenters or dams ("how many flights over Texas", "anything above 40,000 feet") — call analyst_query, not get_entity_context. Always set scope by WHERE: "around here" or "near this" while pointing is kind pointer, never view. Filter on the attribute the user names ("MODIS" → sensor eq MODIS). Say the count with its scope in a few words ("37 loaded flights over Texas") plus one or two examples by name. If the needed layer is off, say so and offer to turn it on. "Which of THOSE…" about the last answer → followUp=true with only the new filter/sort.', - 'WORLD QUERIES — the query tools (get_weather, get_wind, search_places, places_nearby, plan_route, get_cyclones, get_fire_perimeters, get_bike_share, get_transit_vehicles, get_traffic_flow, situation_brief, military_awareness and the other get_* and find_* tools you have) look up data anywhere in the world without changing the map and without any layer being on. Use them when the user asks about a place they are not looking at or data whose layer is off ("what is the weather in Tokyo", "how do I drive from Austin to Dallas", "any wildfires in California"). For aircraft, ships, earthquakes, active fires, datacenters, dams and satellites overhead, use analyst_query over the layers instead, turning the layer on first when the user wants it. Use analyst_query and get_entity_context for what the app has loaded or what is on screen. Answer from the result summary and data, mention its source when it has one, and never claim the map changed. If the user also wants to SEE it, use the matching app action (fly_to_location, set_layer_visibility) as well.', + 'WORLD QUERIES: query tools (get_weather, get_wind, search_places, places_nearby, plan_route, get_cyclones, get_fire_perimeters, get_bike_share, get_transit_vehicles, get_traffic_flow, situation_brief, military_awareness and other get_* and find_* tools) look up any place without changing the map or enabling layers. Use them for places out of view or data whose layer is off. For aircraft, ships, earthquakes, active fires, datacenters, dams and satellites overhead, use analyst_query over layers instead; enable the layer first if asked. Use analyst_query and get_entity_context for loaded data or what is on screen. Answer from the result; name its source if supplied and never claim the map changed. If asked to show it, also use the matching app action (fly_to_location, set_layer_visibility).', 'WHERE, for every tool that takes a place or scope, in this order: (1) a place the user names, or an areaId you already have; (2) explicit pointing — "this/that one/here/around here" while pointer_context shows pointing or a target → "pointer"; (3) the Contacts subject while Contacts is active, or the selection when the user refers to it; (4) the current view. A selected datacenter, dam, fire or cable never silently becomes the centre.', 'AREAS: resolve_area turns a named boundary (country, state, province, county, city, district, natural region) into an areaId; to outline it pass draw=true; annotate_map is for marks, not boundaries. Count inside it → analyst_query kind=area with the areaId (or kind=region); "the area I drew" → kind=drawn; "the area you outlined" → kind=annotation. Imagery of a place → resolve_area, then find_imagery. Ambiguous name: call resolve_area; on needsClarification ask which, never guess.' + (overpass diff --git a/server/providers/openai/toolDescriptions.js b/server/providers/openai/toolDescriptions.js index d3116f06a1..490de5c0b0 100644 --- a/server/providers/openai/toolDescriptions.js +++ b/server/providers/openai/toolDescriptions.js @@ -309,6 +309,11 @@ export const ACTION_DESCRIPTIONS = { }, }, }, + open_stories: { + description: + 'Open the Stories Explore list on request ("open Stories", "show the story list"). Turns off voice.', + $position: 1, + }, control_scene: { description: 'Cinematic scene playback: list scenes, play one scene by name, stop, advance, or read status. Play starts a single named scene and returns immediately.', diff --git a/src/app/tools.js b/src/app/tools.js index 71f0970b10..e35d861cfd 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -21,6 +21,7 @@ import { createLibraryBrowser } from '../ui/libraryBrowser.js'; import { useDataLibraryStore } from '../ui/stores/dataLibrary.js'; import { localGeoJsonServices } from './localGeojsonServices.js'; import { initGevVoiceCommands } from '../voice/gevRealtime.js'; +import { isStoriesOpen } from '../voice/realtimeInputPolicy.js'; import { installViews, isEmbeddedInline } from './embed.js'; import { installScopeMask, @@ -81,12 +82,23 @@ export function createApplicationTools({ onSceneDirector?.(sceneDirector); // Stories: GEV scenes on this globe, from a Stories button. Its screens, // styles, story data and controller load on first use. + const storiesStore = useStoriesStore(applicationPinia()); + let voiceCommands; const stories = bootStories({ // Inline in a host page, the URL and history are the host's. available: !isEmbeddedInline(), viewer, director: sceneDirector, - store: useStoriesStore(applicationPinia()), + store: storiesStore, + onEnter: () => { + const session = voiceCommands?.session; + // A typed command can finish its reply without keeping a microphone on. + if (!session || session.adapter.getStartOptions?.().textOnly) return; + const wasActive = session.isActive(); + session.stop(); + if (wasActive) + storiesStore.flashToast(t('Voice is disabled in Stories.'), 4000); + }, onLoadFailed: () => styleManager._showToast?.( t('Stories could not load. Check the connection and try again.'), @@ -299,8 +311,15 @@ export function createApplicationTools({ defer(() => { if (window.__godsEyeView === debug) delete window.__godsEyeView; }); - const voiceCommands = initGevVoiceCommands({ + voiceCommands = initGevVoiceCommands({ ...voice, + canStartVoice: () => !isStoriesOpen(), + openStories: storiesStore.available + ? ({ isCurrent }) => + storiesStore.mode === 'closed' + ? stories.open({ isCurrent }) + : 'already-open' + : null, floorServices: operations.surface.groundFloor, annotationResolver: operations.annotationResolver, searchNavigation: operations.searchAndFlyTo, diff --git a/src/firstRunExperience.test.mjs b/src/firstRunExperience.test.mjs index e81e4651e9..9365ae74f7 100644 --- a/src/firstRunExperience.test.mjs +++ b/src/firstRunExperience.test.mjs @@ -991,6 +991,7 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping 'find_imagery', 'osm_query', 'show_street_level', + 'open_stories', ].includes(tool.name), ); const hudLayout = legacyTools.find((tool) => tool.name === 'set_hud') diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 7aae7547da..c31e12f58a 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -205,6 +205,7 @@ "Hold Space to talk": "اضغط مطولًا على Space للتحدث", "Release Space to send": "حرّر Space للإرسال", "Ask or command": "اسأل أو أصدر أمرًا", + "Voice is disabled in Stories.": "التحكم الصوتي معطّل في القصص.", "Voice off": "الصوت متوقف", "Running command": "جارٍ تنفيذ الأمر", "Radio did not start": "لم يبدأ الراديو", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 2fdd5d27ce..3f5ef6fe0b 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -784,6 +784,7 @@ "Requesting microphone": "Mikrofonzugriff wird angefordert", "Ask or command": "Fragen oder Befehl geben", "Running command": "Befehl läuft", + "Voice is disabled in Stories.": "Die Sprachsteuerung ist in Stories deaktiviert.", "Voice off": "Sprache aus", "WebRTC microphone support unavailable": "WebRTC-Mikrofonunterstützung nicht verfügbar", "VOICE UNAVAILABLE": "SPRACHE N. V.", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index b2867f41ae..c837a8d9d3 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -968,6 +968,7 @@ "Hold Space to talk": "Mantén Space y habla", "Release Space to send": "Suelta Space para enviar", "Ask or command": "Pregunta o ordena", + "Voice is disabled in Stories.": "El control por voz está desactivado en Historias.", "Voice off": "Voz desactivada", "Running command": "Ejecutando comando", "Radio did not start": "La radio no se inició", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 7c31a92a6d..ca2dfae595 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -2526,6 +2526,7 @@ "Gemini voice is not connected": "La voix Gemini n'est pas connectée", "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "La saisie interrompue de Gemini a dépassé sa limite de tampon ou d'attente. Relancez la voix.", "Gemini Live connection is expiring. Start voice again for a new conversation.": "La connexion à Gemini Live expire. Relancez la voix pour une nouvelle conversation.", + "Voice is disabled in Stories.": "La commande vocale est désactivée dans les Stories.", "Voice off": "Voix désactivée", "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Les sessions vocales Gemini sont limitées dans le temps. Quand une session expire, relancez la voix pour une nouvelle conversation.", "Stopped by voice": "Arrêté par la voix", diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 7c9a37fbe6..8382005520 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -2862,6 +2862,7 @@ "Gemini voice is not connected": "הקול של Gemini אינו מחובר", "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "הקלט שהופסק של Gemini חרג מהחוצץ או ממגבלת ההמתנה. הפעל את הקול שוב.", "Gemini Live connection is expiring. Start voice again for a new conversation.": "חיבור Gemini Live עומד לפוג. הפעל את הקול שוב לשיחה חדשה.", + "Voice is disabled in Stories.": "השליטה הקולית מושבתת בסיפורים.", "Voice off": "הקול כבוי", "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "הפעלות הקול של Gemini מוגבלות בזמן. כשההפעלה פגה, הפעל את הקול שוב לשיחה חדשה.", "Stopped by voice": "נעצר בקול", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 243b2b0498..b0e3df7299 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -2526,6 +2526,7 @@ "Gemini voice is not connected": "La voce Gemini non è connessa", "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "L'input interrotto di Gemini ha superato il limite di buffer o di attesa. Riavvia la voce.", "Gemini Live connection is expiring. Start voice again for a new conversation.": "La connessione a Gemini Live sta scadendo. Riavvia la voce per una nuova conversazione.", + "Voice is disabled in Stories.": "Il controllo vocale è disattivato nelle Storie.", "Voice off": "Voce disattivata", "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Le sessioni vocali Gemini hanno un limite di tempo. Quando una sessione scade, riavvia la voce per una nuova conversazione.", "Stopped by voice": "Fermato dalla voce", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index f95f3255d7..c89fc74f65 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -2426,6 +2426,7 @@ "Gemini voice is not connected": "Gemini音声が接続されていません", "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "Geminiの中断された入力がバッファーまたは待機の上限を超えました。音声をもう一度開始してください。", "Gemini Live connection is expiring. Start voice again for a new conversation.": "Gemini Liveの接続がまもなく期限切れです。新しい会話を始めるには、音声をもう一度開始してください。", + "Voice is disabled in Stories.": "ストーリーでは音声操作が無効になります。", "Voice off": "音声 オフ", "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Gemini音声のセッションには時間制限があります。セッションが期限切れになったら、音声をもう一度開始して新しい会話を始めてください。", "Stopped by voice": "音声で停止しました", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 2f336b3ab9..93fa6f71e3 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -2526,6 +2526,7 @@ "Gemini voice is not connected": "A voz do Gemini não está conectada", "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "A entrada interrompida do Gemini excedeu o limite de buffer ou de espera. Inicie a voz de novo.", "Gemini Live connection is expiring. Start voice again for a new conversation.": "A conexão com o Gemini Live vai expirar. Inicie a voz de novo para uma nova conversa.", + "Voice is disabled in Stories.": "O controle por voz está desativado nas Histórias.", "Voice off": "Voz desligada", "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "As sessões de voz do Gemini têm limite de tempo. Quando uma sessão expirar, inicie a voz de novo para uma nova conversa.", "Stopped by voice": "Parado por voz", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 60e7731a38..d87a192267 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1024,6 +1024,7 @@ "Ask or command": "Спросите или дайте команду", "WebRTC microphone support unavailable": "Поддержка микрофона WebRTC недоступна", "Requesting microphone": "Запрос доступа к микрофону", + "Voice is disabled in Stories.": "Голосовое управление в историях отключено.", "Voice off": "Голос выключен", "VOICE UNAVAILABLE": "ГОЛОС НЕДОСТУПЕН", "VOICE ACTIVE": "ГОЛОС АКТИВЕН", diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index f8319e5853..e1976a8a57 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -740,6 +740,7 @@ "Requesting microphone": "Begär åtkomst till mikrofonen", "Ask or command": "Fråga eller ge ett kommando", "Running command": "Kör kommando", + "Voice is disabled in Stories.": "Röststyrning är avstängd i Stories.", "Voice off": "Röst av", "WebRTC microphone support unavailable": "Mikrofonstöd för WebRTC saknas", "VOICE UNAVAILABLE": "RÖST OTILLGÄNGLIG", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 70bba2d73d..14d32aec38 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -2575,6 +2575,7 @@ "Gemini voice is not connected": "Голосовий режим Gemini не підключено", "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "Перерване введення Gemini перевищило ліміт буфера або очікування. Запустіть голосовий режим знову.", "Gemini Live connection is expiring. Start voice again for a new conversation.": "Термін дії зʼєднання з Gemini Live спливає. Запустіть голосовий режим знову для нової розмови.", + "Voice is disabled in Stories.": "Голосове керування в історіях вимкнено.", "Voice off": "Голос вимкнено", "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Тривалість голосових сеансів Gemini обмежена. Коли сеанс завершиться, запустіть голосовий режим знову для нової розмови.", "Stopped by voice": "Зупинено голосовою командою", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 5afbbab41f..08926db8bc 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -2332,6 +2332,7 @@ "Release Space to send": "松开空格键发送", "Hold Space to talk": "按住空格键说话", "Ask or command": "提问或下达指令", + "Voice is disabled in Stories.": "故事模式下语音控制已禁用。", "Voice off": "语音已关闭", "VOICE UNAVAILABLE": "语音不可用", "VOICE ACTIVE": "语音已启用", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 21a4463e59..eea3781dc4 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -2322,6 +2322,7 @@ "Release Space to send": "鬆開空格鍵發送", "Hold Space to talk": "按住空格鍵說話", "Ask or command": "提問或下達指令", + "Voice is disabled in Stories.": "故事模式下語音控制已停用。", "Voice off": "語音已關閉", "VOICE UNAVAILABLE": "語音不可用", "VOICE ACTIVE": "語音已啟用", diff --git a/src/radioMarkup.test.mjs b/src/radioMarkup.test.mjs index 6dec02b140..8cfa09ba6d 100644 --- a/src/radioMarkup.test.mjs +++ b/src/radioMarkup.test.mjs @@ -25,15 +25,16 @@ const css = readStylesheet(new URL('../style.css', import.meta.url)); function realtimeTools() { return GEV_REALTIME_TOOLS; } -test('Realtime schema exposes the authoritative 35-tool inventory', () => { +test('Realtime schema exposes the authoritative 36-tool inventory', () => { const tools = realtimeTools(); - assert.equal(tools.length, 35); + assert.equal(tools.length, 36); const names = tools.map((tool) => tool.name); - assert.equal(new Set(names).size, 35, 'tool names are unique'); + assert.equal(new Set(names).size, 36, 'tool names are unique'); assert.ok(names.includes('resolve_area')); assert.ok(names.includes('find_imagery')); assert.ok(names.includes('osm_query')); assert.ok(names.includes('show_street_level')); + assert.ok(names.includes('open_stories')); assert.ok(names.includes('set_context_mode')); assert.ok(names.includes('control_cockpit')); assert.ok(names.includes('set_voice_inactivity_timeout')); @@ -209,6 +210,8 @@ test('no unchanged Realtime tool definition drifts silently', () => { 'osm_query', // Street-level photos: a new composite tool, not an edit to a shipped one. 'show_street_level', + // Stories Explore: a new entry action. + 'open_stories', ]); const unchanged = realtimeTools() .filter((tool) => !TOUCHED.has(tool.name)) diff --git a/src/sharelink.js b/src/sharelink.js index b427b5a8b5..91461923dd 100644 --- a/src/sharelink.js +++ b/src/sharelink.js @@ -756,6 +756,11 @@ export class ShareLinkManager { history.replaceState(history.state, '', url.href); } + /** Capture the live share hash without changing the current history entry. */ + snapshotHash() { + return this._buildHashParams()?.toString() ?? null; + } + /** Build a deterministic snapshot without mutating history. */ _buildHashParams() { if (this._destroyed) return null; diff --git a/src/sharelink.navigation.test.mjs b/src/sharelink.navigation.test.mjs index 087812ef08..0d18b5b7cc 100644 --- a/src/sharelink.navigation.test.mjs +++ b/src/sharelink.navigation.test.mjs @@ -167,6 +167,12 @@ test('holding writes first writes a view change still waiting for its debounce', manager.holdWrites(true); assert.equal(window.location.hash, '#v=2&lat=5', 'written before the hold'); manager._buildHashParams = () => new URLSearchParams('v=2&lat=9'); + assert.equal(manager.snapshotHash(), 'v=2&lat=9'); + assert.equal( + window.location.hash, + '#v=2&lat=5', + 'snapshot leaves the URL alone', + ); manager._scheduleUpdate(); assert.equal(timers.size, 0, 'nothing scheduled while held'); manager.destroy(); diff --git a/src/stories/boot.js b/src/stories/boot.js index 7ea77efa85..1b0162b47a 100644 --- a/src/stories/boot.js +++ b/src/stories/boot.js @@ -14,6 +14,7 @@ const wantsStories = () => { * @param {{viewer: import('cesium').Viewer, * director: import('../scenes/director.js').SceneDirector, * store: ReturnType, + * onEnter?: () => void, * onLoadFailed?: () => void, * loadModules?: () => Promise<[object, object]>}} options `onLoadFailed` * tells the person a click did nothing because Stories could not load; @@ -26,6 +27,7 @@ export function bootStories({ viewer, director, store, + onEnter, onLoadFailed, available = true, loadModules = () => @@ -67,6 +69,7 @@ export function bootStories({ viewer, director, store, + onEnter, }); store.connect(real, listStories()); return real; diff --git a/src/stories/boot.test.mjs b/src/stories/boot.test.mjs index 1d540d72a8..bb353bbb31 100644 --- a/src/stories/boot.test.mjs +++ b/src/stories/boot.test.mjs @@ -70,7 +70,14 @@ test('the shell loads the controller on first open, then steps aside', async () setActivePinia(createPinia()); history.replaceState(null, '', '/'); const store = useStoriesStore(); - const shell = bootStories({ viewer, director, store }); + const entries = []; + const shell = bootStories({ + viewer, + director, + store, + onEnter: () => + entries.push(document.body.classList.contains('stories-mode')), + }); assert.equal(store.controller, shell); assert.equal(store.stories.length, 0, 'no catalog until Stories is used'); const engineLoaded = () => @@ -78,7 +85,14 @@ test('the shell loads the controller on first open, then steps aside', async () /stories\/(controller|catalog|protoEngine)\.js$/.test(u), ); assert.equal(engineLoaded(), false, 'GEV starts without the Stories chunk'); - await shell.open(); + let current = true; + const staleOpen = shell.open({ isCurrent: () => current }); + current = false; + assert.equal(await staleOpen, false); + assert.equal(store.mode, 'closed'); + assert.deepEqual(entries, []); + assert.equal(await shell.open(), true); + assert.deepEqual(entries, [true]); assert.equal(engineLoaded(), true); assert.notEqual(store.controller, shell); assert.ok(store.stories.length > 0); @@ -115,10 +129,10 @@ test('a failed load is reported and the next open tries again', async () => { ? Promise.reject(new Error('offline')) : Promise.all([import('./controller.js'), import('./catalog.js')]), }); - await shell.open(); + assert.equal(await shell.open(), undefined); assert.equal(failures, 1); assert.equal(store.mode, 'closed'); - await shell.open(); + assert.equal(await shell.open(), true); assert.equal(attempts, 2, 'the failure was not kept'); assert.equal(store.mode, 'explore'); shell.destroy(); diff --git a/src/stories/controller.js b/src/stories/controller.js index f72acc0c89..327b8ee25b 100644 --- a/src/stories/controller.js +++ b/src/stories/controller.js @@ -19,6 +19,20 @@ import { registerNavigationAuthorityListener } from '../navigationPolicy.js'; const PARAM_STORIES = 'stories'; const PARAM_STORY = 'story'; +const PARAM_STORY_TIME = 'storyTime'; +const PARAM_SELECTED_STORY = 'selectedStory'; + +function exploreSelection(params) { + const id = params.get(PARAM_SELECTED_STORY); + const story = id ? storyById(id) : null; + return story && !story.mine ? story.id : null; +} + +function storyTime(params) { + const value = params.get(PARAM_STORY_TIME); + const ms = Number(value); + return value && /^\d+$/.test(value) && Number.isSafeInteger(ms) ? ms : 0; +} /** * Stories: Explore (the story list over the person's own Cesium globe, with @@ -34,19 +48,28 @@ const PARAM_STORY = 'story'; * * @param {{viewer: Cesium.Viewer, * director: import('../scenes/director.js').SceneDirector, - * store: ReturnType}} options + * store: ReturnType, + * onEnter?: () => void}} options */ -export function createStoriesController({ viewer, director, store }) { +export function createStoriesController({ viewer, director, store, onEnter }) { let player = null; let saved = null; // The view a Close is about to restore, once a stopping scene has settled. let pendingView = null; + // Reopening reuses the saved view, but supersedes the old close request. + let closeGeneration = 0; let removeReadout = null; let destroyed = false; // Close steps back over Stories' own entries; the landing popstate is ours. let closingHistory = false; // A Back to Explore traversal is on its way. let steppingBack = false; + let backTimer = 0; + let readyTimer = 0; + function cancelInitialLink() { + clearTimeout(readyTimer); + readyTimer = 0; + } // A call made while a traversal is landing runs from the entry it lands on, // so two traversals never stack (Close after Back to Explore would step // one entry too far). @@ -78,7 +101,7 @@ export function createStoriesController({ viewer, director, store }) { // A draft's THUMBNAIL or tags. 'story-details-changed', ]); - const unsubscribeScenes = director.subscribe?.((change) => { + const unsubscribeScenes = director.subscribe?.(({ change }) => { if (!LIST_CHANGES.has(change?.type) || destroyed) return; store.stories = markRaw(listStories()); if (removePins) { @@ -96,6 +119,8 @@ export function createStoriesController({ viewer, director, store }) { const url = new URL(location.href); url.searchParams.delete(PARAM_STORIES); url.searchParams.delete(PARAM_STORY); + url.searchParams.delete(PARAM_STORY_TIME); + url.searchParams.delete(PARAM_SELECTED_STORY); for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v); if (Object.keys(params).length) url.hash = ''; return url.toString(); @@ -168,6 +193,7 @@ export function createStoriesController({ viewer, director, store }) { } const onPopState = () => { if (destroyed) return; + cancelInitialLink(); const queued = afterTraversal; afterTraversal = null; try { @@ -177,6 +203,8 @@ export function createStoriesController({ viewer, director, store }) { } }; function handlePopState() { + clearTimeout(backTimer); + backTimer = 0; steppingBack = false; if (closingHistory) { closingHistory = false; @@ -189,12 +217,24 @@ export function createStoriesController({ viewer, director, store }) { } const params = new URLSearchParams(location.search); const id = params.get(PARAM_STORY); - if (id && storyById(id)) controller.openStory(id, { fromHistory: true }); + if (id && storyById(id)) + controller.openStory(id, { + fromHistory: true, + atMs: storyTime(params), + }); else if (params.has(PARAM_STORIES)) store.mode === 'closed' ? controller.open({ fromHistory: true }) : controller.backToExplore({ fromHistory: true }); else if (store.mode !== 'closed') controller.close({ fromHistory: true }); + else if (pendingView) { + // Another browser navigation landed while the scene was stopping. + // The destination owns the globe now, so discard the earlier restore. + pendingView = null; + closeGeneration += 1; + document.body.classList.remove('stories-mode'); + shareLink()?.holdWrites?.(false); + } } addEventListener('popstate', onPopState); @@ -209,9 +249,8 @@ export function createStoriesController({ viewer, director, store }) { time: viewer.clock.currentTime.clone(), animate: viewer.clock.shouldAnimate, openedAt: Date.now(), - // The share state (layers, style, camera) as it was, for after a GEV - // scene has changed it. - hash: location.hash, + // Story history entries have no hash. Capture the live globe state. + hash: shareLink()?.snapshotHash?.() ?? location.hash, ranScene: false, // Whether a scene played during this visit, which selects it in // AUTHORING (ranScene clears once Back to Explore has undone the look). @@ -585,7 +624,9 @@ export function createStoriesController({ viewer, director, store }) { saved = pendingView; pendingView = null; } else saveView(); + closeGeneration += 1; document.body.classList.add('stories-mode'); + onEnter?.(); return true; } @@ -678,34 +719,41 @@ export function createStoriesController({ viewer, director, store }) { } const controller = { - open({ fromHistory = false } = {}) { + open({ fromHistory = false, isCurrent } = {}) { + if (destroyed || (isCurrent && !isCurrent())) return false; + cancelInitialLink(); if (!fromHistory && traversing()) { - afterTraversal = () => controller.open(); - return; + if (!isCurrent) afterTraversal = () => controller.open(); + return false; } - if (store.mode !== 'closed') return; - if (!enterStories()) return; - store.picked = null; + if (store.mode !== 'closed' || !enterStories()) return false; + store.picked = fromHistory + ? exploreSelection(new URLSearchParams(location.search)) + : null; showExplore(); if (!fromHistory) navigate({ [PARAM_STORIES]: 'explore' }, true); + return true; }, close({ fromHistory = false, keepCamera = false } = {}) { + if (destroyed) return; + cancelInitialLink(); if (store.mode === 'closed') return; if (!fromHistory && traversing()) { afterTraversal = () => controller.close({ keepCamera }); return; } + const generation = ++closeGeneration; dropPlayer(); stopPins(); viewer.camera.cancelFlight(); - // GEV comes back on screen now; `stories-mode` (keyboard guard, voice - // refusal) stays until the view is back, so nothing acts on GEV under - // a scene that is still tearing down. + // Close the Stories screens now and keep their input guard until the + // scene and share view have finished restoring. document.body.classList.remove('stories-scene'); store.mode = 'closed'; store.storyId = null; store.picked = null; store.expanded = false; + store.toast = ''; const was = saved; saved = null; pendingView = was; @@ -727,9 +775,14 @@ export function createStoriesController({ viewer, director, store }) { canvas.removeEventListener('pointerdown', onDrag); stopWatching(); // Reopened meanwhile (the reopen took `was` over), or torn down. - if (pendingView !== was || destroyed || viewer.isDestroyed?.()) return; + if ( + generation !== closeGeneration || + pendingView !== was || + destroyed || + viewer.isDestroyed?.() + ) + return; pendingView = null; - document.body.classList.remove('stories-mode'); if (!navigated) restoreView(was, { keepCamera }); // AUTHORING shows what it showed before, unless the person opened // the story there. @@ -740,6 +793,7 @@ export function createStoriesController({ viewer, director, store }) { // over the earlier entry instead. if (!keepCamera && !navigated) restoreShareState(was); shareLink()?.holdWrites?.(false); + document.body.classList.remove('stories-mode'); }; if (fromHistory) afterLanding(); else leaveHistory(afterLanding); @@ -759,6 +813,8 @@ export function createStoriesController({ viewer, director, store }) { * @param {{autoplay?: boolean, fromHistory?: boolean, atMs?: number}} [opts] */ openStory(id, { autoplay = false, fromHistory = false, atMs = 0 } = {}) { + if (destroyed) return; + cancelInitialLink(); const story = storyById(id); if (!story) return; if (!fromHistory && traversing()) { @@ -777,6 +833,9 @@ export function createStoriesController({ viewer, director, store }) { store.sheet = 'peek'; store.bigPlay = !autoplay; syncSceneShots(story); + atMs = Number.isFinite(atMs) + ? Math.max(0, Math.min(story.durationMs, Math.round(atMs))) + : 0; store.playback = { wallMs: atMs, worldMs: null, @@ -796,15 +855,26 @@ export function createStoriesController({ viewer, director, store }) { // Opened paused, a scene frames its first shot (or the moment asked). if (atMs || !autoplay) player.seek(atMs); if (autoplay) player.play(); - if (!fromHistory) navigate({ [PARAM_STORY]: story.id }, true); + if (!fromHistory) + navigate( + atMs + ? { [PARAM_STORY]: story.id, [PARAM_STORY_TIME]: atMs } + : { [PARAM_STORY]: story.id }, + true, + ); if (!store.hintSeen) { store.hintSeen = true; store.flashHint(t('Drag the map to explore · Resume any time'), 4200); } }, backToExplore({ fromHistory = false } = {}) { - // A second press while the first is landing does nothing more. - if (!fromHistory && traversing()) return; + if (destroyed) return; + cancelInitialLink(); + // A second Back keeps the traversal, but cancels a story queued since. + if (!fromHistory && traversing()) { + if (steppingBack) afterTraversal = null; + return; + } dropPlayer(); store.expanded = false; if (!fromHistory) { @@ -816,7 +886,9 @@ export function createStoriesController({ viewer, director, store }) { if (params.has(PARAM_STORY) && to != null && depth() > to) { steppingBack = true; // A step that never lands gives up, as Close's does. - setTimeout(() => { + clearTimeout(backTimer); + backTimer = setTimeout(() => { + backTimer = 0; if (!steppingBack) return; steppingBack = false; const queued = afterTraversal; @@ -827,6 +899,10 @@ export function createStoriesController({ viewer, director, store }) { return; } navigate({ [PARAM_STORIES]: 'explore' }, true); + } else { + const params = new URLSearchParams(location.search); + if (params.has(PARAM_SELECTED_STORY)) + store.picked = exploreSelection(params); } showExplore(); }, @@ -855,7 +931,10 @@ export function createStoriesController({ viewer, director, store }) { player.pause(); // After Close has settled: the scene's teardown restores GEV's look // and panels, which would fold the Scenes panel again. - await controller.close({ keepCamera: true }); + const closing = controller.close({ keepCamera: true }); + const generation = closeGeneration; + await closing; + if (destroyed || generation !== closeGeneration) return; director.selectShot?.(s.sceneId, shotId); director.styleManager?.setPanelCollapsed?.('scene-panel', false, { explicit: true, @@ -871,15 +950,35 @@ export function createStoriesController({ viewer, director, store }) { shareLink() { const here = new URL(location.href); const url = new URL(here.pathname, here.origin); - for (const key of [PARAM_STORIES, PARAM_STORY]) - if (here.searchParams.has(key)) - url.searchParams.set(key, here.searchParams.get(key)); + const id = store.mode === 'story' ? store.storyId : store.picked; + const story = id ? storyById(id) : null; + if (store.mode === 'story' && story && !story.mine) { + url.searchParams.set(PARAM_STORY, story.id); + const ms = Math.round(store.playback.wallMs); + if (Number.isSafeInteger(ms) && ms > 0) + url.searchParams.set(PARAM_STORY_TIME, String(ms)); + } else { + url.searchParams.set(PARAM_STORIES, 'explore'); + if (story && !story.mine) + url.searchParams.set(PARAM_SELECTED_STORY, story.id); + } return url.toString(); }, destroy() { if (destroyed) return; - controller.close(); destroyed = true; + cancelInitialLink(); + clearTimeout(backTimer); + clearTimeout(landingTimer); + steppingBack = closingHistory = false; + afterTraversal = landed = null; + dropPlayer(); + stopPins(); + viewer.camera.cancelFlight(); + store.mode = 'closed'; + store.storyId = null; + store.picked = null; + store.expanded = false; // Torn down mid-close: what the close would undo once settled is // undone now (keyboard and voice guard, held share writes). document.body.classList.remove('stories-mode', 'stories-scene'); @@ -893,7 +992,6 @@ export function createStoriesController({ viewer, director, store }) { canvas.removeEventListener('pointerup', onExploreInput); canvas.removeEventListener('pointercancel', onExploreInput); canvas.removeEventListener('wheel', onExploreInput); - stopTour(); canvas.removeEventListener('pointerup', onUp); }, }; @@ -901,17 +999,21 @@ export function createStoriesController({ viewer, director, store }) { // A shared link opens where it points once GEV has finished loading. const params = new URLSearchParams(location.search); if (params.has(PARAM_STORY) || params.has(PARAM_STORIES)) { - const id = params.get(PARAM_STORY); const started = Date.now(); const whenReady = () => { + readyTimer = 0; if (destroyed) return; + const params = new URLSearchParams(location.search); + if (!params.has(PARAM_STORY) && !params.has(PARAM_STORIES)) return; + const id = params.get(PARAM_STORY); + const atMs = storyTime(params); const loading = document.getElementById('loading-screen'); if ( loading && !loading.classList.contains('hidden') && Date.now() - started < 30000 ) { - setTimeout(whenReady, 300); + readyTimer = setTimeout(whenReady, 300); return; } // A reload, or Back/Forward into a Stories entry: its history is @@ -920,11 +1022,19 @@ export function createStoriesController({ viewer, director, store }) { // GEV's boot wrote its share hash onto the entry: Stories' entries // carry none. const own = Object.fromEntries( - [...params].filter(([k]) => k === PARAM_STORIES || k === PARAM_STORY), + [...params].filter( + ([key]) => + key === PARAM_STORIES || + key === PARAM_STORY || + (key === PARAM_STORY_TIME && id && atMs) || + (key === PARAM_SELECTED_STORY && + !id && + params.has(PARAM_STORIES)), + ), ); history.replaceState(history.state, '', urlFor(own)); if (id && storyById(id)) - controller.openStory(id, { fromHistory: true }); + controller.openStory(id, { fromHistory: true, atMs }); else { controller.open({ fromHistory: true }); if (id) store.flashToast(t('That story is not available here')); @@ -933,19 +1043,24 @@ export function createStoriesController({ viewer, director, store }) { } // A new link: Explore sits under a story it opens, so Back lands there. const landing = { stories: 'explore', depth: 0, explore: 0 }; + const selected = + !id && params.has(PARAM_STORIES) ? exploreSelection(params) : null; history.replaceState( { ...(history.state ?? {}), gevStories: landing }, '', - urlFor({ [PARAM_STORIES]: 'explore' }), + urlFor({ + [PARAM_STORIES]: 'explore', + ...(selected ? { [PARAM_SELECTED_STORY]: selected } : {}), + }), ); - if (id && storyById(id)) controller.openStory(id); + if (id && storyById(id)) controller.openStory(id, { atMs }); else { controller.open({ fromHistory: true }); // A story saved on someone else's device, or no longer here. if (id) store.flashToast(t('That story is not available here')); } }; - setTimeout(whenReady, 300); + readyTimer = setTimeout(whenReady, 300); } if (import.meta.env?.DEV) globalThis.__gevStories = { viewer, controller }; diff --git a/src/stories/controller.test.mjs b/src/stories/controller.test.mjs index ee5594acce..c8569df6e8 100644 --- a/src/stories/controller.test.mjs +++ b/src/stories/controller.test.mjs @@ -6,6 +6,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { createPinia, setActivePinia } from 'pinia'; +import { createStateChannel } from '../app/stateChannel.js'; registerHooks({ load(url, context, next) { @@ -123,21 +124,31 @@ function setup(options = {}) { const store = useStoriesStore(); const viewer = fakeViewer(); const director = fakeDirector(options); - const controller = createStoriesController({ viewer, director, store }); + const controller = createStoriesController({ + viewer, + director, + store, + onEnter: options.onEnter, + }); store.connect(controller, listStories()); return { store, viewer, director, controller }; } test('Close steps back over every entry Stories pushed', async () => { - const { controller } = setup(); + const entered = []; + const { controller } = setup({ + onEnter: () => + entered.push(document.body.classList.contains('stories-mode')), + }); const steps = []; const go = history.go; history.go = (n) => steps.push(n); try { - controller.open(); + assert.equal(controller.open(), true); assert.equal(history.state.gevStories.depth, 1); controller.openStory('gev:flights-radar'); assert.equal(history.state.gevStories.depth, 2); + assert.deepEqual(entered, [true]); await controller.close(); // Back after Close would otherwise land on ?story=… and reopen it. assert.deepEqual(steps, [-2]); @@ -158,8 +169,13 @@ test('Close from a Stories link clears Stories from the URL in place', async () }); test('Cockpit keeps the camera: Stories does not open', () => { - const { controller, store, director } = setup({ refuse: true }); - controller.open(); + const { controller, store, director } = setup({ + refuse: true, + onEnter: () => assert.fail('refused entry should not stop voice'), + }); + assert.equal(controller.open({ isCurrent: () => false }), false); + assert.deepEqual(director.claims, []); + assert.equal(controller.open(), false); assert.equal(store.mode, 'closed'); assert.equal(director.stops, 0); // The navigation policy shows the refusal; it needs a sentence for the noun. @@ -169,17 +185,21 @@ test('Cockpit keeps the camera: Stories does not open', () => { }); test('reopening while a scene tears down keeps the view from before Stories', async () => { - const { controller, viewer, director } = setup(); + const { controller, viewer, director, store } = setup(); const before = viewer.camera.positionWC; controller.open(); controller.openStory('gev:bhote-koshi-nepal-scene'); director.running = true; - const closing = controller.close(); + const toast = store.hostedToast; + const closing = controller.openInGev(); // The scene has moved the camera; the person opens Stories again at once. viewer.camera.positionWC = new Cesium.Cartesian3(9, 9, 9); controller.open(); director.running = false; await closing; + assert.deepEqual(director.selected, []); + assert.deepEqual(director.styleManager.panels, []); + assert.equal(store.hostedToast, toast); assert.equal( viewer.camera.views.length, 0, @@ -204,14 +224,36 @@ test('after a GEV scene, the person’s view comes back once the scene has torn controller.destroy(); }); -test('a share link carries the story, not the sender’s camera and layers', () => { - const { controller } = setup(); +test('Share links to the selection and captures the playing story’s timeline', () => { + const { controller, store } = setup(); controller.open(); + assert.equal(new URL(controller.shareLink()).search, '?stories=explore'); + controller.pick('gev:orbital-watch'); + assert.equal( + new URL(controller.shareLink()).search, + '?stories=explore&selectedStory=gev%3Aorbital-watch', + ); controller.openStory('gev:flights-radar'); + store.playback = { ...store.playback, playing: true, wallMs: 1250.6 }; const link = new URL(controller.shareLink()); - assert.equal(link.searchParams.get('story'), 'gev:flights-radar'); + assert.deepEqual( + [...link.searchParams], + [ + ['story', 'gev:flights-radar'], + ['storyTime', '1251'], + ], + ); assert.equal(link.hash, ''); - assert.equal(link.searchParams.has('x'), false, 'no other query parameters'); + store.playback.wallMs = 1850; + assert.equal( + new URL(controller.shareLink()).searchParams.get('storyTime'), + '1850', + ); + controller.backToExplore({ fromHistory: true }); + assert.equal( + new URL(controller.shareLink()).search, + '?stories=explore&selectedStory=gev%3Aflights-radar', + ); controller.destroy(); }); @@ -227,7 +269,7 @@ function recordGo(t) { } test('Back to Explore after a related story steps past both stories', (t) => { - const { controller } = setup(); + const { controller, store } = setup(); const steps = recordGo(t); controller.open(); controller.openStory('gev:flights-radar'); @@ -235,9 +277,19 @@ test('Back to Explore after a related story steps past both stories', (t) => { assert.equal(history.state.gevStories.depth, 3); assert.equal(history.state.gevStories.explore, 1); controller.backToExplore(); - // A second click before the traversal lands does nothing more. + controller.openStory('gev:flights-radar'); // queued behind Back + // The latest Back cancels that queued story without another traversal. controller.backToExplore(); assert.deepEqual(steps, [-2]); + history.replaceState( + { gevStories: { stories: 'explore', depth: 1, explore: 1 } }, + '', + '/?stories=explore', + ); + dispatchEvent(new PopStateEvent('popstate')); + assert.equal(store.mode, 'explore'); + assert.equal(store.storyId, null); + assert.equal(history.state.gevStories.depth, 1, 'no queued story pushed'); controller.destroy(); }); @@ -246,13 +298,13 @@ test('a second Close after a quick reopen still waits for the scene to tear down controller.open(); controller.openStory('gev:bhote-koshi-nepal-scene'); director.running = true; - controller.close(); + const first = controller.close({ keepCamera: true }); controller.open(); // reopened while the scene is still stopping const closing = controller.close(); // Explore: no GEV story on screen assert.ok(closing, 'this Close waits too'); assert.equal(viewer.camera.views.length, 0, 'nothing restored yet'); setTimeout(() => (director.running = false), 120); - await closing; + await Promise.all([first, closing]); assert.equal(viewer.camera.views.length, 1); controller.destroy(); }); @@ -262,7 +314,7 @@ test('a reload of a Stories entry keeps its history; Close steps all of it back' history.replaceState( { gevStories: { story: 'gev:flights-radar', depth: 2, explore: 1 } }, '', - '/?story=gev%3Aflights-radar', + '/?story=gev%3Aflights-radar&storyTime=1250', ); const steps = recordGo(t); const store = useStoriesStore(); @@ -274,6 +326,8 @@ test('a reload of a Stories entry keeps its history; Close steps all of it back' store.connect(controller, listStories()); await new Promise((resolve) => setTimeout(resolve, 400)); assert.equal(store.storyId, 'gev:flights-radar'); + assert.equal(store.playback.wallMs, 1250); + assert.equal(store.playback.playing, false); assert.equal(history.state.gevStories.depth, 2, 'no extra entry pushed'); await controller.close(); assert.deepEqual(steps, [-2]); @@ -282,7 +336,7 @@ test('a reload of a Stories entry keeps its history; Close steps all of it back' test('a new story link puts Explore under the story', async (t) => { setActivePinia(createPinia()); - history.replaceState(null, '', '/?story=gev%3Aflights-radar'); + history.replaceState(null, '', '/?story=gev%3Aflights-radar&storyTime=1250'); const steps = recordGo(t); const store = useStoriesStore(); const controller = createStoriesController({ @@ -293,8 +347,11 @@ test('a new story link puts Explore under the story', async (t) => { store.connect(controller, listStories()); await new Promise((resolve) => setTimeout(resolve, 400)); assert.equal(store.storyId, 'gev:flights-radar'); + assert.equal(store.playback.wallMs, 1250); + assert.equal(store.playback.playing, false); assert.deepEqual(history.state.gevStories, { story: 'gev:flights-radar', + storyTime: 1250, depth: 1, explore: 0, }); @@ -377,6 +434,29 @@ function land(hash = '#v=2&lat=1') { dispatchEvent(new PopStateEvent('popstate')); } +test('a second browser Back during scene teardown supersedes the Stories restore', async () => { + const { controller, director, store, viewer } = setup(); + const share = director.styleManager.shareLinkManager; + const holds = []; + share.holdWrites = (held) => holds.push(held); + director.selection = () => ({ sceneId: 'previous', shotId: 'shot-1' }); + controller.open(); + controller.openStory('gev:bhote-koshi-nepal-scene'); + director.running = true; + land(); + assert.equal(store.mode, 'closed'); + land('#v=2&lat=2'); + director.running = false; + await tick(0); + assert.equal(location.hash, '#v=2&lat=2'); + assert.equal(viewer.camera.views.length, 0); + assert.deepEqual(share.restored, []); + assert.deepEqual(director.selected, []); + assert.deepEqual(holds, [true, false]); + assert.equal(document.body.classList.contains('stories-mode'), false); + controller.destroy(); +}); + test('Close after a GEV scene puts the share state back once the step back lands', async (t) => { const { controller, director } = setup(); const steps = recordGo(t); @@ -386,8 +466,10 @@ test('Close after a GEV scene puts the share state back once the step back lands await controller.close(); assert.deepEqual(steps, [-2]); assert.deepEqual(restored, [], 'not before the landing'); + assert.equal(document.body.classList.contains('stories-mode'), true); land(); assert.deepEqual(restored, ['v=2&lat=1']); + assert.equal(document.body.classList.contains('stories-mode'), false); controller.destroy(); }); @@ -435,7 +517,7 @@ test('a reloaded Stories entry drops the share hash GEV wrote on boot', async () history.replaceState( { gevStories: { stories: 'explore', depth: 1, explore: 1 } }, '', - '/?stories=explore#v=2&lat=7', + '/?stories=explore&selectedStory=gev%3Aorbital-watch#v=2&lat=7', ); const store = useStoriesStore(); const controller = createStoriesController({ @@ -447,7 +529,19 @@ test('a reloaded Stories entry drops the share hash GEV wrote on boot', async () await new Promise((resolve) => setTimeout(resolve, 400)); assert.equal(store.mode, 'explore'); assert.equal(location.hash, ''); - assert.equal(new URL(location.href).searchParams.get('stories'), 'explore'); + assert.equal(store.picked, 'gev:orbital-watch'); + assert.equal( + location.search, + '?stories=explore&selectedStory=gev%3Aorbital-watch', + ); + const exploreState = history.state; + const exploreUrl = location.href; + controller.openStory('gev:flights-radar'); + assert.equal(location.search, '?story=gev%3Aflights-radar'); + history.replaceState(exploreState, '', exploreUrl); + dispatchEvent(new PopStateEvent('popstate')); + assert.equal(store.mode, 'explore'); + assert.equal(store.picked, 'gev:orbital-watch'); controller.destroy(); }); @@ -478,13 +572,13 @@ test('a scene saved to Stories from AUTHORING joins the list at once', () => { shotCount: 2, }, ]; - listener({ type: 'stories-changed' }); + listener({ change: { type: 'stories-changed' } }); const story = store.byId('gev:my-scene'); assert.equal(story?.title, 'Harbour at dawn'); assert.equal(story.mine, true); assert.equal(store.stories[0].id, 'gev:my-scene', 'the person’s own first'); mine = []; - listener({ type: 'stories-changed' }); + listener({ change: { type: 'stories-changed' } }); assert.equal(store.byId('gev:my-scene'), null, 'removed from Stories'); controller.destroy(); assert.equal(listener, null, 'unsubscribed'); @@ -492,10 +586,13 @@ test('a scene saved to Stories from AUTHORING joins the list at once', () => { test('Back to Explore after a scene puts the look back once the scene has torn down, then frames Explore', async () => { const { controller, viewer, director } = setup(); + history.replaceState(null, '', '/'); const flights = []; viewer.camera.flyTo = (f) => flights.push(f); viewer.camera.flyToBoundingSphere = (f) => flights.push(f); const share = director.styleManager.shareLinkManager; + const original = 'v=2&lat=1&style=normal'; + share.snapshotHash = () => original; // GEV's restore writes the hash it applies; Explore's address drops it. share.restore = function (hash) { this.restored.push(hash); @@ -506,13 +603,18 @@ test('Back to Explore after a scene puts the look back once the scene has torn d controller.openStory('gev:bhote-koshi-nepal-scene'); director.running = true; flights.length = 0; - controller.backToExplore({ fromHistory: true }); + history.replaceState( + { gevStories: { stories: 'explore', depth: 1, explore: 1 } }, + '', + '/?stories=explore', + ); + dispatchEvent(new PopStateEvent('popstate')); await tick(30); assert.deepEqual(share.restored, [], 'not under the stopping scene'); assert.equal(flights.length, 0, 'Explore waits for the scene'); director.running = false; await tick(40); - assert.deepEqual(share.restored, ['v=2&lat=1']); + assert.deepEqual(share.restored, [original]); assert.equal(location.hash, '', 'the address names only Stories'); assert.equal(flights.length, 1, 'then Explore frames the globe'); // A later Back to Explore with no scene in between restores nothing more. @@ -579,9 +681,16 @@ test('Explore tours from story to story once idle, stops on a pick or a touch, a test('a new Explore link keeps the address free of the share hash GEV writes as Stories opens', async () => { setActivePinia(createPinia()); - history.replaceState(null, '', '/?stories=explore'); + history.replaceState( + null, + '', + '/?stories=explore&selectedStory=gev%3Aorbital-watch', + ); const store = useStoriesStore(); const director = fakeDirector(); + const playbackCalls = []; + director.startScene = () => playbackCalls.push('start'); + director.seekScene = () => playbackCalls.push('seek'); // Holding writes first writes the view change still waiting. director.styleManager.shareLinkManager.holdWrites = (held) => { if (held) history.replaceState(history.state, '', `${location.search}#v=2`); @@ -595,7 +704,13 @@ test('a new Explore link keeps the address free of the share hash GEV writes as await tick(400); assert.equal(store.mode, 'explore'); assert.equal(location.hash, ''); - assert.equal(location.search, '?stories=explore'); + assert.equal( + location.search, + '?stories=explore&selectedStory=gev%3Aorbital-watch', + ); + assert.equal(store.picked, 'gev:orbital-watch'); + assert.equal(store.storyId, null); + assert.deepEqual(playbackCalls, []); controller.destroy(); }); @@ -690,13 +805,12 @@ test('Close after Back to Explore still puts AUTHORING’s selection back', asyn controller.destroy(); }); -test('the person’s unsaved scenes list as drafts, which cannot be shared', () => { +test('unsaved scenes appear as local drafts and disappear when deleted', () => { setActivePinia(createPinia()); history.replaceState(null, '', '/'); const store = useStoriesStore(); const director = fakeDirector(); - director.subscribe = () => () => {}; - director.draftScenes = () => [ + const drafts = [ { id: 'sketch', title: 'Sketch', @@ -706,6 +820,9 @@ test('the person’s unsaved scenes list as drafts, which cannot be shared', () tags: [], }, ]; + const channel = createStateChannel(() => ({ scenes: drafts })); + director.subscribe = channel.subscribe; + director.draftScenes = () => drafts; const controller = createStoriesController({ viewer: fakeViewer(), director, @@ -715,6 +832,10 @@ test('the person’s unsaved scenes list as drafts, which cannot be shared', () const draft = store.byId('gev:sketch'); assert.equal(draft?.draft, true); assert.equal(draft.mine, true, 'local only: no Share'); + drafts.length = 0; + channel.publish({ type: 'scene-deleted' }); + controller.open(); + assert.equal(store.byId('gev:sketch'), null); controller.destroy(); }); @@ -755,20 +876,31 @@ test('the tour waits again after a wheel turn or a cancelled press, and a list c assert.equal(flights.length, before + 1, `${type}: then tours`); } canvas.dispatchEvent(new Event('pointerdown')); - listener({ type: 'stories-changed' }); + listener({ change: { type: 'stories-changed' } }); const held = flights.length; t.mock.timers.tick(30000); assert.equal(flights.length, held, 'nothing flies under the drag'); again.destroy(); }); -test('teardown mid-close lets the share link write again', () => { - const { controller, director } = setup(); +test('teardown mid-close releases share writes and cancels a queued reopen', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { controller, director, store, viewer } = setup(); + recordGo(t); const held = []; director.styleManager.shareLinkManager.holdWrites = (on) => held.push(on); + let flights = 0; + viewer.camera.flyTo = () => flights++; controller.open(); + await controller.close(); + controller.open(); // queued until the Close traversal lands controller.destroy(); + const before = flights; assert.equal(held.at(-1), false); + t.mock.timers.tick(3000); + assert.equal(store.mode, 'closed'); + assert.equal(held.at(-1), false, 'no late reopen holds writes again'); + assert.equal(flights, before, 'no late flight after teardown'); }); test('place names name only a shipped scene’s untitled shots', () => { @@ -785,3 +917,76 @@ test('place names name only a shipped scene’s untitled shots', () => { ); controller.destroy(); }); + +test('new navigation cancels a delayed initial story link', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + for (const action of ['back', 'open', 'close']) { + setActivePinia(createPinia()); + history.replaceState(null, '', '/?story=gev%3Aflights-radar'); + const store = useStoriesStore(); + const controller = createStoriesController({ + viewer: fakeViewer(), + director: fakeDirector(), + store, + }); + store.connect(controller, listStories()); + try { + if (action === 'back') land(); + else if (action === 'open') controller.open(); + else controller.close(); + const url = location.href; + t.mock.timers.tick(400); + assert.equal( + store.mode, + action === 'open' ? 'explore' : 'closed', + action, + ); + assert.equal(store.storyId, null, action); + assert.equal( + location.href, + url, + 'the old link does not rewrite navigation', + ); + } finally { + controller.destroy(); + } + } +}); + +test('an earlier Back timeout cannot release a later traversal', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const { controller, store } = setup(); + const steps = recordGo(t); + const landExplore = () => { + history.replaceState( + { gevStories: { stories: 'explore', depth: 1, explore: 1 } }, + '', + '/?stories=explore', + ); + dispatchEvent(new PopStateEvent('popstate')); + }; + try { + controller.open(); + controller.openStory('gev:flights-radar'); + controller.backToExplore(); + landExplore(); + t.mock.timers.tick(1500); + controller.openStory('gev:orbital-watch'); + controller.backToExplore(); + controller.close(); + t.mock.timers.tick(600); + assert.equal(store.mode, 'story', 'Close still waits for the second Back'); + assert.deepEqual(steps, [-1, -1]); + landExplore(); + // Drain the director's already-idle promise without advancing timers. + for (let i = 0; i < 12; i++) await Promise.resolve(); + assert.equal(store.mode, 'closed'); + assert.deepEqual( + steps, + [-1, -1, -1], + 'queued Close runs once after landing', + ); + } finally { + controller.destroy(); + } +}); diff --git a/src/stories/gevPlayer.js b/src/stories/gevPlayer.js index 5a43a624a4..35210ea658 100644 --- a/src/stories/gevPlayer.js +++ b/src/stories/gevPlayer.js @@ -44,7 +44,7 @@ export function createGevPlayer(director, story, hooks = {}) { let shotIndex = 0; let destroyed = false; // Each Play, Pause, Seek and Destroy takes a new number; a Play that waited - // for a teardown or a start goes ahead only if nothing came after it. + // for a teardown or a run to finish acts only if nothing came after it. let request = 0; const state = () => ({ @@ -65,7 +65,8 @@ export function createGevPlayer(director, story, hooks = {}) { wallMs = (snap.sceneElapsedSec ?? 0) * 1000; shotIndex = snap.shotIndex ?? shotIndex; playing = !!snap.running && !snap.seeking; - if (!playing && wallMs >= durationMs - 250) wallMs = durationMs; + if (!playing && !snap.seeking && wallMs >= durationMs - 250) + wallMs = durationMs; tick(); }); @@ -100,13 +101,9 @@ export function createGevPlayer(director, story, hooks = {}) { afterShotId, preview: true, }); - if (destroyed) return; - if (mine !== request) { - // Paused or scrubbed while the run was starting: that wins. - if (result?.started) - director.seekScene(sceneId, durationMs ? wallMs / durationMs : 0); - return; - } + // startScene resolves after the run finishes, not when it starts. + // A newer pause, seek or play already owns the director by then. + if (destroyed || mine !== request) return; if (!result?.started) { playing = false; tick(); diff --git a/src/stories/gevPlayer.test.mjs b/src/stories/gevPlayer.test.mjs index eeef43108f..e94093d193 100644 --- a/src/stories/gevPlayer.test.mjs +++ b/src/stories/gevPlayer.test.mjs @@ -1,5 +1,5 @@ // A GEV scene's Play waits for the last run to tear down and for the new run -// to start; a Pause, Seek or Destroy meanwhile must win. +// to finish; a Pause, Seek or Destroy meanwhile must win. import test from 'node:test'; import assert from 'node:assert/strict'; import { createGevPlayer } from './gevPlayer.js'; @@ -10,7 +10,7 @@ const story = { chapters: [{ wallMs: 0 }, { wallMs: 30000 }], }; -/** A director whose start resolves when the test says so. */ +/** A director whose run starts immediately and ends when the test says so. */ function deferredDirector({ running = false } = {}) { const calls = []; let release = null; @@ -30,14 +30,15 @@ function deferredDirector({ running = false } = {}) { seekScene: (id, f) => calls.push(`seek ${f}`), startScene: () => { calls.push('start'); + director.running = true; return new Promise((resolve) => { release = () => { - director.running = true; + director.running = false; resolve({ started: true }); }; }); }, - finishStart: () => release?.(), + finishRun: () => release?.(), }; return director; } @@ -70,17 +71,39 @@ test('a Seek during the last run’s teardown cancels the waiting Play', async ( assert.equal(player.state.wallMs, 30000); }); -test('a Pause while the run is starting is applied once it has started', async () => { +test('a stopped run’s completion does not repeat a newer seek', async () => { const director = deferredDirector(); const player = createGevPlayer(director, story); const playing = player.play(); await turns(); assert.deepEqual(director.calls, ['start']); + assert.equal(director.running, true); player.pause(); - director.finishStart(); + player.seek(30000); + director.finishRun(); await playing; - // Pause seeks once when pressed, and again after the late start. - assert.equal(director.calls.filter((c) => c.startsWith('seek')).length, 2); + assert.deepEqual(director.calls, ['start', 'seek 0', 'seek 0.5']); + assert.equal(player.state.playing, false); + assert.equal(player.state.wallMs, 30000); +}); + +test('a paused seek keeps its exact position near the end of a story', () => { + const director = deferredDirector(); + let publishClock; + director.subscribeSceneClock = (listener) => { + publishClock = listener; + return () => {}; + }; + const player = createGevPlayer(director, story); + player.seek(59800); + publishClock({ + sceneId: story.sceneId, + sceneElapsedSec: 59.8, + sceneDurationSec: 60, + running: false, + seeking: true, + }); + assert.equal(player.state.wallMs, 59800); assert.equal(player.state.playing, false); }); diff --git a/src/ui/views/stories/StoriesHeader.vue b/src/ui/views/stories/StoriesHeader.vue index e53d35b3b3..72502064aa 100644 --- a/src/ui/views/stories/StoriesHeader.vue +++ b/src/ui/views/stories/StoriesHeader.vue @@ -22,15 +22,19 @@ const props = defineProps({ const emit = defineEmits(['back', 'home', 'crumb', 'search']); const store = useStoriesStore(); // A scene saved on this device only: a link to it opens nothing elsewhere. -const localOnly = computed(() => !!store.byId(store.storyId)?.mine); +const localOnly = computed( + () => + !!store.byId(props.screen === 'story' ? store.storyId : store.picked)?.mine, +); async function share() { const what = props.screen === 'story' ? t('Story') : t('Stories'); + const url = store.controller.shareLink(); try { - await navigator.clipboard.writeText(store.controller.shareLink()); + await navigator.clipboard.writeText(url); store.flashToast(t('{what} link copied', { what })); } catch { - store.flashToast(t('Copy this link: {url}', { url: location.href }), 4000); + store.flashToast(t('Copy this link: {url}', { url }), 4000); } } // Long titles scroll gently so the whole name can be read. @@ -131,7 +135,7 @@ onBeforeUnmount(() => observer?.disconnect()); - {{ t(c) }}
@@ -623,10 +619,7 @@ defineExpose({ alt="" loading="lazy" /> - {{ t('LIVE') }} - {{ + {{ s.draft ? t('DRAFT') : t('STORY') }} {{ fmtDur(s.durationMs) }} diff --git a/src/ui/views/stories/StoryScreen.vue b/src/ui/views/stories/StoryScreen.vue index 058190f97d..ad32f837fe 100644 --- a/src/ui/views/stories/StoryScreen.vue +++ b/src/ui/views/stories/StoryScreen.vue @@ -342,7 +342,7 @@ watch([k, page], () => nextTick(sizeCard));
{{ - story.live ? t('LIVE') : story.draft ? t('DRAFT') : t('STORY') + story.draft ? t('DRAFT') : t('STORY') }}
{{ title }}
From 0ed6cde956d0b141f066853a847113796b4cc8a0 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:10:01 -0800 Subject: [PATCH 32/70] Idle frame rate in the app, timed line batching, KEY REQUIRED status Three fixes to how the globe draws and reports loading. **The idle frame rate is the app's rule.** The Cesium frame port capped the loop at `IDLE_FRAME_RATE` whenever nothing held it, so the rule lived inside the renderer. The render governor now sets the rate: the display's own while the loop is held, `IDLE_FRAME_RATE` while not. The frame port gains `onHeldChange(cb)`, which says when its first hold is taken and its last released (animated visual styles included), so the governor hears every hold. The quality setting's frame-rate cap is kept apart from the governor's rate, and the loop draws at the lower of the two, so neither overwrites the other. **Line batching is timed.** A line set waited 30 drawn frames before its unchanged lines settled into a static batch (300 for the long wait), so the batch built twice as fast at 120 Hz as at 60 Hz, and took seconds at the idle rate. It now waits `SETTLE_MS` (500 ms) and `LONG_SETTLE_MS` (5 s), and moved shapes go back into their batches on the same timing. **KEY REQUIRED.** A layer that cannot load without a provider key ended the global status chip LOAD FAILED. The chip now has a KEY REQUIRED outcome, ranked below a real failure: a layer whose stats say `keyRequired` ends KEY REQUIRED, any other failure still ends LOAD FAILED. Vessels report a missing AISStream key as `keyRequired` and name the key in the panel; a later outage clears it, as it is no longer the key that is missing. Checked: the full suite (new tests for `onHeldChange`, the quality cap against the governor's rate, timed settling, and the chip with and without a key), format, boundaries, build, the stub renderer boot and the Cesium conformance run; in the browser, the idle and held frame rates; and the first-run check now asserts that with no keys set the chip never says LOAD FAILED. --- docs/CURRENT-STATE.md | 31 ++++---- docs/PERFORMANCE.md | 2 +- scripts/qa-firstrun.mjs | 17 +++-- src/firstRunExperience.js | 13 +--- src/firstRunExperience.test.mjs | 18 +++-- src/layers/vessels/ingestion.js | 4 + src/layers/vessels/ingestion.test.mjs | 38 ++++++++++ src/layers/vessels/ownership.test.mjs | 18 +++++ src/layers/vessels/queries.js | 3 + src/loadingFeedback.js | 46 ++++++++---- src/loadingFeedback.test.mjs | 100 +++++++++++++++++++++++-- src/render/cesium/appRenderer.js | 3 - src/render/cesium/appRenderer.test.mjs | 24 ++++-- src/render/cesium/applicationViewer.js | 5 +- src/render/cesium/draw.js | 66 +++++++++------- src/render/cesium/draw.test.mjs | 73 ++++++++++++++---- src/render/cesium/frame.js | 7 ++ src/render/cesium/frame.test.mjs | 17 +++++ src/render/cesium/harness.js | 1 + src/render/cesium/ports.js | 54 +++++++------ src/render/cesium/ports.test.mjs | 50 ++++++++----- src/render/cesium/quality.js | 15 +++- src/render/conformance/checks/ports.js | 20 +++++ src/render/contract/frame.d.ts | 5 ++ src/render/contract/index.js | 1 + src/render/stub/index.js | 21 +++++- src/renderGovernor.js | 34 +++++++-- src/renderGovernor.test.mjs | 59 +++++++++++++-- src/sources/live/standalone.js | 2 + src/sources/live/standalone.test.mjs | 27 +++++++ src/testSupport/fakeFramePort.mjs | 23 +++++- src/ui/shellFeedback.js | 1 + src/ui/styles/status.css | 10 ++- 33 files changed, 629 insertions(+), 179 deletions(-) create mode 100644 src/sources/live/standalone.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 811e2a1fd6..6d4b2c853e 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -12,11 +12,13 @@ north. While anything moves (a layer in motion, the camera, a followed contact), the globe draws at the display's own refresh rate; there is no fixed 60 FPS cap. -The Cesium frame port (`src/render/cesium/ports.js`, its `idleFps`) caps a -parked scene at `IDLE_FRAME_RATE` (60, `src/renderGovernor.js`) ticks a -second while no hold is out, because Cesium still runs the clock, data sources -and update listeners on every animation frame even when it skips the draw; the -viewer starts at that cap until the frame port takes over. Through the idle +The render governor (`src/renderGovernor.js`) caps a parked scene at +`IDLE_FRAME_RATE` (60) ticks a second while nothing holds the loop, because +Cesium still runs the clock, data sources and update listeners on every +animation frame even when it skips the draw, and lifts the cap while anything +does: the frame port tells it when the loop's first hold is taken and its last +released, its own holds (animated visual styles) included. The viewer starts +at that cap until the governor is installed. Through the idle render governor, the camera port holds continuous render from `moveStart` to `moveEnd`, and samples its pose every 250 ms in between, so a camera drifting by rounding errors (no `moveEnd`) is released after half a second at rest and held again if it moves. The world clock holds continuous render while @@ -3809,10 +3811,10 @@ which embeds the MAP_KEY. > a layer that needs no key, already holds one, or names a key the registry does > not recognise. The earthquakes half > still delivers in full. The shared loading reducer now treats an explicitly -> declared missing optional key as a configured terminal state rather than a -> failed multi-layer mission, so the global chip completes without showing -> `LOAD FAILED`. A genuine lifecycle or fetch failure still retains failure -> priority. +> declared missing optional key as its own terminal state rather than a +> failed multi-layer mission, so the global chip ends `KEY REQUIRED` (amber) +> instead of `LOAD FAILED`, on the first load and on every refresh. A genuine +> lifecycle or fetch failure still retains failure priority. > > **Acceptance changed with that ruling (2026-08-23).** `qa-firstrun` no longer > asserts "a keyless Environmental never shows a failure chip" — that stopped @@ -4504,12 +4506,13 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > specific error or availability state. The shared presentation is delayed to > avoid flashes, visible outside the rails, and retained in > Cockpit. One continuous overlapping load interval retains the strongest -> terminal outcome (`failed`, then `cancelled`, then `complete`) until every -> participant settles, so a later success cannot mask an earlier failure. -> A participating producer's terminal error, unavailable status, or -> key-required state also outranks generic completion without requiring a +> terminal outcome (`failed`, then `key required`, then `cancelled`, then +> `complete`) until every participant settles, so a later success cannot +> mask an earlier failure. A participating producer's terminal error or +> unavailable status also outranks generic completion without requiring a > separate manager failure event; AIS first-connect expiry therefore ends as -> `LOAD FAILED`, not `LOAD COMPLETE`. +> `LOAD FAILED`, not `LOAD COMPLETE`. A producer whose only problem is a +> missing provider key (`stats.keyRequired`) ends the batch `KEY REQUIRED`. > Slow disable work is labeled as turning live data off rather than > as a completed load. Street Traffic's dedicated sync chip shows genuine > work and one bounded completion; steady TomTom coverage, including 0%, does diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 8b33ce6244..32f5fdf030 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -34,7 +34,7 @@ hardware-rendered overlay scenes. These frame rates were measured when the globe was capped at 60 FPS. It now draws at the display's refresh rate while anything moves and ticks at most 60 -times a second when parked (the Cesium frame port's idle rate, +times a second when parked (the render governor's idle rate, `IDLE_FRAME_RATE` in `src/renderGovernor.js`). The initial-settle measurement is the more useful launch reference because it diff --git a/scripts/qa-firstrun.mjs b/scripts/qa-firstrun.mjs index c8291ed62b..021d1b58dc 100644 --- a/scripts/qa-firstrun.mjs +++ b/scripts/qa-firstrun.mjs @@ -590,14 +590,9 @@ async function main() { * * KEYED — both datasets must actually arrive, and a failure banner in * that state is a real defect, so the chip IS asserted. - * KEYLESS — only the LAYER ROW is asserted: FIRMS reports KEY REQUIRED, - * which is the honest surface a keyless visitor is judged on. - * The GLOBAL chip is deliberately NOT asserted in either - * direction here: it has no key-required terminal state and - * folds that row into a misleading LOAD FAILED. That - * aggregation is a defect in the shared state machine - * (`src/loadingFeedback.js`), LEDGERED post-launch — it is not - * a desirable outcome and not this tile's contract. + * KEYLESS — the LAYER ROW reports KEY REQUIRED, and the GLOBAL chip + * never says LOAD FAILED: a missing key ends the batch + * KEY REQUIRED (`src/loadingFeedback.js`). */ const keyless = state.firmsError === 'KEY REQUIRED'; console.log(` \x1b[2m FIRMS key state: ${keyless ? 'KEYLESS' : 'KEYED'} ` @@ -613,6 +608,12 @@ async function main() { (state.counts.earthquakes ?? 0) > 0, `${state.counts.earthquakes} quakes`, ); + const keylessChip = await readLoadingChip(page); + record( + 'KEYLESS: the global chip never says LOAD FAILED for a missing key', + !keylessChip.some((entry) => /LOAD FAILED/i.test(entry)), + keylessChip.join(' → ') || 'no chip', + ); } else { record( 'KEYED: both datasets actually arrive', diff --git a/src/firstRunExperience.js b/src/firstRunExperience.js index b1a38a2733..79d5460aef 100644 --- a/src/firstRunExperience.js +++ b/src/firstRunExperience.js @@ -98,15 +98,10 @@ export const FIRST_RUN_MISSIONS = Object.freeze({ // for the FULLY CONFIGURED experience (owner ruling, 2026-08-23): the tile // promises both, so it turns on both, and the subcopy in index.html says so. // - // Keyless, FIRMS is honest where it counts — its own layer row reads - // "UNAVAILABLE · NASA FIRMS · LIVE · KEY REQUIRED", and the quakes half of - // the tile still delivers in full. What is NOT honest is the GLOBAL status - // chip, which has no key-required terminal state and folds that row into - // "LOAD FAILED". That aggregation is the defect, not this preset: fixing it - // means a KEY REQUIRED terminal state in src/loadingFeedback.js, a state - // machine shared by every layer and not a thing to refactor the night - // before a launch. LEDGERED post-launch. Until it lands, keyless visitors - // are judged on the layer row, which tells them the truth. + // Keyless, FIRMS says so: its layer row reads + // "UNAVAILABLE · NASA FIRMS · LIVE · KEY REQUIRED", the global status chip + // ends KEY REQUIRED (src/loadingFeedback.js), and the quakes half of the + // tile still delivers in full. layerIds: Object.freeze(['earthquakes', 'local-firms']), busyKey: msg('Scanning active events…'), }), diff --git a/src/firstRunExperience.test.mjs b/src/firstRunExperience.test.mjs index e81e4651e9..ef0af4df4d 100644 --- a/src/firstRunExperience.test.mjs +++ b/src/firstRunExperience.test.mjs @@ -386,8 +386,13 @@ test('one ESC does one thing — a Cockpit utility disclosure stops later docume // they own the same contract: their capture handler is the only one that can // keep a later document listener (Cockpit exit, the launcher) off the key, and // only the immediate form does it. - const utilityEsc = ui.slice(ui.indexOf('if (!displayOpen && !radioOpen) return;')); - const claim = utilityEsc.slice(0, utilityEsc.indexOf('setCockpitDisclosure(kind, false')); + const utilityEsc = ui.slice( + ui.indexOf('if (!displayOpen && !radioOpen) return;'), + ); + const claim = utilityEsc.slice( + 0, + utilityEsc.indexOf('setCockpitDisclosure(kind, false'), + ); assert.match(claim, /event\.preventDefault\(\);/); assert.match(claim, /event\.stopImmediatePropagation\(\);/); assert.doesNotMatch( @@ -606,11 +611,8 @@ test('the tile is the FULLY CONFIGURED experience: quakes and fires together', ( const environmental = FIRST_RUN_MISSIONS.environmental; assert.deepEqual(environmental.layerIds, ['earthquakes', 'local-firms']); - // Keyless, the honest surface is the LAYER ROW ("KEY REQUIRED"), which the - // FIRMS layer already reports. The misleading part is the GLOBAL chip folding - // that row into LOAD FAILED — a defect in the shared state machine, ledgered - // post-launch, and the note must stay where the next editor will read it - // rather than being re-discovered as a launcher bug. + // Keyless, FIRMS says so on its layer row and in the global chip (both + // KEY REQUIRED), and the note says where the chip's ending comes from. const module = fs.readFileSync( new URL('./firstRunExperience.js', import.meta.url), 'utf8', @@ -621,7 +623,7 @@ test('the tile is the FULLY CONFIGURED experience: quakes and fires together', ( ); assert.match(table, /KEY REQUIRED/); assert.match(table, /src\/loadingFeedback\.js/); - assert.match(table, /LEDGERED post-launch/); + assert.match(table, /global status chip\s+\/\/\s+ends KEY REQUIRED/); }); test('every visitor gets the same tile — there is no degraded keyless variant', async () => { diff --git a/src/layers/vessels/ingestion.js b/src/layers/vessels/ingestion.js index c5a2ca74c3..b70d1ee88b 100644 --- a/src/layers/vessels/ingestion.js +++ b/src/layers/vessels/ingestion.js @@ -121,6 +121,10 @@ export function createIngestion({ ownsAisRequest(requestController, requestSessionId) && error?.name !== 'AbortError' ) { + // The key is missing only while the source says so; any other + // failure is an outage, not a key to add. + feed.transportStatus = + error?.code === 'key-required' ? 'missing-key' : null; markUnavailable(error?.message || msg('AIS live load failed')); console.warn('[Data:ais-live-vessels]', feed.error, error); } diff --git a/src/layers/vessels/ingestion.test.mjs b/src/layers/vessels/ingestion.test.mjs index 1366ca61d9..6c1a90baa9 100644 --- a/src/layers/vessels/ingestion.test.mjs +++ b/src/layers/vessels/ingestion.test.mjs @@ -147,3 +147,41 @@ test('vessels are asked for by the area in view, and again only when the view mo await ingestion.refreshIfMoved(); assert.deepEqual(asked.at(-1), { maxRows: 500 }); }); + +test('a source refusing for want of a key leaves the feed waiting for its key', async () => { + const keyless = Object.assign(new Error('AISSTREAM_API_KEY not set'), { + code: 'key-required', + }); + const probe = setup({ + getSnapshot: async () => { + throw keyless; + }, + }); + await probe.methods.update(); + assert.equal(probe.feed.transportStatus, 'missing-key'); + assert.equal(probe.feed.error, 'AISSTREAM_API_KEY not set'); + const down = setup({ + getSnapshot: async () => { + throw new Error('feed down'); + }, + }); + await down.methods.update(); + assert.notEqual(down.feed.transportStatus, 'missing-key'); +}); + +test('a source failing for another reason after a missing key is an outage, not a key to add', async () => { + let fail = Object.assign(new Error('AISSTREAM_API_KEY not set'), { + code: 'key-required', + }); + const probe = setup({ + getSnapshot: async () => { + throw fail; + }, + }); + await probe.methods.update(); + assert.equal(probe.feed.transportStatus, 'missing-key'); + fail = new Error('feed down'); + await probe.methods.update(); + assert.equal(probe.feed.transportStatus, null); + assert.equal(probe.feed.error, 'feed down'); +}); diff --git a/src/layers/vessels/ownership.test.mjs b/src/layers/vessels/ownership.test.mjs index 265c25e270..b4b8772eda 100644 --- a/src/layers/vessels/ownership.test.mjs +++ b/src/layers/vessels/ownership.test.mjs @@ -601,3 +601,21 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async () assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true); assert.match(atob(icons.item('993672009').image.split(',')[1]), / { + let current = snapshot([], { + transportStatus: 'missing-key', + complete: false, + }); + const { layer } = setup({ + async getSnapshot() { + return current; + }, + }); + assert.equal(layer.requiresKeyId, 'aisstream'); + await layer.update(); + assert.equal(layer.getStats().keyRequired, true); + current = snapshot([observation('111')]); + await layer.update(); + assert.equal(layer.getStats().keyRequired, false); +}); diff --git a/src/layers/vessels/queries.js b/src/layers/vessels/queries.js index 38bf0f5b7b..d5fa214f0b 100644 --- a/src/layers/vessels/queries.js +++ b/src/layers/vessels/queries.js @@ -299,6 +299,8 @@ export function createQueries({ icon: '◭', source: 'AISStream', + // Without an AISStream key the feed cannot start; the panel names the key. + requiresKeyId: 'aisstream', updateInterval: REFRESH_MS, @@ -713,6 +715,7 @@ export function createQueries({ ? 'unavailable' : undefined, transportStatus: state.feed.transportStatus, + keyRequired: state.feed.transportStatus === 'missing-key', lastMessageAt: state.feed.lastMessageAt, rawRowCount: state.feed.rawRowCount, acceptedRowCount: state.feed.acceptedRowCount, diff --git a/src/loadingFeedback.js b/src/loadingFeedback.js index b4ea03ba11..3da12d0268 100644 --- a/src/loadingFeedback.js +++ b/src/loadingFeedback.js @@ -82,16 +82,22 @@ export function normalizeLayerLoading(layer = {}) { }; } +/** + * A batch's ending from its layers' stats: a layer that failed fails it; a + * layer only waiting for its provider key (whose error is that missing key) + * ends it KEY REQUIRED, which asks the user to act rather than reporting a + * fault. + */ function terminalFromParticipantStats(summary, participantIds) { if (!participantIds?.length) return null; const participants = new Set(participantIds); - return summary.records.some( - (record) => - participants.has(record.id) && - (record.error || record.unavailable || record.keyRequired), - ) - ? 'error' - : null; + let keyRequired = false; + for (const record of summary.records) { + if (!participants.has(record.id)) continue; + if (record.keyRequired) keyRequired = true; + else if (record.error || record.unavailable) return 'error'; + } + return keyRequired ? 'key-required' : null; } /** Aggregate all manager layers without changing their lifecycle authority. */ @@ -272,17 +278,26 @@ export function reduceTrafficSyncFeedback( }; } -function terminalFromEvent(event) { +/** + * A lifecycle event's ending. A layer that failed only for want of its + * provider key (its stats say `keyRequired`) ends KEY REQUIRED on every + * load or refresh, not just the first. + */ +function terminalFromEvent(event, summary) { const type = String(event?.type || ''); if (type === 'visibility-failed' || type === 'refresh-failed' || event?.error) - return 'error'; + return summary?.records?.some( + (record) => record.id === event?.layerId && record.keyRequired, + ) + ? 'key-required' + : 'error'; if (type === 'visibility-cancelled' || event?.cancelled) return 'cancelled'; if (type === 'visibility' || type === 'refresh') return 'complete'; return null; } function mergeTerminalOutcome(current, next) { - const severity = { complete: 1, cancelled: 2, error: 3 }; + const severity = { complete: 1, cancelled: 2, 'key-required': 3, error: 4 }; if (!next) return current || null; if (!current || severity[next] > severity[current]) return next; return current; @@ -306,7 +321,7 @@ export function reduceLoadingFeedback(previous, summary, nowMs, event = null) { beginning ? null : state.batchOutcome, terminalFromParticipantStats(summary, activeIds), ), - eventParticipates ? terminalFromEvent(event) : null, + eventParticipates ? terminalFromEvent(event, summary) : null, ); return { phase: 'loading', @@ -325,7 +340,7 @@ export function reduceLoadingFeedback(previous, summary, nowMs, event = null) { failedEventIds: [ ...new Set([ ...(beginning ? [] : state.failedEventIds || []), - ...(eventParticipates && terminalFromEvent(event) === 'error' + ...(eventParticipates && terminalFromEvent(event, summary) === 'error' ? [eventLayerId] : []), ]), @@ -343,13 +358,13 @@ export function reduceLoadingFeedback(previous, summary, nowMs, event = null) { state.batchOutcome, terminalFromParticipantStats(summary, state.activeIds), ), - eventParticipates ? terminalFromEvent(event) : null, + eventParticipates ? terminalFromEvent(event, summary) : null, ) || 'complete'; const wasVisible = state.visible || now >= state.showAt; if (!wasVisible && terminal === 'complete') return createLoadingFeedbackState(); const dwell = - terminal === 'error' + terminal === 'error' || terminal === 'key-required' ? LOADING_FAILURE_DWELL_MS : LOADING_TERMINAL_DWELL_MS; return { @@ -362,7 +377,7 @@ export function reduceLoadingFeedback(previous, summary, nowMs, event = null) { failedEventIds: [ ...new Set([ ...(state.failedEventIds || []), - ...(eventParticipates && terminalFromEvent(event) === 'error' + ...(eventParticipates && terminalFromEvent(event, summary) === 'error' ? [eventLayerId] : []), ]), @@ -424,6 +439,7 @@ export function presentLoadingFeedback(state, summary, nowMs) { const labels = { complete: 'LOAD COMPLETE', cancelled: 'LOAD CANCELLED', + 'key-required': 'KEY REQUIRED', error: 'LOAD FAILED', }; const label = diff --git a/src/loadingFeedback.test.mjs b/src/loadingFeedback.test.mjs index ab26f6a3e9..d5fa36c1f0 100644 --- a/src/loadingFeedback.test.mjs +++ b/src/loadingFeedback.test.mjs @@ -474,15 +474,15 @@ test('reveals sustained loading and then a bounded completion state', () => { ); }); -test('terminal loading feedback centers its label without an empty detail slot', () => { +test('terminal loading feedback, KEY REQUIRED included, centers its label without an empty detail slot', () => { const css = readStylesheet(new URL('../style.css', import.meta.url)); assert.match( css, - /#global-loading-status:is\(\s*\[data-state='complete'\],\s*\[data-state='cancelled'\],\s*\[data-state='error'\]\s*\)\s*\{[\s\S]*?justify-content:\s*center;[\s\S]*?text-align:\s*center;/, + /#global-loading-status:is\(\s*\[data-state='complete'\],\s*\[data-state='cancelled'\],\s*\[data-state='key-required'\],\s*\[data-state='error'\]\s*\)\s*\{[\s\S]*?justify-content:\s*center;[\s\S]*?text-align:\s*center;/, ); assert.match( css, - /#global-loading-status:is\(\s*\[data-state='complete'\],\s*\[data-state='cancelled'\],\s*\[data-state='error'\]\s*\)\s*#global-loading-detail\s*\{\s*display:\s*none;/, + /#global-loading-status:is\(\s*\[data-state='complete'\],\s*\[data-state='cancelled'\],\s*\[data-state='key-required'\],\s*\[data-state='error'\]\s*\)\s*#global-loading-detail\s*\{\s*display:\s*none;/, ); }); @@ -618,7 +618,7 @@ test('AIS first-connect grace expiry reports failure even without a terminal man ); }); -test('participant stats failure outranks a simultaneous visibility completion', () => { +test('a participant waiting for its key outranks a simultaneous visibility completion', () => { const enabling = aggregateLayerLoading([ { id: 'ais-live-vessels', @@ -645,7 +645,97 @@ test('participant stats failure outranks a simultaneous visibility completion', enabled: true, }); - assert.equal(state.terminal, 'error'); + assert.equal(state.terminal, 'key-required'); + const view = presentLoadingFeedback(state, missingKey, 250); + assert.equal(view.label, 'KEY REQUIRED'); + assert.equal(view.state, 'key-required'); + assert.equal( + state.hideAt, + 250 + LOADING_FAILURE_DWELL_MS, + 'shown long enough to read', + ); +}); + +test('a keyless layer’s refresh failing ends KEY REQUIRED, and another layer’s LOAD FAILED', () => { + const refreshEnd = (layer) => { + const refreshing = aggregateLayerLoading([ + { + ...layer, + enabled: true, + lifecycleState: 'enabled', + stats: { ...layer.stats, refreshing: true }, + }, + ]); + let state = reduceLoadingFeedback( + createLoadingFeedbackState(), + refreshing, + 0, + ); + state = reduceLoadingFeedback(state, refreshing, 200); + const done = aggregateLayerLoading([ + { ...layer, enabled: true, lifecycleState: 'enabled' }, + ]); + state = reduceLoadingFeedback(state, done, 300, { + type: 'refresh-failed', + layerId: layer.id, + error: new Error(layer.stats.error), + }); + return presentLoadingFeedback(state, done, 300).label; + }; + assert.equal( + refreshEnd({ + id: 'ais-live-vessels', + stats: { keyRequired: true, error: 'AISSTREAM_API_KEY not set' }, + }), + 'KEY REQUIRED', + ); + assert.equal( + refreshEnd({ id: 'ais-live-vessels', stats: { error: 'feed down' } }), + 'LOAD FAILED', + ); +}); + +test('a missing key ends a batch KEY REQUIRED, and another layer failing still ends it LOAD FAILED', () => { + const loading = (ids) => + aggregateLayerLoading( + ids.map((id) => ({ id, lifecycleState: 'enabling' })), + ); + const ended = (layers) => { + let state = reduceLoadingFeedback( + createLoadingFeedbackState(), + loading(layers.map((layer) => layer.id)), + 0, + ); + state = reduceLoadingFeedback( + state, + loading(layers.map((layer) => layer.id)), + 200, + ); + const done = aggregateLayerLoading( + layers.map((layer) => ({ + ...layer, + enabled: true, + lifecycleState: 'enabled', + })), + ); + state = reduceLoadingFeedback(state, done, 300); + return presentLoadingFeedback(state, done, 300).label; + }; + // A keyless layer's own error is the missing key. + const keyless = { + id: 'ais-live-vessels', + stats: { keyRequired: true, error: 'AISSTREAM_API_KEY not set' }, + }; + assert.equal(ended([keyless]), 'KEY REQUIRED'); + assert.equal( + ended([keyless, { id: 'quakes', stats: { count: 3 } }]), + 'KEY REQUIRED', + ); + assert.equal( + ended([keyless, { id: 'flights', stats: { error: 'Failed' } }]), + 'LOAD FAILED', + ); + assert.equal(ended([{ id: 'quakes', stats: { count: 3 } }]), 'LOAD COMPLETE'); }); test('retains the worst terminal outcome until every concurrent load drains', () => { diff --git a/src/render/cesium/appRenderer.js b/src/render/cesium/appRenderer.js index d0673069a2..49cb009f43 100644 --- a/src/render/cesium/appRenderer.js +++ b/src/render/cesium/appRenderer.js @@ -30,7 +30,6 @@ import { bindRenderer } from '../rendererOf.js'; import { FREE_LOOK_MAX_HEIGHT_METERS } from '../../globeInView.js'; import { createCesiumInput } from './input.js'; import { cesiumCapabilities, createCesiumPorts } from './ports.js'; -import { IDLE_FRAME_RATE } from '../../renderGovernor.js'; import { cesiumMapEngine } from './mapEngine.js'; import { installFreeLookHeightLimit } from './freeLookLimit.js'; import { trimStaleSceneCommands } from './sceneCommandRelease.js'; @@ -128,8 +127,6 @@ export function createCesiumRendererPlugin({ capabilities = new ReadonlySet(cesiumCapabilities(viewer.scene)); ports = createCesiumPorts(viewer, { capabilities, - // Ticking at the display's rate only while anything moves. - idleFps: IDLE_FRAME_RATE, credentials: { googleApiKey, googleTokens, worldDataToken }, ...(cameraController ? { cameraController } : {}), ...(clock ? { now, date: () => clock.date() } : {}), diff --git a/src/render/cesium/appRenderer.test.mjs b/src/render/cesium/appRenderer.test.mjs index 6b684914a0..53a26ba884 100644 --- a/src/render/cesium/appRenderer.test.mjs +++ b/src/render/cesium/appRenderer.test.mjs @@ -3,7 +3,14 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import { CONTRACT_VERSION, checkRendererShape } from '../contract/index.js'; import { rendererOf } from '../rendererOf.js'; -import { IDLE_FRAME_RATE } from '../../renderGovernor.js'; +import { + _resetRenderGovernorForTest, + holdContinuousRender, + IDLE_FRAME_RATE, + installRenderGovernor, + releaseContinuousRender, + uninstallRenderGovernor, +} from '../../renderGovernor.js'; import { cesiumMapEngine } from './mapEngine.js'; import { ReadonlySet, @@ -169,7 +176,7 @@ test('the plugin wraps the viewer it is given, behind the accessor only', async assert.deepEqual(log, ['resize', 'destroy'], 'destroying twice is safe'); }); -test('the application’s loop ticks at the idle rate while nothing moves, and at the display’s while anything does', async (t) => { +test('with the governor installed, the loop ticks at the idle rate while nothing moves, and at the display’s while anything does, the renderer’s own holds included', async (t) => { withDocument(t, fakeDocument()); let viewer; const plugin = createCesiumRendererPlugin({ @@ -184,12 +191,19 @@ test('the application’s loop ticks at the idle rate while nothing moves, and a container: {}, signal: new AbortController().signal, }); + installRenderGovernor(renderer.frame); + t.after(() => _resetRenderGovernorForTest()); + assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE, 'idle'); + holdContinuousRender('flights'); + assert.equal(viewer.targetFrameRate, undefined, 'a layer moving'); + releaseContinuousRender('flights'); assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE); - assert.equal(renderer.frame.diagnostics().targetFps, 0, 'no cap'); - const release = renderer.frame.holdContinuous('flights'); - assert.equal(viewer.targetFrameRate, undefined); + // As animated visual styles hold it (effects.js). + const release = renderer.frame.holdContinuous('effects:animated'); + assert.equal(viewer.targetFrameRate, undefined, 'the renderer’s own hold'); release(); assert.equal(viewer.targetFrameRate, IDLE_FRAME_RATE); + uninstallRenderGovernor(renderer.frame); renderer.destroy(); }); diff --git a/src/render/cesium/applicationViewer.js b/src/render/cesium/applicationViewer.js index 91c2f50e59..31e2622ee9 100644 --- a/src/render/cesium/applicationViewer.js +++ b/src/render/cesium/applicationViewer.js @@ -106,8 +106,9 @@ export function createApplicationViewer({ }), ); try { - // Until the frame port takes over (appRenderer.js), tick at the idle - // rate so the startup load does not compete with drawing at 240 fps. + // Until the render governor takes over (src/renderGovernor.js, installed + // by src/app/scene.js), tick at the idle rate so the startup load does + // not compete with drawing at 240 fps. viewer.targetFrameRate = IDLE_FRAME_RATE; // No double-click follow or zoom: the Viewer's own (it tracked or // zoomed to the entity picked) is off. Following is a layer's click. diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 3d9793d416..5cfdb0e7d0 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -413,18 +413,25 @@ function flowTime(speed) { } /** - * Drawn frames a line set's lines stay unchanged before the solid ones - * among them settle into a static batch (`settleLines`). + * Milliseconds a line set's lines stay unchanged before the solid ones + * among them settle into a static batch (`settleLines`), and a shape set's + * moved shapes go back into its batches (`settleShapes`). Timed, so a + * batch builds as soon at every refresh rate. */ -export const SETTLE_FRAMES = 30; +export const SETTLE_MS = 500; /** * Fewer lines than this left in the collection beside a static batch wait - * `LONG_SETTLE_FRAMES` to settle, as rebuilding the batch for them costs + * `LONG_SETTLE_MS` to settle, as rebuilding the batch for them costs * more than drawing them in the collection for a while. */ export const FEW_LOOSE_LINES = 64; -export const LONG_SETTLE_FRAMES = 300; +export const LONG_SETTLE_MS = 5000; + +/** A line set's settling: waiting the short time, the long one, or done. */ +const SETTLE_SHORT = 0; +const SETTLE_LONG = 1; +const SETTLE_DONE = 2; /** * Clamped fills a set draws alone at most, each where it last moved @@ -452,12 +459,14 @@ const animating = (record) => record.gpu?.animating(); * @param {{scene: object, report: (error: unknown) => void, * capabilities?: ReadonlySet, * requestRender?: (reason: string) => void, - * date?: () => number}} options `capabilities` gate + * date?: () => number, + * now?: () => number}} options `capabilities` gate * the GPU icon sets' members (by default they all are); `requestRender`, * the frame port's, asks for the frames a GPU icon set needs on its own * (its images packed), under the reason `icons:` (by default the * scene's, with no reason); `date`, the epoch ms a `live` motion clock - * reads (by default the system clock's). + * reads (by default the system clock's); `now`, the milliseconds settling + * waits are timed by (`performance.now` by default). */ export function createCesiumDraw({ scene, @@ -465,6 +474,7 @@ export function createCesiumDraw({ capabilities = new Set(GPU_ICON_CAPABILITIES), requestRender: requestFrame = null, date = null, + now = () => performance.now(), }) { const sets = new Map(); // Fields share the sets' ids. @@ -3107,7 +3117,8 @@ export function createCesiumDraw({ record.lineBox = settling ? own : null; record.batch = null; record.batchPending = null; - record.settled = 0; + record.changedAt = now(); + record.settleStage = SETTLE_SHORT; if (!draped.size && !glows.size && !alone.length && !groundPieces.length) { noteFlows(record); return replaceHost(record, own); @@ -3581,7 +3592,8 @@ export function createCesiumDraw({ * still building drew them as they were, so it is dropped. */ function unsettle(record) { - record.settled = 0; + record.changedAt = now(); + record.settleStage = SETTLE_SHORT; const pending = record.batchPending; if (!pending) return; record.batchPending = null; @@ -3736,10 +3748,10 @@ export function createCesiumDraw({ } /** - * After a draw: a line set whose lines have not changed for - * `SETTLE_FRAMES` drawn frames starts building its static batch, of all - * its lines that `settles`, once some are still in the collection (when - * it has a batch and only a few are, after `LONG_SETTLE_FRAMES`); one + * After a draw: a line set whose lines have not changed for `SETTLE_MS` + * starts building its static batch, of all its lines that `settles`, once + * some are still in the collection (when it has a batch and only a few + * are, after `LONG_SETTLE_MS`); one * built swaps in for the collection's lines it draws (`swapBatch`). * Unchanged lines in a polyline collection cost a material id a line * every frame; in a batch they cost nothing until they change. @@ -3750,13 +3762,10 @@ export function createCesiumDraw({ swapBatch(record); return; } - if (record.settled > LONG_SETTLE_FRAMES) return; - record.settled += 1; - if ( - record.settled !== SETTLE_FRAMES && - record.settled !== LONG_SETTLE_FRAMES - ) - return; + if (record.settleStage === SETTLE_DONE) return; + const wait = + record.settleStage === SETTLE_SHORT ? SETTLE_MS : LONG_SETTLE_MS; + if (now() - record.changedAt < wait) return; // The lines that can settle still in the collection: a batch is // rebuilt whole for them, so a few wait longer, as a few cost little. let loose = 0; @@ -3765,10 +3774,12 @@ export function createCesiumDraw({ if ( record.batch && loose < FEW_LOOSE_LINES && - record.settled < LONG_SETTLE_FRAMES - ) + record.settleStage === SETTLE_SHORT + ) { + record.settleStage = SETTLE_LONG; return; - record.settled = LONG_SETTLE_FRAMES + 1; + } + record.settleStage = SETTLE_DONE; if (!loose) return; const members = []; for (const [itemId, part] of record.lineParts) { @@ -5007,7 +5018,7 @@ export function createCesiumDraw({ if (part.batch.ready) showOn(part.batch, part.id, false); } hideRetiringShape(record, item.id); - record.shapesStill = 0; + record.shapesMovedAt = now(); part.solo = true; part.pendingShow = undefined; part.look = lookOf(item); @@ -5081,7 +5092,7 @@ export function createCesiumDraw({ /** * After a draw: a shape set whose shapes drawn alone have not moved for - * `SETTLE_FRAMES` drawn frames rebuilds, so they go back into its + * `SETTLE_MS` rebuilds, so they go back into its * batches; the host drawing them alone draws until the rebuild is ready. */ function settleShapes(record) { @@ -5093,9 +5104,8 @@ export function createCesiumDraw({ break; } if (!alone) return; - record.shapesStill = (record.shapesStill ?? 0) + 1; - if (record.shapesStill < SETTLE_FRAMES) return; - record.shapesStill = 0; + if (now() - record.shapesMovedAt < SETTLE_MS) return; + record.shapesMovedAt = now(); record.rebuild(); requestRender(); } diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 8a5ae33a5f..63f42ad4ab 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -5,10 +5,10 @@ import { bindRenderer, drawOf, findDraw } from '../rendererOf.js'; import { createCesiumDraw, FEW_LOOSE_LINES, - LONG_SETTLE_FRAMES, + LONG_SETTLE_MS, MOVING_SHAPES, revealUniform, - SETTLE_FRAMES, + SETTLE_MS, unboundDrawPart, } from './draw.js'; import { drawHitOf } from './drawHit.js'; @@ -93,6 +93,19 @@ test('nothing to draw into, no port', () => { }); /** A draw port over a fake scene, with its frame hooks. */ +/** + * Settling waits are timed. A test that settles times them by `frameClock` + * (`timeFrames`), which each fake frame moves on by `FRAME_MS`. + */ +const FRAME_MS = 20; +const SETTLE_FRAMES = SETTLE_MS / FRAME_MS; +const LONG_SETTLE_FRAMES = LONG_SETTLE_MS / FRAME_MS; +const frameClock = { ms: 0 }; +function timeFrames(t) { + frameClock.ms = 0; + t.mock.method(performance, 'now', () => frameClock.ms); +} + function drawOver(scene = fakeScene()) { const viewer = { scene }; const draw = drawOf(viewer); @@ -100,6 +113,7 @@ function drawOver(scene = fakeScene()) { scene, draw, frame() { + frameClock.ms += FRAME_MS; scene.preRender.raiseEvent(); scene.postRender.raiseEvent(); }, @@ -2978,8 +2992,9 @@ function settlingSet(id = 'stems') { }; } -test('unchanged solid 3D lines settle into a static batch, changed there in place', () => +test('unchanged solid 3D lines settle into a static batch, changed there in place', (t) => withImageClasses(() => { + timeFrames(t); const s = settlingSet(); const { set, frame } = s; const stem = settleStem; @@ -3114,8 +3129,24 @@ test('unchanged solid 3D lines settle into a static batch, changed there in plac set.dispose(); })); -test('many lines left beside a static batch settle as soon as they are unchanged', () => +test('lines settle after the same time at any refresh rate', (t) => withImageClasses(() => { + timeFrames(t); + const s = settlingSet(); + s.set.set([settleStem('a', 100)]); + const host = s.host(); + // Two frames are enough when they are half a second apart. + frameClock.ms = SETTLE_MS - FRAME_MS - 1; + s.frame(); + assert.equal(host.length, 1, 'not before the time'); + s.frame(); + assert.equal(host.length, 2, 'building once it has passed'); + s.set.dispose(); + })); + +test('many lines left beside a static batch settle as soon as they are unchanged', (t) => + withImageClasses(() => { + timeFrames(t); const s = settlingSet(); const { set } = s; const stems = (height) => @@ -3134,8 +3165,9 @@ test('many lines left beside a static batch settle as soon as they are unchanged set.dispose(); })); -test('an outlined solid line draws one outline material, recoloured in place, and never settles', () => +test('an outlined solid line draws one outline material, recoloured in place, and never settles', (t) => withImageClasses(() => { + timeFrames(t); const s = settlingSet(); const outlined = (core, halo) => settleStem('ring', 100, { @@ -3177,8 +3209,9 @@ test('an outlined solid line draws one outline material, recoloured in place, an s.set.dispose(); })); -test('a line that moves by as many points is written into the points it draws; by more, it takes new ones', () => +test('a line that moves by as many points is written into the points it draws; by more, it takes new ones', (t) => withImageClasses(() => { + timeFrames(t); const s = settlingSet(); const style = { kind: 'solid', @@ -3232,8 +3265,9 @@ test('a line that moves by as many points is written into the points it draws; b s.set.dispose(); })); -test('a line under half a pixel wide, which the collection does not draw, never settles', () => +test('a line under half a pixel wide, which the collection does not draw, never settles', (t) => withImageClasses(() => { + timeFrames(t); const s = settlingSet(); s.set.set([ settleStem('thin', 100, { widthPx: 0.25 }), @@ -3248,8 +3282,9 @@ test('a line under half a pixel wide, which the collection does not draw, never s.set.dispose(); })); -test('a settling line set keeps what was drawn, not the item a caller changes in place', () => +test('a settling line set keeps what was drawn, not the item a caller changes in place', (t) => withImageClasses(() => { + timeFrames(t); const s = settlingSet(); const { set } = s; const a = settleStem('a', 100); @@ -3276,8 +3311,9 @@ test('a settling line set keeps what was drawn, not the item a caller changes in set.dispose(); })); -test('a settling line set rebuilt or gone while its batch builds, or after the viewer went, lets the batch go', () => +test('a settling line set rebuilt or gone while its batch builds, or after the viewer went, lets the batch go', (t) => withImageClasses(() => { + timeFrames(t); const s = settlingSet(); const { set } = s; set.set([settleStem('a', 100), settleStem('b', 200)]); @@ -3308,17 +3344,22 @@ test('a settling line set rebuilt or gone while its batch builds, or after the v set.dispose(); })); -test('a static batch that fails to build is reported once, and its lines stay in the collection', () => +test('a static batch that fails to build is reported once, and its lines stay in the collection', (t) => withImageClasses(() => { + timeFrames(t); const scene = fakeScene(); const reported = []; const part = createCesiumDraw({ scene, report: (error) => reported.push(error), }); + const afterFrame = () => { + frameClock.ms += FRAME_MS; + part.afterRender(); + }; const set = part.port.lines({ id: 'failing' }); set.set([settleStem('a', 100)]); - for (let i = 0; i < SETTLE_FRAMES; i++) part.afterRender(); + for (let i = 0; i < SETTLE_FRAMES; i++) afterFrame(); const host = scene.added[0]; const batch = host.get(1); assert.ok(batch, 'building'); @@ -3326,11 +3367,11 @@ test('a static batch that fails to build is reported once, and its lines stay in // batch keeps the error rather than throw it every frame. batch.update({ passes: { render: true }, mode: Cesium.SceneMode.SCENE3D }); assert.ok(batch.failed, 'kept'); - part.afterRender(); + afterFrame(); assert.deepEqual(reported, [batch.failed]); assert.equal(host.length, 1, 'the build is gone'); assert.equal(host.get(0).length, 1, 'the collection draws the line'); - for (let i = 0; i < SETTLE_FRAMES * 2; i++) part.afterRender(); + for (let i = 0; i < SETTLE_FRAMES * 2; i++) afterFrame(); assert.equal(host.length, 1, 'it settles no more'); assert.equal(reported.length, 1); set.dispose(); @@ -7482,8 +7523,9 @@ test('an inertial line with a depth-fail style draws behind the surface too, tur set.dispose(); })); -test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', () => +test('a pattern line draws its image along it, repeated, and an inertial line turns with the sky', (t) => withImageClasses(() => { + timeFrames(t); const { scene, draw, frame } = drawOver(); const set = draw.lines({ id: 'orbit-rings' }); const ring = [ @@ -7777,8 +7819,9 @@ const firstGround = (host) => { return null; }; -test('moved clamped fills go back into a rebuilt batch once they have been still for a while', () => +test('moved clamped fills go back into a rebuilt batch once they have been still for a while', (t) => withTerrainHeights(() => { + timeFrames(t); const { scene, draw, frame } = drawOver(); const set = draw.shapes({ id: 'settling' }); set.set([groundBox('a', 1), groundBox('b', 2)]); diff --git a/src/render/cesium/frame.js b/src/render/cesium/frame.js index dada22146c..6220f4642a 100644 --- a/src/render/cesium/frame.js +++ b/src/render/cesium/frame.js @@ -161,6 +161,8 @@ export function createSceneFrame(viewer) { liveTick = null; }; const holds = new Map(); + // Told when the first hold is taken and the last released. + const heldListeners = listenerList(uncaught); const pendingRenders = new Set(); const gone = () => disposed || scene.isDestroyed?.(); const sceneTime = (time) => @@ -244,8 +246,10 @@ export function createSceneFrame(viewer) { }, holdContinuous(reason) { if (disposed) return () => {}; + const first = holds.size === 0; holds.set(reason, (holds.get(reason) ?? 0) + 1); if (!gone()) scene.requestRender(); + if (first) heldListeners.fire(true); let released = false; return () => { if (released) return; @@ -255,8 +259,10 @@ export function createSceneFrame(viewer) { else holds.delete(reason); // What changed in the last held frame still gets drawn. if (!gone()) scene.requestRender(); + if (holds.size === 0) heldListeners.fire(false); }; }, + onHeldChange: (cb) => heldListeners.on(cb), mode: () => (scene.requestRenderMode ? 'demand' : 'continuous'), diagnostics: () => ({ mode: port.mode(), @@ -324,6 +330,7 @@ export function createSceneFrame(viewer) { settleTick(false); for (const off of removers.splice(0)) off(); for (const list of Object.values(listeners)) list.clear(); + heldListeners.clear(); holds.clear(); // Waits settle rather than stay attached to a scene gone quiet. for (const done of [...pendingRenders]) done(); diff --git a/src/render/cesium/frame.test.mjs b/src/render/cesium/frame.test.mjs index e8b69447af..cac2692693 100644 --- a/src/render/cesium/frame.test.mjs +++ b/src/render/cesium/frame.test.mjs @@ -190,6 +190,23 @@ test('a built frame port counts holds per reason, times out a wait, and settles unbind(); }); +test('a built frame port says when its first hold is taken and its last released', () => { + const viewer = fakeViewer(); + viewer.useDefaultRenderLoop = false; + const frame = frameOf(viewer); + const heard = []; + const off = frame.onHeldChange((held) => heard.push(held)); + const a = frame.holdContinuous('spin'); + const b = frame.holdContinuous('glow'); + a(); + assert.deepEqual(heard, [true], 'once for the first hold'); + b(); + assert.deepEqual(heard, [true, false], 'once for the last release'); + off(); + frame.holdContinuous('spin')(); + assert.deepEqual(heard, [true, false], 'nothing once off'); +}); + test('renderNow throws the error Cesium raises on renderError', () => { const listeners = new Set(); const failure = new Error('worker failed'); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index 59bb1e84af..62f06cf0fc 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -149,6 +149,7 @@ export const CESIUM_CHECKS = new Set([ 'renderer.releaseUnused', 'renderer.whenSettled', 'renderer.resize', + 'frame.onHeldChange', 'frame.setTargetFps', 'globe.setTerrain', 'globe.setPhotoreal', diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 5488b0fcc0..e368983307 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -116,22 +116,18 @@ const destroyedError = () => new Error('renderer destroyed'); * @param {{capabilities: ReadonlySet, credentials?: object, * cameraController?: import('../contract/camera').CameraControllerFactory, * now?: () => number, - * date?: () => number, - * idleFps?: number}} options + * date?: () => number}} options * The renderer's capabilities, which gate the members that need them, and * the credentials its globe loads photoreal tiles and world data with * (`googleApiKey`, `googleTokens`, `worldDataToken`). `now` is the clock * each tick reads (`performance.now` by default; a test's virtual one); * `date`, the epoch ms a `live` motion clock reads (the system clock's by - * default). With `idleFps`, the loop ticks at most that often while no - * hold is out (Cesium ticks its clock and every update listener each - * animation frame even when it draws nothing), and at the display's rate - * while one is; `setTargetFps` then caps both, and the loop starts with no - * cap of its own. Without it, the widget's own rate is the cap. - * With - * `cameraController`, the camera port is that controller's over Cesium's - * camera (`controlledCamera.js`); the ports then have `attachInput` and - * `suspendCamera`, which the renderer's input port is wired with. + * default). The loop's rate starts as the widget's own; once set, it is + * the lower of `setTargetFps`'s and the quality port's `targetFps` cap. + * With `cameraController`, the camera port is that controller's over + * Cesium's camera (`controlledCamera.js`); the ports then have + * `attachInput` and `suspendCamera`, which the renderer's input port is + * wired with. */ export function createCesiumPorts( widget, @@ -141,7 +137,6 @@ export function createCesiumPorts( cameraController, now: clockNow = () => performance.now(), date = null, - idleFps = 0, }, ) { const scene = widget.scene; @@ -290,27 +285,30 @@ export function createCesiumPorts( // Holds keep the loop drawing every frame; counted per reason. const holds = new Map(); + // Told when the first hold is taken and the last released. + const heldListeners = listenerList(report); function applyHolds() { const continuous = holds.size > 0; - if (idleFps > 0) applyRate(); if (scene.requestRenderMode === !continuous) return; scene.requestRenderMode = !continuous; - } - /** The loop's rate: the cap, and at most `idleFps` while nothing holds. */ - function applyRate() { - const idle = holds.size === 0 && idleFps > 0; - const rate = - idle && !(targetFps > 0 && targetFps < idleFps) ? idleFps : targetFps; - widget.targetFrameRate = rate || undefined; + heldListeners.fire(continuous); } // On demand means drawn when asked, held or the view changed: never // because scene time moved on by itself. With no holds yet, it starts so. scene.maximumRenderTimeChange = Infinity; scene.requestRenderMode = true; let suspended = false; - let targetFps = - idleFps <= 0 && widget.targetFrameRate > 0 ? widget.targetFrameRate : 0; - if (idleFps > 0) applyRate(); + // The rate `setTargetFps` asks for (the application's), and the quality + // port's cap; the loop draws at the lower of those set. + let targetFps = widget.targetFrameRate > 0 ? widget.targetFrameRate : 0; + let qualityFps = 0; + function applyRate() { + const rate = + targetFps > 0 && qualityFps > 0 + ? Math.min(targetFps, qualityFps) + : targetFps || qualityFps; + widget.targetFrameRate = rate || undefined; + } // Pending one-shot renders; disposal rejects them rather than leave them // attached to a scene that will not render again. @@ -369,6 +367,7 @@ export function createCesiumPorts( if (holds.size === 0) scene.requestRender(); }; }, + onHeldChange: (cb) => heldListeners.on(cb), /** Cesium can idle, so it draws on demand. */ mode: () => 'demand', diagnostics: () => ({ @@ -429,6 +428,7 @@ export function createCesiumPorts( capabilities, requestRender: (reason) => frame.requestRender(reason), date, + now: clockNow, }); const { port: draw, sets, tilesets } = drawPart; @@ -494,6 +494,13 @@ export function createCesiumPorts( report, tickStarted: () => tickNow, gl: capabilities.has('gpuTiming') ? webglContext(scene) : null, + fpsCap: { + get: () => qualityFps, + set(fps) { + qualityFps = fps > 0 ? fps : 0; + applyRate(); + }, + }, }); const creditsPart = createCesiumCredits({ @@ -837,6 +844,7 @@ export function createCesiumPorts( // A listener that disposes the renderer stops the rest of its event. for (const list of Object.values(rendererListeners)) list.clear(); for (const list of Object.values(frameListeners)) list.clear(); + heldListeners.clear(); drawPart.dispose(); cameraPart.dispose(); creditsPart.dispose(); diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index de36429493..04ef937fd1 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -507,26 +507,40 @@ test('suspend stops the loop at once and resumes it; target fps caps it', () => ports.dispose(); }); -test('with an idle rate, idle ticks at it and anything held draws at the display rate', () => { +test('the quality cap and the rate setTargetFps asks for draw at the lower, and neither overwrites the other', () => { + const { widget } = tickingWidget(); + const ports = createCesiumPorts(widget, { capabilities: all }); + assert.equal(ports.quality.get().targetFps, 0, 'no cap by default'); + ports.quality.set({ targetFps: 30 }); + ports.frame.setTargetFps(60); + assert.equal(widget.targetFrameRate, 30, 'the cap is lower'); + ports.frame.setTargetFps(0); + assert.equal(widget.targetFrameRate, 30, 'the cap holds at the display rate'); + assert.equal(ports.quality.get().targetFps, 30, 'the cap reads back'); + ports.frame.setTargetFps(24); + assert.equal(widget.targetFrameRate, 24, 'the asked rate is lower'); + ports.quality.set({ targetFps: 0 }); + assert.equal(widget.targetFrameRate, 24, 'cap lifted'); + ports.dispose(); +}); + +test('the loop says when its first hold is taken and its last released, and leaves its rate alone', () => { const { widget } = tickingWidget(); widget.targetFrameRate = 60; - const ports = createCesiumPorts(widget, { capabilities: all, idleFps: 60 }); - assert.equal(widget.targetFrameRate, 60, 'idle: the idle rate'); - assert.equal(ports.frame.diagnostics().targetFps, 0, 'no cap of its own'); - const release = ports.frame.holdContinuous('flights'); - assert.equal(widget.targetFrameRate, undefined, 'held: the display rate'); - release(); - assert.equal(widget.targetFrameRate, 60); - // A cap holds while held, and idle ticks at the lower of the two. - ports.frame.setTargetFps(30); - assert.equal(widget.targetFrameRate, 30); - const again = ports.frame.holdContinuous('flights'); - assert.equal(widget.targetFrameRate, 30); - ports.frame.setTargetFps(120); - assert.equal(widget.targetFrameRate, 120); - again(); - assert.equal(widget.targetFrameRate, 60); - assert.equal(ports.frame.diagnostics().targetFps, 120); + const ports = createCesiumPorts(widget, { capabilities: all }); + assert.equal(ports.frame.diagnostics().targetFps, 60, 'the widget’s cap'); + const heard = []; + const off = ports.frame.onHeldChange((held) => heard.push(held)); + const flights = ports.frame.holdContinuous('flights'); + const effects = ports.frame.holdContinuous('effects:animated'); + flights(); + assert.deepEqual(heard, [true], 'once for the first hold'); + effects(); + assert.deepEqual(heard, [true, false], 'once for the last release'); + assert.equal(widget.targetFrameRate, 60, 'its rate is its caller’s'); + off(); + ports.frame.holdContinuous('flights')(); + assert.deepEqual(heard, [true, false], 'heard no more once off'); ports.dispose(); }); diff --git a/src/render/cesium/quality.js b/src/render/cesium/quality.js index 09afc6c537..21c196a998 100644 --- a/src/render/cesium/quality.js +++ b/src/render/cesium/quality.js @@ -15,7 +15,10 @@ * at 0. While tile detail is lowered, a tileset added later is brought * to it on the next drawn frame; an error is written only when it * changes, since each write resets the tileset's memory-adjusted error. - * - `targetFps`: the frame port's target frame rate, 0 for none. + * - `targetFps`: a cap on the loop's frame rate, 0 for none (`fpsCap`: by + * default the frame port's own `setTargetFps`; the renderer's ports keep + * it apart from the rate the application sets there, and draw at the + * lower of the two). * * Building the port changes nothing in the scene; each setting is applied * when it is first set, and a detail set back to 1 hands each tileset and @@ -156,6 +159,10 @@ export function createCesiumQuality( limits = Cesium.ContextLimits, tickStarted = null, gl = webglContext(widget.scene), + fpsCap = { + get: () => frame.diagnostics?.().targetFps ?? 0, + set: (fps) => frame.setTargetFps(fps), + }, }, ) { const scene = widget.scene; @@ -171,7 +178,7 @@ export function createCesiumQuality( : []; // What the scene had before the port first changed it: the defaults. - const builtFps = frame.diagnostics?.().targetFps ?? 0; + const builtFps = fpsCap.get(); let msaaAtBuild = null; let shadowsAtBuild = null; // Cesium clamps the count to the context's only when it is set. @@ -334,7 +341,7 @@ export function createCesiumQuality( }, targetFps(value) { const fps = inRange(value, 0, MAX_FPS); - if (fps !== null) frame.setTargetFps(fps); + if (fps !== null) fpsCap.set(fps); }, }; @@ -343,7 +350,7 @@ export function createCesiumQuality( pixelRatio, tiles3dDetail: detail.tiles, terrainDetail: detail.terrain, - targetFps: frame.diagnostics?.().targetFps ?? 0, + targetFps: fpsCap.get(), }; if (scene.shadowMap) settings.shadows = Boolean(scene.shadowMap.enabled); if (msaaOptions().length > 1) diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index b14f5a07e7..faf4a8468e 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -5769,6 +5769,26 @@ fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { ); }, ), + check( + 'frame.onHeldChange', + 'onHeldChange is told the first hold and the last release, whoever holds, and nothing once off', + (h, r) => { + const heard = []; + const off = r.frame.onHeldChange((held) => heard.push(held)); + try { + const one = r.frame.holdContinuous('conformance:one'); + const two = r.frame.holdContinuous('conformance:two'); + one(); + deepEqual(heard, [true], 'once for the first hold'); + two(); + deepEqual(heard, [true, false], 'once for the last release'); + } finally { + off(); + } + r.frame.holdContinuous('conformance:after')(); + deepEqual(heard, [true, false], 'nothing once off'); + }, + ), check( 'frame.setTargetFps', 'setTargetFps caps the loop; diagnostics say the cap, 0 the display rate', diff --git a/src/render/contract/frame.d.ts b/src/render/contract/frame.d.ts index 8c35411da6..948450bb42 100644 --- a/src/render/contract/frame.d.ts +++ b/src/render/contract/frame.d.ts @@ -73,6 +73,11 @@ export interface FramePort { requestRender(reason: string): void; /** Keep drawing every frame until released. Holds are counted. */ holdContinuous(reason: string): Release; + /** + * Hear the loop start drawing every frame (its first hold, whoever took + * it) and stop (its last released): `true` held, `false` not. + */ + onHeldChange(cb: (held: boolean) => void): Off; mode(): 'demand' | 'continuous'; diagnostics(): FrameDiagnostics; /** Stop ticking while the page is hidden; resume on `false`. */ diff --git a/src/render/contract/index.js b/src/render/contract/index.js index 700f8cf583..d494467fab 100644 --- a/src/render/contract/index.js +++ b/src/render/contract/index.js @@ -118,6 +118,7 @@ export const PORTS = deepFreeze({ 'on', 'requestRender', 'holdContinuous', + 'onHeldChange', 'mode', 'diagnostics', 'suspend', diff --git a/src/render/stub/index.js b/src/render/stub/index.js index b5db255119..9eb21cfc58 100644 --- a/src/render/stub/index.js +++ b/src/render/stub/index.js @@ -187,6 +187,16 @@ export function createStubRenderer(options = {}) { const pendingReasons = []; const continuous = new Map(); let holdSeq = 0; + // Told when the first hold is taken and the last released. + const heldListeners = new Set(); + function tellHeld(held) { + for (const entry of [...heldListeners]) + try { + entry.cb(held); + } catch (error) { + report(error); + } + } const phaseListeners = { preUpdate: [], preRender: [], postRender: [] }; // The frame under way while its `preUpdate` listeners run. let updating = null; @@ -345,7 +355,16 @@ export function createStubRenderer(options = {}) { holdContinuous(reason) { const key = ++holdSeq; continuous.set(key, String(reason)); - return () => continuous.delete(key); + if (continuous.size === 1) tellHeld(true); + return () => { + if (!continuous.delete(key)) return; + if (continuous.size === 0) tellHeld(false); + }; + }, + onHeldChange(cb) { + const entry = { cb }; + heldListeners.add(entry); + return () => heldListeners.delete(entry); }, mode: () => 'demand', diagnostics: () => ({ diff --git a/src/renderGovernor.js b/src/renderGovernor.js index 7897a620e6..ad160da2be 100644 --- a/src/renderGovernor.js +++ b/src/renderGovernor.js @@ -29,12 +29,15 @@ * short stable strings ('flights', 'traffic', 'style-anim', …) so the * diagnostics read like a story. * - * Frame rate: in continuous mode the loop draws at the display's own - * refresh rate. In idle mode the renderer's frame port ticks it at most at - * IDLE_FRAME_RATE, because Cesium still ticks the clock, data sources and - * every pre/post-update listener once per animation frame even when it skips - * the draw. Camera movement takes a 'camera' hold from `moveStart` to - * `moveEnd`, so drags and flights run at the full rate too. + * Frame rate: while the loop is held it draws at the display's own refresh + * rate; while nothing holds it, the governor caps it at IDLE_FRAME_RATE, + * because Cesium still ticks the clock, data sources and every + * pre/post-update listener once per animation frame even when it skips the + * draw. The frame port says when its first hold is taken and its last + * released (`onHeldChange`), the renderer's own holds included (animated + * visual styles), so those draw at the full rate too. Camera movement takes + * a 'camera' hold from `moveStart` to `moveEnd`, so drags and flights run at + * the full rate as well. * * The governor is O(1) passive: no per-frame work of its own, ever. */ @@ -50,6 +53,13 @@ let _frame = null; const _holds = new Map(); /** Removes the camera move listeners added at install. */ let _removeCameraListeners = null; +/** Stops hearing the installed port's holds. */ +let _offHeldChange = null; + +/** The loop's rate: the display's while held, IDLE_FRAME_RATE while not. */ +function applyRate(held) { + _frame?.setTargetFps(held ? 0 : IDLE_FRAME_RATE); +} /** Debug trail of the most recent one-shot render requests (idle mode only). */ const _recentRequests = []; @@ -163,14 +173,20 @@ export function installRenderGovernor( clearTimeout: unschedule = globalThis.clearTimeout, } = {}, ) { - if (typeof frame?.holdContinuous !== 'function') + if ( + typeof frame?.holdContinuous !== 'function' || + typeof frame.onHeldChange !== 'function' + ) throw new TypeError('installRenderGovernor requires a frame port'); _removeCameraListeners?.(); _removeCameraListeners = null; releaseContinuousRender('camera'); if (_frame !== frame) { if (_frame) releaseFrameHolds(); + _offHeldChange?.(); _frame = frame; + _offHeldChange = frame.onHeldChange(applyRate); + applyRate(frame.diagnostics().holds.length > 0); for (const ownerId of _holds.keys()) holdOnFrame(ownerId); } _removeCameraListeners = watchCameraMotion(camera, { schedule, unschedule }); @@ -247,6 +263,8 @@ export function uninstallRenderGovernor(frame) { _removeCameraListeners?.(); _removeCameraListeners = null; releaseFrameHolds(); + _offHeldChange?.(); + _offHeldChange = null; _frame = null; _holds.clear(); _recentRequests.length = 0; @@ -256,6 +274,8 @@ export function uninstallRenderGovernor(frame) { export function _resetRenderGovernorForTest() { _removeCameraListeners?.(); _removeCameraListeners = null; + _offHeldChange?.(); + _offHeldChange = null; _frame = null; _holds.clear(); _recentRequests.length = 0; diff --git a/src/renderGovernor.test.mjs b/src/renderGovernor.test.mjs index 00c18c2340..060d8a284d 100644 --- a/src/renderGovernor.test.mjs +++ b/src/renderGovernor.test.mjs @@ -8,6 +8,7 @@ import { getRenderGovernorDiagnostics, _resetRenderGovernorForTest, uninstallRenderGovernor, + IDLE_FRAME_RATE, } from './renderGovernor.js'; import { framePortFor } from './testSupport/fakeFramePort.mjs'; @@ -16,7 +17,9 @@ function makeViewer() { const scene = { requestRenderMode: false, maximumRenderTimeChange: 0, - requestRender() { calls.requestRender += 1; }, + requestRender() { + calls.requestRender += 1; + }, }; return { viewer: { scene }, scene, calls }; } @@ -73,7 +76,11 @@ test('holds are identity-keyed: double-hold cannot leak, double-release cannot c holdContinuousRender('traffic'); holdContinuousRender('traffic'); releaseContinuousRender('traffic'); - assert.equal(scene.requestRenderMode, true, 'single release clears an idempotent double-hold'); + assert.equal( + scene.requestRenderMode, + true, + 'single release clears an idempotent double-hold', + ); releaseContinuousRender('traffic'); releaseContinuousRender('never-held'); assert.equal(scene.requestRenderMode, true); @@ -97,7 +104,10 @@ test('governorRequestRender forwards to the scene and records reasons only in id const baseline = calls.requestRender; governorRequestRender('layer-tick:earthquakes'); assert.equal(calls.requestRender, baseline + 1); - assert.equal(getRenderGovernorDiagnostics().recentRequests.at(-1).reason, 'layer-tick:earthquakes'); + assert.equal( + getRenderGovernorDiagnostics().recentRequests.at(-1).reason, + 'layer-tick:earthquakes', + ); holdContinuousRender('flights'); const idleRequests = getRenderGovernorDiagnostics().recentRequests.length; governorRequestRender('slider'); @@ -119,7 +129,11 @@ test('holds registered before install apply at install time', () => { holdContinuousRender('flights'); const { viewer, scene } = makeViewer(); installRenderGovernor(framePortFor(viewer.scene)); - assert.equal(scene.requestRenderMode, false, 'pre-install hold keeps continuous mode'); + assert.equal( + scene.requestRenderMode, + false, + 'pre-install hold keeps continuous mode', + ); releaseContinuousRender('flights'); assert.equal(scene.requestRenderMode, true); }); @@ -146,8 +160,41 @@ function makeCamera({ position = null, direction = null } = {}) { return camera; } -// The frame rate each mode draws at is the frame port's (ports.test.mjs: -// 'with an idle rate, …'); the governor only holds and releases. +test('idle, the loop ticks at the idle rate; held, at the display rate', () => { + const { viewer, scene } = makeViewer(); + installRenderGovernor(framePortFor(viewer.scene)); + assert.equal(scene.targetFps, IDLE_FRAME_RATE, 'idle at install'); + holdContinuousRender('flights'); + assert.equal(scene.targetFps, 0, 'held: the display rate'); + releaseContinuousRender('flights'); + assert.equal(scene.targetFps, IDLE_FRAME_RATE); +}); + +test('a hold already out at install draws at the display rate', () => { + holdContinuousRender('boot'); + const { viewer, scene } = makeViewer(); + installRenderGovernor(framePortFor(viewer.scene)); + assert.equal(scene.targetFps, 0); + releaseContinuousRender('boot'); + assert.equal(scene.targetFps, IDLE_FRAME_RATE); +}); + +test('the renderer holding the loop itself (animated visual styles) also draws at the display rate', () => { + const { viewer, scene } = makeViewer(); + const frame = framePortFor(viewer.scene); + installRenderGovernor(frame); + const release = frame.holdContinuous('effects:animated'); + assert.equal(scene.targetFps, 0, 'held by the renderer'); + holdContinuousRender('flights'); + release(); + assert.equal(scene.targetFps, 0, 'still held by flights'); + releaseContinuousRender('flights'); + assert.equal(scene.targetFps, IDLE_FRAME_RATE); + // Uninstalled, the governor no longer sets the rate. + uninstallRenderGovernor(frame); + frame.holdContinuous('effects:animated'); + assert.equal(scene.targetFps, IDLE_FRAME_RATE); +}); test('a camera move holds continuous render from moveStart to moveEnd', () => { const { viewer, scene } = makeViewer(); diff --git a/src/sources/live/standalone.js b/src/sources/live/standalone.js index 41e858a937..b5ff68a8e7 100644 --- a/src/sources/live/standalone.js +++ b/src/sources/live/standalone.js @@ -261,6 +261,8 @@ export function createVesselSource({ closed: 'feed disconnected', }; error.message = reasons[payload?.status] || error.message; + // No key is not an outage: the feed waits for one. + if (payload?.status === 'missing-key') error.code = 'key-required'; throw error; } return { diff --git a/src/sources/live/standalone.test.mjs b/src/sources/live/standalone.test.mjs new file mode 100644 index 0000000000..f25d4e994b --- /dev/null +++ b/src/sources/live/standalone.test.mjs @@ -0,0 +1,27 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createVesselSource } from './standalone.js'; + +const answering = (status, payload) => async () => ({ + ok: status < 400, + status, + headers: { get: () => null }, + json: async () => payload, +}); + +test('a vessels server with no AISStream key refuses as key-required, a down feed as unavailable', async () => { + const keyless = createVesselSource({ + fetchImpl: answering(503, { status: 'missing-key' }), + }); + await assert.rejects(keyless.getSnapshot(), { + code: 'key-required', + message: 'AISSTREAM_API_KEY not set', + }); + const down = createVesselSource({ + fetchImpl: answering(503, { status: 'error' }), + }); + await assert.rejects(down.getSnapshot(), { + code: 'unavailable', + message: 'feed down', + }); +}); diff --git a/src/testSupport/fakeFramePort.mjs b/src/testSupport/fakeFramePort.mjs index 4f0259c5d2..35fa87cd6b 100644 --- a/src/testSupport/fakeFramePort.mjs +++ b/src/testSupport/fakeFramePort.mjs @@ -3,9 +3,10 @@ * render loop through `renderGovernor.js`. It writes the scene the way the * Cesium port does (`src/render/cesium/ports.js`): holds, counted per * reason, keep `requestRenderMode` false; releasing the last asks for one - * frame; a request is the scene's `requestRender`. Only the members the - * governor uses. One port per scene, so a test can uninstall what it - * installed. + * frame; a request is the scene's `requestRender`; the first hold and the + * last release are told to `onHeldChange`; a rate set is kept as the + * scene's `targetFps`. Only the members the governor uses. One port per + * scene, so a test can uninstall what it installed. * @param {{requestRenderMode?: boolean, requestRender?: () => void}} scene */ export function framePortFor(scene) { @@ -18,11 +19,25 @@ const ports = new WeakMap(); function makePort(scene) { const holds = new Map(); + const heldListeners = new Set(); + let wasHeld = false; const apply = () => { - scene.requestRenderMode = holds.size === 0; + const held = holds.size > 0; + scene.requestRenderMode = !held; + if (held === wasHeld) return; + wasHeld = held; + for (const cb of [...heldListeners]) cb(held); }; apply(); return { + onHeldChange(cb) { + heldListeners.add(cb); + return () => heldListeners.delete(cb); + }, + diagnostics: () => ({ holds: [...holds.keys()] }), + setTargetFps(fps) { + scene.targetFps = fps; + }, requestRender() { scene.requestRender?.(); }, diff --git a/src/ui/shellFeedback.js b/src/ui/shellFeedback.js index 7193c3c3a1..6a7abbfe7a 100644 --- a/src/ui/shellFeedback.js +++ b/src/ui/shellFeedback.js @@ -23,6 +23,7 @@ const STATUS_LABEL_KEYS = Object.freeze({ 'LOAD COMPLETE': msg('LOAD COMPLETE'), 'LOAD CANCELLED': msg('LOAD CANCELLED'), 'LOAD FAILED': msg('LOAD FAILED'), + 'KEY REQUIRED': msg('KEY REQUIRED'), 'LIVE DATA OFF': msg('LIVE DATA OFF'), 'MAPPED SITES LOADED': msg('MAPPED SITES LOADED'), 'RETRYING MAPPED SITES': msg('RETRYING MAPPED SITES'), diff --git a/src/ui/styles/status.css b/src/ui/styles/status.css index ce212a46d0..3b71b17e3b 100644 --- a/src/ui/styles/status.css +++ b/src/ui/styles/status.css @@ -131,6 +131,7 @@ html:not([lang='en']) #global-loading-detail { #global-loading-status:is( [data-state='complete'], [data-state='cancelled'], + [data-state='key-required'], [data-state='error'] ) { justify-content: center; @@ -139,6 +140,7 @@ html:not([lang='en']) #global-loading-detail { #global-loading-status:is( [data-state='complete'], [data-state='cancelled'], + [data-state='key-required'], [data-state='error'] ) #global-loading-detail { @@ -155,11 +157,13 @@ html:not([lang='en']) #global-loading-detail { #global-loading-status[data-state='cancelled'] { color: #ffd488; } -#global-loading-status[data-state='retry'] { +#global-loading-status:is([data-state='retry'], [data-state='key-required']) { border-color: rgba(255, 212, 136, 0.55); } -#global-loading-status[data-state='retry'] #global-loading-label, -#global-loading-status[data-state='retry'] #global-loading-detail { +#global-loading-status:is([data-state='retry'], [data-state='key-required']) + #global-loading-label, +#global-loading-status:is([data-state='retry'], [data-state='key-required']) + #global-loading-detail { color: #ffd488; } #global-loading-status[data-state='cancelled'] #global-loading-label, From 78b8d8dc786cdc5237ac3ed1a36d1f7e9583c46b Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:13:06 -0800 Subject: [PATCH 33/70] Stories: read whether the story was playing before the press stops it The director's own pointerdown listener, added first, stops a run whose camera it drives before Stories heard the press, so the tap still played the story again. Stories now reads the press in the capture phase, and its tap listeners are removed on teardown. --- src/stories/controller.js | 8 +++++--- src/stories/controller.test.mjs | 23 +++++++++++++++++++---- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/stories/controller.js b/src/stories/controller.js index 2473843652..97106fda80 100644 --- a/src/stories/controller.js +++ b/src/stories/controller.js @@ -745,7 +745,8 @@ export function createStoriesController({ let downAt = null; // Whether the story was playing when the tap began: a camera move the // scene drives frame by frame stops on the press itself, before the tap - // ends, and that tap still means pause. + // ends, and that tap still means pause. The press is read in the capture + // phase, before the director's own listener can stop the run. let playingAtDown = false; const onDown = (e) => { downAt = [e.clientX, e.clientY]; @@ -768,7 +769,7 @@ export function createStoriesController({ store.bigPlay = true; } else player.play(); }; - canvas.addEventListener('pointerdown', onDown); + canvas.addEventListener('pointerdown', onDown, true); canvas.addEventListener('pointerup', onUp); /** @returns {boolean} False when the camera is not free (Cockpit). */ @@ -1237,7 +1238,8 @@ export function createStoriesController({ useInstalledScenes(null); removeEventListener('popstate', onPopState); removeEventListener('popstate', onLandingCapture, true); - canvas.removeEventListener('pointerdown', onDown); + canvas.removeEventListener('pointerdown', onDown, true); + canvas.removeEventListener('pointerup', onUp); canvas.removeEventListener('pointerdown', onExploreInput); canvas.removeEventListener('pointerup', onExploreInput); canvas.removeEventListener('pointercancel', onExploreInput); diff --git a/src/stories/controller.test.mjs b/src/stories/controller.test.mjs index 0c613420df..6ee2039a41 100644 --- a/src/stories/controller.test.mjs +++ b/src/stories/controller.test.mjs @@ -783,7 +783,24 @@ test('a story opened while the scene tears down is not undone by the late restor }); test('a tap pauses a story whose camera move stopped on the press', async () => { - const { controller, store, director, canvas } = setup(); + setActivePinia(createPinia()); + history.replaceState(null, '', '/?x=1#v=2&lat=1'); + const store = useStoriesStore(); + const scene = fakeScene(); + const { canvas } = scene; + // As in the app, the director listens for the press before Stories does, + // and stopping its run publishes a stopped clock at once. + canvas.addEventListener('pointerdown', () => { + store.playback = { ...store.playback, playing: false }; + }); + const director = fakeDirector(); + const controller = createStoriesController({ + viewer: scene.viewer, + director, + store, + clock: fakeClock(), + }); + store.connect(controller, listStories()); controller.openStory('gev:flights-radar'); await tick(20); let starts = 0; @@ -793,9 +810,7 @@ test('a tap pauses a story whose camera move stopped on the press', async () => }; store.playback = { ...store.playback, playing: true }; canvas.dispatchEvent(new Event('pointerdown')); - // A camera move the scene drives frame by frame stops on the press, so the - // story already reads as stopped when the tap ends. - store.playback = { ...store.playback, playing: false }; + assert.equal(store.playback.playing, false, 'the press stopped the run'); canvas.dispatchEvent(new Event('pointerup')); await tick(20); assert.equal(starts, 0, 'the tap does not play it again'); From 9e6207d7f277577a5fe1488bea525d801938b6d5 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:14:27 -0800 Subject: [PATCH 34/70] Stories: the button sits left of elements marked data-stories-corner The corner controls are the ACTIVE STYLE readout and any element marked with data-stories-corner, looked for again for 20 s after Stories mounts, in place of an element id this app never has. --- docs/CURRENT-STATE.md | 5 +++-- src/stories/format.js | 18 ++++++++++++++++-- src/ui/storiesCredit.test.mjs | 24 ++++++++++++++++++++++-- src/ui/views/StoriesView.vue | 22 ++++++++++++++-------- 4 files changed, 55 insertions(+), 14 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7a6a56a884..72bbd49146 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -780,8 +780,9 @@ Inside an inline embed Stories is not offered: the URL and history are the host's. The Stories button sits left of whatever holds GEV's top-right corner: the -ACTIVE STYLE readout, or an element placed in that corner (`#account-control`, -with or beside the readout). On GEV's phone layout, +ACTIVE STYLE readout (`#style-indicator`), or an element marked with +`data-stories-corner` (with or beside the readout; one added after Stories +mounts is found within 20 s). On GEV's phone layout, where neither shows, it is icon-only under the corner-actions column (`#corner-actions`), aligned with its right edge. The first-visit popup is a labelled region that does not take focus. The story page's rail offers diff --git a/src/stories/format.js b/src/stories/format.js index 20a99bed34..f960c5882d 100644 --- a/src/stories/format.js +++ b/src/stories/format.js @@ -30,10 +30,24 @@ export function creditPlacement({ map, feed, width, height }) { }; } +/** + * The controls in GEV's top-right corner: the ACTIVE STYLE readout + * (`#style-indicator`) and any element marked with `data-stories-corner`. + * @param {Document|Element} root Where to look. + * @returns {Element[]} + */ +export function cornerControls(root) { + return [ + root.querySelector('#style-indicator'), + ...root.querySelectorAll('[data-stories-corner]'), + ].filter(Boolean); +} + /** * Where the Stories button sits: just left of the leftmost visible control - * in GEV's top-right corner — the ACTIVE STYLE readout, or an element placed - * in that corner (with or beside the readout) — top-aligned with it. + * in GEV's top-right corner — the ACTIVE STYLE readout, or an element marked + * with `data-stories-corner` (with or beside the readout) — top-aligned with + * it. * Where none of those shows (GEV's phone layout, whose top row of icon * buttons spans the corner), it goes icon-only just under the right-hand * column of corner actions, aligned with its right edge. diff --git a/src/ui/storiesCredit.test.mjs b/src/ui/storiesCredit.test.mjs index c77accb01f..803ee62cdf 100644 --- a/src/ui/storiesCredit.test.mjs +++ b/src/ui/storiesCredit.test.mjs @@ -1,7 +1,12 @@ +import '../testSupport/registerDom.mjs'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import test from 'node:test'; -import { creditPlacement, entryPlacement } from '../stories/format.js'; +import { + cornerControls, + creditPlacement, + entryPlacement, +} from '../stories/format.js'; const css = readFileSync( new URL('./styles/stories.css', import.meta.url), @@ -120,6 +125,20 @@ test('the measured place keeps the credit inside the map and on screen', () => { assert.match(view, /root\.removeProperty\('--gs-credit-left'\)/); }); +test('the corner controls are the readout and elements marked data-stories-corner', () => { + const root = document.createElement('div'); + assert.deepEqual(cornerControls(root), [], 'nothing there yet'); + const readout = root.appendChild(document.createElement('div')); + readout.id = 'style-indicator'; + const other = root.appendChild(document.createElement('div')); + assert.deepEqual(cornerControls(root), [readout], 'an unmarked element is not'); + // A marked element added later counts on the next look. + const marked = root.appendChild(document.createElement('button')); + marked.setAttribute('data-stories-corner', ''); + assert.deepEqual(cornerControls(root), [readout, marked]); + assert.ok(other); +}); + test('the Stories button sits left of whatever is in the top-right corner', () => { const box = (left, top, width, height) => ({ left, @@ -134,7 +153,8 @@ test('the Stories button sits left of whatever is in the top-right corner', () = top: 24, right: 270, }); - // An element placed beside the readout; the leftmost wins. + // An element marked with data-stories-corner beside the readout; the + // leftmost wins. assert.deepEqual( entryPlacement([box(1650, 24, 220, 60), box(1898, 22, 38, 38)], 1960), { top: 24, right: 320 }, diff --git a/src/ui/views/StoriesView.vue b/src/ui/views/StoriesView.vue index e3740402ec..1c3ce552ed 100644 --- a/src/ui/views/StoriesView.vue +++ b/src/ui/views/StoriesView.vue @@ -12,7 +12,11 @@ import { storeToRefs } from 'pinia'; import { t } from '../../i18n/index.js'; import { useStoriesStore } from '../stores/stories.js'; import { GEV_LOGO_SYMBOL } from '../../stories/gevLogo.js'; -import { creditPlacement, entryPlacement } from '../../stories/format.js'; +import { + cornerControls, + creditPlacement, + entryPlacement, +} from '../../stories/format.js'; import { guardStoriesKeyboard } from '../../stories/keyboard.js'; // The screens, their styles and the story data load with Stories (see @@ -36,15 +40,15 @@ const reduceMotion = () => globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches; // ── Entry: in GEV's top-right row, left of what sits in the corner ── -// GEV has its ACTIVE STYLE readout there; an element placed in that corner -// (#account-control, with or beside the readout) can come after Stories mounts. -const CORNER = ['style-indicator', 'account-control']; +// GEV has its ACTIVE STYLE readout there; an element marked with +// data-stories-corner (with or beside the readout) can come after Stories +// mounts (cornerControls). // GEV's phone layout shows neither; the button then sits under this column. const COLUMN = 'corner-actions'; const entry = ref({ top: 14, right: 14 }); function placeEntry() { entry.value = entryPlacement( - CORNER.map((id) => document.getElementById(id)?.getBoundingClientRect()), + cornerControls(document).map((el) => el.getBoundingClientRect()), innerWidth, document.getElementById(COLUMN)?.getBoundingClientRect() ?? null, ); @@ -66,15 +70,17 @@ function watchCorner() { }); } if (globalThis.ResizeObserver) cornerObserver ??= new ResizeObserver(placeEntry); - for (const id of [...CORNER, COLUMN]) { - const el = document.getElementById(id); + for (const el of [ + ...cornerControls(document), + document.getElementById(COLUMN), + ]) { if (el && cornerObserver && !observed.has(el)) { cornerObserver.observe(el); observed.add(el); } } // Keep looking for a while for a control that mounts late. - if (observed.size < CORNER.length + 1 && ++entryTries < 20) + if (++entryTries < 20) entryTimer = setTimeout(watchCorner, 1000); } From c3b8013038960e599a67080e4c6eea061693d09d Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:15:15 -0800 Subject: [PATCH 35/70] Stories: format the corner-controls test --- src/ui/storiesCredit.test.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ui/storiesCredit.test.mjs b/src/ui/storiesCredit.test.mjs index 803ee62cdf..775d5a811d 100644 --- a/src/ui/storiesCredit.test.mjs +++ b/src/ui/storiesCredit.test.mjs @@ -131,7 +131,11 @@ test('the corner controls are the readout and elements marked data-stories-corne const readout = root.appendChild(document.createElement('div')); readout.id = 'style-indicator'; const other = root.appendChild(document.createElement('div')); - assert.deepEqual(cornerControls(root), [readout], 'an unmarked element is not'); + assert.deepEqual( + cornerControls(root), + [readout], + 'an unmarked element is not', + ); // A marked element added later counts on the next look. const marked = root.appendChild(document.createElement('button')); marked.setAttribute('data-stories-corner', ''); From 5cce9d07057e5d2746e6da5981e964d3b4c389ab Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:18:21 -0800 Subject: [PATCH 36/70] Nepal evidence: a seek in the hold places a camera-led shot's sequence For a shot whose path runs during the camera move, a seek in the hold showed its evidence sequence at the start and a resumed run jumped to its end. The sequence now stands where its own clock has it (after the clip and its exit), and a resumed run carries on from there. --- src/data/bhoteKoshiEvent.js | 84 +++++++++++++++++++------------ src/data/bhoteKoshiEvent.test.mjs | 64 ++++++++++++++++++++++- 2 files changed, 115 insertions(+), 33 deletions(-) diff --git a/src/data/bhoteKoshiEvent.js b/src/data/bhoteKoshiEvent.js index bbd6abe1dd..86d17e7101 100644 --- a/src/data/bhoteKoshiEvent.js +++ b/src/data/bhoteKoshiEvent.js @@ -1858,6 +1858,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, @@ -1883,41 +1920,24 @@ 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 = diff --git a/src/data/bhoteKoshiEvent.test.mjs b/src/data/bhoteKoshiEvent.test.mjs index a33984d0f6..87159fd18f 100644 --- a/src/data/bhoteKoshiEvent.test.mjs +++ b/src/data/bhoteKoshiEvent.test.mjs @@ -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'; @@ -467,6 +467,68 @@ test('scene media plays again when a run goes on from a seek inside its hold, un } 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('Pinokio source-card fallback selects authored Director dwell, not an impossible player hold', async () => { const previous = { document: globalThis.document, window: globalThis.window }; installEventDom(); From 186f8b76d996635775e0aa63c1fda054a3f6fed7 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:20:55 -0800 Subject: [PATCH 37/70] Scenes: a clip restarted without a media gate plays its hold out A resumed hold waited only its rest unless the layer gave a media gate, and only trimmed clips have one, so an untrimmed clip started again (as on Gyirong) was cut short. The layer now says when a run going on from a seek started its clip again, and the hold then plays out as from its start: through the media gate when there is one, else for the whole hold. --- docs/DIRECTOR.md | 7 ++-- src/data/bhoteKoshiEvent.js | 24 +++++++++++++ src/data/bhoteKoshiEvent.test.mjs | 60 +++++++++++++++++++++++++++++++ src/scenes/director.js | 19 +++++++--- src/scenes/director.test.mjs | 4 ++- 5 files changed, 106 insertions(+), 8 deletions(-) diff --git a/docs/DIRECTOR.md b/docs/DIRECTOR.md index fd2c6eedaa..3a81ef96d5 100644 --- a/docs/DIRECTOR.md +++ b/docs/DIRECTOR.md @@ -41,8 +41,11 @@ goes on from there along the rest of the path a seek samples, over the rest of t flight; inside its hold, the layers take that moment's state as a seek gives them and then play on from it: a reveal goes on from where the seek put it, and a clip the moment falls in starts again from its beginning (a clip cannot be -joined partway), while one the moment is past stays finished. A clip started again is waited -for as in any hold; otherwise only the rest of the hold is waited out. The scene clock carries on from the same point. `SceneDirector` still owns editor state, saved-project import/export, +joined partway), while one the moment is past stays finished. A clip started +again plays the hold out as from its start: until its media gate opens (a +trimmed clip, with its fade), or for the shot's whole hold (a clip without +one). Otherwise only the rest of the hold is waited out. The scene clock +carries on from the same point. `SceneDirector` still owns editor state, saved-project import/export, camera ownership and asynchronous load/seek arbitration. Pure seek calculations live in `src/director/timeline.js`; `src/director/clock.js` owns the run/load/shot tickers, hold deadlines, snapshots and clock subscriptions. Stop settles pending diff --git a/src/data/bhoteKoshiEvent.js b/src/data/bhoteKoshiEvent.js index 86d17e7101..b47dca8e2b 100644 --- a/src/data/bhoteKoshiEvent.js +++ b/src/data/bhoteKoshiEvent.js @@ -1090,6 +1090,8 @@ export function createBhoteKoshiEventLayer({ 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; @@ -1552,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 || @@ -3896,6 +3911,14 @@ export function createBhoteKoshiEventLayer({ 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; @@ -4010,6 +4033,7 @@ export function createBhoteKoshiEventLayer({ setParams, getParams, getSceneShotMediaHold, + sceneShotRestartsMedia, setSceneMediaPlayback, getStats() { return { diff --git a/src/data/bhoteKoshiEvent.test.mjs b/src/data/bhoteKoshiEvent.test.mjs index 87159fd18f..5eb4b78634 100644 --- a/src/data/bhoteKoshiEvent.test.mjs +++ b/src/data/bhoteKoshiEvent.test.mjs @@ -529,6 +529,66 @@ test('a run going on from a seek in Timure’s hold resumes its evidence sequenc } 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(); diff --git a/src/scenes/director.js b/src/scenes/director.js index edc141e010..35387ecba7 100644 --- a/src/scenes/director.js +++ b/src/scenes/director.js @@ -2957,11 +2957,20 @@ export class SceneDirector { ] : []; }); - // Resumed inside the hold, its layers play on from that moment: a clip - // they started again is waited for as in any hold; otherwise only the - // rest of the hold is left to wait. - const resumed = resume?.holdElapsedSec > 0; - if (resumed && !readers.some(({ read }) => read()?.pending === true)) { + // Resumed inside the hold, its layers play on from that moment. A clip + // they started again plays the hold out as from its start (its media + // gate, or the shot's whole hold for a clip without one); otherwise only + // the rest of the hold is left to wait. + const restartedClip = + resume?.holdElapsedSec > 0 && + Object.entries(this._layerStatesForShot(scene, shot)).some( + ([id, state]) => + state.enabled && + this.dataManager?.layers + ?.get(id) + ?.module?.sceneShotRestartsMedia?.(state.params?.beatId) === true, + ); + if (resume?.holdElapsedSec > 0 && !restartedClip) { await this._sleep( Math.max(0, resume.holdDurationSec - resume.holdElapsedSec) * 1000, token, diff --git a/src/scenes/director.test.mjs b/src/scenes/director.test.mjs index f742db9815..dd36ec3897 100644 --- a/src/scenes/director.test.mjs +++ b/src/scenes/director.test.mjs @@ -2140,6 +2140,7 @@ test('a hold resumed partway waits for a clip that starts again, else only its r let reads = 0; const module = { getSceneShotMediaHold: () => ({ pending: reads++ < pendingReads, maxWaitMs: 20000 }), + sceneShotRestartsMedia: () => pendingReads > 0, }; const waits = []; await SceneDirector.prototype._holdShot.call( @@ -2158,7 +2159,8 @@ test('a hold resumed partway waits for a clip that starts again, else only its r return waits; }; // The clip plays again: the hold polls until it is done, as any hold does. - assert.deepEqual(await hold(4), [70, 70]); + const polls = await hold(4); + assert.ok(polls.length && polls.every((ms) => ms === 70), String(polls)); // The moment was past the clip: only the rest of the hold. assert.deepEqual(await hold(0), [2000]); }); From 2788a9f667428f7c570d539823dba86ecb369925 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Mon, 16 Nov 2026 14:20:55 -0800 Subject: [PATCH 38/70] Docs: the timeline waits at a shot's end while a restarted clip plays --- docs/CURRENT-STATE.md | 3 ++- docs/DIRECTOR.md | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 72bbd49146..94b376caa3 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -731,7 +731,8 @@ it seeks the globe once. Play after a pause, a seek or a paused link goes on from that exact moment (`SceneDirector.startScene` with `fromProgress`), even inside a shot or its final quarter-second: the camera, the hold, the scene clock and the layers' reveals carry on from there (a clip that moment falls in -starts again from its beginning, and the hold waits for it). A scene that has actually ended replays from the +starts again from its beginning, and the hold waits for it, with the +timeline held at the shot's end meanwhile). A scene that has actually ended replays from the beginning. Opening Stories claims the camera through the shared navigation policy, so diff --git a/docs/DIRECTOR.md b/docs/DIRECTOR.md index 3a81ef96d5..5dc3427265 100644 --- a/docs/DIRECTOR.md +++ b/docs/DIRECTOR.md @@ -45,7 +45,9 @@ joined partway), while one the moment is past stays finished. A clip started again plays the hold out as from its start: until its media gate opens (a trimmed clip, with its fade), or for the shot's whole hold (a clip without one). Otherwise only the rest of the hold is waited out. The scene clock -carries on from the same point. `SceneDirector` still owns editor state, saved-project import/export, +carries on from the same point; while a restarted clip plays past where the +shot would have ended, the timeline waits at the shot's end until the clip +and the rest of the hold finish. `SceneDirector` still owns editor state, saved-project import/export, camera ownership and asynchronous load/seek arbitration. Pure seek calculations live in `src/director/timeline.js`; `src/director/clock.js` owns the run/load/shot tickers, hold deadlines, snapshots and clock subscriptions. Stop settles pending From cc83763452d6f2092c9355429787815e981333fc Mon Sep 17 00:00:00 2001 From: Manjunath Paparaju Date: Fri, 13 Nov 2026 10:33:43 +0530 Subject: [PATCH 39/70] Rebuild the Context panel around the selected item and the view Clicking anything a layer can identify opens one card in Context: a hero tile (route globe and 3D model for a flight, the camera for CCTV, headline figures otherwise), its facts, actions with Cockpit or the orbital view as the primary one, and a standard set of nearby blocks (weather and local time, flights, vessels, hazards, alerts) within one radius the user sets. Aircraft show altitude as a graph. Things that move are followed when picked, and a card closes when its layer is turned off. With nothing selected the panel describes the view: the layers that are on with a breakdown of what each holds, the camera's height, what is in view, then time, weather and local news. From far out it shows worldwide counts per layer. A search field in the header narrows whatever the panel shows. Prototype. Context reads weather and hazard feeds while its panel is closed, the two 3D previews on a flight card repaint continuously, Follow can show pressed after tracking has ended elsewhere, and most new strings are fixed English. Same-named sites are told apart by position, not by a stable id. --- src/data/entityContext.js | 1249 +++++++++++++++++ src/data/entityContext.test.mjs | 204 +++ src/layers/flights/queries.js | 32 + src/ui/contextLayerTabs.js | 82 ++ src/ui/contextRadius.js | 43 + src/ui/contextSearch.js | 24 + src/ui/entityContextBridge.js | 215 +++ src/ui/spotConditions.js | 172 +++ src/ui/stores/entityCard.js | 258 ++++ src/ui/styles/context-dock.css | 185 +++ src/ui/styles/context-tabs.css | 125 ++ src/ui/styles/entity-card.css | 1752 ++++++++++++++++++++++++ src/ui/styles/spot-conditions.css | 332 +++++ src/ui/styles/sun-dial.css | 110 ++ src/ui/views/ContextView.vue | 127 +- src/ui/views/panels/AltitudeGraph.vue | 116 ++ src/ui/views/panels/CctvPreview.vue | 100 ++ src/ui/views/panels/EntityCard.vue | 326 +++++ src/ui/views/panels/SpotConditions.vue | 392 ++++++ src/ui/views/panels/SunDial.vue | 364 +++++ src/ui/views/panels/ViewContext.vue | 388 ++++++ 21 files changed, 6595 insertions(+), 1 deletion(-) create mode 100644 src/data/entityContext.js create mode 100644 src/data/entityContext.test.mjs create mode 100644 src/ui/contextLayerTabs.js create mode 100644 src/ui/contextRadius.js create mode 100644 src/ui/contextSearch.js create mode 100644 src/ui/entityContextBridge.js create mode 100644 src/ui/spotConditions.js create mode 100644 src/ui/stores/entityCard.js create mode 100644 src/ui/styles/context-dock.css create mode 100644 src/ui/styles/context-tabs.css create mode 100644 src/ui/styles/entity-card.css create mode 100644 src/ui/styles/spot-conditions.css create mode 100644 src/ui/styles/sun-dial.css create mode 100644 src/ui/views/panels/AltitudeGraph.vue create mode 100644 src/ui/views/panels/CctvPreview.vue create mode 100644 src/ui/views/panels/EntityCard.vue create mode 100644 src/ui/views/panels/SpotConditions.vue create mode 100644 src/ui/views/panels/SunDial.vue create mode 100644 src/ui/views/panels/ViewContext.vue diff --git a/src/data/entityContext.js b/src/data/entityContext.js new file mode 100644 index 0000000000..78fe791bc0 --- /dev/null +++ b/src/data/entityContext.js @@ -0,0 +1,1249 @@ +import { getContextStore } from './contextStore.js'; + +/** + * One way to read any thing on the map, whichever layer holds it. + * + * Layers already list their loaded items through `getAnalystRecords()` (the + * records voice and the analyst answer from) and identify a clicked item + * through `resolvePickedContext()`. This module joins the two: it finds the + * record behind an identity, turns it into a card (title, kind, facts), lists + * the nearest items of the same kind and of other layers, and searches every + * enabled layer by name for the omnibar. + * + * It reads only; nothing here moves the camera or changes a layer. + */ + +/** + * How a layer's items are named and drawn, by layer id. `headline` names the + * fields that lead a card as its big figures, in order; `name` is what an + * item without a name of its own goes by. + */ +const AIRCRAFT = { kind: 'aircraft', icon: 'flight', moving: true, headline: ['altitudeM', 'speedMps', 'heading'] }; +const KINDS = Object.freeze({ + flights: AIRCRAFT, + military: AIRCRAFT, + 'local-adsb': AIRCRAFT, + 'ais-live-vessels': { kind: 'vessel', icon: 'directions_boat', moving: true, headline: ['speedKts', 'courseDeg', 'navStatus'] }, + satellites: { kind: 'satellite', icon: 'satellite_alt', moving: true, headline: ['altitudeM', 'speedMps'] }, + 'rocket-launches': { kind: 'launch', icon: 'rocket_launch' }, + 'local-firms': { kind: 'fire', icon: 'local_fire_department', headline: ['frp', 'confidence'], name: 'Fire detection' }, + 'fire-perimeters': { kind: 'fire perimeter', icon: 'local_fire_department', headline: ['acres', 'containedPct'] }, + earthquakes: { kind: 'earthquake', icon: 'earthquake', headline: ['magnitude', 'depthKm'] }, + 'weather-cyclones': { kind: 'storm', icon: 'cyclone', headline: ['windKt', 'pressureHpa'] }, + 'air-quality': { kind: 'air quality station', icon: 'air', headline: ['value', 'band'] }, + 'military-installations': { kind: 'installation', icon: 'factory' }, + 'local-dams': { kind: 'dam', icon: 'factory', headline: ['capacity'] }, + 'local-datacenters': { kind: 'data centre', icon: 'factory', headline: ['capacity'] }, + 'osm-places': { kind: 'place', icon: 'location_on' }, + transit: { kind: 'vehicle', icon: 'train', moving: true, headline: ['speedMps', 'courseDeg'] }, + bikeshare: { kind: 'bike station', icon: 'pedal_bike', headline: ['bikesAvailable', 'docksAvailable'] }, + 'alpr-cameras': { kind: 'plate reader', icon: 'videocam' }, + cctv: { kind: 'camera', icon: 'videocam' }, + 'drone-airspace': { kind: 'airspace', icon: 'pentagon', headline: ['lowerAltitude', 'upperAltitude'] }, + 'wildlife-sightings': { kind: 'sighting', icon: 'pets' }, +}); + +/** Fields a record may name itself by, best first. */ +const TITLE_FIELDS = [ + 'callsign', + 'name', + 'title', + 'label', + 'place', + 'registration', +]; +/** Fields that identify an item, for matching a click or a search. */ +const KEY_FIELDS = ['icao24', 'mmsi', 'noradId', 'usgsId', 'id']; +/** + * How many records to ask a layer for when all are wanted. Layers read a + * missing or unbounded count as their own small default, so this is a number + * above any layer's size. + */ +const ALL_RECORDS = 100_000; +/** Fields searched by the omnibar, besides the key fields. */ +const SEARCH_FIELDS = ['callsign', 'name', 'registration', 'place', 'operator', 'icao24', 'mmsi']; + +/** Never shown as facts: positions and identities already on the card. */ +const HIDDEN_FACTS = new Set([ + // Shown as the card's route line instead. + 'routeOrigin', + 'routeDestination', + 'routeFrom', + 'routeTo', + 'routeScheduled', + // Shown as the card's warning instead. + 'emergency', + 'emergencyKind', + 'emergencySource', + 'emergencyBroadcast', + 'tsunami', + 'warning', + 'alert', + 'advisory', + 'id', + 'lat', + 'lon', + 'latitude', + 'longitude', + 'name', + 'title', + 'label', + 'properties', + 'tags', + 'emergency', + 'emergencySource', + 'emergencyKind', + 'military', + // Repeats of what another fact already says, and feed bookkeeping. + 'vesselId', + 'typeCode', + 'group', + 'provider', + 'zone', + 'scale', + 'routeId', + 'building', +]); + +/** Facts that lead the list when a record has them, in this order. */ +const FACT_ORDER = [ + 'callsign', + 'registration', + 'operator', + 'aircraftClass', + 'routeOrigin', + 'routeDestination', + 'altitudeM', + 'speedMps', + 'speedKts', + 'heading', + 'courseDeg', + 'squawk', + 'emergencyBroadcast', + 'shipType', + 'destination', + 'magnitude', + 'depthKm', + 'place', + 'frp', + 'confidence', + 'acres', + 'containedPct', + 'windKt', + 'pressureHpa', + 'classification', + 'value', + 'band', + 'risk', + 'bikesAvailable', + 'docksAvailable', + 'lowerAltitude', + 'upperAltitude', + 'satellite', + 'sensor', + 'noradId', + 'satelliteClass', + 'mmsi', + 'icao24', + 'capacity', + 'output', + 'river', + 'class', + 'kind', + 'originCountry', +]; + +/** Plain labels for record fields. Unlisted fields are spelled out. */ +const FACT_LABELS = Object.freeze({ + callsign: 'Callsign', + registration: 'Registration', + operator: 'Operator', + aircraftClass: 'Aircraft class', + routeOrigin: 'From', + routeDestination: 'To', + altitudeM: 'Altitude', + speedMps: 'Speed', + speedKts: 'Speed', + heading: 'Heading', + courseDeg: 'Course', + verticalRateMps: 'Vertical rate', + squawk: 'Squawk', + emergencyBroadcast: 'Emergency', + onGround: 'On the ground', + originCountry: 'Country', + lastContactAtMs: 'Last contact', + shipType: 'Ship type', + destination: 'Destination', + navStatus: 'Status', + magnitude: 'Magnitude', + depthKm: 'Depth', + timeMs: 'Time', + place: 'Place', + frp: 'Fire power', + confidence: 'Confidence', + satellite: 'Satellite', + sensor: 'Sensor', + acqTime: 'Detected', + acres: 'Area', + containedPct: 'Contained', + discoveredTime: 'Discovered', + category: 'Type', + windKt: 'Wind', + pressureHpa: 'Pressure', + classification: 'Class', + basin: 'Basin', + value: 'Index', + band: 'Level', + risk: 'Health risk', + bikesAvailable: 'Bikes', + docksAvailable: 'Docks', + lowerAltitude: 'Floor', + upperAltitude: 'Ceiling', + timesOfUse: 'Active', + mode: 'Mode', + noradId: 'NORAD ID', + satelliteClass: 'Class', + mmsi: 'MMSI', + icao24: 'ICAO24', + capacity: 'Capacity', + output: 'Output', + river: 'River', + class: 'Class', + kind: 'Type', + 'addr:city': 'City', + 'addr:state': 'State', + 'addr:country': 'Country', + 'addr:street': 'Street', + start_date: 'Opened', + height: 'Height', + 'plant:source': 'Source', + 'plant:output:electricity': 'Output', + 'generator:source': 'Source', + 'capacity:it_load': 'IT load', + waterway: 'Waterway', + military: 'Military', + landuse: 'Land use', + power: 'Power', + telecom: 'Telecom', +}); + +/** OSM bookkeeping tags that say nothing about the place itself. */ +const NOISE_TAG = + /^(name:|alt_name|old_name|official_name|short_name|osm_|source|note|fixme|check_date|ref:|wikimedia|wikipedia|wikidata|website|url|image|layer$|area$|type$|id$|@)|:wikidata$|:wikipedia$/; + +const MAX_FACTS = 8; +const EARTH_RADIUS_KM = 6371; + +const text = (value) => { + if (value === null || value === undefined) return ''; + if (typeof value === 'object') return ''; + const shown = String(value).trim(); + return shown === 'undefined' || shown === 'null' ? '' : shown; +}; + +const finite = (value) => + value === null || value === undefined || value === '' + ? null + : Number.isFinite(Number(value)) + ? Number(value) + : null; + +/** What a layer's items are, and the glyph that stands for them. */ +export function entityKind(layerId) { + return KINDS[layerId] || { kind: 'feature', icon: 'location_on' }; +} + +/** Latitude and longitude of a record, whichever names it uses. */ +export function recordPosition(record) { + const lat = finite(record?.lat ?? record?.latitude); + const lon = finite(record?.lon ?? record?.longitude); + return lat === null || lon === null ? null : { lat, lon }; +} + +/** The name a person would use for a record. */ +export function recordTitle(record) { + for (const field of TITLE_FIELDS) { + const value = text(record?.[field]); + if (value) return value; + } + // An unnamed site goes by its operator before a bare database number. + const id = text(record?.id); + const operator = text(record?.operator); + if (operator && (!id || /^\d+$/.test(id))) return operator; + return id; +} + +/** A key that stays the same for one item across feed refreshes. */ +export function recordKey(layerId, record) { + for (const field of KEY_FIELDS) { + const value = text(record?.[field]); + if (value) return `${layerId}:${value}`; + } + const at = recordPosition(record); + return at ? `${layerId}:${at.lat.toFixed(4)},${at.lon.toFixed(4)}` : ''; +} + +/** Great-circle distance in kilometres. */ +export function distanceKm(a, b) { + const rad = Math.PI / 180; + const dLat = (b.lat - a.lat) * rad; + const dLon = (b.lon - a.lon) * rad; + const h = + Math.sin(dLat / 2) ** 2 + + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2; + return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h))); +} + +/** Spell out a field name: `originCountry` → `Origin country`. */ +function spellOut(field) { + const words = String(field) + .replace(/[_:]+/g, ' ') + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .toLowerCase() + .trim(); + return words ? words[0].toUpperCase() + words.slice(1) : ''; +} + +const isEpochMs = (value) => + Number.isFinite(value) && value > 1e11 && value < 1e13; + +/** + * A fact's value as shown, or '' to leave it out. Units follow the field + * name's suffix, the convention the layers' records already use. + * @param {string} field + * @param {*} value + * @param {object} [options] + * @param {number} [options.nowMs] + * @returns {{value: string, age?: number}|null} + */ +/** Codes the feeds use, in words. */ +const CODE_WORDS = Object.freeze({ + classification: { + TD: 'Tropical depression', + TS: 'Tropical storm', + HU: 'Hurricane', + MH: 'Major hurricane', + TY: 'Typhoon', + STY: 'Super typhoon', + TC: 'Tropical cyclone', + SD: 'Subtropical depression', + SS: 'Subtropical storm', + PTC: 'Post-tropical cyclone', + }, + category: { WF: 'Wildfire', RX: 'Prescribed burn' }, + basin: { + AL: 'Atlantic', + EP: 'Eastern Pacific', + CP: 'Central Pacific', + WP: 'Western Pacific', + IO: 'Indian Ocean', + SH: 'Southern Hemisphere', + }, +}); + +/** A feed's bare lowercase word as people write it: `data_center` → `Data center`. */ +function plainWord(shown) { + if (!/^[a-z][a-z_]*$/.test(shown)) return shown; + const words = shown.replace(/_/g, ' '); + return words[0].toUpperCase() + words.slice(1); +} + +/** An AIS ship type number as the kind of vessel it stands for. */ +function shipTypeName(code) { + const n = Number(code); + if (!Number.isInteger(n) || n < 1 || n > 99) return ''; + if (n === 30) return 'Fishing'; + if (n === 31 || n === 32 || n === 52) return 'Tug'; + if (n === 35) return 'Military'; + if (n === 36) return 'Sailing'; + if (n === 37) return 'Pleasure craft'; + if (n === 50) return 'Pilot vessel'; + if (n === 51) return 'Search and rescue'; + if (n === 55) return 'Law enforcement'; + if (n >= 40 && n <= 49) return 'High-speed craft'; + if (n >= 60 && n <= 69) return 'Passenger'; + if (n >= 70 && n <= 79) return 'Cargo'; + if (n >= 80 && n <= 89) return 'Tanker'; + return 'Other'; +} + +export function formatFact(field, value, { nowMs = Date.now(), kind = '' } = {}) { + if (field === 'shipType' && shipTypeName(value)) return { value: shipTypeName(value) }; + if (value === true) return { value: 'Yes' }; + if (value === false || value === null || value === undefined) return null; + const number = typeof value === 'number' ? value : null; + if (number !== null && !Number.isFinite(number)) return null; + const round = (n, digits = 0) => + n.toLocaleString('en-US', { maximumFractionDigits: digits }); + if (number !== null) { + if (/AtMs$|^timeMs$|^acqTime$|^observedMs$|^updatedTime$/.test(field) && isEpochMs(number)) + return { value: '', age: Math.max(0, nowMs - number) }; + // Any other moment reads as a date. + if (/(Time|Ms|At)$/.test(field) && isEpochMs(number)) + return { + value: new Date(number).toLocaleDateString('en-GB', { + day: 'numeric', + month: 'short', + year: 'numeric', + timeZone: 'UTC', + }), + }; + // Aviation altitudes read in feet; orbits in kilometres. + if (field === 'altitudeM') + return { + value: + number >= 100_000 + ? `${round(number / 1000)} km` + : `${round(number * 3.28084)} ft`, + }; + // Orbital speeds read in km/s, road and rail in km/h, the rest in knots. + if (field === 'speedMps' && number >= 2000) + return { value: `${round(number / 1000, 2)} km/s` }; + if (field === 'speedMps' && kind === 'vehicle') + return { value: `${round(number * 3.6)} km/h` }; + if (field === 'speedMps') return { value: `${round(number * 1.94384)} kt` }; + if (field === 'speedKts') return { value: `${round(number, 1)} kt` }; + if (field === 'verticalRateMps') + return { value: `${round(number * 196.85)} ft/min` }; + if (/^(heading|courseDeg)$/.test(field)) return { value: `${round(number)}°` }; + if (field === 'depthKm') return { value: `${round(number, 1)} km` }; + if (field === 'magnitude') return { value: `M ${round(number, 1)}` }; + if (field === 'frp') return { value: `${round(number, 1)} MW` }; + if (field === 'confidence' && number <= 1) + return { value: `${round(number * 100)}%` }; + if (/Pct$/.test(field)) return { value: `${round(number)}%` }; + if (/Kt$/.test(field)) return { value: `${round(number)} kt` }; + if (/Hpa$/.test(field)) return { value: `${round(number)} hPa` }; + if (field === 'acres') return { value: `${round(number)} acres` }; + if (/Km$/.test(field)) return { value: `${round(number, 1)} km` }; + if (/M$/.test(field)) return { value: `${round(number)} m` }; + return { value: round(number, 2) }; + } + const raw = text(value); + if (!raw) return null; + // Identifiers and names stay exactly as the feed gives them. + const verbatim = KEY_FIELDS.includes(field) || TITLE_FIELDS.includes(field); + const shown = CODE_WORDS[field]?.[raw] || (verbatim ? raw : plainWord(raw)); + return { value: shown.length > 80 ? `${shown.slice(0, 77)}…` : shown }; +} + +/** + * The facts a card lists for a record: known fields first, in a fixed order, + * then whatever else the record carries, up to a handful. + */ +export function recordFacts(record, { nowMs = Date.now(), skip = [], kind = '' } = {}) { + const facts = []; + let observedAgeMs = null; + const seen = new Set(skip); + const fields = [ + ...FACT_ORDER.filter((field) => field in (record || {})), + ...Object.keys(record || {}).filter((field) => !FACT_ORDER.includes(field)), + ]; + for (const field of fields) { + if (HIDDEN_FACTS.has(field) || seen.has(field)) continue; + seen.add(field); + const formatted = formatFact(field, record[field], { nowMs, kind }); + if (!formatted) continue; + if (formatted.age !== undefined) { + observedAgeMs ??= formatted.age; + continue; + } + if (facts.length < MAX_FACTS) + facts.push({ + field, + // An index goes by the scale it is on (AQHI, AQI). + label: + (field === 'value' && text(record.scale)) || + FACT_LABELS[field] || + spellOut(field), + value: formatted.value, + }); + } + return { facts, observedAgeMs }; +} + +/** Facts from a context-store record's properties (GeoJSON / OSM tags). */ +function propertyFacts(properties) { + const flat = { + ...(properties || {}), + ...(properties?.tags && typeof properties.tags === 'object' + ? properties.tags + : {}), + }; + const keep = {}; + for (const [field, value] of Object.entries(flat)) { + if (NOISE_TAG.test(field)) continue; + if (text(value)) keep[field] = value; + } + return recordFacts(keep); +} + +/** A reference link a record carries (Wikipedia, Wikidata or a website). */ +function recordLinks(record, properties) { + const flat = { + ...(properties || {}), + ...(properties?.tags && typeof properties.tags === 'object' + ? properties.tags + : {}), + ...(record || {}), + }; + const links = []; + const wikipedia = text(flat.wikipedia); + if (wikipedia) { + const [lang, ...title] = wikipedia.includes(':') + ? wikipedia.split(':') + : ['en', wikipedia]; + // The language part becomes the link's host, so only a language code is + // let through. + if (/^[a-z]{2,3}(-[a-z0-9]+)*$/.test(lang)) + links.push({ + kind: 'wikipedia', + label: 'Wikipedia', + href: `https://${lang}.wikipedia.org/wiki/${encodeURIComponent(title.join(':').replace(/ /g, '_'))}`, + }); + } + const wikidata = text(flat.wikidata); + if (/^Q\d+$/.test(wikidata)) + links.push({ + kind: 'wikidata', + label: 'Wikidata', + href: `https://www.wikidata.org/wiki/${wikidata}`, + }); + const website = text(flat.website); + if (/^https?:\/\//.test(website)) + links.push({ kind: 'website', label: 'Website', href: website }); + return links; +} + +/** Enabled layers, as the data manager lists them. */ +function enabledLayers(dataManager) { + try { + return (dataManager?.getAll?.() || []).filter((layer) => layer.enabled); + } catch { + return []; + } +} + +/** + * The items a layer has loaded, with a usable position. Empty while the layer + * is off or keeps no list. + */ +export function layerRecords(dataManager, layerId, maxCount = ALL_RECORDS) { + if (dataManager?.isEnabled && !dataManager.isEnabled(layerId)) return []; + let records = []; + try { + records = + dataManager?.layers?.get?.(layerId)?.module?.getAnalystRecords?.(maxCount) || + []; + } catch { + records = []; + } + return records.filter((record) => recordPosition(record)); +} + +function layerName(dataManager, layerId) { + const layer = dataManager?.layers?.get?.(layerId); + return text(layer?.name) || text(layer?.module?.name) || layerId; +} + +const sameText = (a, b) => + Boolean(a) && Boolean(b) && a.toLowerCase() === b.toLowerCase(); + +/** + * The layer record behind an identity from a click, a search or the store: + * matched by key, then by name, then as the nearest item to its position. + * @param {object} dataManager + * @param {{layerId: string, id?: string, label?: string, lat?: number|null, lon?: number|null}} identity + * @returns {object|null} + */ +export function findRecord(dataManager, identity) { + const { layerId } = identity || {}; + if (!layerId) return null; + const records = layerRecords(dataManager, layerId); + if (!records.length) return null; + const id = text(identity.id); + const bare = id.startsWith(`${layerId}:`) ? id.slice(layerId.length + 1) : id; + const at = + finite(identity.lat) !== null && finite(identity.lon) !== null + ? { lat: Number(identity.lat), lon: Number(identity.lon) } + : null; + const nearest = (pool) => { + let best = null; + let bestKm = Infinity; + for (const record of pool) { + const km = distanceKm(at, recordPosition(record)); + if (km < bestKm) { + best = record; + bestKm = km; + } + } + return { best, bestKm }; + }; + const byKey = records.filter((record) => + KEY_FIELDS.some((field) => { + const value = text(record[field]); + return value && (sameText(value, id) || sameText(value, bare)); + }), + ); + // Sites can share a key (many are keyed by a name such as an operator's): + // of several, the one where the identity says it is. + if (byKey.length === 1 || (byKey.length && !at)) return byKey[0]; + if (byKey.length) return nearest(byKey).best; + const label = text(identity.label); + const byName = records.filter((record) => + SEARCH_FIELDS.some((field) => sameText(text(record[field]), label)), + ); + if (byName.length === 1 || (byName.length && !at)) return byName[0]; + if (!at) return null; + // A moving item is matched by its key or name above; guessing the nearest + // could name another craft. + if (!byName.length && entityKind(layerId).moving) return null; + const { best, bestKm } = nearest(byName.length ? byName : records); + // A static item a click names sits where it was drawn. + return bestKm <= 1 ? best : null; +} + +/** The context-store record for an identity, when the layer keeps one. */ +function storeRecord(identity) { + try { + const store = getContextStore(); + const direct = store.entities.get(String(identity.id)); + if (direct?.layerId === identity.layerId) return direct; + // Of several stored sites with the same name, the one at the identity's + // position; a name alone picks the first. + const at = recordPosition(identity); + let best = null; + let bestKm = Infinity; + for (const record of store.entities.values()) { + if (record?.layerId !== identity.layerId) continue; + if (sameText(text(record.properties?.mmsi), text(identity.id))) return record; + if (!sameText(text(record.label), text(identity.label))) continue; + const where = recordPosition(record); + const km = at && where ? distanceKm(at, where) : best ? Infinity : 0; + if (km < bestKm) { + best = record; + bestKm = km; + } + } + if (best) return best; + } catch { + // No window in unit tests without a DOM. + } + return null; +} + +/** + * The card for one item. + * @param {object} dataManager + * @param {{layerId: string, id?: string, label?: string, lat?: number|null, lon?: number|null, record?: object}} identity + * @param {object} [options] + * @param {number} [options.nowMs] + * @returns {object|null} `{key, layerId, layerName, kind, icon, moving, title, lat, lon, facts, observedAgeMs, links, source}` + */ +/** What a transponder code means when it is one of the emergency codes. */ +const EMERGENCY_SQUAWKS = Object.freeze({ + 7500: 'Hijack (squawk 7500)', + 7600: 'Radio failure (squawk 7600)', + 7700: 'Emergency (squawk 7700)', +}); + +/** + * Warnings a record carries, most serious first: an aircraft emergency or + * emergency squawk, a tsunami flag, or a layer's own alert text. These lead + * the card, ahead of any facts. + * @param {?object} record + * @returns {string[]} + */ +export function recordWarnings(record) { + if (!record) return []; + const found = []; + const kind = text(record.emergencyKind); + if (record.emergency === true || (kind && kind.toLowerCase() !== 'none')) + found.push(kind ? `Emergency: ${kind}` : 'Emergency declared'); + const squawk = EMERGENCY_SQUAWKS[Number(record.squawk)]; + if (squawk && !found.length) found.push(squawk); + if (record.tsunami === true || Number(record.tsunami) === 1) found.push('Tsunami warning issued'); + // `alert` is left out: feeds use it for a level (an earthquake's PAGER + // colour), not a warning to read out. + for (const field of ['warning', 'advisory']) { + const value = text(record[field]); + if (value && !found.includes(value)) found.push(value); + } + return found; +} + +/** What a routine transponder code says, for the codes with a meaning. */ +const SQUAWK_MEANINGS = Object.freeze({ + 1200: 'VFR, no flight plan', + 7000: 'VFR conspicuity', + 2000: 'IFR, no code yet', + 7500: 'Hijack', + 7600: 'Radio failure', + 7700: 'Emergency', +}); + +/** Speed of sound (m/s) at a height, from the standard atmosphere. */ +function speedOfSound(heightM) { + const kelvin = heightM < 11_000 ? 288.15 - 0.0065 * heightM : 216.65; + return 20.05 * Math.sqrt(kelvin); +} + +/** + * What can be worked out about a flight beyond its raw fields: its phase of + * flight, flight level, Mach number, what its squawk means and how fresh its + * signal is. For the callouts on the aircraft card, which show these rather + * than repeat the facts listed below them. + * @param {?object} record + * @param {{nowMs?: number}} [options] + * @returns {Array<{label: string, value: string}>} + */ +export function aircraftInsights(record, { nowMs = Date.now() } = {}) { + if (!record) return []; + const out = []; + const altitudeM = finite(record.altitudeM); + const climbMps = finite(record.verticalRateMps); + const speedMps = finite(record.speedMps ?? (finite(record.speedKts) !== null ? record.speedKts * 0.514444 : null)); + if (record.onGround === true) out.push({ label: 'Phase', value: 'On the ground' }); + else if (climbMps !== null) { + const fpm = climbMps * 196.85; + out.push({ + label: 'Phase', + value: fpm > 300 ? `Climbing ${Math.round(fpm / 100) * 100} ft/min` : fpm < -300 ? `Descending ${Math.round(-fpm / 100) * 100} ft/min` : 'Cruising, level', + }); + } + if (altitudeM !== null && altitudeM > 900) out.push({ label: 'Flight level', value: `FL${String(Math.round(altitudeM * 3.28084 / 1000) * 10).padStart(3, '0')}` }); + if (speedMps !== null && altitudeM !== null && speedMps > 60) + out.push({ label: 'Mach', value: `M ${(speedMps / speedOfSound(altitudeM)).toFixed(2)}` }); + const squawk = Number(record.squawk); + if (SQUAWK_MEANINGS[squawk]) out.push({ label: `Squawk ${record.squawk}`, value: SQUAWK_MEANINGS[squawk] }); + const seen = finite(record.lastContactAtMs ?? record.timeMs); + if (seen !== null) { + const seconds = Math.max(0, Math.round((nowMs - seen) / 1000)); + out.push({ label: 'Signal', value: seconds < 90 ? `${seconds} s ago` : `${Math.round(seconds / 60)} min ago` }); + } + return out; +} + +export function describeEntity(dataManager, identity, { nowMs = Date.now() } = {}) { + if (!identity?.layerId) return null; + const { layerId } = identity; + const kind = entityKind(layerId); + const record = identity.record || findRecord(dataManager, identity); + // Sites drawn from GeoJSON keep their full tags in the context store; the + // layer's record holds only a summary of them. + const stored = + record && kind.moving + ? null + : storeRecord({ ...identity, label: identity.label || recordTitle(record) }); + if (!record && !stored && !identity.label) return null; + + const at = + recordPosition(record) || + recordPosition(stored) || + recordPosition(identity); + const fromRecord = record ? recordFacts(record, { nowMs, kind: kind.kind }) : null; + const fromStore = stored ? propertyFacts(stored.properties) : null; + const facts = [...(fromRecord?.facts || [])]; + for (const fact of fromStore?.facts || []) { + if (facts.length >= MAX_FACTS) break; + const same = facts.some( + (known) => + known.label.toLowerCase() === fact.label.toLowerCase() || + known.value.toLowerCase() === fact.value.toLowerCase(), + ); + if (!same) facts.push(fact); + } + // An item with only a database number goes by what it is. + const ownTitle = recordTitle(record); + const title = + (kind.name && (!ownTitle || ownTitle === text(record?.id)) ? kind.name : ownTitle) || + text(stored?.label) || + text(stored?.properties?.name) || + text(identity.label) || + layerName(dataManager, layerId); + const key = record + ? recordKey(layerId, record) + : `${layerId}:${text(identity.id) || title}`; + return { + key, + layerId, + layerName: text(stored?.layerName) || layerName(dataManager, layerId), + kind: kind.kind, + icon: kind.icon, + moving: Boolean(kind.moving), + // The fields that lead the card as its big figures. + headline: kind.headline || [], + title, + lat: at?.lat ?? null, + lon: at?.lon ?? null, + altitudeM: finite(record?.altitudeM ?? identity.altitudeM), + facts: facts.filter((fact) => fact.value !== title), + warnings: recordWarnings(record), + // For the aircraft card's model and route line. + aircraftClass: kind.kind === 'aircraft' ? text(record?.aircraftClass) || null : null, + insights: kind.kind === 'aircraft' ? aircraftInsights(record, { nowMs }) : [], + operator: text(record?.operator) || null, + heading: finite(record?.heading ?? record?.course), + speedMps: finite(record?.speedMps ?? (finite(record?.speedKts) !== null ? record.speedKts * 0.514444 : null)), + route: + text(record?.routeOrigin) || text(record?.routeDestination) + ? { + from: text(record?.routeOrigin) || '—', + to: text(record?.routeDestination) || '—', + verified: true, + // Airport positions, when known, for the route globe. + fromAt: record?.routeFrom || null, + toAt: record?.routeTo || null, + } + : record?.routeScheduled + ? { + // Scheduled for the flight number but not where the plane is: + // shown as unverified, and never drawn on the globe. + from: text(record.routeScheduled.from) || '—', + to: text(record.routeScheduled.to) || '—', + verified: false, + fromAt: null, + toAt: null, + } + : null, + observedAgeMs: fromRecord?.observedAgeMs ?? null, + links: recordLinks(record, stored?.properties), + source: text(stored?.source) || null, + // What the card was built from: the layer's own record, the store's + // properties, or only the click's identity. + basis: record ? 'record' : stored ? 'store' : 'identity', + identity: { + layerId, + id: record ? recordKey(layerId, record).slice(layerId.length + 1) : text(identity.id), + label: title, + lat: at?.lat ?? null, + lon: at?.lon ?? null, + }, + }; +} + +/** + * What is near an item: the closest items of its own layer, and the closest + * item of each other enabled layer. + * @param {object} dataManager + * @param {{layerId: string, key: string, lat: number|null, lon: number|null}} card + * @param {object} [options] + * @param {number} [options.limit] + * @param {number} [options.radiusKm] + * @returns {{same: Array, other: Array}} + */ +export function nearbyEntities( + dataManager, + card, + { limit = 5, radiusKm = 500 } = {}, +) { + const empty = { same: [], other: [] }; + if (!card || card.lat === null || card.lon === null) return empty; + const here = { lat: card.lat, lon: card.lon }; + const row = (layerId, record, km) => ({ + key: recordKey(layerId, record), + layerId, + layerName: layerName(dataManager, layerId), + icon: entityKind(layerId).icon, + kind: entityKind(layerId).kind, + title: recordTitle(record) || layerName(dataManager, layerId), + distanceKm: km, + identity: { + layerId, + id: recordKey(layerId, record).slice(layerId.length + 1), + label: recordTitle(record), + ...recordPosition(record), + record, + }, + }); + const nearest = (layerId, count) => { + const found = []; + for (const record of layerRecords(dataManager, layerId)) { + const key = recordKey(layerId, record); + if (key === card.key) continue; + const km = distanceKm(here, recordPosition(record)); + if (km > radiusKm) continue; + found.push({ record, km }); + } + return found + .sort((a, b) => a.km - b.km) + .slice(0, count) + .map(({ record, km }) => row(layerId, record, km)); + }; + const same = nearest(card.layerId, limit); + const other = enabledLayers(dataManager) + .filter((layer) => layer.id !== card.layerId) + .map((layer) => nearest(layer.id, 1)[0]) + .filter(Boolean) + .sort((a, b) => a.distanceKm - b.distanceKm) + .slice(0, limit); + return { same, other }; +} + +/** + * What the loaded layers have within a radius of a point, in the groups every + * Context card lists: aircraft, vessels, and the closest item of each other + * enabled layer. Each group is nearest first; `count` is how many are inside + * the radius, of which `items` holds the first few. + * @param {object} dataManager + * @param {{lat: number, lon: number}} here + * @param {object} [options] + * @param {number} [options.radiusKm] + * @param {number} [options.limit] Rows per group. + * @param {string} [options.excludeKey] A record to leave out (the selected one). + * @returns {{flights: {count: number, items: Array}, vessels: {count: number, items: Array}, other: Array}} + */ +export function nearbyByKind( + dataManager, + here, + { radiusKm = 250, limit = 4, excludeKey = '', query = '' } = {}, +) { + const needle = text(query).toLowerCase(); + const groups = { flights: { count: 0, items: [] }, vessels: { count: 0, items: [] }, other: [] }; + if (!here || !Number.isFinite(here.lat) || !Number.isFinite(here.lon)) return groups; + const found = { aircraft: [], vessel: [] }; + const other = []; + for (const layer of enabledLayers(dataManager)) { + const kind = entityKind(layer.id).kind; + const group = found[kind]; + let closest = null; + for (const record of layerRecords(dataManager, layer.id)) { + if (excludeKey && recordKey(layer.id, record) === excludeKey) continue; + const km = distanceKm(here, recordPosition(record)); + if (!(km <= radiusKm)) continue; + if (needle && !recordMatches(record, needle, layer.name)) continue; + if (group) group.push({ layerId: layer.id, record, km }); + // A search lists every match, not only each layer's closest item. + else if (needle) other.push({ layerId: layer.id, record, km }); + else if (!closest || km < closest.km) closest = { layerId: layer.id, record, km }; + } + if (closest) other.push(closest); + } + const row = ({ layerId, record, km }) => ({ + key: recordKey(layerId, record), + layerId, + layerName: layerName(dataManager, layerId), + icon: entityKind(layerId).icon, + title: recordTitle(record) || layerName(dataManager, layerId), + distanceKm: km, + identity: { + layerId, + id: recordKey(layerId, record).slice(layerId.length + 1), + label: recordTitle(record), + ...recordPosition(record), + record, + }, + }); + const nearest = (rows) => ({ + count: rows.length, + items: rows + .sort((a, b) => a.km - b.km) + .slice(0, limit) + .map(row), + }); + groups.flights = nearest(found.aircraft); + groups.vessels = nearest(found.vessel); + groups.other = other + .sort((a, b) => a.km - b.km) + .slice(0, limit) + .map(row); + return groups; +} + +/** Counts of records by a label, largest first, the tail folded into "Other". */ +function tallyBy(records, labelOf, { keep = 4 } = {}) { + const counts = new Map(); + for (const record of records) { + const label = labelOf(record) || 'Unknown'; + counts.set(label, (counts.get(label) || 0) + 1); + } + const sorted = [...counts].sort((a, b) => b[1] - a[1]); + const parts = sorted.slice(0, keep).map(([label, count]) => ({ label, count })); + const rest = sorted.slice(keep).reduce((sum, [, count]) => sum + count, 0); + if (rest) { + // A label that is itself "Other" takes the tail, so the name shows once. + const other = parts.find((part) => part.label === 'Other'); + if (other) other.count += rest; + else parts.push({ label: 'Other', count: rest }); + } + return parts.sort((a, b) => b.count - a.count); +} + +const AIRCRAFT_CLASS_NAMES = { + airliner: 'Airliners', + widebody: 'Widebodies', + bizjet: 'Business jets', + light: 'Light aircraft', + helicopter: 'Helicopters', + turboprop: 'Turboprops', + fastjet: 'Fast jets', + quadjet: 'Four-engine jets', +}; + +/** + * What a layer's items are made of, for Context: one or two ways of splitting + * them, each a list of labelled counts that add up to `total`. Aircraft split + * into civilian in the air, military in the air and on the ground, then by + * type of aircraft; vessels by type of ship; satellites by class; earthquakes + * by magnitude. Counts cover the records the layer hands out (it may cap + * them), inside `rect` when one is given. + * @param {object} dataManager + * @param {string} layerId + * @param {{rect?: ?{west: number, south: number, east: number, north: number}}} [options] + * @returns {?{total: number, splits: Array<{title: string, parts: Array<{label: string, count: number}>}>}} + * null when the layer has nothing to split or no split is known for it. + */ +export function layerBreakdown(dataManager, layerId, { rect = null } = {}) { + const kind = entityKind(layerId).kind; + if (!['aircraft', 'vessel', 'satellite', 'earthquake'].includes(kind)) return null; + let records = layerRecords(dataManager, layerId); + if (rect) { + const wraps = rect.west > rect.east; + records = records.filter((record) => { + const at = recordPosition(record); + return ( + at.lat >= rect.south && + at.lat <= rect.north && + (wraps ? at.lon >= rect.west || at.lon <= rect.east : at.lon >= rect.west && at.lon <= rect.east) + ); + }); + } + if (!records.length) return null; + const splits = []; + if (kind === 'aircraft') { + const ground = records.filter((record) => record.onGround === true).length; + const military = records.filter((record) => record.onGround !== true && record.military === true).length; + splits.push({ + title: 'Status', + parts: [ + { label: 'Civilian, in the air', count: records.length - ground - military }, + { label: 'Military, in the air', count: military }, + { label: 'On the ground', count: ground }, + ].filter((part) => part.count), + }); + splits.push({ title: 'Type', parts: tallyBy(records, (record) => AIRCRAFT_CLASS_NAMES[record.aircraftClass] || plainWord(text(record.aircraftClass))) }); + } else if (kind === 'vessel') { + splits.push({ title: 'Type', parts: tallyBy(records, (record) => shipTypeName(record.shipType)) }); + } else if (kind === 'satellite') { + splits.push({ title: 'Class', parts: tallyBy(records, (record) => plainWord(text(record.satelliteClass || record.group))) }); + } else { + const band = (record) => { + const m = finite(record.magnitude); + return m === null ? '' : m >= 6 ? 'M6 and above' : m >= 5 ? 'M5 to 6' : m >= 4 ? 'M4 to 5' : 'Below M4'; + }; + splits.push({ title: 'Magnitude', parts: tallyBy(records, band) }); + } + return { total: records.length, splits: splits.filter((split) => split.parts.length) }; +} + +/** + * Whether a record holds the searched text in any of its text fields, or in + * its layer's name. + * @param {object} record + * @param {string} needle Lower case; '' matches everything. + * @param {string} [layerLabel] + * @returns {boolean} + */ +export function recordMatches(record, needle, layerLabel = '') { + if (!needle) return true; + if (text(layerLabel).toLowerCase().includes(needle)) return true; + for (const value of Object.values(record || {})) { + if (typeof value === 'string' && value.toLowerCase().includes(needle)) return true; + } + return false; +} + +/** + * Items in enabled layers whose name or id starts with the typed text, best + * first. A whole-word match beats a match inside a word. + * @param {object} dataManager + * @param {string} query + * @param {object} [options] + * @param {number} [options.limit] + * @param {{lat: number, lon: number}|null} [options.near] Ties go to the closer item. + * @returns {Array} + */ +export function searchEntities(dataManager, query, { limit = 4, near = null } = {}) { + const needle = text(query).toLowerCase(); + if (needle.length < 2) return []; + const inWord = new RegExp( + `(^|[^a-z0-9])${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`, + ); + const found = []; + for (const layer of enabledLayers(dataManager)) { + for (const record of layerRecords(dataManager, layer.id)) { + let score = 0; + for (const field of [...SEARCH_FIELDS, ...KEY_FIELDS]) { + const value = text(record[field]).toLowerCase(); + if (!value) continue; + const hit = + value === needle + ? 3 + : value.startsWith(needle) + ? 2 + : needle.length >= 3 && inWord.test(value) + ? 1 + : 0; + score = Math.max(score, hit); + } + if (!score) continue; + const at = recordPosition(record); + found.push({ + score, + km: near ? distanceKm(near, at) : 0, + key: recordKey(layer.id, record), + layerId: layer.id, + layerName: layerName(dataManager, layer.id), + icon: entityKind(layer.id).icon, + title: recordTitle(record) || layer.id, + identity: { + layerId: layer.id, + id: recordKey(layer.id, record).slice(layer.id.length + 1), + label: recordTitle(record), + ...at, + record, + }, + }); + } + } + const seen = new Set(); + return found + .sort((a, b) => b.score - a.score || a.km - b.km) + .filter((item) => !seen.has(item.key) && seen.add(item.key)) + .slice(0, limit); +} + +/** + * What the loaded layers have inside a view: for each enabled layer with + * anything in the rectangle, how many and the few closest to the view's + * centre, as rows the Context panel can open. Layers with the most in view + * come first. + * @param {object} dataManager + * @param {{west: number, south: number, east: number, north: number}} rect Degrees. + * @param {{lat: number, lon: number}} center + * @param {object} [options] + * @param {number} [options.perLayer] Closest items to list for each layer. + * @returns {Array<{layerId: string, layerName: string, icon: string, count: number, items: Array}>} + */ +export function viewSummary(dataManager, rect, center, { perLayer = 3, query = '' } = {}) { + if (!rect || !center) return []; + const needle = text(query).toLowerCase(); + const wraps = rect.west > rect.east; + const inside = (at) => + at && + at.lat >= rect.south && + at.lat <= rect.north && + (wraps ? at.lon >= rect.west || at.lon <= rect.east : at.lon >= rect.west && at.lon <= rect.east); + const groups = []; + for (const layer of enabledLayers(dataManager)) { + const found = []; + for (const record of layerRecords(dataManager, layer.id)) { + const at = recordPosition(record); + if (!inside(at)) continue; + if (needle && !recordMatches(record, needle, layer.name)) continue; + found.push({ record, km: distanceKm(center, at) }); + } + if (!found.length) continue; + found.sort((a, b) => a.km - b.km); + groups.push({ + layerId: layer.id, + layerName: layerName(dataManager, layer.id), + icon: entityKind(layer.id).icon, + count: found.length, + items: found.slice(0, perLayer).map(({ record, km }) => ({ + key: recordKey(layer.id, record), + title: recordTitle(record) || layerName(dataManager, layer.id), + distanceKm: km, + identity: { + layerId: layer.id, + id: recordKey(layer.id, record).slice(layer.id.length + 1), + label: recordTitle(record), + ...recordPosition(record), + record, + }, + })), + }); + } + return groups.sort((a, b) => b.count - a.count); +} + +/** + * A layer's items inside an area that pass a test, closest to the area's + * middle first: how many, and the first few as rows the omnibox and Context + * can open. The area is a rectangle in degrees, or a radius around a point. + * @param {object} dataManager + * @param {string} layerId + * @param {object} area + * @param {{lat: number, lon: number}} area.center + * @param {?{west: number, south: number, east: number, north: number}} [area.rect] + * @param {number} [area.radiusKm] Used when there is no rectangle. + * @param {(record: object) => boolean} [area.test] + * @param {number} [area.limit] + * @returns {{count: number, items: Array}} + */ +export function layerMatches(dataManager, layerId, { center, rect = null, radiusKm = 60, test = () => true, limit = 8 }) { + const found = []; + const wraps = rect && rect.west > rect.east; + for (const record of layerRecords(dataManager, layerId)) { + const at = recordPosition(record); + if (!at) continue; + if (rect) { + const inLon = wraps ? at.lon >= rect.west || at.lon <= rect.east : at.lon >= rect.west && at.lon <= rect.east; + if (!inLon || at.lat < rect.south || at.lat > rect.north) continue; + } + const km = distanceKm(center, at); + if (!rect && km > radiusKm) continue; + if (!test(record)) continue; + found.push({ record, km }); + } + found.sort((a, b) => a.km - b.km); + return { + count: found.length, + items: found.slice(0, limit).map(({ record, km }) => ({ + key: recordKey(layerId, record), + title: recordTitle(record) || layerName(dataManager, layerId), + icon: entityKind(layerId).icon, + distanceKm: km, + identity: { + layerId, + id: recordKey(layerId, record).slice(layerId.length + 1), + label: recordTitle(record), + ...recordPosition(record), + record, + }, + })), + }; +} + +/** + * Loaded records near a point that carry a warning (an aircraft squawking an + * emergency, a quake with a tsunami flag, an advisory), nearest first. These + * are what each feed broadcasts, not confirmed incidents. + */ +export function alertsNear(dataManager, here, { radiusKm = 400, limit = 4 } = {}) { + if (!here || !Number.isFinite(here.lat) || !Number.isFinite(here.lon)) return []; + const found = []; + for (const layer of enabledLayers(dataManager)) { + for (const record of layerRecords(dataManager, layer.id)) { + const warnings = recordWarnings(record); + if (!warnings.length) continue; + const km = distanceKm(here, recordPosition(record)); + if (!(km <= radiusKm)) continue; + found.push({ + key: recordKey(layer.id, record), + icon: entityKind(layer.id).icon, + title: recordTitle(record) || layerName(dataManager, layer.id), + text: warnings[0], + distanceKm: km, + identity: { + layerId: layer.id, + id: recordKey(layer.id, record).slice(layer.id.length + 1), + label: recordTitle(record), + ...recordPosition(record), + record, + }, + }); + } + } + return found.sort((a, b) => a.distanceKm - b.distanceKm).slice(0, limit); +} diff --git a/src/data/entityContext.test.mjs b/src/data/entityContext.test.mjs new file mode 100644 index 0000000000..bfaf8fc1b4 --- /dev/null +++ b/src/data/entityContext.test.mjs @@ -0,0 +1,204 @@ +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 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 7000'), 'VFR conspicuity'); + 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); +}); diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 91ed4ea956..6f6feec989 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -246,6 +246,19 @@ export function createQueries({ * routeDestination: string|null}} */ + /** An airport at one end of a route, when it has a position. */ + function routeEnd(airport) { + const lat = Number(airport?.lat ?? airport?.latitude); + const lon = Number(airport?.lon ?? airport?.longitude); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null; + return { + code: String(airport?.code ?? '').trim() || null, + name: String(airport?.name ?? airport?.municipality ?? '').trim() || null, + lat, + lon, + }; + } + function mapAnalystRecord( icao24, info, @@ -293,6 +306,16 @@ export function createQueries({ lastContactAtMs: num(info?.lastContactEpochMs), routeOrigin: routeOk ? text(info?.route?.origin?.code) : null, routeDestination: routeOk ? text(info?.route?.destination?.code) : null, + // The airports themselves, for the context card's route globe. + routeFrom: routeOk ? routeEnd(info?.route?.origin) : null, + routeTo: routeOk ? routeEnd(info?.route?.destination) : null, + // The scheduled route when it does not fit where the plane is (often + // another leg of the same flight number): the card shows it marked + // unverified, everything else still treats the flight as routeless. + routeScheduled: + !routeOk && info?.route?.origin?.code && info?.route?.destination?.code + ? { from: text(info.route.origin.code), to: text(info.route.destination.code) } + : null, }; } const methods = { @@ -748,6 +771,15 @@ export function createQueries({ return result; }, + /** + * Ask for an aircraft's scheduled route (origin and destination airports), + * as tracking does; it lands on the record when the lookup answers. + * @param {string} icao24 + */ + requestRoute(icao24) { + if (icao24) parts.enrichment._requestRouteEnrichment(String(icao24).trim().toLowerCase()); + }, + /** * Start camera-tracking an aircraft by ICAO24 address. * @param {string} icao24 - ICAO 24-bit transponder address. diff --git a/src/ui/contextLayerTabs.js b/src/ui/contextLayerTabs.js new file mode 100644 index 0000000000..857f4bb846 --- /dev/null +++ b/src/ui/contextLayerTabs.js @@ -0,0 +1,82 @@ +import { computed, ref } from 'vue'; + +// Context's layer tabs: when a layer that has its own settings is on, those +// settings move out of the panel they normally live in (Visual) into a tab +// in the Context panel, so they sit beside what they affect. +// Each tab's content is teleported into `#context-tab-`; when the layer +// goes off the content returns to its usual panel. +const AIRCRAFT = ['flights', 'military', 'local-adsb']; + +// Layers that draw labels and cards through the world overlay, which the +// Dense settings (density, allocation, fade, outside) govern. +export const LABEL_LAYERS = new Set([ + 'satellites', + 'ais-live-vessels', + 'rocket-launches', + 'cctv', + 'transit', + 'bikeshare', + 'radio', + 'local-adsb', + 'earthquakes', + 'local-firms', + 'fire-perimeters', + 'weather-cyclones', + 'air-quality', + 'alpr-cameras', + 'drone-airspace', + 'military-installations', + 'telegeography-submarine-cables', + 'osm-places', + 's2-ghostmaps', + 'directions', +]); + +// Which of the layers that are on each tab acts on. +export const TAB_AFFECTS = { + labels: (on) => [...on].filter((id) => LABEL_LAYERS.has(id)), + aircraft: (on) => [...on].filter((id) => AIRCRAFT.includes(id)), +}; + +export const LAYER_TABS = [ + // Labels and cards the world overlay draws for the label layers. + { id: 'labels', label: 'Labels', icon: 'label', when: (on) => TAB_AFFECTS.labels(on).length > 0 }, + { id: 'aircraft', label: '3D aircraft', icon: 'flight', when: (on) => TAB_AFFECTS.aircraft(on).length > 0 }, +]; + +/** Ids of the layers that are on; Context refreshes it. */ +export const enabledLayerIds = ref(new Set()); + +export function setEnabledLayers(ids) { + const next = new Set(ids); + const prev = enabledLayerIds.value; + if (next.size === prev.size && [...next].every((id) => prev.has(id))) return; + enabledLayerIds.value = next; +} + +/** Whether Context is mounted and can host tab content. */ +export const contextReady = ref(false); + +/** The tabs available now. */ +export const availableTabs = computed(() => + contextReady.value ? LAYER_TABS.filter((tab) => tab.when(enabledLayerIds.value)) : [], +); + +export const hasTab = (id) => availableTabs.value.some((tab) => tab.id === id); + +/** The tab Context shows: 'view' (the card) or a layer tab's id. */ +export const activeTab = ref('view'); + +// Each tab's content lands in an element made here, before any panel mounts, +// so a panel that mounts ahead of Context still has a real target; Context +// places these elements in its tab panes when it mounts. +const targets = new Map(); +export function tabTarget(id) { + if (!targets.has(id) && globalThis.document) { + const el = document.createElement('div'); + el.className = 'context-tab-body'; + el.dataset.tab = id; + targets.set(id, el); + } + return targets.get(id) ?? 'body'; +} diff --git a/src/ui/contextRadius.js b/src/ui/contextRadius.js new file mode 100644 index 0000000000..5b858dfe0a --- /dev/null +++ b/src/ui/contextRadius.js @@ -0,0 +1,43 @@ +import { ref } from 'vue'; + +// How far out Context looks for what is "nearby": one distance for every +// nearby block (flights, vessels, hazards, alerts, other loaded items). The +// control in the Context panel steps through a few distances; the choice is +// kept for the next visit. +const KEY = 'gev.contextRadiusKm'; + +/** The distances the control steps through, in km. */ +export const CONTEXT_RADIUS_STEPS = Object.freeze([25, 50, 100, 250, 500, 1000, 2500]); +export const DEFAULT_CONTEXT_RADIUS_KM = 250; + +/** The step closest to a distance; the default for anything unusable. */ +export function nearestRadiusStep(km) { + const value = Number(km); + if (!Number.isFinite(value) || value <= 0) return DEFAULT_CONTEXT_RADIUS_KM; + return CONTEXT_RADIUS_STEPS.reduce((best, step) => + Math.abs(step - value) < Math.abs(best - value) ? step : best, + ); +} + +function read() { + try { + const saved = globalThis.localStorage?.getItem(KEY); + return saved === null || saved === undefined + ? DEFAULT_CONTEXT_RADIUS_KM + : nearestRadiusStep(saved); + } catch { + return DEFAULT_CONTEXT_RADIUS_KM; + } +} + +/** The radius every nearby block uses, in km. */ +export const contextRadiusKm = ref(read()); + +export function setContextRadiusKm(km) { + contextRadiusKm.value = nearestRadiusStep(km); + try { + globalThis.localStorage?.setItem(KEY, String(contextRadiusKm.value)); + } catch { + // Without storage the choice lasts for this visit. + } +} diff --git a/src/ui/contextSearch.js b/src/ui/contextSearch.js new file mode 100644 index 0000000000..7988a25858 --- /dev/null +++ b/src/ui/contextSearch.js @@ -0,0 +1,24 @@ +import { computed, ref } from 'vue'; + +// The Context panel's own search: one field in its header that narrows what +// the panel is showing (the selected item's details, and every list of what +// is nearby or in view) to what holds the typed text. + +/** Whether the search field is showing. */ +export const contextSearchOpen = ref(false); +/** The text as typed. */ +export const contextSearchText = ref(''); +/** The text to match against: trimmed, lower case, '' when not searching. */ +export const contextNeedle = computed(() => (contextSearchOpen.value ? contextSearchText.value.trim().toLowerCase() : '')); + +/** Whether any of the given strings holds the searched text (true when not searching). */ +export function matchesContextSearch(...parts) { + const needle = contextNeedle.value; + if (!needle) return true; + return parts.some((part) => part !== null && part !== undefined && String(part).toLowerCase().includes(needle)); +} + +export function closeContextSearch() { + contextSearchOpen.value = false; + contextSearchText.value = ''; +} diff --git a/src/ui/entityContextBridge.js b/src/ui/entityContextBridge.js new file mode 100644 index 0000000000..f62903ff9c --- /dev/null +++ b/src/ui/entityContextBridge.js @@ -0,0 +1,215 @@ +import * as Cesium from 'cesium'; +import { pickWorldFromScreen } from '../annotations/annotationResolver.js'; +import { resolvePickedContext } from '../data/pickedContext.js'; +import { isPointerFree } from '../data/inputOwnership.js'; +import { useCockpitStore } from './stores/cockpit.js'; +import { useEntityCardStore } from './stores/entityCard.js'; +import { useOmnibarStore } from './stores/omnibar.js'; +import { useVoiceStore } from './stores/voice.js'; + +/** Camera distance (m) that frames an item of each kind. */ +const FRAME_RANGE = Object.freeze({ + aircraft: 30_000, + vessel: 9_000, + satellite: 2_500_000, + earthquake: 120_000, + storm: 1_500_000, + fire: 20_000, + 'fire perimeter': 40_000, +}); +const DEFAULT_RANGE = 8_000; +/** Items the voice runtime can keep the camera on. */ +const FOLLOWABLE = new Set(['flights', 'military', 'ais-live-vessels', 'satellites']); + +/** + * Connects the Context panel's entity card to the globe: a click on anything a + * layer can identify opens its card, and the card's actions fly to it, follow + * it or ask GEV about it. Layers keep their own click behaviour; this listens + * alongside them. + * @param {object} options + * @param {object} options.viewer Cesium viewer. + * @param {() => object} options.getDataManager Layer lifecycle. + * @param {object} options.pinia + * @returns {() => void} disconnects + */ +export function installEntityContext({ viewer, getDataManager, pinia }) { + const store = useEntityCardStore(pinia); + const omnibar = useOmnibarStore(pinia); + const voice = useVoiceStore(pinia); + const cockpitStore = useCockpitStore(pinia); + const doc = globalThis.document; + + function openPanel() { + const button = doc?.querySelector( + '.ui-rail--right .ui-rail__item[data-rail-item="global-context-panel"]', + ); + if (button && button.getAttribute('aria-pressed') !== 'true') button.click(); + } + + function flyTo(card) { + if (!Number.isFinite(card?.lat) || !Number.isFinite(card?.lon)) return; + const height = Number.isFinite(card.altitudeM) ? card.altitudeM : 0; + const range = FRAME_RANGE[card.kind] ?? DEFAULT_RANGE; + viewer.camera.flyToBoundingSphere( + new Cesium.BoundingSphere( + Cesium.Cartesian3.fromDegrees(card.lon, card.lat, Math.max(0, height)), + 1, + ), + { + offset: new Cesium.HeadingPitchRange( + viewer.camera.heading, + Cesium.Math.toRadians(card.kind === 'satellite' ? -90 : -45), + range, + ), + duration: 2, + }, + ); + } + + function follow(card) { + const run = omnibar.runner; + if (!run || !FOLLOWABLE.has(card.layerId)) return flyTo(card); + void run('track_entity', { + query: card.identity.id || card.title, + layerId: card.layerId, + }); + } + + // Aircraft can be flown from, and a satellite ridden in the orbital view: + // track the craft, then enter Cockpit on it. + const COCKPIT_LAYERS = new Set(['flights', 'military', 'local-adsb', 'satellites']); + async function cockpit(card) { + const run = omnibar.runner; + if (!run || !COCKPIT_LAYERS.has(card.layerId)) return; + await run('track_entity', { query: card.identity.id || card.title, layerId: card.layerId }); + if (card.layerId !== 'satellites') { + await run('control_cockpit', { action: 'enter' }); + return; + } + // A satellite is ridden through the app's own Cockpit entry, which offers + // the orbital view once the satellite is tracked. Wait for it to say so; + // if it never does (a class that cannot be ridden), nothing is entered. + for (let tries = 0; tries < 40; tries++) { + const presence = cockpitStore.presence; + if (presence?.entryAvailable && presence.entryKind === 'satellite') { + doc?.getElementById('cockpit-entry')?.click(); + return; + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + + function askText(prompt) { + voice.controls?.emit('chat-restore'); + voice.controls?.emit('chat-prompt', prompt); + voice.controls?.emit('chat-submit'); + } + + function ask(card) { + const where = + Number.isFinite(card.lat) && Number.isFinite(card.lon) + ? ` at ${card.lat.toFixed(3)}, ${card.lon.toFixed(3)}` + : ''; + const prompt = `Tell me about the ${card.kind} ${card.title} (${card.layerName})${where}, and what is around it.`; + voice.controls?.emit('chat-restore'); + voice.controls?.emit('chat-prompt', prompt); + voice.controls?.emit('chat-submit'); + } + + store.connect({ + dataManager: getDataManager, + openPanel, + flyTo, + follow, + ask, + askText, + cockpit, + canCockpit: (card) => Boolean(omnibar.runner) && COCKPIT_LAYERS.has(card?.layerId), + canFollow: (card) => FOLLOWABLE.has(card?.layerId), + // Where the camera is, so a search prefers what is close by. + here: () => { + const at = viewer.camera.positionCartographic; + return at + ? { + lat: Cesium.Math.toDegrees(at.latitude), + lon: Cesium.Math.toDegrees(at.longitude), + } + : null; + }, + }); + + // What the camera shows, for the Context panel to describe when nothing is + // picked: the ground under the middle of the screen, the view's bounds and + // the height. Read when the camera settles, not every frame. + const readView = () => { + const camera = viewer.camera; + const height = camera.positionCartographic?.height ?? 0; + const middle = pickWorldFromScreen(viewer, 0.5, 0.5); + const center = middle + ? { lat: middle.lat, lon: middle.lon } + : { + lat: Cesium.Math.toDegrees(camera.positionCartographic.latitude), + lon: Cesium.Math.toDegrees(camera.positionCartographic.longitude), + }; + const r = camera.computeViewRectangle?.(viewer.scene.globe.ellipsoid); + const rect = r + ? { + west: Cesium.Math.toDegrees(r.west), + south: Cesium.Math.toDegrees(r.south), + east: Cesium.Math.toDegrees(r.east), + north: Cesium.Math.toDegrees(r.north), + } + : { west: -180, south: -90, east: 180, north: 90 }; + store.setView({ center, rect, heightM: height }); + }; + const removeMoveEnd = viewer.camera.moveEnd.addEventListener(readView); + // A camera that keeps moving (following an aircraft, a long fly-to) never + // settles, so also read it on large changes, at most once a second. + let lastRead = 0; + const removeChanged = viewer.camera.changed.addEventListener(() => { + const now = performance.now(); + if (now - lastRead < 1000) return; + lastRead = now; + readView(); + }); + setTimeout(readView, 0); + + const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); + handler.setInputAction(({ position }) => { + // A tool that owns the pointer (draw, measure) keeps its clicks. + if (!isPointerFree()) return; + let picked = null; + try { + picked = viewer.scene.pick(position); + } catch { + picked = null; + } + const identity = resolvePickedContext(picked, { + dataManager: getDataManager(), + }); + // A click on open ground or sea selects nothing and leaves the card as it is. + if (identity) store.select(identity); + }, Cesium.ScreenSpaceEventType.LEFT_CLICK); + + // Layers that select through the context store (GeoJSON sites, fires, + // installations) announce it; their selection opens the card too. + const onSelected = ({ detail: record }) => { + if (!record?.layerId) return; + store.select({ + layerId: record.layerId, + id: record.id, + label: record.label || record.properties?.name, + lat: record.latitude, + lon: record.longitude, + }); + }; + globalThis.addEventListener?.('gev:entity-selected', onSelected); + + return () => { + handler.destroy(); + removeMoveEnd(); + removeChanged(); + globalThis.removeEventListener?.('gev:entity-selected', onSelected); + store.connect(null); + }; +} diff --git a/src/ui/spotConditions.js b/src/ui/spotConditions.js new file mode 100644 index 0000000000..9d723562ec --- /dev/null +++ b/src/ui/spotConditions.js @@ -0,0 +1,172 @@ +import { distanceKm } from '../data/entityContext.js'; +import { createUsgsEarthquakeSource } from '../layers/earthquakes/source.js'; +import { createCycloneSource } from '../layers/cyclones/source.js'; +import { createWfigsPerimeterSource } from '../layers/perimeters/source.js'; +import { createFirmsSource } from '../layers/firms/source.js'; + +// What is going on around one spot on the map: the weather there now and the +// local headlines (the app's regional brief, the same one Cockpit shows), and +// the natural hazards near it from the feeds the hazard layers read +// (earthquakes, tropical storms, wildfire perimeters, satellite fire hits). +// The feeds are global snapshots, so each is fetched once and kept for a few +// minutes whichever spot asks; the brief is kept per spot. + +const BRIEF_TTL_MS = 10 * 60_000; +const FEED_TTL_MS = 5 * 60_000; + +const briefs = new Map(); +/** The regional brief for a spot: `{weather, articles, place, newsSource}`. */ +export function regionalBrief(lat, lon) { + const key = `${lat.toFixed(2)},${lon.toFixed(2)}`; + const kept = briefs.get(key); + if (kept && Date.now() - kept.at < BRIEF_TTL_MS) return kept.promise; + const query = `latitude=${lat.toFixed(5)}&longitude=${lon.toFixed(5)}`; + const promise = fetch(`/api/regional-brief?${query}`) + .then((response) => (response.ok ? response.json() : null)) + .catch(() => null); + briefs.set(key, { at: Date.now(), promise }); + if (briefs.size > 40) briefs.delete(briefs.keys().next().value); + return promise; +} + +const feeds = new Map(); +function snapshot(name, load) { + const kept = feeds.get(name); + if (kept && Date.now() - kept.at < FEED_TTL_MS) return kept.promise; + const promise = load().catch(() => null); + feeds.set(name, { at: Date.now(), promise }); + return promise; +} +const quakes = () => snapshot('quakes', () => createUsgsEarthquakeSource().getSnapshot()); +const storms = () => snapshot('storms', () => createCycloneSource().getSnapshot()); +const perimeters = () => snapshot('perimeters', () => createWfigsPerimeterSource().getSnapshot()); +const fires = () => snapshot('fires', () => createFirmsSource().getSnapshot()); + +const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; +/** The compass point from one spot to another, like "NE". */ +export function compassPoint(from, to) { + const rad = Math.PI / 180; + const y = Math.sin((to.lon - from.lon) * rad) * Math.cos(to.lat * rad); + const x = + Math.cos(from.lat * rad) * Math.sin(to.lat * rad) - + Math.sin(from.lat * rad) * Math.cos(to.lat * rad) * Math.cos((to.lon - from.lon) * rad); + const deg = (Math.atan2(y, x) / rad + 360) % 360; + return compassName(deg); +} + +/** The compass point for a bearing in degrees. */ +export function compassName(deg) { + return COMPASS[Math.round((((deg % 360) + 360) % 360) / 45) % 8]; +} + +// The middle of a perimeter's first ring, close enough for "how far". +function perimeterMiddle(row) { + const ring = row?.polygons?.[0]?.[0]; + if (!Array.isArray(ring) || !ring.length) return null; + let lat = 0; + let lon = 0; + for (const [x, y] of ring) { + lon += x; + lat += y; + } + return { lat: lat / ring.length, lon: lon / ring.length }; +} + +/** + * Hazards within a radius of a spot, nearest first within each kind: + * `[{kind, icon, title, detail, distanceKm, at}]`. Every kind uses the same + * radius, the one Context's radius control sets. + */ +export async function hazardsNear(lat, lon, radiusKm = 250) { + const here = { lat, lon }; + const [quakeRows, stormSnap, perimeterRows, fireSnap] = await Promise.all([ + quakes(), + storms(), + perimeters(), + fires(), + ]); + const found = []; + const add = (row) => { + row.distanceKm = distanceKm(here, row.at); + row.direction = compassPoint(here, row.at); + found.push(row); + }; + + for (const quake of Array.isArray(quakeRows) ? quakeRows : []) { + const at = { lat: quake.lat, lon: quake.lon }; + if (!(distanceKm(here, at) <= radiusKm)) continue; + add({ + kind: 'quake', + icon: 'earthquake', + title: Number.isFinite(Number.parseFloat(quake.mag)) ? `M${Number(quake.mag).toFixed(1)} earthquake` : 'Earthquake', + detail: quake.place || '', + time: quake.time, + at, + }); + } + for (const storm of stormSnap?.storms || []) { + const at = { lat: storm.position?.latitude, lon: storm.position?.longitude }; + if (!(distanceKm(here, at) <= radiusKm)) continue; + add({ + kind: 'storm', + icon: 'cyclone', + title: [storm.classification, storm.name].filter(Boolean).join(' '), + detail: storm.windKt ? `${storm.windKt} kt winds` : '', + time: Date.parse(storm.positionAt) || null, + at, + }); + } + for (const fire of Array.isArray(perimeterRows) ? perimeterRows : []) { + const at = perimeterMiddle(fire); + if (!at || !(distanceKm(here, at) <= radiusKm)) continue; + const acres = Number(fire.acres); + add({ + kind: 'wildfire', + icon: 'local_fire_department', + title: fire.name || 'Wildfire', + detail: [ + Number.isFinite(acres) ? `${Math.round(acres).toLocaleString()} acres` : '', + Number.isFinite(fire.containedPct) ? `${fire.containedPct}% contained` : '', + fire.category === 'RX' ? 'prescribed burn' : '', + ] + .filter(Boolean) + .join(' · '), + time: fire.updatedTime || fire.discoveredTime || null, + at, + }); + } + // Satellite fire hits are many small points: count the close ones. + const hits = (Array.isArray(fireSnap?.fires) ? fireSnap.fires : []) + .map((fire) => ({ lat: Number(fire.lat ?? fire.latitude), lon: Number(fire.lon ?? fire.longitude) })) + .filter((at) => distanceKm(here, at) <= radiusKm); + if (hits.length) { + const nearest = hits.reduce((a, b) => (distanceKm(here, a) <= distanceKm(here, b) ? a : b)); + add({ + kind: 'hotspots', + icon: 'local_fire_department', + title: `${hits.length} satellite fire ${hits.length === 1 ? 'hit' : 'hits'}`, + detail: 'last day', + time: null, + at: nearest, + }); + } + const order = { storm: 0, wildfire: 1, hotspots: 2, quake: 3 }; + return found.sort((a, b) => order[a.kind] - order[b.kind] || a.distanceKm - b.distanceKm); +} + +/** Title-case copy for a WMO weather code, and the icon that goes with it. */ +export function weatherLook(code) { + const value = Number(code); + if (!Number.isFinite(value)) return { label: 'Conditions unknown', icon: 'partly_cloudy_day' }; + if (value === 0) return { label: 'Clear', icon: 'sunny' }; + if (value <= 2) return { label: 'Partly cloudy', icon: 'partly_cloudy_day' }; + if (value === 3) return { label: 'Overcast', icon: 'cloud' }; + if (value === 45 || value === 48) return { label: 'Fog', icon: 'foggy' }; + if (value >= 51 && value <= 57) return { label: 'Drizzle', icon: 'rainy' }; + if (value >= 61 && value <= 67) return { label: 'Rain', icon: 'rainy' }; + if (value >= 71 && value <= 77) return { label: 'Snow', icon: 'weather_snowy' }; + if (value >= 80 && value <= 82) return { label: 'Rain showers', icon: 'rainy' }; + if (value >= 85 && value <= 86) return { label: 'Snow showers', icon: 'weather_snowy' }; + if (value >= 95) return { label: 'Thunderstorm', icon: 'thunderstorm' }; + return { label: 'Mixed conditions', icon: 'partly_cloudy_day' }; +} diff --git a/src/ui/stores/entityCard.js b/src/ui/stores/entityCard.js new file mode 100644 index 0000000000..ffee353e3e --- /dev/null +++ b/src/ui/stores/entityCard.js @@ -0,0 +1,258 @@ +import { defineStore } from 'pinia'; +import { markRaw, ref, shallowRef } from 'vue'; +import { sourceLabel } from '../layerNames.js'; +import { + alertsNear, + describeEntity, + layerBreakdown, + nearbyByKind, + layerMatches, + searchEntities, + viewSummary, +} from '../../data/entityContext.js'; + +/** How often an open card re-reads its item, so moving things stay current. */ +const REFRESH_MS = 2000; + +/** + * The thing the Context panel is about: whatever was last clicked on the + * globe, chosen in the omnibar, or picked from the card's nearby list. + * + * The shell connects `{dataManager(), flyTo(card), follow(card), openPanel()}`; + * until then nothing can be selected. + */ +export const useEntityCardStore = defineStore('gev-entity-card', () => { + const shell = shallowRef(null); + /** The card model from `describeEntity`, or null. */ + const card = shallowRef(null); + /** True once a moving item has dropped out of its feed. */ + const lost = ref(false); + /** Bumped on each refresh, so ages shown on the card tick. */ + const tick = ref(0); + /** + * What the camera shows, for the panel to describe when nothing is picked: + * `{center: {lat, lon}, rect: {west, south, east, north}, heightM}`. + */ + const view = shallowRef(null); + let timer = null; + + function connect(next) { + shell.value = next ? markRaw(next) : null; + if (!next) clear(); + } + + const dataManager = () => shell.value?.dataManager?.() || null; + + function read(identity) { + const next = describeEntity(dataManager(), identity); + if (!next) return false; + card.value = markRaw(next); + lost.value = false; + tick.value++; + return true; + } + + /** + * Where a card's data comes from, for its footer: the item's own source, + * else its layer's live feed (the name the layer list shows). + */ + function sourceOf(current) { + if (!current) return ''; + if (current.source) return current.source; + const dm = shell.value?.dataManager?.(); + const layer = dm?.getAll?.().find((row) => row.id === current.layerId); + const stats = layer?.stats || {}; + const raw = stats.sourceVerbatim === true && stats.source ? stats.source : sourceLabel(stats.source || layer?.source); + return raw || ''; + } + const canCockpit = () => Boolean(shell.value?.canCockpit?.(card.value)); + function cockpit() { + if (card.value) shell.value?.cockpit?.(card.value); + } + + function setView(next) { + view.value = next ? markRaw(next) : null; + } + /** Ask a flight's layer for its route, so the card can draw it. */ + function requestRoute(identity) { + if (!identity?.id || !['flights'].includes(identity.layerId)) return; + const layer = shell.value?.dataManager?.()?.layers?.get?.(identity.layerId); + try { + layer?.module?.requestRoute?.(identity.id); + } catch { + // No route then; the card shows without one. + } + } + + /** A layer's items in an area that pass a test (see layerMatches). */ + function matchesIn(layerId, area) { + const dm = shell.value?.dataManager?.(); + if (!dm || !dm.isEnabled?.(layerId)) return null; + return layerMatches(dm, layerId, area); + } + + /** What the loaded layers have in the current view, by layer. */ + function inView(options) { + const dm = shell.value?.dataManager?.(); + if (!dm || !view.value) return []; + return viewSummary(dm, view.value.rect, view.value.center, options); + } + /** Ask GEV about the view, with what is in it. */ + function askAboutView(summary) { + const where = view.value; + if (!where) return; + const counts = summary.map((group) => `${group.count} ${group.layerName}`).join(', '); + shell.value?.askText?.( + `What am I looking at? The view is centred on ${where.center.lat.toFixed(4)}, ${where.center.lon.toFixed(4)} from about ${Math.round(where.heightM)} m up${counts ? `, showing ${counts}` : ''}. What is here and what stands out?`, + ); + } + + /** What is loaded around a ground point, as the card's nearby lists. */ + /** The layers that are on, as the data manager lists them. */ + function liveLayers() { + const dm = shell.value?.dataManager?.(); + try { + return (dm?.getAll?.() || []).filter((row) => row.enabled); + } catch { + return []; + } + } + + /** What a layer's items are made of (see layerBreakdown). */ + function breakdown(layerId, options) { + return layerBreakdown(shell.value?.dataManager?.(), layerId, options); + } + + /** Loaded records near a point that broadcast a warning. */ + function alertsAt(lat, lon, options) { + return alertsNear(shell.value?.dataManager?.(), { lat, lon }, options); + } + + /** + * What the loaded layers have within a radius of a point, grouped the way + * every card lists it: `{flights, vessels, other}` (see nearbyByKind). + */ + function nearbyGroups(lat, lon, options) { + return nearbyByKind(shell.value?.dataManager?.(), { lat, lon }, options); + } + + /** Whether a card's layer is known to the layer manager and switched off. */ + function layerOff(layerId) { + const dm = dataManager(); + const id = layerId; + if (!dm?.isEnabled || !dm.layers?.has?.(id)) return false; + return dm.isEnabled(id) === false; + } + + function refresh() { + const current = card.value; + if (!current) return; + // A card does not outlive its layer: turning the layer off (or clearing + // all layers) closes it and lets go of the camera. + if (layerOff(current.layerId)) return clear(); + const next = describeEntity(dataManager(), current.identity); + // Keep showing the last reading when the item drops out of its feed. + if (!next || next.key !== current.key || next.basis !== 'record') { + lost.value = current.basis === 'record'; + tick.value++; + return; + } + card.value = markRaw(next); + lost.value = false; + tick.value++; + } + + /** + * Show an item on the card. + * @param {object} identity `{layerId, id, label, lat, lon, record?}` + * @param {object} [options] + * @param {boolean} [options.fly] Also fly the camera to it. + * @returns {boolean} Whether a card could be made. + */ + /** Things that move are followed as soon as they are picked. */ + const AUTO_FOLLOW = new Set(['flights', 'military', 'local-adsb', 'satellites', 'ais-live-vessels']); + /** The key of the item the camera is following, if any. */ + const following = ref(null); + + /** + * @param {object} identity + * @param {{fly?: boolean, follow?: boolean}} [options] `follow: false` + * keeps the camera where it is even for an aircraft. + */ + function select(identity, { fly = false, follow: autoFollow = true } = {}) { + if (!read(identity)) return false; + clearInterval(timer); + timer = setInterval(refresh, REFRESH_MS); + shell.value?.openPanel?.(); + const current = card.value; + const followNow = autoFollow && AUTO_FOLLOW.has(current?.layerId) && shell.value?.canFollow?.(current); + if (followNow) { + // Tracking can announce the craft again; following what is already + // followed would loop, so it only starts once per item. + if (following.value !== current.key) { + following.value = current.key; + shell.value?.follow?.(current); + } + } else { + if (following.value && following.value !== current?.key) following.value = null; + if (fly) shell.value?.flyTo?.(current); + } + requestRoute(current?.identity); + return true; + } + + function clear() { + following.value = null; + clearInterval(timer); + timer = null; + card.value = null; + lost.value = false; + } + + const flyTo = () => card.value && shell.value?.flyTo?.(card.value); + const follow = () => { + if (!card.value) return; + following.value = card.value.key; + shell.value?.follow?.(card.value); + }; + const isFollowing = () => Boolean(card.value && following.value === card.value.key); + const ask = () => card.value && shell.value?.ask?.(card.value); + const canFollow = () => Boolean(shell.value?.canFollow?.(card.value)); + /** Loaded items whose name or id matches typed text, for the omnibar. */ + const search = (query, options) => + shell.value + ? searchEntities(dataManager(), query, { + near: shell.value.here?.() || null, + ...options, + }) + : []; + + return { + card, + lost, + tick, + connect, + select, + clear, + refresh, + flyTo, + follow, + ask, + canFollow, + isFollowing, + following, + search, + nearbyGroups, + alertsAt, + liveLayers, + breakdown, + view, + setView, + matchesIn, + sourceOf, + canCockpit, + cockpit, + inView, + askAboutView, + }; +}); diff --git a/src/ui/styles/context-dock.css b/src/ui/styles/context-dock.css new file mode 100644 index 0000000000..7e07f08e2a --- /dev/null +++ b/src/ui/styles/context-dock.css @@ -0,0 +1,185 @@ +/* ── Context expanded ─────────────────────────────────────────────────── + Expanded, Context becomes a full-height column over the right edge of the + screen. The globe and HUD stay where they are, under it. */ +:root { + --context-dock-width: clamp(360px, 30vw, 460px); +} + +/* The column: edge to edge, top to bottom, no rail beside it. */ +body.context-docked #right-context-rail { + z-index: 170; + top: 0 !important; + right: 0 !important; + bottom: 0 !important; + width: var(--context-dock-width) !important; + max-height: none !important; + height: 100vh !important; +} + +body.context-docked #right-context-rail > .gev-panel-rail { + display: none; +} + +body.context-docked #right-context-rail > :not(#global-context-panel):not(.gev-panel-rail) { + display: none !important; +} + +body.context-docked #right-context-rail > #global-context-panel { + flex: 1 1 auto !important; + width: 100% !important; + height: 100% !important; + max-height: none !important; +} + +body.context-docked #global-context-panel .global-context-panel-inner { + height: 100%; + padding: 22px 24px 16px; + background: rgba(10, 11, 16, 0.94); + border: 0; + border-left: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 0; + box-shadow: -18px 0 40px rgba(0, 0, 0, 0.35); +} + +body.context-docked #global-context-panel .panel-glow { + display: none; +} + +/* The expand button sits beside the collapse button in the header. */ +.context-dock-btn { + display: grid; + flex: none; + place-items: center; + width: 28px; + height: 28px; + margin-inline-end: 6px; + padding: 0; + color: var(--text-secondary); + background: transparent; + border: 1px solid var(--glass-border); + border-radius: var(--btn-radius); + cursor: pointer; +} + +.context-dock-btn .material-symbols-outlined { + font-size: 16px; +} + +.context-dock-btn:hover, +.context-dock-btn:focus-visible, +.context-dock-btn[aria-pressed='true'] { + color: var(--accent); + border-color: var(--accent-dim); + background: var(--accent-dim); +} + +/* Phones keep their sheets; the dock is a desktop layout. */ +body.mobile-shell .context-dock-btn { + display: none; +} + +/* Context's own search field, under the header: narrows what the panel shows. + Sized and framed like the tab bar beneath it. */ +.context-search { + position: sticky; + top: 0; + z-index: 2; + display: flex; + flex: none; + box-sizing: border-box; + align-items: center; + gap: 8px; + min-height: 34px; + margin: 0 0 0.5rem; + padding: 0 6px 0 10px; + color: rgba(199, 214, 222, 0.65); + background: rgba(16, 22, 28, 0.94); + border: 1px solid rgba(54, 220, 255, 0.35); + border-radius: 10px; + backdrop-filter: blur(8px); +} + +.context-search:focus-within { + color: #7af0ff; + border-color: rgba(54, 220, 255, 0.7); + box-shadow: 0 0 0 3px rgba(54, 220, 255, 0.1); +} + +.context-search .material-symbols-outlined { + font-size: 17px; +} + +.context-search__input::placeholder { + color: rgba(199, 214, 222, 0.45); +} + +.context-search__input { + flex: 1; + min-width: 0; + height: 100%; + padding: 0; + color: var(--text-primary, #e8eaed); + font: inherit; + font-size: 0.74rem; + line-height: 32px; + background: transparent; + border: 0; + outline: 0; +} + +.context-search__input::-webkit-search-cancel-button { + display: none; +} + +.context-search__clear { + display: grid; + flex: none; + place-items: center; + width: 24px; + height: 24px; + padding: 0; + color: rgba(199, 214, 222, 0.65); + background: transparent; + border: 0; + border-radius: 50%; + cursor: pointer; +} + +.context-search__clear:hover, +.context-search__clear:focus-visible { + color: var(--accent); +} + +.entity-card__no-match { + margin: 0 0 0.7rem; + color: rgba(199, 214, 222, 0.6); + font-size: 0.66rem; +} + +.context-search__input:focus, +.context-search__input:focus-visible { + outline: 0; + box-shadow: none; +} + +/* While a search is typed, what cannot match steps aside so the matches lead: + the weather, the view's own figures, the route and altitude graph, and the + layer switches. The radius stays: it sets how far the search looks. */ +.context-searching :is( + .spot-conditions__weather, + .spot-conditions__loading, + .spot-conditions__source, + .view-context__facts, + .view-context__live, + .view-context__total, + .view-context__actions, + .view-context__towns:has(.view-context__chip--layer), + .altitude-graph, + .entity-card__route, + .entity-card__route-stats, + .entity-card__route-places, + .entity-card__route-note, + .entity-card__links + ) { + display: none; +} diff --git a/src/ui/styles/context-tabs.css b/src/ui/styles/context-tabs.css new file mode 100644 index 0000000000..1dd7c23e49 --- /dev/null +++ b/src/ui/styles/context-tabs.css @@ -0,0 +1,125 @@ +/* ── Context layer tabs ───────────────────────────────────────────────── + Settings for the layers that are on, as tabs beside the card. */ +.context-tabs { + display: flex; + flex: none; + min-height: 34px; + box-sizing: border-box; + gap: 4px; + margin: 0 0 0.7rem; + padding: 3px; + overflow-x: auto; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 10px; + scrollbar-width: none; +} + +.context-tabs::-webkit-scrollbar { + display: none; +} + +.context-tabs__tab { + display: inline-flex; + flex: none; + min-height: 26px; + align-items: center; + gap: 0.3rem; + max-width: 9.5rem; + padding: 0.3rem 0.55rem; + color: rgba(199, 214, 222, 0.65); + font-family: var(--font-mono); + font-size: 0.56rem; + letter-spacing: 0.08rem; + text-transform: uppercase; + background: none; + border: 1px solid transparent; + border-radius: 7px; + cursor: pointer; +} + +.context-tabs__tab .material-symbols-outlined { + font-size: 14px; +} + +.context-tabs__label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.context-tabs__tab:hover { + color: #fff; + background: rgba(255, 255, 255, 0.05); +} + +.context-tabs__tab.active { + color: #7af0ff; + background: rgba(54, 220, 255, 0.12); + border-color: rgba(54, 220, 255, 0.35); +} + +.context-tab-pane[hidden] { + display: none !important; +} + +/* Controls moved in from Visual show their rows openly here. */ +.context-tab-pane .pp-toggle-group { + margin: 0; +} + +/* Two even tabs: Inspector and Properties. */ +.context-tabs__tab { + flex: 1 1 0; + justify-content: center; + max-width: none; +} + +.context-props[hidden] { + display: none !important; +} + +.context-props__section + .context-props__section { + margin-top: 0.9rem; +} + +.context-props__heading { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0 0 0.45rem; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.14rem; + text-transform: uppercase; +} + +.context-props__heading .material-symbols-outlined { + font-size: 14px; +} + +.context-props__layers { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.75rem; + margin: -0.15rem 0 0.5rem; + padding: 0; + list-style: none; +} + +.context-props__layers li { + display: inline-flex; + align-items: center; + gap: 0.35rem; + color: rgba(214, 228, 236, 0.8); + font-size: 0.66rem; +} + +.context-props__layers i { + width: 7px; + height: 7px; + border-radius: 50%; + box-shadow: 0 0 6px currentColor; +} diff --git a/src/ui/styles/entity-card.css b/src/ui/styles/entity-card.css new file mode 100644 index 0000000000..bea47e724a --- /dev/null +++ b/src/ui/styles/entity-card.css @@ -0,0 +1,1752 @@ +/* ── Context panel: the card for one thing on the map ────────────────── + Sits at the top of the Context panel, above the mode switch. Glass like + the omnibar sheet; the title in the mono face the HUD uses. */ +.entity-card { + margin: 0 0 0.75rem; + padding: 0.7rem 0.75rem 0.6rem; + color: rgba(225, 236, 242, 0.92); + background: rgba(40, 44, 52, 0.55); + border: 1px solid rgba(255, 255, 255, 0.09); + border-radius: 10px; +} + +.entity-card__head { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.entity-card__icon { + display: grid; + flex: none; + place-items: center; + width: 1.9rem; + height: 1.9rem; + color: #36dcff; + font-size: 1.1rem; + background: rgba(29, 69, 81, 0.35); + border: 1px solid rgba(48, 194, 224, 0.35); + border-radius: 7px; +} + +.entity-card__kind { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + font-size: 0.62rem; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.entity-card__kind > span:first-child { + color: rgba(225, 236, 242, 0.85); +} + +.entity-card__layer { + overflow: hidden; + color: rgba(199, 214, 222, 0.5); + text-overflow: ellipsis; + white-space: nowrap; +} + +.entity-card__status { + flex: none; + padding: 0.12rem 0.45rem; + font-size: 0.58rem; + white-space: nowrap; + border: 1px solid currentColor; + border-radius: 999px; +} + +.entity-card__status--live { + color: #5ee6a0; +} + +.entity-card__status--live::before { + display: inline-block; + width: 5px; + height: 5px; + margin-right: 0.3rem; + vertical-align: middle; + background: currentColor; + border-radius: 50%; + content: ''; + animation: entity-card-pulse 1.6s ease-in-out infinite; +} + +.entity-card__status--aged { + color: rgba(199, 214, 222, 0.6); +} + +.entity-card__status--lost { + color: #ff9f43; +} + +.entity-card__close { + display: grid; + flex: none; + place-items: center; + width: 1.5rem; + height: 1.5rem; + padding: 0; + color: rgba(199, 214, 222, 0.6); + background: none; + border: 0; + border-radius: 6px; + cursor: pointer; +} + +.entity-card__close:hover, +.entity-card__close:focus-visible { + color: #fff; + background: rgba(255, 255, 255, 0.08); +} + +.entity-card__close .material-symbols-outlined { + font-size: 1rem; +} + +.entity-card__title { + margin: 0.55rem 0 0.1rem; + overflow-wrap: anywhere; + font-family: var(--font-mono); + font-size: 1rem; + font-weight: 600; + letter-spacing: 0.02rem; +} + +.entity-card__where { + margin: 0 0 0.5rem; + color: rgba(199, 214, 222, 0.5); + font-family: var(--font-mono); + font-size: 0.62rem; + white-space: pre; +} + +.entity-card__facts { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.4rem 0.75rem; + margin: 0 0 0.55rem; +} + +.entity-card__fact { + min-width: 0; +} + +.entity-card__fact dt { + color: rgba(199, 214, 222, 0.5); + font-size: 0.56rem; + letter-spacing: 0.05rem; + text-transform: uppercase; +} + +.entity-card__fact dd { + margin: 0.1rem 0 0; + overflow: hidden; + font-family: var(--font-mono); + font-size: 0.72rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.entity-card__empty { + margin: 0 0 0.55rem; + color: rgba(199, 214, 222, 0.55); + font-size: 0.68rem; +} + +.entity-card__links { + display: flex; + flex-wrap: wrap; + gap: 0.35rem; + margin: 0 0 0.55rem; +} + +.entity-card__links a { + padding: 0.15rem 0.5rem; + color: #36dcff; + font-size: 0.64rem; + text-decoration: none; + border: 1px solid rgba(48, 194, 224, 0.35); + border-radius: 999px; +} + +.entity-card__links a:hover, +.entity-card__links a:focus-visible { + background: rgba(48, 194, 224, 0.12); +} + +.entity-card__actions { + display: flex; + gap: 0.35rem; + padding-top: 0.5rem; + border-top: 1px solid rgba(255, 255, 255, 0.07); +} + +.entity-card__action { + display: inline-flex; + flex: 1; + align-items: center; + justify-content: center; + gap: 0.3rem; + height: 1.9rem; + padding: 0 0.4rem; + color: rgba(225, 236, 242, 0.88); + font-size: 0.66rem; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 7px; + cursor: pointer; + transition: + background 140ms ease, + border-color 140ms ease; +} + +.entity-card__action .material-symbols-outlined { + font-size: 0.95rem; +} + +.entity-card__action:hover, +.entity-card__action:focus-visible { + background: rgba(48, 194, 224, 0.12); + border-color: rgba(48, 194, 224, 0.45); +} + +.entity-card__action--ask { + color: #ffb877; +} + +.entity-card__action--ask:hover, +.entity-card__action--ask:focus-visible { + background: rgba(255, 159, 67, 0.12); + border-color: rgba(255, 159, 67, 0.5); +} + +.entity-card__nearby { + margin-top: 0.65rem; +} + +.entity-card__nearby h4 { + margin: 0 0 0.25rem; + color: rgba(199, 214, 222, 0.5); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.entity-card__nearby ul { + margin: 0; + padding: 0; + list-style: none; +} + +.entity-card__nearby button { + display: flex; + align-items: center; + gap: 0.5rem; + width: 100%; + padding: 0.3rem 0.35rem; + color: rgba(225, 236, 242, 0.85); + font-size: 0.68rem; + text-align: left; + background: none; + border: 0; + border-radius: 6px; + cursor: pointer; +} + +.entity-card__nearby button:hover, +.entity-card__nearby button:focus-visible { + background: rgba(255, 255, 255, 0.06); +} + +.entity-card__nearby .material-symbols-outlined { + color: rgba(199, 214, 222, 0.6); + font-size: 0.95rem; +} + +.entity-card__row-title { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.entity-card__row-title small { + color: rgba(199, 214, 222, 0.45); + font-size: 0.56rem; +} + +.entity-card__row-meta { + flex: none; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.6rem; +} + +.entity-card-enter-active, +.entity-card-leave-active { + transition: + opacity 200ms ease, + transform 220ms cubic-bezier(0.22, 1, 0.36, 1); +} + +.entity-card-enter-from, +.entity-card-leave-to { + opacity: 0; + transform: translateY(-6px); +} + +@keyframes entity-card-pulse { + 50% { + opacity: 0.35; + } +} + +@media (prefers-reduced-motion: reduce) { + .entity-card-enter-active, + .entity-card-leave-active { + transition: opacity 120ms ease; + } + + .entity-card-enter-from, + .entity-card-leave-to { + transform: none; + } + + .entity-card__status--live::before { + animation: none; + } +} + +/* Context is one card for whatever is picked: the old Contacts and Space + Missions modes and the Radio strip are out of it. Their markup stays, as + their controls still find their buttons by id, but none of it shows. */ +#global-context-panel + :is( + .global-context-modes, + #context-mode-standby, + #context-flights-view, + #context-missions-view, + #radio-panel + ) { + display: none !important; +} + +/* ── In view: what the panel shows while nothing is picked ───────────── */ +.view-context { + margin: 0 0 0.75rem; + padding: 0.7rem 0.75rem 0.6rem; + color: rgba(225, 236, 242, 0.92); + background: rgba(40, 44, 52, 0.55); + border: 1px solid rgba(255, 255, 255, 0.09); + border-radius: 10px; +} + +.view-context__head { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.view-context__icon { + display: grid; + flex: none; + place-items: center; + width: 1.9rem; + height: 1.9rem; + color: #36dcff; + font-size: 1.1rem; + background: rgba(29, 69, 81, 0.35); + border: 1px solid rgba(48, 194, 224, 0.35); + border-radius: 7px; +} + +.view-context__kind { + display: flex; + flex-direction: column; + font-size: 0.62rem; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.view-context__sub { + color: rgba(199, 214, 222, 0.5); +} + +.view-context__title { + margin: 0.55rem 0 0.1rem; + overflow-wrap: anywhere; + font-family: var(--font-mono); + font-size: 1rem; + font-weight: 600; +} + +.view-context__where { + margin: 0 0 0.55rem; + color: rgba(199, 214, 222, 0.5); + font-family: var(--font-mono); + font-size: 0.62rem; + white-space: pre; +} + +.view-context__total, +.view-context__empty { + margin: 0 0 0.4rem; + color: rgba(199, 214, 222, 0.7); + font-size: 0.68rem; + line-height: 1.45; +} + +.view-context__group + .view-context__group { + margin-top: 0.45rem; +} + +.view-context__group h4 { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0 0 0.15rem; + color: rgba(199, 214, 222, 0.6); + font-size: 0.58rem; + font-weight: 500; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.view-context__group h4 .material-symbols-outlined { + font-size: 0.95rem; +} + +.view-context__count { + margin-inline-start: auto; + color: #36dcff; + font-family: var(--font-mono); +} + +.view-context__group ul { + margin: 0; + padding: 0; + list-style: none; +} + +.view-context__group button { + display: flex; + align-items: center; + gap: 0.5rem; + width: 100%; + padding: 0.28rem 0.35rem 0.28rem 1.75rem; + color: rgba(225, 236, 242, 0.85); + font-size: 0.68rem; + text-align: left; + background: none; + border: 0; + border-radius: 6px; + cursor: pointer; +} + +.view-context__group button:hover, +.view-context__group button:focus-visible { + background: rgba(255, 255, 255, 0.06); +} + +.view-context__row-title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.view-context__row-meta { + flex: none; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.6rem; +} + +.view-context__actions { + display: flex; + margin-top: 0.6rem; + padding-top: 0.5rem; + border-top: 1px solid rgba(255, 255, 255, 0.07); +} + +.context-empty { + display: grid; + justify-items: start; + gap: 6px; + padding: 14px 4px 6px; + color: var(--text-secondary); + font: 12px/1.45 var(--font-sans); +} + +.context-empty .material-symbols-outlined { + color: var(--accent); + font-size: 22px; +} + +.context-empty strong { + color: var(--text-primary); + font: 600 11px/1.2 var(--font-mono); + letter-spacing: 0.14em; + text-transform: uppercase; +} + +/* A warning leads the card, above the name: an emergency, a tsunami flag. */ +.entity-card__warning { + display: flex; + align-items: flex-start; + gap: 0.4rem; + margin: 0.55rem 0 0; + padding: 0.4rem 0.55rem; + color: #ffd6d0; + font-size: 0.68rem; + font-weight: 600; + line-height: 1.35; + background: rgba(255, 75, 62, 0.16); + border: 1px solid rgba(255, 75, 62, 0.55); + border-radius: 7px; +} + +.entity-card__warning .material-symbols-outlined { + flex: none; + color: #ff6b5e; + font-size: 1rem; +} + +/* Where the card's data comes from, and how fresh it is. */ +.entity-card__source { + margin: 0.6rem 0 0; + padding-top: 0.45rem; + color: rgba(199, 214, 222, 0.5); + font-size: 0.6rem; + border-top: 1px solid rgba(255, 255, 255, 0.07); +} + +.entity-card__source span { + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +/* Open, Context fills the right column top to bottom, its card scrolling + inside rather than the panel growing and shrinking with each selection. */ +#right-context-rail > #global-context-panel:not(.collapsed), +#right-context-rail.layout-focus > #global-context-panel:not(.collapsed) { + flex: 0 0 var(--right-stack-max-height, auto); + height: var(--right-stack-max-height, auto); + max-height: var(--right-stack-max-height, 100%); +} + +#right-context-rail + > #global-context-panel:not(.collapsed) + .global-context-panel-inner { + height: 100%; +} + +/* The icon font's own rules (display: block, 24px) beat the badge's; keep + the glyph centred in its square at the badge's size. */ +.entity-card__head .entity-card__icon.material-symbols-outlined, +.view-context__head .view-context__icon.material-symbols-outlined { + display: grid; + place-items: center; + box-sizing: border-box; + width: 1.9rem; + height: 1.9rem; + font-size: 1.1rem; + line-height: 1; + overflow: hidden; +} + +/* The aircraft's model, turning at the top of its card on a soft spotlight. */ + +/* Origin to destination, as one line with the craft on it. */ +.entity-card__route { + display: flex; + align-items: center; + gap: 0.5rem; + margin: 0.15rem 0 0.55rem; + font-family: var(--font-mono); + font-size: 0.85rem; +} + +.entity-card__route-line { + position: relative; + display: grid; + flex: 1; + place-items: center; + height: 1rem; + background: linear-gradient( + 90deg, + rgba(199, 214, 222, 0.35) 50%, + transparent 0 + ) + center / 7px 1px repeat-x; +} + +.entity-card__route-line .material-symbols-outlined { + padding: 0 0.25rem; + color: #36dcff; + font-size: 0.95rem; + background: rgba(40, 44, 52, 1); + transform: rotate(90deg); +} + +/* Headline figures: big numbers, small labels. */ +.entity-card__tiles { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0.35rem; + margin: 0.2rem 0 0.55rem; +} + +.entity-card__tile { + display: grid; + gap: 0.2rem; + padding: 0.45rem 0.4rem; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 8px; +} + +.entity-card__tile span { + color: rgba(199, 214, 222, 0.5); + font-size: 0.54rem; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.entity-card__tile strong { + overflow: hidden; + color: rgba(236, 244, 248, 0.95); + font-family: var(--font-mono); + font-size: 0.76rem; + font-weight: 600; + letter-spacing: -0.02em; + text-overflow: ellipsis; + white-space: nowrap; +} + +/* The callout on the turning model, in the frame's top-left corner. The + leader sits under the text: a dot near the craft lights first, the line + draws from it up to the corner, then the label and value fade in. */ + +/* The parts legend and the scan caption, bottom right of the model. */ + +/* ── Card, second pass ────────────────────────────────────────────────── + One surface: inside Context the card is the panel's content, not a box in + a box. Identity leads (kind, name, who and what), then status and place, + the model, headline figures, details, actions, what is near, the source. */ +#global-context-panel .entity-card, +#global-context-panel .view-context { + margin: 0; + padding: 0.15rem 0 0.4rem; + background: none; + border: 0; + border-radius: 0; +} + +.entity-card__head { + align-items: flex-start; + gap: 0.6rem; +} + +.entity-card__name { + display: grid; + flex: 1; + gap: 0.12rem; + min-width: 0; +} + +#entity-card .entity-card__kind { + display: block; + color: rgba(199, 214, 222, 0.5); + font-size: 0.56rem; + letter-spacing: 0.08rem; + text-transform: uppercase; +} + +#entity-card .entity-card__title { + margin: 0; + font-size: 1.15rem; + line-height: 1.1; + letter-spacing: 0.03rem; +} + +.entity-card__subtitle { + overflow: hidden; + color: rgba(225, 236, 242, 0.72); + font-size: 0.7rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.entity-card__meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem 0.6rem; + margin: 0.55rem 0 0.15rem; +} + +#entity-card .entity-card__where { + margin: 0; + font-size: 0.6rem; +} + +/* The model sits edge to edge under the name, framed by hairlines. */ + +/* Tiles: the number leads, its unit sits small beside it. */ +#entity-card .entity-card__tile strong { + display: flex; + align-items: baseline; + gap: 0.2rem; + font-size: 0.95rem; + letter-spacing: -0.01em; +} + +#entity-card .entity-card__tile small { + color: rgba(199, 214, 222, 0.6); + font-size: 0.6rem; + font-weight: 500; +} + +/* Sections get a quiet heading with a hairline under it. */ +.entity-card__section { + margin-top: 0.75rem; +} + +.entity-card__section > h4, +#entity-card .entity-card__nearby h4 { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0 0 0.35rem; + padding-bottom: 0.3rem; + color: rgba(199, 214, 222, 0.55); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.08rem; + text-transform: uppercase; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.entity-card__section > h4 span { + padding: 0 0.3rem; + color: rgba(54, 220, 255, 0.85); + font-family: var(--font-mono); + background: rgba(54, 220, 255, 0.1); + border-radius: 999px; +} + +/* Actions: the three moves in a row, then asking GEV across the width. */ +#entity-card .entity-card__actions { + display: grid; + gap: 0.35rem; + margin-top: 0.8rem; + padding-top: 0; + border-top: 0; +} + +.entity-card__action-row { + display: flex; + gap: 0.35rem; +} + +#entity-card .entity-card__action--ask { + width: 100%; + height: 2.1rem; + color: #ffb86b; + background: rgba(255, 159, 67, 0.08); + border-color: rgba(255, 159, 67, 0.35); +} + +#entity-card .entity-card__action--ask:hover, +#entity-card .entity-card__action--ask:focus-visible { + background: rgba(255, 159, 67, 0.16); + border-color: rgba(255, 159, 67, 0.6); +} + +/* ── Callout states ────────────────────────────────────────────────────── + Enter 0-2.3 s (dot, leader, text), hold to 5.2 s (dot breathes, timer + fills), exit over 1 s (text, then leader back into the dot, then dot). */ + +/* Exit: text first, then the leader retracts toward the dot, then the dot. */ + +/* The route on its small globe, and the Route / Model switch above it. */ + +/* In view, richer: region, the view's figures as tiles, places in view and + layer switches as chips. */ +.view-context__region { + margin: 0 0 0.15rem; + color: rgba(225, 236, 242, 0.7); + font-size: 0.7rem; +} + +.view-context__facts { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.35rem; + margin: 0.4rem 0 0.7rem; +} + +.view-context__fact { + display: grid; + gap: 0.18rem; + padding: 0.45rem 0.5rem; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 8px; +} + +.view-context__fact span { + color: rgba(199, 214, 222, 0.5); + font-size: 0.54rem; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.view-context__fact strong { + overflow: hidden; + color: rgba(236, 244, 248, 0.95); + font-family: var(--font-mono); + font-size: 0.78rem; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.view-context__towns { + margin: 0.2rem 0 0.7rem; +} + +.view-context__towns h4 { + margin: 0 0 0.35rem; + padding-bottom: 0.3rem; + color: rgba(199, 214, 222, 0.55); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.08rem; + text-transform: uppercase; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.view-context__chips { + display: flex; + flex-wrap: wrap; + gap: 0.3rem; +} + +.view-context__chips button { + display: inline-flex; + align-items: center; + gap: 0.2rem; + padding: 0.28rem 0.6rem; + color: rgba(225, 236, 242, 0.85); + font-size: 0.66rem; + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.09); + border-radius: 999px; + cursor: pointer; +} + +.view-context__chips button:hover, +.view-context__chips button:focus-visible { + color: #fff; + background: rgba(54, 220, 255, 0.12); + border-color: rgba(54, 220, 255, 0.4); +} + +.view-context__chips .material-symbols-outlined { + font-size: 0.85rem; +} + +/* A scheduled route that does not fit the plane's position: amber, dashed, + with a note, so it cannot pass for the flight's actual route. */ +.entity-card__route--unverified strong { + color: #ffb86b; +} + +.entity-card__route--unverified .entity-card__route-line { + background-image: linear-gradient( + 90deg, + rgba(255, 184, 107, 0.55) 50%, + transparent 0 + ); +} + +.entity-card__route--unverified + .entity-card__route-line + .material-symbols-outlined { + color: #ffb86b; +} + +.entity-card__route-note { + display: flex; + align-items: center; + gap: 0.3rem; + margin: -0.3rem 0 0.55rem; + color: rgba(255, 184, 107, 0.85); + font-size: 0.6rem; +} + +.entity-card__route-note .material-symbols-outlined { + font-size: 0.85rem; +} + +/* Route progress: the line filled from the origin up to the plane, which + sits at its share of the way, and dashed beyond it to the destination. */ +.entity-card__route--progress .entity-card__route-line { + display: block; + background: + linear-gradient(90deg, #36dcff, #36dcff) left center / + var(--route-share, 0%) 2px no-repeat, + linear-gradient(90deg, rgba(199, 214, 222, 0.35) 50%, transparent 0) + center / 7px 1px repeat-x; + transition: background-size 600ms ease; +} + +.entity-card__route--progress + .entity-card__route-line + .material-symbols-outlined { + position: absolute; + top: 50%; + left: var(--route-share, 0%); + padding: 0 0.15rem; + transform: translate(-50%, -50%) rotate(90deg); + transition: left 600ms ease; +} + +.entity-card__route-stats { + display: flex; + justify-content: space-between; + gap: 0.5rem; + margin: -0.3rem 0 0.6rem; + color: rgba(199, 214, 222, 0.6); + font-family: var(--font-mono); + font-size: 0.58rem; +} + +/* The route globe's corner label: each airport's code over its city and + state, on a soft scrim so it reads over the imagery. */ + +/* The airports' cities, under the progress bar: origin left, destination right. */ +.entity-card__route-places { + display: flex; + justify-content: space-between; + gap: 0.75rem; + margin: -0.35rem 0 0.65rem; + color: rgba(225, 236, 242, 0.75); + font-size: 0.64rem; +} + +.entity-card__route-places span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.entity-card__route-places span:last-child { + text-align: right; +} + +/* While the preview takes turns, a hairline under the active tab fills until + the switch; a tab the viewer picked stays put and shows no timer. */ +/* The minimap's compass, top right: north at the top (the view is north up), + the cyan needle on the course to the destination, its bearing beneath. */ + +/* Follow, while the camera is on the craft. */ +#entity-card .entity-card__action--on { + color: #36dcff; + background: rgba(54, 220, 255, 0.12); + border-color: rgba(54, 220, 255, 0.45); +} + +/* ── Context refinements: one heading style, one tile style, even rhythm ── */ +.view-context__towns h4, +.view-context__group h4, +.spot-conditions__block h4, +.entity-card__section h4, +.entity-card__nearby h4 { + margin: 0 0 0.4rem; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.14rem; + text-transform: uppercase; +} + +.view-context__towns, +.view-context__groups, +.spot-conditions__block, +.entity-card__section { + margin-top: 0.85rem; +} + +.view-context__fact, +.entity-card__tile, +.spot-conditions__weather { + border-radius: 8px; + border-color: rgba(255, 255, 255, 0.07); +} + +.view-context__title { + letter-spacing: 0.02em; +} + +.view-context__where { + margin-bottom: 0.2rem; +} + +/* Place chips match the omnibox's chips. */ +.view-context__chips button { + border-radius: 999px; +} + +/* ── In view: the layers that are on ── */ +.view-context__live { + margin-top: 0.85rem; +} + +.view-context__live h4 { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0 0 0.4rem; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.14rem; + text-transform: uppercase; +} + +.view-context__live h4 .view-context__count { + margin-inline-start: auto; +} + +.view-context__live ul { + display: grid; + gap: 0.25rem; + margin: 0; + padding: 0; + list-style: none; +} + +.view-context__live-row { + display: flex; + align-items: center; + gap: 0.55rem; + padding: 0.4rem 0.45rem 0.4rem 0.55rem; + background: rgba(255, 255, 255, 0.035); + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.view-context__live-icon { + flex: none; + font-size: 0.95rem; +} + +.view-context__live-main { + display: grid; + flex: 1 1 auto; + gap: 0.08rem; + min-width: 0; +} + +.view-context__live-name { + overflow: hidden; + color: rgba(236, 244, 248, 0.94); + font-size: 0.72rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.view-context__live-meta { + overflow: hidden; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.58rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.view-context__live-state { + flex: none; + padding: 0.12rem 0.4rem; + font-family: var(--font-mono); + font-size: 0.52rem; + letter-spacing: 0.1rem; + text-transform: uppercase; + border: 1px solid currentColor; + border-radius: 999px; +} + +.view-context__live-state--live { + color: #4be3a0; +} +.view-context__live-state--loading { + color: #36dcff; +} +.view-context__live-state--stale { + color: #ffb547; +} +.view-context__live-state--error { + color: #ff5c6c; +} + +.view-context__live-off { + display: grid; + flex: none; + place-items: center; + width: 22px; + height: 22px; + padding: 0; + color: rgba(199, 214, 222, 0.5); + background: none; + border: 1px solid transparent; + border-radius: 6px; + cursor: pointer; +} + +.view-context__live-off .material-symbols-outlined { + font-size: 14px; +} + +.view-context__live-off:hover, +.view-context__live-off:focus-visible { + color: #fff; + border-color: rgba(255, 255, 255, 0.18); +} + +/* ── Selected camera: thumbnail, facts, More info ── */ +.cctv-preview { + display: grid; + gap: 0.5rem; + margin: 0.5rem 0 0.75rem; +} + +.cctv-preview__frame { + position: relative; + display: grid; + place-items: center; + aspect-ratio: 16 / 9; + overflow: hidden; + background: #05080b; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; +} + +.cctv-preview__frame img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.cctv-preview__frame.is-empty span:first-child { + color: rgba(199, 214, 222, 0.5); + font-family: var(--font-mono); + font-size: 0.58rem; + letter-spacing: 0.12rem; + text-transform: uppercase; +} + +.cctv-preview__badge { + position: absolute; + left: 6px; + bottom: 6px; + padding: 2px 7px; + color: #4be3a0; + font-family: var(--font-mono); + font-size: 0.5rem; + letter-spacing: 0.1rem; + background: rgba(5, 8, 11, 0.8); + border: 1px solid rgba(75, 227, 160, 0.45); + border-radius: 999px; +} + +.cctv-preview__name { + margin: 0; + color: rgba(236, 244, 248, 0.94); + font-size: 0.78rem; +} + +.cctv-preview__facts { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.35rem; + margin: 0; +} + +.cctv-preview__facts div { + padding: 0.35rem 0.5rem; + background: rgba(255, 255, 255, 0.035); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 7px; +} + +.cctv-preview__facts dt { + color: rgba(199, 214, 222, 0.5); + font-size: 0.52rem; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.cctv-preview__facts dd { + overflow: hidden; + margin: 0.1rem 0 0; + color: rgba(236, 244, 248, 0.92); + font-family: var(--font-mono); + font-size: 0.68rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cctv-preview__more { + justify-content: center; +} + +.cctv-preview__expand { + position: absolute; + top: 6px; + right: 6px; + display: grid; + place-items: center; + width: 26px; + height: 26px; + padding: 0; + color: rgba(236, 244, 248, 0.9); + background: rgba(5, 8, 11, 0.7); + border: 1px solid rgba(255, 255, 255, 0.18); + border-radius: 7px; + cursor: pointer; +} + +.cctv-preview__expand .material-symbols-outlined { + font-size: 15px; +} + +.cctv-preview__expand:hover, +.cctv-preview__expand:focus-visible { + color: #7af0ff; + border-color: rgba(54, 220, 255, 0.6); +} + +/* ── Bigger camera view ── */ +.cctv-popup { + position: fixed; + inset: 0; + z-index: 400; + display: grid; + place-items: center; + padding: 2rem; + background: rgba(2, 4, 8, 0.55); + backdrop-filter: blur(3px); + -webkit-backdrop-filter: blur(3px); + animation: cctv-popup-in 160ms ease; +} + +@keyframes cctv-popup-in { + from { + opacity: 0; + } +} + +.cctv-popup__card { + display: grid; + gap: 0.6rem; + width: min(960px, 92vw); + margin: 0; + padding: 0.7rem; + background: rgba(12, 12, 20, 0.92); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 14px; + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.6); +} + +.cctv-popup__head { + display: flex; + align-items: center; + gap: 0.55rem; + padding: 0 0.2rem; + color: rgba(236, 244, 248, 0.94); + font-family: var(--font-mono); + font-size: 0.8rem; + letter-spacing: 0.04em; +} + +.cctv-popup__head > .material-symbols-outlined { + color: #36dcff; + font-size: 18px; +} + +.cctv-popup__badge { + padding: 2px 8px; + color: #4be3a0; + font-size: 0.55rem; + letter-spacing: 0.1rem; + border: 1px solid rgba(75, 227, 160, 0.45); + border-radius: 999px; +} + +.cctv-popup__close { + display: grid; + place-items: center; + width: 28px; + height: 28px; + margin-inline-start: auto; + padding: 0; + color: rgba(236, 244, 248, 0.8); + background: none; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 8px; + cursor: pointer; +} + +.cctv-popup__close:hover { + color: #fff; + border-color: rgba(255, 255, 255, 0.3); +} + +.cctv-popup__card img { + width: 100%; + max-height: 72vh; + object-fit: contain; + background: #000; + border-radius: 8px; +} + +.cctv-popup__card figcaption { + display: flex; + flex-wrap: wrap; + gap: 0.3rem 1.1rem; + padding: 0 0.2rem 0.1rem; + color: rgba(199, 214, 222, 0.6); + font-family: var(--font-mono); + font-size: 0.6rem; + letter-spacing: 0.08rem; + text-transform: uppercase; +} + +.cctv-popup__card figcaption b { + color: rgba(236, 244, 248, 0.92); + font-weight: 500; +} + +/* CCTV, open, fills the right column top to bottom like Context. */ +#right-context-rail > #cctv-panel:not(.collapsed), +#right-context-rail.layout-focus > #cctv-panel:not(.collapsed) { + flex: 0 0 var(--right-stack-max-height, auto); + height: var(--right-stack-max-height, auto); + max-height: var(--right-stack-max-height, 100%); +} + +#right-context-rail > #cctv-panel:not(.collapsed) > .cctv-panel-inner, +#right-context-rail > #cctv-panel:not(.collapsed) > [class$='-inner'] { + height: 100%; +} + +/* ── Hero tile ─────────────────────────────────────────────────────────── + One slot at the top of every card: an aircraft's route globe and turning + model, a camera's frame, or a quiet placeholder with the item's icon and + name. */ +.entity-hero { + position: relative; + margin: 0 0 0.6rem; + overflow: hidden; + border-radius: 10px; +} + +/* Both previews fill the tile, one over the other; the hidden one keeps its + size, so showing it needs no layout and no fresh canvas. */ + +.entity-hero .cctv-preview { + margin: 0; +} + +.entity-hero__placeholder { + display: grid; + grid-template-columns: auto 1fr; + align-items: center; + gap: 0.9rem; + min-height: 84px; + padding: 0.7rem 0.9rem; + background: + radial-gradient( + ellipse 45% 90% at 12% 50%, + rgba(54, 220, 255, 0.1), + transparent 70% + ), + rgba(255, 255, 255, 0.025); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 10px; +} + +.entity-hero__placeholder--bare { + grid-template-columns: 1fr; + justify-items: center; + gap: 0.3rem; + text-align: center; +} + +.entity-hero__glyph.material-symbols-outlined { + display: grid; + place-items: center; + width: 3.2rem; + height: 3.2rem; + color: #36dcff; + font-size: 1.9rem; + background: rgba(54, 220, 255, 0.08); + border: 1px solid rgba(54, 220, 255, 0.18); + border-radius: 50%; +} + +.entity-hero__figures { + display: flex; + flex-wrap: wrap; + gap: 0.4rem 1.1rem; + min-width: 0; +} + +.entity-hero__figure { + display: grid; + gap: 0.15rem; + min-width: 0; +} + +.entity-hero__figure strong { + overflow: hidden; + color: rgba(240, 247, 250, 0.98); + font-family: var(--font-mono); + font-size: 1.15rem; + font-weight: 600; + line-height: 1.05; + text-overflow: ellipsis; + white-space: nowrap; +} + +.entity-hero__figure strong small { + margin-inline-start: 0.2rem; + color: rgba(199, 214, 222, 0.7); + font-size: 0.62rem; + font-weight: 500; +} + +.entity-hero__figure span, +.entity-hero__kind { + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.52rem; + letter-spacing: 0.12rem; + text-transform: uppercase; +} + +/* ── Cockpit leads an aircraft's actions ─────────────────────────────── */ +#entity-card .entity-card__action--primary { + width: 100%; + height: 2.3rem; + color: #04131a; + font-size: 0.74rem; + font-weight: 600; + letter-spacing: 0.04rem; + background: #36dcff; + border-color: #36dcff; + box-shadow: 0 0 18px rgba(54, 220, 255, 0.28); +} + +#entity-card .entity-card__action--primary:hover, +#entity-card .entity-card__action--primary:focus-visible { + color: #04131a; + background: #7be8ff; + border-color: #7be8ff; +} + +/* Following is a state, not the main action: outlined, not filled. */ +#entity-card .entity-card__action--on { + background: transparent; +} + +/* ── Worldwide counts (globe view, nothing selected) ─────────────────── */ +.view-context__world { + margin: 0.6rem 0 0.75rem; +} + +.view-context__world h4 { + margin: 0 0 0.4rem; + color: rgba(199, 214, 222, 0.55); + font-family: var(--font-mono); + font-size: 0.56rem; + font-weight: 500; + letter-spacing: 0.14rem; + text-transform: uppercase; +} + +.view-context__world-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.35rem; +} + +.view-context__world-tile { + display: grid; + grid-template-columns: auto 1fr; + align-items: center; + gap: 0.05rem 0.5rem; + padding: 0.5rem 0.6rem; + color: inherit; + font: inherit; + text-align: start; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 8px; +} + +.view-context__world-tile .material-symbols-outlined { + grid-row: 1 / 3; + color: #36dcff; + font-size: 1.3rem; +} + +.view-context__world-tile strong { + color: rgba(240, 247, 250, 0.98); + font-family: var(--font-mono); + font-size: 1rem; + font-weight: 600; + line-height: 1.1; +} + +.view-context__world-tile span:last-child { + overflow: hidden; + color: rgba(199, 214, 222, 0.6); + font-size: 0.58rem; + letter-spacing: 0.04rem; + text-overflow: ellipsis; + text-transform: uppercase; + white-space: nowrap; +} + +.view-context__world-tile.is-off { + cursor: pointer; + border-style: dashed; +} + +.view-context__world-tile.is-off .material-symbols-outlined, +.view-context__world-tile.is-off strong { + color: rgba(199, 214, 222, 0.45); +} + +.view-context__world-tile.is-off:hover, +.view-context__world-tile.is-off:focus-visible { + background: rgba(54, 220, 255, 0.08); + border-color: rgba(54, 220, 255, 0.3); +} + +/* An aircraft's altitude as a filled graph, graded by height: bright at + the top, fading towards the baseline. */ +.altitude-graph { + margin: 0 0 0.7rem; + padding: 0.5rem 0.6rem 0.45rem; + border: 1px solid rgba(160, 200, 220, 0.14); + border-radius: 8px; + background: rgba(255, 255, 255, 0.025); +} + +.altitude-graph__head, +.altitude-graph__foot { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.5rem; + margin: 0; +} + +.altitude-graph__label, +.altitude-graph__foot { + color: rgba(199, 214, 222, 0.6); + font-family: var(--font-mono); + font-size: 0.56rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.altitude-graph__now { + color: #eef6fa; + font-family: var(--font-mono); + font-size: 0.78rem; + font-weight: 600; +} + +.altitude-graph__plot { + position: relative; + height: 3.4rem; + margin: 0.35rem 0 0.3rem; + border-bottom: 1px solid rgba(160, 200, 220, 0.22); + background: repeating-linear-gradient( + to bottom, + rgba(160, 200, 220, 0.08) 0 1px, + transparent 1px 25% + ); +} + +.altitude-graph__plot svg { + display: block; + width: 100%; + height: 100%; +} + +.altitude-graph__stop--high { + stop-color: var(--accent); + stop-opacity: 0.75; +} + +.altitude-graph__stop--mid { + stop-color: var(--accent); + stop-opacity: 0.3; +} + +.altitude-graph__stop--low { + stop-color: var(--accent); + stop-opacity: 0.04; +} + +.altitude-graph__line { + fill: none; + stroke: var(--accent); + stroke-width: 1.5; + stroke-linejoin: round; + vector-effect: non-scaling-stroke; +} + +.altitude-graph__head-dot { + position: absolute; + right: -3px; + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--accent); + box-shadow: 0 0 6px var(--accent); + transform: translateY(-50%); +} + +.altitude-graph__scale { + position: absolute; + top: 1px; + left: 2px; + color: rgba(199, 214, 222, 0.45); + font-family: var(--font-mono); + font-size: 0.5rem; +} + +.altitude-graph[data-trend='up'] .altitude-graph__change { + color: #7fe0a8; +} + +.altitude-graph[data-trend='down'] .altitude-graph__change { + color: #f0b46a; +} + +.altitude-graph__scale--low { + top: auto; + bottom: 1px; +} + +/* What a layer that is on is made of: under its row, a bar per split whose + segments are the parts, and a legend with each part's count. */ +.view-context__live-item { + background: rgba(255, 255, 255, 0.035); + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.view-context__live-item > .view-context__live-row { + background: none; + border: 0; +} + +.view-context__split { + display: grid; + gap: 0.45rem; + padding: 0 0.55rem 0.55rem; +} + +.view-context__split-basis { + margin: 0; + color: rgba(199, 214, 222, 0.5); + font-family: var(--font-mono); + font-size: 0.54rem; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.view-context__split-bar { + display: flex; + gap: 2px; + height: 6px; + overflow: hidden; + border-radius: 3px; + background: rgba(255, 255, 255, 0.06); +} + +.view-context__split-bar i { + min-width: 2px; +} + +.view-context__split-legend { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.15rem 0.6rem; + margin: 0.3rem 0 0; + padding: 0; + list-style: none; +} + +.view-context__split-legend li { + display: flex; + align-items: center; + gap: 0.3rem; + min-width: 0; + color: rgba(199, 214, 222, 0.75); + font-size: 0.6rem; +} + +.view-context__split-legend i { + flex: none; + width: 6px; + height: 6px; + border-radius: 50%; +} + +.view-context__split-legend span { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.view-context__split-legend strong { + color: #eef6fa; + font-family: var(--font-mono); + font-weight: 600; +} + +/* The compact graph: caption, figure and a short line, nothing else. */ +.altitude-graph--compact { + padding-bottom: 0.5rem; +} + +.altitude-graph--compact .altitude-graph__plot { + height: 1.9rem; + margin-bottom: 0; + background: none; +} + +/* "Layers on" leads the view, under the place name. */ +.view-context__live { + margin: 0.6rem 0 0.7rem; +} diff --git a/src/ui/styles/spot-conditions.css b/src/ui/styles/spot-conditions.css new file mode 100644 index 0000000000..a45f05bf34 --- /dev/null +++ b/src/ui/styles/spot-conditions.css @@ -0,0 +1,332 @@ +/* ── Conditions around a spot (entity card, In view) ────────────────────── */ +.spot-conditions { + display: grid; + gap: 0.6rem; + margin: 0.5rem 0 0.75rem; +} + +.spot-conditions__weather { + display: grid; + grid-template-columns: auto 1fr; + align-items: center; + gap: 0.3rem 0.65rem; + padding: 0.6rem 0.7rem; + background: linear-gradient(135deg, rgba(54, 220, 255, 0.09), rgba(255, 255, 255, 0.025)); + border: 1px solid rgba(54, 220, 255, 0.16); + border-radius: 10px; +} + +.spot-conditions__weather-icon { + color: #36dcff; + font-size: 2rem; +} + +.spot-conditions__weather-now { + display: grid; + gap: 0.1rem; +} + +.spot-conditions__weather-now strong { + color: rgba(240, 247, 250, 0.98); + font-family: var(--font-mono); + font-size: 1.35rem; + font-weight: 600; + line-height: 1; +} + +.spot-conditions__weather-now span { + color: rgba(199, 214, 222, 0.72); + font-size: 0.68rem; +} + +.spot-conditions__weather-facts { + display: grid; + grid-column: 1 / -1; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 0.3rem; + margin: 0.25rem 0 0; +} + +.spot-conditions__weather-facts div { + display: grid; + gap: 0.1rem; + min-width: 0; +} + +.spot-conditions__weather-facts dt { + color: rgba(199, 214, 222, 0.5); + font-size: 0.52rem; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.spot-conditions__weather-facts dd { + overflow: hidden; + margin: 0; + color: rgba(236, 244, 248, 0.92); + font-family: var(--font-mono); + font-size: 0.66rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.spot-conditions__loading, +.spot-conditions__none { + margin: 0; + color: rgba(199, 214, 222, 0.55); + font-size: 0.66rem; +} + +.spot-conditions__block h4 { + display: flex; + align-items: center; + gap: 0.4rem; + margin: 0 0 0.25rem; + color: rgba(199, 214, 222, 0.6); + font-size: 0.58rem; + font-weight: 500; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.spot-conditions__block h4 .material-symbols-outlined { + font-size: 0.95rem; +} + +.spot-conditions__count { + margin-inline-start: auto; + color: rgba(199, 214, 222, 0.6); + font-family: var(--font-mono); +} + +.spot-conditions__count--hot { + color: #ffb547; +} + +.spot-conditions__query { + overflow: hidden; + margin-inline-start: auto; + max-width: 50%; + color: rgba(199, 214, 222, 0.45); + text-overflow: ellipsis; + text-transform: none; + white-space: nowrap; +} + +.spot-conditions__block ul { + display: grid; + gap: 0.2rem; + margin: 0; + padding: 0; + list-style: none; +} + +.spot-conditions__block button, +.spot-conditions__block a { + display: flex; + align-items: center; + gap: 0.5rem; + width: 100%; + padding: 0.4rem 0.5rem; + color: inherit; + text-align: start; + text-decoration: none; + background: rgba(255, 255, 255, 0.035); + border: 1px solid rgba(255, 255, 255, 0.06); + border-left: 2px solid var(--hazard-tone, rgba(54, 220, 255, 0.5)); + border-radius: 7px; + cursor: pointer; +} + +.spot-conditions__block button:hover, +.spot-conditions__block a:hover, +.spot-conditions__block button:focus-visible, +.spot-conditions__block a:focus-visible { + background: rgba(54, 220, 255, 0.08); + border-color: rgba(54, 220, 255, 0.25); + border-left-color: var(--hazard-tone, #36dcff); +} + +.spot-conditions__block button > .material-symbols-outlined { + color: var(--hazard-tone, #36dcff); + font-size: 1.05rem; +} + +.spot-conditions__hazard--quake { --hazard-tone: #ffd166; } +.spot-conditions__hazard--storm { --hazard-tone: #c792ff; } +.spot-conditions__hazard--wildfire, +.spot-conditions__hazard--hotspots { --hazard-tone: #ff7a45; } +.spot-conditions__hazard--alert { --hazard-tone: #ff5c6c; } + +.spot-conditions__row-main { + display: grid; + flex: 1 1 auto; + gap: 0.08rem; + min-width: 0; +} + +.spot-conditions__row-title { + overflow: hidden; + color: rgba(236, 244, 248, 0.94); + font-size: 0.7rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.spot-conditions__row-title--wrap { + display: -webkit-box; + white-space: normal; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; +} + +.spot-conditions__row-detail { + overflow: hidden; + color: rgba(199, 214, 222, 0.55); + font-size: 0.6rem; + text-overflow: ellipsis; + white-space: nowrap; +} + +.spot-conditions__row-layer { + display: inline-flex; + align-items: center; + gap: 5px; + margin-top: 2px; + color: rgba(199, 214, 222, 0.5); + font-family: var(--font-mono); + font-size: 0.55rem; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.spot-conditions__row-dot { + width: 6px; + height: 6px; + border: 1px solid rgba(199, 214, 222, 0.55); + border-radius: 50%; +} + +.spot-conditions__row-layer.is-on { + color: rgba(0, 212, 255, 0.85); +} + +.spot-conditions__row-layer.is-on .spot-conditions__row-dot { + background: #00d4ff; + border-color: #00d4ff; + box-shadow: 0 0 5px rgba(0, 212, 255, 0.7); +} + +.spot-conditions__row-meta { + flex: none; + color: rgba(199, 214, 222, 0.7); + font-family: var(--font-mono); + font-size: 0.6rem; +} + +.spot-conditions__source { + margin: 0; + color: rgba(199, 214, 222, 0.4); + font-size: 0.55rem; +} + +/* The hazard tone as an L along the left edge and the bottom-left corner, + in place of a solid left edge. */ +.spot-conditions__block button, +.spot-conditions__block a { + position: relative; + border-radius: 0; + border-left-width: 1px; + border-left-color: rgba(255, 255, 255, 0.06); +} + +.spot-conditions__block button::before, +.spot-conditions__block a::before { + content: ''; + position: absolute; + inset: -1px auto -1px -1px; + width: 9px; + border-radius: 0; + pointer-events: none; + --tone: var(--hazard-tone, rgba(54, 220, 255, 0.6)); + background: + linear-gradient(var(--tone), var(--tone)) left bottom / 9px 1.5px no-repeat, + linear-gradient(var(--tone), var(--tone)) left bottom / 1.5px 100% no-repeat; +} + +.spot-conditions__block button:hover, +.spot-conditions__block a:hover, +.spot-conditions__block button:focus-visible, +.spot-conditions__block a:focus-visible { + border-left-color: rgba(54, 220, 255, 0.25); +} + +/* A grey rule under each list: hazards, alerts, news. */ +.spot-conditions__block { + padding-bottom: 0.65rem; + border-bottom: 1px solid rgba(255, 255, 255, 0.08); +} + +/* Local time beside the weather on a selected item's card. */ +.spot-conditions__weather--timed { + grid-template-columns: auto 1fr auto; +} + +.spot-conditions__weather-wait { + grid-column: 1 / 3; +} + +.spot-conditions__time { + display: grid; + gap: 0.1rem; + justify-items: end; + grid-column: 3; +} + +.spot-conditions__time strong { + color: rgba(240, 247, 250, 0.98); + font-family: var(--font-mono); + font-size: 1.05rem; + font-weight: 600; + line-height: 1; +} + +.spot-conditions__time span { + color: rgba(199, 214, 222, 0.6); + font-size: 0.56rem; + letter-spacing: 0.05rem; + text-transform: uppercase; +} + +/* The one distance every nearby block looks out to. */ +.spot-conditions__radius { + display: grid; + grid-template-columns: auto 1fr auto; + align-items: center; + gap: 0.6rem; + padding: 0.4rem 0.6rem; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 8px; +} + +.spot-conditions__radius-label { + color: rgba(199, 214, 222, 0.6); + font-size: 0.58rem; + font-weight: 500; + letter-spacing: 0.06rem; + text-transform: uppercase; +} + +.spot-conditions__radius-slider { + width: 100%; + min-width: 0; +} + +.spot-conditions__radius-value { + min-width: 4.2rem; + color: #36dcff; + font-family: var(--font-mono); + font-size: 0.7rem; + text-align: end; +} diff --git a/src/ui/styles/sun-dial.css b/src/ui/styles/sun-dial.css new file mode 100644 index 0000000000..fe2cc2ab73 --- /dev/null +++ b/src/ui/styles/sun-dial.css @@ -0,0 +1,110 @@ +/* ── Sundial (Context, nothing selected) ──────────────────────────────── */ +.sun-dial { + margin: 0.5rem 0 0.6rem; + padding: 0.35rem 0.3rem 0.45rem; + background: + radial-gradient(90% 70% at 50% 45%, rgba(54, 220, 255, 0.06), transparent 70%), + rgba(255, 255, 255, 0.025); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 8px; +} + +.sun-dial svg { + display: block; + width: 100%; + height: auto; +} + +.sun-dial__hours line { + stroke: rgba(54, 220, 255, 0.38); + stroke-width: 0.5; +} + +.sun-dial__hours line.major { + stroke: rgba(122, 240, 255, 0.7); + stroke-width: 0.8; +} + +.sun-dial__ticks line { + stroke: rgba(54, 220, 255, 0.3); + stroke-width: 0.4; +} + +.sun-dial__ticks line.major { + stroke: rgba(122, 240, 255, 0.65); + stroke-width: 0.7; +} + +.sun-dial__hours text, +.sun-dial__pole { + fill: rgba(196, 244, 255, 0.85); + font-family: var(--font-mono); + font-size: 7px; + font-weight: 500; + letter-spacing: 0.04em; + text-anchor: middle; +} + +.sun-dial__pole { + fill: #ff6b5e; + font-size: 8px; + font-weight: 700; +} + +.sun-dial figcaption { + margin-top: 0.2rem; + color: rgba(199, 214, 222, 0.62); + font-family: var(--font-mono); + font-size: 0.58rem; + letter-spacing: 0.05rem; + text-align: center; +} + +/* Night: the plate under starlight. */ +.sun-dial--night svg { + filter: saturate(0.4) brightness(0.6); +} + +/* Small compass beside the dial, in the same cyan instrument style. */ +.sun-dial__compass-ring { + fill: rgba(5, 14, 20, 0.85); + stroke: rgba(54, 220, 255, 0.5); + stroke-width: 0.8; +} + +.sun-dial__compass-inner { + fill: none; + stroke: rgba(54, 220, 255, 0.18); + stroke-width: 0.5; + stroke-dasharray: 1.5 2; +} + +.sun-dial__compass-tick { + stroke: rgba(122, 240, 255, 0.7); + stroke-width: 0.8; +} + +.sun-dial__compass-north { + fill: #ff6b5e; +} + +.sun-dial__compass-south { + fill: rgba(196, 244, 255, 0.55); +} + +.sun-dial__compass-sun { + fill: #ffd166; + filter: drop-shadow(0 0 2px rgba(255, 209, 102, 0.9)); +} + +.sun-dial__compass-label { + fill: rgba(196, 244, 255, 0.75); + font-family: var(--font-mono); + font-size: 6.5px; + text-anchor: middle; +} + +.sun-dial__compass-label.north { + fill: #ff6b5e; + font-weight: 700; +} diff --git a/src/ui/views/ContextView.vue b/src/ui/views/ContextView.vue index 1c06840029..980ba990e8 100644 --- a/src/ui/views/ContextView.vue +++ b/src/ui/views/ContextView.vue @@ -1,5 +1,5 @@