From ca98ed191998e7320a487b8cce978ed3d978d423 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 14:19:45 -0800 Subject: [PATCH 01/24] feat(app): a host names the layers a bare address starts with createApplicationControls takes startLayers, the layer ids that turn on when the address carries no link (none by default). They restore through the passive start-up path, so they are never written as the user's own choice, and a link's own layers always win. --- docs/CURRENT-STATE.md | 3 +++ src/app/controls.js | 4 +++ src/data/layerState.test.mjs | 43 +++++++++++++++++++++++++++++++ src/data/layerStateCoordinator.js | 9 ++++++- src/ui/applicationShell.js | 4 +++ src/ui/shareRestoration.js | 4 +++ 6 files changed, 66 insertions(+), 1 deletion(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index b89acd8ae3..2889698b97 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -8824,6 +8824,9 @@ remembers" are different promises: a link restores what its hash carries, and a bare URL starts with the default layers and options (`src/ui/shareRestoration.js` passes `allowLocalState: false`), so clearing the address always resets the view. + A host may name the layers a bare URL starts with (`startLayers` on + `createApplicationControls`, e.g. `['flights', 'satellites']`); they are + restored passively, never written to storage, and a link's own layers win. - **Detection mode/density and scope feather have NO storage key at all.** Their only durable carrier is the URL hash (`dm`/`dd`, `scf`), written on a 500 ms debounce. A same-URL reload therefore keeps them only if that debounce already diff --git a/src/app/controls.js b/src/app/controls.js index 8e152a1e02..e7965f39ed 100644 --- a/src/app/controls.js +++ b/src/app/controls.js @@ -21,6 +21,8 @@ export { START_VIEW }; * `homeView` is where the title's logo goes back to (with the clock live): the * start view unless given, for a host whose `startView` only carries a view * across a rebuild. + * `startLayers` are the layer ids a bare address (one that carries no link) + * starts with: none by default; a host may pass `['flights', 'satellites']`. * `services.cockpitSubjects` adds the application's own first-person subjects * to the Cockpit (src/cockpitSubjectProviders.js). */ @@ -36,6 +38,7 @@ export function createApplicationControls({ localePicker = true, startView = START_VIEW, homeView = startView, + startLayers = [], }) { // Every boot starts from the same view, before share restoration flies on. applyStartView(viewer, startView); @@ -59,6 +62,7 @@ export function createApplicationControls({ initialShareCode, localePicker, homeView, + startLayers, }); defer(() => styleManager.orbitController.stop()); defer(() => styleManager.hud.destroy()); diff --git a/src/data/layerState.test.mjs b/src/data/layerState.test.mjs index 116a77c883..93f4f8e568 100644 --- a/src/data/layerState.test.mjs +++ b/src/data/layerState.test.mjs @@ -3231,3 +3231,46 @@ test('an application with every layer registered keeps every requested layer', a ]); coordinator.destroy(); }); + +test('start layers turn on when nothing names any, and are never written as the user choice', async () => { + const storage = memoryStorage(); + const manager = productionManager(); + const coordinator = new LayerStateCoordinator(manager, shareSink(), { + storage, + }); + const results = await coordinator.start({ + allowLocalState: false, + startLayerIds: ['earthquakes', 'traffic', 'not-a-layer'], + }); + assert.equal(coordinator.source, 'start'); + assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [ + 'earthquakes', + 'traffic', + ]); + assert.equal(manager.isEnabled('earthquakes'), true); + assert.equal(manager.isEnabled('traffic'), true); + assert.equal( + results.every((result) => result.persistenceWrite === false), + true, + ); + assert.deepEqual(storage.writes, []); + coordinator.destroy(); +}); + +test('a shared layer payload wins over start layers', async () => { + const manager = productionManager(); + const coordinator = new LayerStateCoordinator(manager, shareSink(), { + storage: memoryStorage(), + }); + const shared = createDefaultLayerState(); + shared.enabledLayerIds = ['radio']; + await coordinator.start({ + shareLayerState: shared, + allowLocalState: false, + startLayerIds: ['earthquakes'], + }); + assert.equal(coordinator.source, 'share'); + assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['radio']); + assert.equal(manager.isEnabled('earthquakes'), false); + coordinator.destroy(); +}); diff --git a/src/data/layerStateCoordinator.js b/src/data/layerStateCoordinator.js index 7cd5545392..ad1b3e31aa 100644 --- a/src/data/layerStateCoordinator.js +++ b/src/data/layerStateCoordinator.js @@ -103,6 +103,7 @@ export class LayerStateCoordinator { shareLayerState = null, allowLocalState = true, shareCreatedAtMs = null, + startLayerIds = [], } = {}) { if (this._destroyed) throw new Error('Layer-state coordinator is destroyed'); @@ -125,7 +126,13 @@ export class LayerStateCoordinator { selected = this._normalize(stored); this._source = 'local'; } - } else { + } + if (!selected && startLayerIds.length) { + // The layers the application starts with when nothing names any: + // restored passively, so they are never written as the user's choice. + selected = this._normalize({ enabledLayerIds: startLayerIds }); + this._source = 'start'; + } else if (!selected && !allowLocalState) { // A valid historical camera/style share with no v2 layer payload keeps // the exact legacy default-layer behavior. It must not inherit an // unrelated recipient's saved local layer preferences. diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index cf270e6c47..1adbe4ad84 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -117,6 +117,8 @@ export class StyleManager extends ShellFacade { * @param {{lon: number, lat: number, height: number, heading?: number, * pitch?: number}|null} [options.homeView] - where the title's logo goes * back to (degrees): the view the app started from. + * @param {string[]} [options.startLayers] - the layers a bare address (one + * that carries no link) starts with; none by default. */ constructor( viewer, @@ -128,6 +130,7 @@ export class StyleManager extends ShellFacade { initialShareCode = null, localePicker = true, homeView = null, + startLayers = [], } = {}, ) { super(); @@ -256,6 +259,7 @@ export class StyleManager extends ShellFacade { updateFeedback: () => this._updateGlobalLoadingFeedback(), applyFollowOffset: (followed, offset) => applyShareFollowOffset(viewer, followed, offset), + startLayers, }); this._visualSettings = new VisualSettings({ diff --git a/src/ui/shareRestoration.js b/src/ui/shareRestoration.js index 6d93d5061c..0b34ffbd55 100644 --- a/src/ui/shareRestoration.js +++ b/src/ui/shareRestoration.js @@ -167,7 +167,10 @@ export class ShareRestoration { feedback, updateFeedback, applyFollowOffset = null, + startLayers = [], }) { + // The layers a bare address starts with; a link names its own. + this._startLayers = startLayers; Object.assign(this, { viewer, navigation, @@ -421,6 +424,7 @@ export class ShareRestoration { // with the default layers. Saved layer choices never come back on // their own, so clearing the address always resets the view. allowLocalState: false, + startLayerIds: this._initialShareState ? [] : this._startLayers, }); if (this._initialShareSelectionSuperseded) { this._layerStateCoordinator.cancelPendingShareTracking( From 23837768e1ae2acb95e4237146f3789fc0b1ca41 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 14:19:55 -0800 Subject: [PATCH 02/24] Add the changelog entry for #1867 --- changelog.d/1867-start-layers.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1867-start-layers.md diff --git a/changelog.d/1867-start-layers.md b/changelog.d/1867-start-layers.md new file mode 100644 index 0000000000..d617556057 --- /dev/null +++ b/changelog.d/1867-start-layers.md @@ -0,0 +1,4 @@ +- An application can name the layers a bare address starts with + (`startLayers` on `createApplicationControls`; none by default): they turn on + without being saved as the user's own choice, and a link's own layers always + win (samehkhamis, #1867). From 591650d786d5d41bc450a412a55a00637ffe89d4 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 14:59:16 -0800 Subject: [PATCH 03/24] Vue kit: the view scan forbids any hand-written button, glyph, checkbox or range viewControls.test.mjs now reads every SFC outside the kit for a raw ';")); + assert.ok( + !sees(STRING_MARKUP, "''".replace('', '')), + ); + + const sources = scriptSources(); + assert.ok( + sources.some(({ file }) => file === 'src/ui/views/panels/ChatPanel.vue'), + ); const found = []; - for (const file of scriptFiles()) { - const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/'); - const source = readFileSync(file, 'utf8'); - source.split('\n').forEach((line, index) => { - if (SCRIPT_CONTROL.test(line) || SCRIPT_GLYPH.test(line)) - found.push(`${relative}:${index + 1}: ${line.trim()}`); - }); + for (const { file, source } of sources) { + found.push( + ...hits(file, source, SCRIPT_CONTROL), + ...hits(file, source, SCRIPT_GLYPH), + ); + if (!STRING_MARKUP_PAGES.has(file)) + found.push(...hits(file, uncommented(source), STRING_MARKUP)); } assert.deepEqual(found, []); + for (const file of STRING_MARKUP_PAGES) { + const page = sources.find((s) => s.file === file); + assert.ok( + page && hits(file, page.source, STRING_MARKUP).length, + `${file} no longer writes markup`, + ); + } }); From 22e9c58d845c5691245928d99b515fd9d7bfbf5a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 15:40:31 -0800 Subject: [PATCH 06/24] Find a selected vessel or aircraft again from its card While a selected vessel, aircraft or military aircraft is off screen, behind the globe or out of its layer's feed, its Context card shows Find it. One still in its feed is flown to (an aircraft followed). One out of its feed is looked up on its own track at the layer's time (the world clock's while the layer follows it), the card moves to that reading and says how old it is, and the camera flies there; once the feed has it again its layer selects it again. With no reading at or before the time the card says so and the camera stays. A vessel its layer announces is named by its own id, as a click names it, not by the context store's. --- docs/CURRENT-STATE.md | 14 +++ scripts/package-boundaries.json | 6 + src/data/locate.js | 102 ++++++++++++++++ src/data/locate.test.mjs | 114 ++++++++++++++++++ src/i18n/locales/ar.json | 6 +- src/i18n/locales/de.json | 6 +- src/i18n/locales/es.json | 6 +- src/i18n/locales/fr.json | 6 +- src/i18n/locales/he.json | 6 +- src/i18n/locales/it.json | 6 +- src/i18n/locales/ja.json | 6 +- src/i18n/locales/pt.json | 6 +- src/i18n/locales/ru.json | 6 +- src/i18n/locales/sv.json | 6 +- src/i18n/locales/uk.json | 6 +- src/i18n/locales/zh-CN.json | 6 +- src/i18n/locales/zh-Hant.json | 6 +- src/layers/flights/queries.js | 41 +++++++ src/layers/military/queries.js | 41 +++++++ src/layers/vessels/queries.js | 34 ++++++ src/ui/entityContextBridge.js | 31 ++++- src/ui/entityContextBridge.test.mjs | 57 +++++++++ src/ui/kit/entityCardControls.test.mjs | 13 +- src/ui/stores/entityCard.js | 125 +++++++++++++++++++ src/ui/stores/entityCardLocate.test.mjs | 154 ++++++++++++++++++++++++ src/ui/styles/entity-card.css | 33 ++++- src/ui/views/panels/EntityCard.vue | 12 +- 27 files changed, 833 insertions(+), 22 deletions(-) create mode 100644 src/data/locate.js create mode 100644 src/data/locate.test.mjs create mode 100644 src/ui/stores/entityCardLocate.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8b01b335ad..ed3531e5cb 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -10,6 +10,20 @@ or an older position from another feed) and one reported slower than 2 m/s give no course and keep the last; an aircraft with no course at all faces north. +A selected vessel, aircraft or military aircraft can be found again from its +Context card. While it is off screen, behind the globe or out of its layer's +feed (the clock jumped to a time the feed lacks it, or the view moved away +from it), the card's header shows Find it (`store.locate()`, +`src/ui/stores/entityCard.js`). One still in its feed is flown to (an +aircraft followed). One out of its feed is looked up at the layer's time on +its own track (`locate` on the vessels, flights and military layers, through +`locateOnTrack` in `src/data/locate.js`): the newest point at or before the +world clock's time while the layer follows the clock, else the newest. The card +moves to it and says how old that reading is, and the camera flies there. Once +the feed has it again, its layer selects it again (an aircraft is followed). +With no point at or before the time, the card says there is no reading then and +the camera stays. A followed item is never counted as off screen. + 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 render governor (`src/renderGovernor.js`) caps a parked scene at diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index cea396ce3a..babd7e52b0 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1690,6 +1690,7 @@ "src/data/aircraftEmergency.js", "src/ui/stores/entityCard.js", "src/ui/entityContextBridge.js", + "src/data/locate.js", "src/data/trackingClickGesture.js", "src/ui/stores/sceneSharing.js", "src/maps/attribution.js", @@ -1966,6 +1967,7 @@ "src/layers/flights/policy.js", "src/render/color.js", "src/layers/flights/queries.js", + "src/data/locate.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -2117,6 +2119,7 @@ "src/layers/military/policy.js", "src/render/color.js", "src/layers/military/queries.js", + "src/data/locate.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -2284,6 +2287,7 @@ "src/layers/vessels/lifecycle.js", "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", + "src/data/locate.js", "src/geo/vector.js", "src/layers/vessels/rendering.js", "src/render/camera/poseSignature.js", @@ -5533,6 +5537,7 @@ "src/data/entityContext.js", "src/ui/stores/entityCard.js", "src/ui/entityContextBridge.js", + "src/data/locate.js", "src/render/cesium/cardPreviews.js" ], "external": [ @@ -5974,6 +5979,7 @@ "src/layers/vessels/lifecycle.js", "src/layers/vessels/policy.js", "src/layers/vessels/queries.js", + "src/data/locate.js", "src/layers/vessels/rendering.js", "src/render/motion/iconBook.js", "src/layers/vessels/iconBook.js", diff --git a/src/data/locate.js b/src/data/locate.js new file mode 100644 index 0000000000..7845820f6b --- /dev/null +++ b/src/data/locate.js @@ -0,0 +1,102 @@ +import { fromDegreesInto } from '../geo/ellipsoid.js'; + +/** + * Finding a selected vessel or aircraft again once it has left the screen or + * its layer's feed: where its own track has it at a time, and whether a point + * is on screen at all. + */ + +/** + * The newest point of a track at or before `atMs` (any time when `atMs` is + * not given), from a live source's `getTrack` records + * (`{observedAtMs, latitude, longitude, baroAltitudeM?}`). + * @param {Array} points + * @param {number} [atMs] + * @returns {{lat: number, lon: number, altitudeM: ?number, observedAtMs: number}|null} + */ +export function readingAt(points, atMs) { + let best = null; + for (const point of points ?? []) { + const lat = Number(point?.latitude); + const lon = Number(point?.longitude); + const observedAtMs = point?.observedAtMs; + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + if (!Number.isFinite(observedAtMs)) continue; + if (Number.isFinite(atMs) && observedAtMs > atMs) continue; + if (best && best.observedAtMs >= observedAtMs) continue; + const altitude = Number(point.baroAltitudeM ?? point.altitudeM); + best = { + lat, + lon, + altitudeM: Number.isFinite(altitude) ? altitude : null, + observedAtMs, + }; + } + return best; +} + +/** + * Where a source's track has a vessel or aircraft at `atMs` (now, when not + * given): `{status: 'found', lat, lon, altitudeM, observedAtMs, atMs}`, or + * `{status: 'none'}` when the track has no point at or before the time, the + * source keeps no tracks or the lookup fails. + * @param {{getTrack?: Function}|null} source + * @param {string} reference The track reference the layer's records carry. + * @param {{atMs?: number, signal?: AbortSignal}} [options] + */ +export async function locateOnTrack(source, reference, { atMs, signal } = {}) { + if (typeof source?.getTrack !== 'function' || !reference) + return { status: 'none' }; + try { + const track = await source.getTrack( + reference, + Number.isFinite(atMs) ? { signal, atMs } : { signal }, + ); + const reading = readingAt(track?.records, atMs); + // The time it was looked up for, so its reading's age can be told. + const at = Number.isFinite(atMs) ? atMs : Date.now(); + return reading + ? { status: 'found', ...reading, atMs: at } + : { status: 'none' }; + } catch (error) { + if (signal?.aborted) throw error; + return { status: 'none' }; + } +} + +/** Mean Earth radius (m), for the horizon test. */ +const EARTH_RADIUS_M = 6_371_000; + +/** + * Whether a point is in the camera's view: in front of it, inside its field + * of view and on the near side of the globe. + * @param {{position: {x, y, z}, direction: {x, y, z}, up: {x, y, z}, + * right: {x, y, z}, fovy: number, aspectRatio: number}} pose + * @param {number} lat + * @param {number} lon + * @param {number} [heightM] + * @returns {boolean} + */ +export function onScreen(pose, lat, lon, heightM = 0) { + if (!pose?.position || !Number.isFinite(lat) || !Number.isFinite(lon)) + return false; + const p = fromDegreesInto(lon, lat, Math.max(0, heightM || 0), { + x: 0, + y: 0, + z: 0, + }); + const c = pose.position; + const v = { x: p.x - c.x, y: p.y - c.y, z: p.z - c.z }; + const dot = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z; + const ahead = dot(v, pose.direction); + if (!(ahead > 0)) return false; + const tanY = Math.tan(pose.fovy / 2); + const tanX = tanY * (pose.aspectRatio || 1); + if (Math.abs(dot(v, pose.right) / ahead) > tanX) return false; + if (Math.abs(dot(v, pose.up) / ahead) > tanY) return false; + // Behind the globe: the camera is below the point's horizon plane. Judged + // on a sphere through the point, which is close enough for a button. + const length = Math.hypot(p.x, p.y, p.z) || EARTH_RADIUS_M; + const normal = { x: p.x / length, y: p.y / length, z: p.z / length }; + return dot({ x: c.x - p.x, y: c.y - p.y, z: c.z - p.z }, normal) > 0; +} diff --git a/src/data/locate.test.mjs b/src/data/locate.test.mjs new file mode 100644 index 0000000000..f0fde4ed2c --- /dev/null +++ b/src/data/locate.test.mjs @@ -0,0 +1,114 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { locateOnTrack, onScreen, readingAt } from './locate.js'; +import { fromDegreesInto } from '../geo/ellipsoid.js'; + +const point = (observedAtMs, latitude, longitude, extra = {}) => ({ + observedAtMs, + latitude, + longitude, + ...extra, +}); + +test('the reading at a time is the newest point at or before it', () => { + const track = [ + point(3_000, 3, 30), + point(1_000, 1, 10, { baroAltitudeM: 900 }), + point(2_000, 2, 20), + point(Number.NaN, 9, 90), + point(4_000, Number.NaN, 40), + ]; + assert.deepEqual(readingAt(track, 2_500), { + lat: 2, + lon: 20, + altitudeM: null, + observedAtMs: 2_000, + }); + assert.equal(readingAt(track, 1_000).altitudeM, 900, 'at its own time'); + assert.equal(readingAt(track).observedAtMs, 3_000, 'no time: the newest'); + assert.equal(readingAt(track, 500), null, 'before its first point'); + assert.equal(readingAt([], 500), null); +}); + +test('a track lookup asks for the time and reads the point at it', async () => { + const asked = []; + const source = { + async getTrack(reference, options) { + asked.push([reference, options.atMs]); + return { records: [point(1_000, 1, 10), point(5_000, 5, 50)] }; + }, + }; + assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 2_000 }), { + status: 'found', + lat: 1, + lon: 10, + altitudeM: null, + observedAtMs: 1_000, + atMs: 2_000, + }); + assert.deepEqual(asked, [['vessel:a', 2_000]]); + assert.deepEqual(await locateOnTrack(source, 'vessel:a', { atMs: 500 }), { + status: 'none', + }); + const live = await locateOnTrack(source, 'vessel:a'); + assert.equal(live.observedAtMs, 5_000, 'live: its newest point'); + assert.equal(asked.at(-1)[1], undefined, 'live asks for no time'); +}); + +test('a source without tracks, or one that fails, finds nothing', async () => { + assert.deepEqual(await locateOnTrack({}, 'a'), { status: 'none' }); + assert.deepEqual(await locateOnTrack(null, 'a'), { status: 'none' }); + const failing = { + getTrack: async () => { + throw new Error('down'); + }, + }; + assert.deepEqual(await locateOnTrack(failing, 'a'), { status: 'none' }); + assert.deepEqual( + await locateOnTrack({ getTrack: async () => ({ records: [] }) }, ''), + { status: 'none' }, + 'no reference', + ); +}); + +/** A camera 1000 km above a point, looking straight down. */ +function poseAbove(lat, lon) { + const at = fromDegreesInto(lon, lat, 0, { x: 0, y: 0, z: 0 }); + const length = Math.hypot(at.x, at.y, at.z); + const up = { x: at.x / length, y: at.y / length, z: at.z / length }; + const position = { + x: at.x + up.x * 1e6, + y: at.y + up.y * 1e6, + z: at.z + up.z * 1e6, + }; + const direction = { x: -up.x, y: -up.y, z: -up.z }; + // North-ish screen up, east right: any pair at right angles will do. + const east = { + x: -Math.sin((lon * Math.PI) / 180), + y: Math.cos((lon * Math.PI) / 180), + z: 0, + }; + const north = { + x: up.y * east.z - up.z * east.y, + y: up.z * east.x - up.x * east.z, + z: up.x * east.y - up.y * east.x, + }; + return { + position, + direction, + up: north, + right: east, + fovy: Math.PI / 3, + aspectRatio: 1.5, + }; +} + +test('a point is on screen in view, and not out of view or behind the globe', () => { + const pose = poseAbove(10, 20); + assert.equal(onScreen(pose, 10, 20), true, 'under the camera'); + assert.equal(onScreen(pose, 11, 21), true, 'near it'); + assert.equal(onScreen(pose, 30, 20), false, 'outside the view'); + assert.equal(onScreen(pose, -10, -160), false, 'the far side of the globe'); + assert.equal(onScreen(pose, Number.NaN, 20), false, 'no position'); + assert.equal(onScreen(null, 10, 20), false, 'no camera'); +}); diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index fd73175edf..a21ba50c5f 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -4739,5 +4739,9 @@ "Select a map item to see its details.": "اختر عنصرًا على الخريطة لرؤية تفاصيله.", "Bilawal on {site}": "بلال على {site}", "Bilawal's website": "موقع بلال الإلكتروني", - "BACK": "رجوع" + "BACK": "رجوع", + "Finding it…": "جارٍ البحث عنه…", + "No reading at this time": "لا توجد قراءة في هذا الوقت", + "Last reading · {age}": "آخر قراءة · {age}", + "Find it": "اعثر عليه" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 9f18360ee8..19e2c44d82 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -4315,5 +4315,9 @@ "Select a map item to see its details.": "Wähle ein Kartenelement aus, um seine Details zu sehen.", "Bilawal on {site}": "Bilawal auf {site}", "Bilawal's website": "Bilawals Website", - "BACK": "ZURÜCK" + "BACK": "ZURÜCK", + "Finding it…": "Wird gesucht…", + "No reading at this time": "Zu dieser Zeit kein Messwert", + "Last reading · {age}": "Letzter Stand · {age}", + "Find it": "Finden" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 8bb3db1509..f7af0945a9 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Selecciona un elemento del mapa para ver sus detalles.", "Bilawal on {site}": "Bilawal en {site}", "Bilawal's website": "Sitio web de Bilawal", - "BACK": "ATRÁS" + "BACK": "ATRÁS", + "Finding it…": "Buscando…", + "No reading at this time": "Sin lectura a esta hora", + "Last reading · {age}": "Última lectura · {age}", + "Find it": "Encontrar" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 26447fb193..83371618bd 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Sélectionnez un élément de la carte pour voir ses détails.", "Bilawal on {site}": "Bilawal sur {site}", "Bilawal's website": "Site web de Bilawal", - "BACK": "RETOUR" + "BACK": "RETOUR", + "Finding it…": "Recherche…", + "No reading at this time": "Aucune donnée à cette heure", + "Last reading · {age}": "Dernière donnée · {age}", + "Find it": "Retrouver" } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 0221989c99..8fffebdc2d 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -4421,5 +4421,9 @@ "Bilawal on YouTube": "בילוואל ב־YouTube", "The studio behind GEV": "הסטודיו שמאחורי GEV", "Open source. Self-host, fork, add a layer.": "קוד פתוח. אירוח עצמאי, יצירת עותק והוספת שכבה.", - "ENTER GOD MODE": "כניסה למצב אלוהים" + "ENTER GOD MODE": "כניסה למצב אלוהים", + "Finding it…": "מחפש…", + "No reading at this time": "אין קריאה בזמן הזה", + "Last reading · {age}": "קריאה אחרונה · {age}", + "Find it": "מצא" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index a6d1bb283d..0894a26b95 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Seleziona un elemento della mappa per vederne i dettagli.", "Bilawal on {site}": "Bilawal su {site}", "Bilawal's website": "Sito web di Bilawal", - "BACK": "INDIETRO" + "BACK": "INDIETRO", + "Finding it…": "Ricerca in corso…", + "No reading at this time": "Nessun dato a quest'ora", + "Last reading · {age}": "Ultimo dato · {age}", + "Find it": "Trova" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 882a005589..2912466cc6 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -4209,5 +4209,9 @@ "Select a map item to see its details.": "地図上の項目を選択すると詳細が表示されます。", "Bilawal on {site}": "{site}のBilawal", "Bilawal's website": "Bilawalのウェブサイト", - "BACK": "戻る" + "BACK": "戻る", + "Finding it…": "検索中…", + "No reading at this time": "この時刻のデータなし", + "Last reading · {age}": "最終データ・{age}", + "Find it": "探す" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index e2a6dc60ed..c67e58da14 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -4421,5 +4421,9 @@ "Select a map item to see its details.": "Selecione um item do mapa para ver seus detalhes.", "Bilawal on {site}": "Bilawal no {site}", "Bilawal's website": "Site de Bilawal", - "BACK": "VOLTAR" + "BACK": "VOLTAR", + "Finding it…": "A procurar…", + "No reading at this time": "Sem leitura nesta hora", + "Last reading · {age}": "Última leitura · {age}", + "Find it": "Encontrar" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index b323df4d5d..a5fff95f77 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -4527,5 +4527,9 @@ "Select a map item to see its details.": "Выберите объект на карте, чтобы увидеть подробности.", "Bilawal on {site}": "Билал на {site}", "Bilawal's website": "Сайт Билала", - "BACK": "НАЗАД" + "BACK": "НАЗАД", + "Finding it…": "Поиск…", + "No reading at this time": "Нет данных на это время", + "Last reading · {age}": "Последние данные · {age}", + "Find it": "Найти" } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index b457512d26..317f70d61d 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -4315,5 +4315,9 @@ "Bilawal on YouTube": "Bilawal på YouTube", "The studio behind GEV": "Studion bakom GEV", "Open source. Self-host, fork, add a layer.": "Öppen källkod. Kör själv, skapa en egen variant, lägg till ett lager.", - "ENTER GOD MODE": "STARTA GUDLÄGE" + "ENTER GOD MODE": "STARTA GUDLÄGE", + "Finding it…": "Söker…", + "No reading at this time": "Ingen avläsning vid den här tiden", + "Last reading · {age}": "Senaste avläsning · {age}", + "Find it": "Hitta" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index edcce4e88d..e57e61af76 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -4527,5 +4527,9 @@ "Select a map item to see its details.": "Виберіть об’єкт на карті, щоб побачити подробиці.", "Bilawal on {site}": "Білал на {site}", "Bilawal's website": "Сайт Білала", - "BACK": "НАЗАД" + "BACK": "НАЗАД", + "Finding it…": "Пошук…", + "No reading at this time": "Немає даних на цей час", + "Last reading · {age}": "Останні дані · {age}", + "Find it": "Знайти" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 05ddb36bc4..f72c5e0b08 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -4209,5 +4209,9 @@ "Select a map item to see its details.": "选择地图上的项目以查看详情。", "Bilawal on {site}": "Bilawal 的 {site} 主页", "Bilawal's website": "Bilawal 的网站", - "BACK": "返回" + "BACK": "返回", + "Finding it…": "正在查找…", + "No reading at this time": "此时无数据", + "Last reading · {age}": "最后数据 · {age}", + "Find it": "查找" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index a84085e7e4..0e481762ed 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -4209,5 +4209,9 @@ "Select a map item to see its details.": "選擇地圖上的項目以查看詳情。", "Bilawal on {site}": "Bilawal 的 {site} 主頁", "Bilawal's website": "Bilawal 的網站", - "BACK": "返回" + "BACK": "返回", + "Finding it…": "正在查找…", + "No reading at this time": "此時無數據", + "Last reading · {age}": "最後數據 · {age}", + "Find it": "查找" } diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index a696165b9a..7ebb9feb12 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -21,6 +21,7 @@ import { followsClock, } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; +import { locateOnTrack } from '../../data/locate.js'; export function createQueries({ flightState, @@ -778,6 +779,46 @@ export function createQueries({ return result; }, + /** + * The track reference of a loaded aircraft, so it can be looked up again + * once it has left the feed (see locate). + * @param {string} icao24 + * @returns {string|null} + */ + referenceOf(icao24) { + const id = String(icao24 ?? '') + .trim() + .toLowerCase(); + if (!id) return null; + return flightState.records.data.get(id)?.sourceReference ?? id; + }, + + /** + * Where an aircraft is at the layer's time (the world clock's while the + * layer follows it, else now), from its own track: for an aircraft that + * has left the feed, so it can be found again. + * @param {string} icao24 + * @param {{reference?: string, signal?: AbortSignal}} [options] + * @returns {Promise<{status: 'found', lat: number, lon: number, + * altitudeM: ?number, observedAtMs: number}|{status: 'none'}>} + */ + locate(icao24, { reference, signal } = {}) { + const atMs = followsClock(flightState) ? flightState.now() : undefined; + return locateOnTrack( + flightState.feed._source, + reference ?? + flightState.records.data.get( + String(icao24 ?? '') + .trim() + .toLowerCase(), + )?.sourceReference ?? + String(icao24 ?? '') + .trim() + .toLowerCase(), + { atMs, signal }, + ); + }, + /** * Ask for an aircraft's scheduled route (origin and destination airports), * as tracking does; it lands on the record when the lookup answers. diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index 52221f6d6e..8b14315781 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -19,6 +19,7 @@ import { followsClock, } from './policy.js'; import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js'; +import { locateOnTrack } from '../../data/locate.js'; export function createQueries({ flightState, @@ -651,6 +652,46 @@ export function createQueries({ return result; }, + /** + * The track reference of a loaded aircraft, so it can be looked up again + * once it has left the feed (see locate). + * @param {string} icao24 + * @returns {string|null} + */ + referenceOf(icao24) { + const id = String(icao24 ?? '') + .trim() + .toLowerCase(); + if (!id) return null; + return flightState.records.data.get(id)?.sourceReference ?? id; + }, + + /** + * Where an aircraft is at the layer's time (the world clock's while the + * layer follows it, else now), from its own track: for an aircraft that + * has left the feed, so it can be found again. + * @param {string} icao24 + * @param {{reference?: string, signal?: AbortSignal}} [options] + * @returns {Promise<{status: 'found', lat: number, lon: number, + * altitudeM: ?number, observedAtMs: number}|{status: 'none'}>} + */ + locate(icao24, { reference, signal } = {}) { + const atMs = followsClock(flightState) ? flightState.now() : undefined; + return locateOnTrack( + flightState.feed._source, + reference ?? + flightState.records.data.get( + String(icao24 ?? '') + .trim() + .toLowerCase(), + )?.sourceReference ?? + String(icao24 ?? '') + .trim() + .toLowerCase(), + { atMs, signal }, + ); + }, + /** * Start camera-tracking an aircraft by ICAO hex identifier. * @param {string} icao24 - ICAO hex identifier of the aircraft. diff --git a/src/layers/vessels/queries.js b/src/layers/vessels/queries.js index d5fa214f0b..e9dbb296bd 100644 --- a/src/layers/vessels/queries.js +++ b/src/layers/vessels/queries.js @@ -27,6 +27,7 @@ import { followsClock, } from './policy.js'; import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js'; +import { locateOnTrack } from '../../data/locate.js'; const UUID_KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -628,6 +629,39 @@ export function createQueries({ return components.selection.selectAndFocusVessel(record); }, + /** + * The track reference of a loaded vessel, so it can be looked up again + * once it has left the feed (see locate). + * @param {string} id + * @returns {string|null} + */ + referenceOf(id) { + if (id === null || id === undefined) return null; + return recordFor(String(id).trim())?.reference ?? null; + }, + + /** + * Where a vessel is at the layer's time (the world clock's while the + * layer follows it, else now), from its own track: for a vessel that has + * left the feed, so it can be found again. + * @param {string} id + * @param {{reference?: string, signal?: AbortSignal}} [options] + * @returns {Promise<{status: 'found', lat: number, lon: number, + * altitudeM: ?number, observedAtMs: number}|{status: 'none'}>} + */ + locate(id, { reference, signal } = {}) { + const atMs = followsClock(vesselState) + ? vesselState.worldNow() + : undefined; + return locateOnTrack( + vesselState._source, + reference ?? + recordFor(String(id ?? '').trim())?.reference ?? + String(id ?? ''), + { atMs, signal }, + ); + }, + /** * Return a subset of vessels for the universal detection overlay. * Deterministic stride sampling distributes selections evenly across the diff --git a/src/ui/entityContextBridge.js b/src/ui/entityContextBridge.js index d431d25225..2090ee4d77 100644 --- a/src/ui/entityContextBridge.js +++ b/src/ui/entityContextBridge.js @@ -1,4 +1,5 @@ import { resolvePickedContext } from '../data/pickedContext.js'; +import { onScreen } from '../data/locate.js'; import { clickCard } from '../data/pickRegistry.js'; import { followedOf, onFollowChanged } from '../data/followed.js'; import { fromDegreesInto } from '../geo/ellipsoid.js'; @@ -136,6 +137,21 @@ export function installEntityContext({ } } + // An item back in its feed after it left it is selected again in its layer, + // as the click that picked it: a vessel is highlighted with its trail, and + // an aircraft found again (`follow`) is followed. + function reselect(card, { follow: andFollow = false } = {}) { + const layer = getDataManager()?.layers?.get?.(card?.layerId)?.module; + const id = card?.identity?.id; + if (!layer || !id) return; + try { + if (card.layerId === 'ais-live-vessels') layer.selectById?.(id); + else if (andFollow && FOLLOWABLE.has(card.layerId)) follow(card); + } catch { + // A layer going away meanwhile has nothing to select. + } + } + // Aircraft can be flown from, and a satellite ridden in the orbital view: // track the craft, then enter Cockpit on it. Only layers the tracking // action can follow are offered (local ADS-B cannot be tracked). @@ -197,6 +213,14 @@ export function installEntityContext({ flyTo, follow, letGo, + reselect, + // Whether the camera shows the card's item; null when it cannot tell. + onScreen: (card) => { + const pose = camera()?.pose(); + if (!pose || !Number.isFinite(card?.lat) || !Number.isFinite(card?.lon)) + return null; + return onScreen(pose, card.lat, card.lon, card.altitudeM ?? 0); + }, isOpen, regionalBrief, // The renderer's card previews, when it has them. @@ -343,7 +367,12 @@ export function installEntityContext({ if (!record?.layerId || inCockpit()) return; store.select({ layerId: record.layerId, - id: record.id, + // A vessel goes by its own id, as a click on it names it, not by the + // context store's (src/data/pickedContext.js). + id: + record.layerId === 'ais-live-vessels' && record.properties?.vesselId + ? String(record.properties.vesselId) + : record.id, label: record.label || record.properties?.name, lat: record.latitude, lon: record.longitude, diff --git a/src/ui/entityContextBridge.test.mjs b/src/ui/entityContextBridge.test.mjs index 025b23df57..c83cdb6e14 100644 --- a/src/ui/entityContextBridge.test.mjs +++ b/src/ui/entityContextBridge.test.mjs @@ -83,3 +83,60 @@ test('Context names nothing under a card painted on top, and keeps its card', (t tap(null, null); assert.equal(clears, cleared, 'a card over open map is not open map'); }); + +// A vessel's layer announces its selection with the context store's id; the +// card names it by the vessel's own id, as a click on it does. +test('a vessel announced by its layer is named by its own id', (t) => { + // The page's events, which Node lacks. + const events = new EventTarget(); + for (const name of [ + 'addEventListener', + 'removeEventListener', + 'dispatchEvent', + ]) + globalThis[name] = events[name].bind(events); + t.after(() => { + for (const name of [ + 'addEventListener', + 'removeEventListener', + 'dispatchEvent', + ]) + delete globalThis[name]; + }); + const pinia = createPinia(); + const viewer = { scene: { pick: () => null, drillPick: () => [] } }; + const input = fakeInput(viewer); + const disconnect = installEntityContext({ + viewer, + getDataManager: () => ({ + isEnabled: () => true, + layers: new Map(), + getAll: () => [], + }), + pinia, + }); + t.after(() => { + disconnect(); + input.destroy(); + }); + const store = useEntityCardStore(pinia); + const named = []; + store.select = (identity) => named.push(identity.id); + globalThis.dispatchEvent( + new CustomEvent('gev:entity-selected', { + detail: { + layerId: 'ais-live-vessels', + id: 'ais-5fdca702', + properties: { vesselId: '5fdca702' }, + latitude: 1, + longitude: 2, + }, + }), + ); + globalThis.dispatchEvent( + new CustomEvent('gev:entity-selected', { + detail: { layerId: 'fires', id: 'fire:1', latitude: 1, longitude: 2 }, + }), + ); + assert.deepEqual(named, ['5fdca702', 'fire:1']); +}); diff --git a/src/ui/kit/entityCardControls.test.mjs b/src/ui/kit/entityCardControls.test.mjs index 5dd3f24587..39406f5709 100644 --- a/src/ui/kit/entityCardControls.test.mjs +++ b/src/ui/kit/entityCardControls.test.mjs @@ -31,9 +31,9 @@ const heroViews = [ test('the entity card hand-writes no button; each is a UiButton', () => { for (const markup of [card, camera, nearby, ...heroViews]) assert.deepEqual(markup.match(/ { for (const markup of [card, camera, nearby, ...heroViews]) assert.deepEqual(markup.match(/material-symbols-outlined/g) ?? [], []); const counts = [ - // The preview switch's three, the hero glyph, the header icon, the - // warning, the route's plane, the route note and the three actions. - [card, 11], + // The preview switch's three, the hero glyph, the header icon, Find + // it, the warning, the route's plane, the route note and the three + // actions. + [card, 12], // Bigger view, the popup's camera and More info. [camera, 3], // The two weather glyphs, five headings and three row glyphs. diff --git a/src/ui/stores/entityCard.js b/src/ui/stores/entityCard.js index a0186fea2c..9fd63cdb3e 100644 --- a/src/ui/stores/entityCard.js +++ b/src/ui/stores/entityCard.js @@ -93,6 +93,26 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { const lost = ref(false); /** Bumped on each refresh, so ages shown on the card tick. */ const tick = ref(0); + /** + * True while the item is not to be seen: out of its feed, off screen or + * behind the globe. The card then offers to find it. + */ + const away = ref(false); + /** + * Finding the item again (see locate): `'idle'`, `'finding'` while its + * layer looks it up, or `'none'` when it has no reading at the time. + */ + const finding = ref('idle'); + /** + * Where an item out of its feed was found (see locate): + * `{lat, lon, altitudeM, observedAtMs, atMs}`, or null. + */ + const located = shallowRef(null); + /** The track reference of the card's item, kept for when it leaves its feed. */ + let reference = null; + let locating = null; + /** An aircraft found again is followed once it is back in its feed. */ + let followWhenBack = false; /** * What the camera shows, for the panel to describe when nothing is picked: * `{center: {lat, lon}, rect: {west, south, east, north}, heightM}`. @@ -229,12 +249,105 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { // 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'; + away.value = lost.value || !shown(current); tick.value++; return; } + const wasLost = lost.value; card.value = markRaw(next); lost.value = false; + // The camera follows it where it is drawn, which can be ahead of its last + // reading; one being followed is always in view. + away.value = !isFollowing() && !shown(next); tick.value++; + if (wasLost) back(next); + } + + /** Whether the camera shows the item; true when the shell cannot tell. */ + function shown(current) { + const test = shell.value?.onScreen; + return typeof test === 'function' ? test(current) !== false : true; + } + + /** + * The item is back in its feed: its layer selects it again, as the click + * that picked it did, and an aircraft just found is followed. + */ + function back(current) { + const follows = followWhenBack; + // A lookup still running is no longer needed: the feed has it. + stopLocating(); + reference = + layerOf(current.layerId)?.referenceOf?.(current.identity?.id) ?? + reference; + shell.value?.reselect?.(current, { follow: follows }); + } + + const layerOf = (layerId) => + shell.value?.dataManager?.()?.layers?.get?.(layerId)?.module ?? null; + + /** + * Take the camera back to the item. One the camera can see or one still in + * its feed is flown to (an aircraft followed); one out of its feed is + * looked up at the layer's time (the world clock's while it follows the + * clock) on its own track, shown there and flown to, and its layer picks + * it up again once its feed has it. + * @returns {Promise} + */ + async function locate() { + const current = card.value; + if (!current) return; + if (!lost.value) { + if (canFollow()) follow(); + else flyTo(); + return; + } + const layer = layerOf(current.layerId); + if (typeof layer?.locate !== 'function') { + flyTo(); + return; + } + locating?.abort(); + const controller = new AbortController(); + locating = controller; + finding.value = 'finding'; + let result; + try { + result = await layer.locate(current.identity?.id, { + reference, + signal: controller.signal, + }); + } catch { + result = { status: 'none' }; + } + if (locating !== controller) return; + locating = null; + const now = card.value; + if (!now || now.key !== current.key) return; + if (result?.status !== 'found') { + finding.value = 'none'; + return; + } + finding.value = 'idle'; + located.value = markRaw({ ...result }); + card.value = markRaw({ + ...now, + lat: result.lat, + lon: result.lon, + altitudeM: Number.isFinite(result.altitudeM) + ? result.altitudeM + : now.altitudeM, + }); + followWhenBack = canFollow(); + shell.value?.flyTo?.(card.value); + } + + function stopLocating() { + locating?.abort(); + locating = null; + finding.value = 'idle'; + located.value = null; + followWhenBack = false; } /** @@ -261,6 +374,11 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { */ function select(identity, { fly = false, follow: autoFollow = true } = {}) { if (!read(identity)) return false; + stopLocating(); + away.value = false; + reference = + layerOf(identity.layerId)?.referenceOf?.(card.value?.identity?.id) ?? + null; clearInterval(timer); timer = setInterval(refresh, REFRESH_MS); shell.value?.openPanel?.(); @@ -292,6 +410,9 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { timer = null; card.value = null; lost.value = false; + away.value = false; + reference = null; + stopLocating(); } const flyTo = () => card.value && shell.value?.flyTo?.(card.value); @@ -324,6 +445,10 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { card, lost, tick, + away, + finding, + located, + locate, connect, select, clear, diff --git a/src/ui/stores/entityCardLocate.test.mjs b/src/ui/stores/entityCardLocate.test.mjs new file mode 100644 index 0000000000..3200bb316e --- /dev/null +++ b/src/ui/stores/entityCardLocate.test.mjs @@ -0,0 +1,154 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createPinia } from 'pinia'; +import { useEntityCardStore } from './entityCard.js'; + +/** + * A vessels layer whose one vessel can leave its feed, and a shell that + * records what the card asks of it. + */ +function setup({ found = true } = {}) { + const vessel = { + id: 'v1', + name: 'ARCADIA', + lat: 1, + lon: 10, + reference: 'vessel:v1', + }; + let inFeed = true; + const asked = []; + const module = { + getAnalystRecords: () => (inFeed ? [{ ...vessel }] : []), + referenceOf: (id) => (id === 'v1' && inFeed ? vessel.reference : null), + async locate(id, { reference }) { + asked.push({ id, reference }); + return found + ? { + status: 'found', + lat: 5, + lon: 50, + altitudeM: null, + observedAtMs: 1_000, + atMs: 61_000, + } + : { status: 'none' }; + }, + }; + const dataManager = { + isEnabled: () => true, + layers: new Map([['ais-live-vessels', { module }]]), + getAll: () => [], + }; + const shell = { + flown: [], + followed: [], + reselected: [], + visible: true, + dataManager: () => dataManager, + openPanel() {}, + flyTo(card) { + shell.flown.push([card.lat, card.lon]); + }, + follow(card) { + shell.followed.push(card.key); + }, + reselect(card, options) { + shell.reselected.push([card.identity.id, options.follow]); + }, + onScreen: () => shell.visible, + canFollow: () => false, + }; + const store = useEntityCardStore(createPinia()); + store.connect(shell); + return { + store, + shell, + asked, + leave: () => (inFeed = false), + come: () => (inFeed = true), + }; +} + +test('a vessel out of its feed is looked up, shown where it was and flown to', async (t) => { + const { store, shell, asked, leave, come } = setup(); + t.after(() => store.clear()); + assert.equal(store.select({ layerId: 'ais-live-vessels', id: 'v1' }), true); + assert.equal(store.away, false, 'on screen and in its feed'); + + leave(); + store.refresh(); + assert.equal(store.lost, true); + assert.equal(store.away, true, 'out of its feed: the card offers to find it'); + + await store.locate(); + assert.deepEqual( + asked, + [{ id: 'v1', reference: 'vessel:v1' }], + 'by the reference it had', + ); + assert.equal(store.card.lat, 5); + assert.equal(store.card.lon, 50); + assert.deepEqual(shell.flown, [[5, 50]]); + assert.equal(store.located.observedAtMs, 1_000); + assert.equal(store.finding, 'idle'); + + come(); + store.refresh(); + assert.equal(store.lost, false, 'back in its feed'); + assert.equal(store.located, null); + assert.deepEqual( + shell.reselected, + [['v1', false]], + 'its layer selects it again', + ); +}); + +test('a vessel with no reading at the time says so and stays put', async (t) => { + const { store, shell, leave } = setup({ found: false }); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + leave(); + store.refresh(); + await store.locate(); + assert.equal(store.finding, 'none'); + assert.deepEqual(shell.flown, [], 'the camera stays'); + assert.equal(store.card.lat, 1, 'the card keeps its last reading'); +}); + +test('an item in its feed but off screen is flown to without a lookup', async (t) => { + const { store, shell, asked } = setup(); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + shell.visible = false; + store.refresh(); + assert.equal(store.away, true, 'off screen'); + await store.locate(); + assert.deepEqual(asked, []); + assert.deepEqual(shell.flown, [[1, 10]]); +}); + +test('an item the camera follows is never away, wherever its last reading is', (t) => { + const { store, shell } = setup(); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + shell.visible = false; + store.following = store.card.key; + store.refresh(); + assert.equal(store.away, false); +}); + +test('a lookup still running when the item comes back is dropped', async (t) => { + const { store, shell, leave, come } = setup(); + t.after(() => store.clear()); + store.select({ layerId: 'ais-live-vessels', id: 'v1' }); + leave(); + store.refresh(); + const pending = store.locate(); + come(); + store.refresh(); + await pending; + assert.equal(store.lost, false); + assert.equal(store.located, null, 'no old reading on a live card'); + assert.equal(store.card.lat, 1, 'the card keeps its live position'); + assert.deepEqual(shell.flown, [], 'the camera stays'); +}); diff --git a/src/ui/styles/entity-card.css b/src/ui/styles/entity-card.css index 223acca6e2..4d4a9d01c9 100644 --- a/src/ui/styles/entity-card.css +++ b/src/ui/styles/entity-card.css @@ -104,6 +104,33 @@ font-size: 1rem; } +/* Find it: shown while the selected item is off screen or out of its feed. */ +.entity-card__find { + display: grid; + flex: none; + place-items: center; + width: 1.9rem; + height: 1.9rem; + color: #36dcff; + background: rgba(29, 69, 81, 0.35); + border: 1px solid rgba(48, 194, 224, 0.55); + border-radius: 7px; +} + +.entity-card__find:hover, +.entity-card__find:focus-visible { + color: #fff; + background: rgba(48, 194, 224, 0.3); +} + +.entity-card__find:disabled { + opacity: 0.55; +} + +.entity-card__find .material-symbols-outlined { + font-size: 1.1rem; +} + .entity-card__title { margin: 0.55rem 0 0.1rem; overflow-wrap: anywhere; @@ -2180,7 +2207,11 @@ border-radius: 3px; } -.entity-hero:is([data-hero='flight'], [data-hero='satellite'], [data-hero='photo']) { +.entity-hero:is( + [data-hero='flight'], + [data-hero='satellite'], + [data-hero='photo'] +) { height: 168px; background: radial-gradient( ellipse 55% 60% at 50% 55%, diff --git a/src/ui/views/panels/EntityCard.vue b/src/ui/views/panels/EntityCard.vue index fd787d97fc..f76d28c926 100644 --- a/src/ui/views/panels/EntityCard.vue +++ b/src/ui/views/panels/EntityCard.vue @@ -26,7 +26,7 @@ const props = defineProps({ withContacts: Boolean, }); const store = useEntityCardStore(); -const { card, lost, tick } = storeToRefs(store); +const { card, lost, tick, away, finding, located } = storeToRefs(store); // Cameras carry only an id; the CCTV panel's store knows the picked one's name. const { frame: cctvFrame } = storeToRefs(useCctvStore()); const shownTitle = computed(() => { @@ -56,6 +56,15 @@ const status = computed(() => { void tick.value; const current = card.value; if (!current) return null; + if (finding.value === 'finding') return { tone: 'aged', text: t('Finding it…') }; + if (finding.value === 'none') return { tone: 'lost', text: t('No reading at this time') }; + if (lost.value && located.value) + return { + tone: 'aged', + text: t('Last reading · {age}', { + age: ago(Math.max(0, located.value.atMs - located.value.observedAtMs)), + }), + }; if (lost.value) return { tone: 'lost', text: t('Out of feed · last reading') }; if (current.observedAgeMs !== null) return { @@ -399,6 +408,7 @@ watch(

{{ shownTitle }}

{{ subtitle }} + From c586087147c35a34e290a4bf6f2e9e37c81c6d18 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 15:40:48 -0800 Subject: [PATCH 07/24] Add the changelog entry for #1870 --- changelog.d/1870-find-it.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1870-find-it.md diff --git a/changelog.d/1870-find-it.md b/changelog.d/1870-find-it.md new file mode 100644 index 0000000000..6e70db31ca --- /dev/null +++ b/changelog.d/1870-find-it.md @@ -0,0 +1,4 @@ +- A selected vessel or aircraft can be found again from its card: while it is + off screen or has left its feed (the clock moved, or the view moved away), + Find it flies back to it, looking it up where it was at the clock's time + when the feed no longer has it (samehkhamis, #1870). From 33ac0545efafe1679a4357347aaf83a4d5c96e79 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 15:48:50 -0800 Subject: [PATCH 08/24] Street Level photo viewer: settle opens, a gapless picker, a stated contract Follow-ups to the photo viewer's move to a Vue view (#1868): - A panorama's open waits for a draw of the canvas counted from before it is shown, so a view that draws at once inside its listener no longer leaves the open pending; and when the last view unsubscribes, an open waiting on a draw goes on instead of hanging. - photoViewers.js supersedes the mounts not drawn on a microtask, after the winning presentation has reached every subscriber: a second subscriber sees the earlier mount, then the later one, never null between. - A presentation without a mountKey counts as the latest mount (among several without, the one that began presenting last), and one without actions or supersede is passed over without throwing. Both fields are documented on ViewerAdapter.subscribeView in registry.js and in the store's comment. - The guard test also refuses .width, .height, .ariaLabel, .id and .value writes in photoViewer.js, and .src writes outside loadImage, where only the off-page Image it creates may take one. - The test fakes draw every viewer through one shared view behind photoViewers.js's picker, as the application does, so provider and layer tests see supersede. Nothing changes in the running app. Co-authored-by: Manjunath Paparaju --- docs/CURRENT-STATE.md | 5 +- src/layers/streetLevel/photoViewer.js | 61 ++++++++----- src/layers/streetLevel/photoViewer.test.mjs | 91 ++++++++++++++++++++ src/layers/streetLevel/photoViewers.js | 64 ++++++++++---- src/layers/streetLevel/photoViewers.test.mjs | 80 ++++++++++++++++- src/layers/streetLevel/registry.js | 9 +- src/testSupport/kartaViewFakes.mjs | 49 +++++++++-- src/ui/kit/streetLevelPhotoControls.test.mjs | 18 +++- src/ui/stores/streetLevelPhoto.js | 9 +- 9 files changed, 337 insertions(+), 49 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 06c3093d7d..ce7a0e21c7 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -6354,8 +6354,9 @@ viewer host and hands back the canvas the panorama is drawn on (a fresh one after a lost context). Each mount and each canvas has a key of its own, so a viewer never draws on another one's elements, and of two viewers mounting at once only the later one is drawn (`photoViewers.js`): the -earlier one's mount closes. Without a subscribed view these photos cannot -open. +earlier one's mount closes. A view may draw at once or later; what it +reads (`mountKey`, `actions.supersede()`) is `ViewerAdapter.subscribeView` +in `registry.js`. Without a subscribed view these photos cannot open. Panoramax (`providers/panoramax/`) is keyless and browser-side: the meta-catalogue `api.panoramax.xyz` (CORS open) federates every instance, and diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index c9b9f48a11..f802777e78 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -228,13 +228,15 @@ export function panoSizeFor(canvasPixels, fovDeg) { * each change, * or null while unmounted. A view draws it into `host` (the application's is * `StreetLevelPhotoViewer`), forwards its events to `actions` and hands each - * element back through `actions.attach(name, element)`: the panorama canvas - * to draw on, the frame and picture to measure, the root and buttons to - * keep focus. Each mount has its own `mountKey`, and a new `canvasKey` asks - * for a fresh canvas (a lost WebGL context): neither is ever reused. - * `actions.supersede()` tells a viewer another one is drawn in its place: - * it unmounts, and a mount still waiting to be drawn fails as closed. - * Mounting with no view subscribed fails. + * element back through `actions.attach(name, element)` on every draw: the + * panorama canvas to draw on, the frame and picture to measure, the root + * and buttons to keep focus. A view may draw at once, inside its listener, + * or later (Vue draws on a microtask). Each mount has its own `mountKey`, + * and a new `canvasKey` asks for a fresh canvas (a lost WebGL context): + * neither is ever reused. `actions.supersede()` tells a viewer another one + * is drawn in its place: it unmounts, and a mount still waiting to be drawn + * fails as closed. Mounting with no view subscribed fails; an open waiting + * on a draw when the last view leaves goes on without it. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -284,6 +286,8 @@ export function createPhotoViewer({ /** Waiting for the view's root (a mount), or its canvas: a fresh one, or the next draw. */ const rootWaiters = new Set(); const canvasWaiters = new Set(); + /** How many times the view has handed the canvas back (once per draw). */ + let canvasDraws = 0; let renderer = null; /** WebGL failed once: 360° photos show their front view instead. */ let rendererFailed = false; @@ -396,22 +400,28 @@ export function createPhotoViewer({ waiters.clear(); } - /** The panorama canvas once the view has drawn it, or the open stopped. */ - function canvasReady(signal) { - if (canvas || !presented || signal?.aborted) return Promise.resolve(); + /** A draw of the canvas, or none coming: unmounted, no view, or the open stopped. */ + function canvasDrawn(drawn, signal) { + if (drawn() || !presented || !viewListeners.size || signal?.aborted) + return Promise.resolve(); return new Promise((resolve) => { canvasWaiters.add(resolve); signal?.addEventListener?.('abort', resolve, { once: true }); }); } - /** The view's next draw (it hands the canvas back each time), or none coming. */ - function nextDraw(signal) { - if (!presented || signal?.aborted) return Promise.resolve(); - return new Promise((resolve) => { - canvasWaiters.add(resolve); - signal?.addEventListener?.('abort', resolve, { once: true }); - }); + /** The panorama canvas once the view has drawn it, or the open stopped. */ + function canvasReady(signal) { + return canvasDrawn(() => Boolean(canvas), signal); + } + + /** + * A draw of the canvas after the `count`th (it hands the canvas back each + * time), or none coming. A view may draw synchronously, inside the + * presentation, before anything waits: counted, that draw is not missed. + */ + function drawnAfter(count, signal) { + return canvasDrawn(() => canvasDraws > count, signal); } function syncButtons() { @@ -667,7 +677,10 @@ export function createPhotoViewer({ if (presented?.actions !== actions || !element) return; ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); - if (name === 'canvas') wake(canvasWaiters); + if (name === 'canvas') { + canvasDraws++; + wake(canvasWaiters); + } }, keydown: current(onKeyDown), pointerdown: current(onPointerDown), @@ -865,9 +878,11 @@ export function createPhotoViewer({ renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG }); photo = target; // Shown first: a hidden canvas measures 0 and would be sized 1×1. The - // view draws it shown on a microtask, and hands the canvas back then. + // view draws it shown, at once or on a microtask, and hands the canvas + // back then. + const draws = canvasDraws; show('pano'); - await nextDraw(signal); + await drawnAfter(draws, signal); if (seq !== openSeq || !renderer) { image.close?.(); if (seq !== openSeq) return false; @@ -1029,7 +1044,11 @@ export function createPhotoViewer({ subscribeView(listener) { viewListeners.add(listener); listener(presented); - return () => viewListeners.delete(listener); + return () => { + // The last view went: an open waiting on its draw goes on without. + if (viewListeners.delete(listener) && !viewListeners.size) + wake(canvasWaiters); + }; }, }; return adapter; diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index 97c8bf4000..e1e9b14f5d 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -636,3 +636,94 @@ test('a panorama reopened after a lost context waits for the view’s fresh canv ); assert.equal(shown.kind, 'pano', 'not the front view'); }); + +/** + * A panorama viewer whose sequence goes on both ways (its ‹ › present no + * change once shown), drawn by `view` alone, not by the shared fake view. + */ +function panoramaViewer() { + const images = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => 'b', + onStep() {}, + load: async (url) => ({ src: url }), + createRenderer: () => ({ + setImage: (image) => images.push(image.src), + setView() {}, + getView: () => ({ yaw: 0, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy() {}, + }), + }); + return { viewer, images }; +} + +/** Elements a view hands back: what the viewer measures and focuses. */ +const elements = () => + Object.fromEntries( + ['root', 'picture', 'canvas', 'prev', 'next'].map((name) => [ + name, + { clientWidth: 400, clientHeight: 250 }, + ]), + ); + +/** Whether `promise` settles within a few macrotasks. */ +const settles = (promise) => + Promise.race([ + promise.then( + () => true, + () => true, + ), + new Promise((resolve) => setTimeout(() => resolve(false), 50)), + ]); + +test('a view that draws at once, inside its listener, opens a panorama', async () => { + const { viewer, images } = panoramaViewer(); + const parts = elements(); + const unsubscribe = viewer.subscribeView((view) => { + if (!view) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }); + await viewer.mount(fakeHost()); + assert.equal(await settles(viewer.open('a')), true, 'not left pending'); + assert.deepEqual(images, ['a-first']); + viewer.unmount(); + unsubscribe(); +}); + +test('an open waiting on the view’s draw goes on when the view unsubscribes', async () => { + const { viewer } = panoramaViewer(); + const parts = elements(); + const kinds = []; + // Draws the mount, then nothing more. + const unsubscribe = viewer.subscribeView((view) => { + if (!view) return; + kinds.push(view.kind); + if (kinds.length > 1) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }); + await viewer.mount(fakeHost()); + const opening = viewer.open('a'); + assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw'); + unsubscribe(); + assert.equal(await settles(opening), true, 'not left pending'); + viewer.unmount(); +}); + +test('the shared fake view draws only the later of two mounts, as the app does', async () => { + const one = setup(); + const two = setup(); + await one.viewer.mount(one.host); + assert.equal(one.host.children.length, 1); + await two.viewer.mount(one.host); + assert.equal(one.host.children.length, 1, 'one root, not one per viewer'); + await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded'); + two.viewer.unmount(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index ecf4eab5a1..bb1ddf404f 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,37 +1,70 @@ /** * Receive the photo viewer to draw, out of several photo viewers mounting - * in one host (see photoViewer.js): the one mounted last, by its mount key, - * whatever order they present in. One view draws one viewer, so a viewer - * still mounting when a later one presents is superseded: it settles its - * mount as closed and stops presenting. Starts with the current one (null - * while none is mounted). + * in one host (see photoViewer.js): the one mounted last, whatever order + * they present in. One view draws one viewer, so a viewer still mounting + * when a later one presents is superseded: it settles its mount as closed + * and stops presenting. Starts with the current one (null while none is + * mounted). + * + * Two fields of a presentation are read here (see ViewerAdapter.subscribeView + * in registry.js): + * - `mountKey`, a number larger for each later mount, orders the mounts. A + * presentation without one counts as the latest mount; among several + * without, the one that began presenting last is. + * - `actions.supersede()`, where present, is called on each presentation + * not drawn once the pick changes. It runs on a microtask, after the + * presentation that won has reached every subscriber: a subscriber never + * sees the superseded one withdraw before it sees the one replacing it. * @param {Iterable<{subscribeView?: Function}>} viewers * @param {(view: ?object) => void} listener * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation. + // Each viewer's current presentation, and when it began presenting. const shown = new Map(); + let arrivals = 0; let ready = false; + let closed = false; + let superseding = false; let last; + /** Whether `a` was mounted after `b`. */ + const later = (a, b) => { + const key = ({ view }) => + Number.isFinite(view.mountKey) ? view.mountKey : Infinity; + const ka = key(a); + const kb = key(b); + return ka !== kb ? ka > kb : a.arrival > b.arrival; + }; + // The others are not drawn: a mount still waiting on the view never + // would be. + const supersede = () => { + superseding = false; + if (closed || !last) return; + for (const { view } of [...shown.values()]) + if (view !== last) view.actions?.supersede?.(); + }; const publish = () => { let next = null; - for (const view of shown.values()) - if (!next || view.mountKey > next.mountKey) next = view; + for (const entry of shown.values()) + if (!next || later(entry, next)) next = entry; + next = next?.view ?? null; if (!ready || next === last) return; last = next; listener(next); - // The others are not drawn: a mount still waiting on the view never - // would be. - if (next) - for (const view of [...shown.values()]) - if (view.mountKey < next.mountKey) view.actions.supersede(); + if (next && shown.size > 1 && !superseding) { + superseding = true; + queueMicrotask(supersede); + } }; const unsubscribes = []; for (const viewer of viewers) { const unsubscribe = viewer?.subscribeView?.((view) => { - if (view) shown.set(viewer, view); - else shown.delete(viewer); + if (closed) return; + const entry = shown.get(viewer); + if (!view) shown.delete(viewer); + else if (entry && entry.view.mountKey === view.mountKey) + entry.view = view; + else shown.set(viewer, { view, arrival: ++arrivals }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); @@ -40,6 +73,7 @@ export function subscribePhotoViewers(viewers, listener) { publish(); if (last === undefined) listener((last = null)); return () => { + closed = true; for (const unsubscribe of unsubscribes.splice(0)) unsubscribe(); }; } diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index a4525723bc..f9b3f609d6 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -29,7 +29,7 @@ function fakeViewer() { return viewer; } -test('the later mount is drawn, whatever order the viewers present in', () => { +test('the later mount is drawn, whatever order the viewers present in', async () => { const a = fakeViewer(); const b = fakeViewer(); const shown = []; @@ -40,6 +40,8 @@ test('the later mount is drawn, whatever order the viewers present in', () => { const later = b.view(2); b.present(later); assert.equal(shown.at(-1), later); + // Once every subscriber has the later one. + await Promise.resolve(); assert.equal(a.superseded, 1, 'the earlier mount is told it is not drawn'); // The earlier viewer presents again: it does not take the view back. a.present({ ...first, kind: 'flat' }); @@ -53,3 +55,79 @@ test('the later mount is drawn, whatever order the viewers present in', () => { a.present(first); assert.equal(shown.length, 5, 'unsubscribed'); }); + +/** A viewer that, superseded, unmounts as photoViewer.js does: it presents null. */ +function unmountingViewer() { + const viewer = fakeViewer(); + const view = viewer.view; + viewer.view = (mountKey) => { + const presented = view(mountKey); + const supersede = presented.actions.supersede; + presented.actions.supersede = () => { + supersede(); + viewer.present(null); + }; + return presented; + }; + return viewer; +} + +test('every subscriber sees the earlier mount, then the later one, with no gap', async () => { + const a = unmountingViewer(); + const b = unmountingViewer(); + const first = []; + const second = []; + const unsubscribes = [ + subscribePhotoViewers([a, b], (view) => first.push(view)), + subscribePhotoViewers([a, b], (view) => second.push(view)), + ]; + const earlier = a.view(1); + a.present(earlier); + const later = b.view(2); + b.present(later); + await Promise.resolve(); + assert.equal(a.superseded, 1, 'superseded once, by both'); + assert.deepEqual(first, [null, earlier, later]); + assert.deepEqual(second, [null, earlier, later], 'never null between'); + for (const unsubscribe of unsubscribes) unsubscribe(); +}); + +test('a presentation without a mount key counts as the latest mount', () => { + const a = fakeViewer(); + const b = fakeViewer(); + const c = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b, c], (view) => + shown.push(view), + ); + a.present(a.view(5)); + const keyless = { actions: {} }; + b.present(keyless); + assert.equal(shown.at(-1), keyless, 'after the keyed one'); + // A keyed mount presenting later does not take it back. + a.present(a.view(6)); + assert.equal(shown.at(-1), keyless); + // Of two without, the one that began presenting last. + const newer = { actions: {} }; + c.present(newer); + assert.equal(shown.at(-1), newer); + b.present({ ...keyless, kind: 'flat' }); + assert.equal(shown.at(-1), newer, 'presenting again is not a new mount'); + unsubscribe(); +}); + +test('a presentation without actions or supersede is drawn and passed over without throwing', async () => { + const a = fakeViewer(); + const b = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view)); + a.present({ mountKey: 1 }); + const later = { mountKey: 2, actions: {} }; + assert.doesNotThrow(() => b.present(later)); + await Promise.resolve(); + assert.equal(shown.at(-1), later); + a.present({ mountKey: 3 }); + await Promise.resolve(); + assert.equal(shown.at(-1).mountKey, 3); + unsubscribe(); +}); diff --git a/src/layers/streetLevel/registry.js b/src/layers/streetLevel/registry.js index b74cfcdc99..177028d570 100644 --- a/src/layers/streetLevel/registry.js +++ b/src/layers/streetLevel/registry.js @@ -65,7 +65,14 @@ export function filtersOf(provider) { * @property {(listener: (pose: StreetPose) => void) => () => void} onPose * @property {(listener: (view: ?object) => void) => () => void} [subscribeView] * An adapter that draws nothing itself presents its viewer here, for the - * layer's `subscribePhotoViewer()` (see photoViewer.js). + * layer's `subscribePhotoViewer()` (see photoViewer.js): its current + * presentation at once, then each new one, null while unmounted. One view + * draws one viewer (photoViewers.js picks it), reading two fields: + * `mountKey`, a number larger for each later mount (the later mount is + * drawn; a presentation without one counts as the latest), and + * `actions.supersede()`, called on a mount that is not drawn because a + * later one is (it should unmount, failing a mount still waiting to be + * drawn; an adapter without it is simply not drawn). * * @typedef {object} StreetPose * @property {string} providerId diff --git a/src/testSupport/kartaViewFakes.mjs b/src/testSupport/kartaViewFakes.mjs index 83ed5f38f5..c4b5ba5cce 100644 --- a/src/testSupport/kartaViewFakes.mjs +++ b/src/testSupport/kartaViewFakes.mjs @@ -1,4 +1,5 @@ // DOM stand-ins for the KartaView viewer's tests (no browser in Node). +import { subscribePhotoViewers } from '../layers/streetLevel/photoViewers.js'; /** A DOM element with what the viewer touches: children, events, attributes. */ function fakeElement(tag) { @@ -71,7 +72,45 @@ export function fakeHost(viewer = null) { } /** - * Draw a photo viewer's presentations with fake elements, as + * The one view of the photo viewers given to `drawPhotoViewer`, as the + * application has one StreetLevelPhotoViewer: the viewers reach it through + * photoViewers.js's picker, as the layer's `subscribePhotoViewer()` does, + * so only the mount made last is drawn and the earlier ones are superseded. + */ +const shared = { + viewers: new Set(), + draw: null, + unsubscribe: null, + generation: 0, +}; + +/** Subscribe the view to the viewers it has now, then let the old picker go. */ +function resubscribe() { + const previous = shared.unsubscribe; + const generation = ++shared.generation; + // The new picker first: a viewer is never left without a view. + shared.unsubscribe = subscribePhotoViewers([...shared.viewers], (view) => { + if (generation === shared.generation) shared.draw(view); + }); + previous?.(); +} + +/** + * Draw a photo viewer with the shared view, alongside every other viewer + * given here (see `shared`). + * @returns {() => void} Stop drawing it. + */ +export function drawPhotoViewer(viewer) { + shared.draw ??= photoView(); + shared.viewers.add(viewer); + resubscribe(); + return () => { + if (shared.viewers.delete(viewer)) resubscribe(); + }; +} + +/** + * A view drawing the presentations it is given with fake elements, as * StreetLevelPhotoViewer does through Vue: changes made in one tick are * drawn once, on a microtask, with their final value; the root (keyed by * the mount) holds the picture, the panorama canvas (keyed by its canvas @@ -79,9 +118,9 @@ export function fakeHost(viewer = null) { * is handed back on each draw. A value is written only when the drawn * presentation changes it, and the elements' events reach the viewer's * actions. - * @returns {() => void} Stop drawing. + * @returns {(view: ?object) => void} Draw this presentation. */ -export function drawPhotoViewer(viewer) { +function photoView() { let parts = null; let last = null; let pending = null; @@ -162,7 +201,7 @@ export function drawPhotoViewer(viewer) { for (const name of ['root', 'picture', 'canvas', 'prev', 'next']) view.actions.attach(name, parts[name]); }; - return viewer.subscribeView((view) => { + return (view) => { pending = view; if (queued) return; queued = true; @@ -170,7 +209,7 @@ export function drawPhotoViewer(viewer) { queued = false; draw(pending); }); - }); + }; } /** diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index be1d65a8b5..5f20b03faf 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -74,10 +74,20 @@ test('the step buttons are not pressed toggles', () => { } }); +/** + * `loadImage`, which downloads through an Image of its own that is never on + * the page: the one place a `.src` is written. + */ +const LOADER = /^export function loadImage\([\s\S]*?^}$/m; + test('the photo viewer is drawn by its view, and its layer needs no Vue', () => { const source = read(VIEWER); + const loader = source.match(LOADER)?.[0]; + assert.ok(loader, 'loadImage is found'); + const rest = source.replace(LOADER, ''); // No element made, inserted, moved, removed or written: the view does - // all of that. (An Image the loader downloads with is not on the page.) + // all of that. (The panorama renderer in panorama.js sizes its canvas's + // drawing buffer, as WebGL drawing does; nothing here does.) for (const write of [ /createElement/, /\b(?:inner|outer)HTML\b/, @@ -87,9 +97,15 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /\.(?:set|remove|toggle)Attribute(?:NS)?\(/, /\.(?:classList|className|dataset|style)\b/, /\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/, + /\.(?:width|height|ariaLabel|id|value)\s*=[^=]/, /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); + assert.doesNotMatch(rest, /\.src\s*=[^=]/, 'a .src written on the page'); + // In loadImage, only on the off-page Image it creates. + assert.match(loader, /\bconst image = new Image\(\);/); + for (const [write] of loader.matchAll(/[\w$.\]]+\.src\s*=(?!=)/g)) + assert.match(write, /^image\.src\s*=$/, write); const markup = template(VIEW); const opening = (name, attribute) => new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`); diff --git a/src/ui/stores/streetLevelPhoto.js b/src/ui/stores/streetLevelPhoto.js index dc0ebffacb..b9498452b3 100644 --- a/src/ui/stores/streetLevelPhoto.js +++ b/src/ui/stores/streetLevelPhoto.js @@ -10,9 +10,12 @@ export const useStreetLevelPhotoStore = defineStore( 'gev-street-level-photo', () => { /** - * `{host, providerId, label, alt, kind, src, fit, canvasKey, dragging, - * prevLabel, prevDisabled, nextLabel, nextDisabled, actions}`, or null - * while no photo viewer is mounted. + * `{host, mountKey, providerId, label, alt, kind, src, fit, canvasKey, + * dragging, prevLabel, prevDisabled, nextLabel, nextDisabled, actions}`, + * or null while no photo viewer is mounted. Of the viewers mounting in + * the host, only the one mounted last (the largest `mountKey`) is + * published; `actions.supersede()` tells the others they are not drawn + * (see `ViewerAdapter.subscribeView` in src/layers/streetLevel/registry.js). */ const photo = shallowRef(null); From e6f21777babd296f71a084e37a3d9c54ef197e33 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:04:21 -0800 Subject: [PATCH 09/24] Street Level photo viewer: keyless ranking, closed waits, a moved canvas Review follow-ups to the previous commit: - photoViewers.js ranks a presentation without a mountKey as mounted when it began presenting (after the latest key seen, before any later mount), so a photo viewer mounting while a keyless one shows is drawn and the keyless one superseded; supersede is queued whenever more than one presents after any change, not only when the pick changes. - A panorama's open still waiting on a draw when the last view leaves fails as closed and leaves no photo shown, instead of uploading to a canvas never drawn. A mount waiting on its first draw then also fails as closed and is unmounted, so a view subscribing later sees nothing. - A view handing back another canvas element than the renderer's drops the renderer and draws the panorama again on the new one, as after a lost context. - The guard test allows a .src write in loadImage only on the one `image` binding, created by new Image() and never rebound or shadowed, and refuses `(expr).src =` and bracket property writes anywhere. - The test fakes' shared view is reset before each test (resetPhotoView), so a viewer left by an earlier test is neither drawn with nor superseded by a later test's. Nothing changes in the running app. Co-authored-by: Manjunath Paparaju --- src/layers/streetLevel/photoViewer.js | 79 ++++++++++--- src/layers/streetLevel/photoViewer.test.mjs | 107 +++++++++++++++++- src/layers/streetLevel/photoViewers.js | 45 +++++--- src/layers/streetLevel/photoViewers.test.mjs | 67 ++++++++++- .../providers/kartaview/provider.test.mjs | 4 + .../providers/kartaview/viewer.test.mjs | 4 + .../providers/panoramax/provider.test.mjs | 4 + .../providers/panoramax/viewer.test.mjs | 9 +- src/layers/streetLevel/registry.js | 8 +- src/testSupport/kartaViewFakes.mjs | 15 ++- src/ui/kit/streetLevelPhotoControls.test.mjs | 35 +++++- 11 files changed, 327 insertions(+), 50 deletions(-) diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index f802777e78..e2d8d14e29 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -159,6 +159,16 @@ async function loadBitmap(url, timeoutMs, resize, failure, signal) { } } +/** + * Unmounted, superseded or left without a view before the view drew what + * was waiting on it (`undrawn`): a mount or an open that fails as closed. + */ +function undrawn() { + return Object.assign(new Error('Street-level viewer was closed'), { + undrawn: true, + }); +} + /** * A picture refused for its size (`tooLarge`): the viewer will not load * that file another way, an having no size limit at all. @@ -235,8 +245,11 @@ export function panoSizeFor(canvasPixels, fovDeg) { * and a new `canvasKey` asks for a fresh canvas (a lost WebGL context): * neither is ever reused. `actions.supersede()` tells a viewer another one * is drawn in its place: it unmounts, and a mount still waiting to be drawn - * fails as closed. Mounting with no view subscribed fails; an open waiting - * on a draw when the last view leaves goes on without it. + * fails as closed. Mounting with no view subscribed fails, and a mount or + * a panorama's open waiting on a draw when the last view leaves fails as + * closed (the mount unmounts; the open leaves no photo shown). A view + * handing back another canvas element than the renderer's (one subscribed + * since) gets the panorama drawn again on it, as after a lost context. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -479,6 +492,27 @@ export function createPhotoViewer({ const from = event?.currentTarget ?? event?.target; if (from && from !== canvas) return; event.preventDefault?.(); + dropRenderer(); + // A lost canvas hands back its lost context: the view draws a new + // element in its place and hands it back. + canvas = null; + present({ canvasKey: ++viewKeys }); + reopen(); + } + + /** + * The view drew the panorama on another canvas element than the + * renderer's (a view that subscribed since): the renderer cannot follow + * it, so the photo is drawn again on a new one, as after a lost context. + */ + function moveCanvas(element) { + dropRenderer(); + canvas = element; + reopen(); + } + + /** Let the renderer go, keeping the user's look for the photo's reopen. */ + function dropRenderer() { const lost = renderer; renderer = null; // The new renderer starts facing the photo's heading: keep the user's look. @@ -489,11 +523,10 @@ export function createPhotoViewer({ } catch { /* already gone */ } - // A lost canvas hands back its lost context: the view draws a new - // element in its place and hands it back. - canvas = null; - present({ canvasKey: ++viewKeys }); - // Show the photo again through the core, unless a newer one is opening. + } + + /** Show the panorama again through the core, unless a newer photo is opening. */ + function reopen() { if (showing === 'pano' && photo && openingId === null) { const again = photo.id; show(null); @@ -675,7 +708,9 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; - ELEMENTS[name]?.(element); + if (name === 'canvas' && renderer && canvas && element !== canvas) + moveCanvas(element); + else ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); if (name === 'canvas') { canvasDraws++; @@ -883,6 +918,14 @@ export function createPhotoViewer({ const draws = canvasDraws; show('pano'); await drawnAfter(draws, signal); + // The last view left before drawing it: the canvas was never shown, and + // nothing is drawn until a view is back. + if (seq === openSeq && canvasDraws === draws && !viewListeners.size) { + image.close?.(); + photo = null; + show(null); + throw undrawn(); + } if (seq !== openSeq || !renderer) { image.close?.(); if (seq !== openSeq) return false; @@ -931,7 +974,8 @@ export function createPhotoViewer({ if (sources.hasPano(target) && ensureRenderer()) { try { shown = await showPano(target, seq, keepView, signal); - } catch { + } catch (error) { + if (error?.undrawn) throw error; // The panorama failed: its front view is better than nothing. if (seq !== openSeq) return; shown = await showFlat(target, seq, signal); @@ -952,12 +996,16 @@ export function createPhotoViewer({ rendererFailed = false; if (!viewListeners.size) throw new Error('Street Level photo viewer has no view to draw it'); - // Resolves once the view drew the viewer, or it was unmounted meanwhile. + // Resolves once the view drew the viewer, or it was unmounted, or its + // last view left, meanwhile. const drawn = new Promise((resolve) => rootWaiters.add(resolve)); build(host); if (!root) await drawn; - // Unmounted or superseded before the view drew it. - if (!root) throw new Error('Street-level viewer was closed'); + if (root) return; + // The last view left before drawing it: no view will. Unmounted, as + // when superseded, so a view subscribing later draws nothing. + if (presented) adapter.unmount(); + throw undrawn(); }, /** Resolves once the photo is on screen and its pose was emitted. */ @@ -1045,9 +1093,12 @@ export function createPhotoViewer({ viewListeners.add(listener); listener(presented); return () => { - // The last view went: an open waiting on its draw goes on without. - if (viewListeners.delete(listener) && !viewListeners.size) + // The last view went: a mount or an open waiting on its draw fails + // as closed. + if (viewListeners.delete(listener) && !viewListeners.size) { + wake(rootWaiters); wake(canvasWaiters); + } }; }, }; diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index e1e9b14f5d..ac3e252885 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -1,7 +1,14 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createPhotoViewer } from './photoViewer.js'; -import { fakeHost, until } from '../../testSupport/kartaViewFakes.mjs'; +import { + fakeHost, + until, + resetPhotoView, +} from '../../testSupport/kartaViewFakes.mjs'; + +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); const PHOTOS = { a: { id: 'a', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true }, @@ -697,12 +704,14 @@ test('a view that draws at once, inside its listener, opens a panorama', async ( unsubscribe(); }); -test('an open waiting on the view’s draw goes on when the view unsubscribes', async () => { - const { viewer } = panoramaViewer(); +test('a panorama’s open waiting on the view’s draw fails as closed when the view leaves', async () => { + const { viewer, images } = panoramaViewer(); const parts = elements(); const kinds = []; + const presented = []; // Draws the mount, then nothing more. const unsubscribe = viewer.subscribeView((view) => { + presented.push(view); if (!view) return; kinds.push(view.kind); if (kinds.length > 1) return; @@ -714,9 +723,85 @@ test('an open waiting on the view’s draw goes on when the view unsubscribes', assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw'); unsubscribe(); assert.equal(await settles(opening), true, 'not left pending'); + await assert.rejects(opening, /viewer was closed/); + assert.deepEqual(images, [], 'nothing uploaded to a canvas never shown'); + // A view back draws the viewer mounted, with no photo shown. + let again = null; + const resubscribe = viewer.subscribeView((view) => (again = view)); + assert.ok(again, 'still mounted'); + assert.equal(again.kind, ''); + resubscribe(); viewer.unmount(); }); +test('a mount waiting on the view’s draw fails as closed when the view leaves, and is unmounted', async () => { + const { viewer } = panoramaViewer(); + const unsubscribe = viewer.subscribeView(() => {}); + const mounting = viewer.mount(fakeHost()); + unsubscribe(); + assert.equal(await settles(mounting), true, 'not left pending'); + await assert.rejects(mounting, /viewer was closed/); + let current; + const resubscribe = viewer.subscribeView((view) => (current = view)); + assert.equal(current, null, 'nothing presented'); + await assert.rejects(viewer.open('a'), /not mounted/); + resubscribe(); +}); + +test('a view handing back another canvas gets the panorama drawn again on it', async () => { + const renderers = []; + const reopened = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => 'b', + onStep() {}, + onReopen: (id) => { + reopened.push(id); + viewer.open(id); + }, + load: async (url) => ({ src: url }), + createRenderer: (canvas) => { + const renderer = { + canvas, + images: [], + destroyed: false, + setImage: (image) => renderer.images.push(image.src), + setView() {}, + getView: () => ({ yaw: 10, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy: () => (renderer.destroyed = true), + }; + renderers.push(renderer); + return renderer; + }, + }); + const drawWith = (parts) => (view) => { + if (!view) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }; + const first = elements(); + const unsubscribe = viewer.subscribeView(drawWith(first)); + await viewer.mount(fakeHost()); + await viewer.open('a'); + assert.equal(renderers[0].canvas, first.canvas); + // Another view takes over, with elements of its own. + const second = elements(); + const resubscribe = viewer.subscribeView(drawWith(second)); + unsubscribe(); + assert.ok(await until(() => renderers[1]?.images.length > 0)); + assert.deepEqual(reopened, ['a']); + assert.equal(renderers[0].destroyed, true); + assert.equal(renderers[1].canvas, second.canvas); + assert.deepEqual(renderers[1].images, ['a-first']); + viewer.unmount(); + resubscribe(); +}); + test('the shared fake view draws only the later of two mounts, as the app does', async () => { const one = setup(); const two = setup(); @@ -727,3 +812,19 @@ test('the shared fake view draws only the later of two mounts, as the app does', await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded'); two.viewer.unmount(); }); + +test('a viewer left by an earlier test is not superseded by a later test’s', async () => { + const earlier = setup(); + await earlier.viewer.mount(earlier.host); + // As before each test. + resetPhotoView(); + const later = setup(); + await later.viewer.mount(later.host); + await tick(); + const opening = earlier.viewer.open('f'); + await until(() => earlier.loads.includes('f-first')); + earlier.release('f-first'); + await opening; + earlier.viewer.unmount(); + later.viewer.unmount(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index bb1ddf404f..d8e0176a98 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -9,31 +9,40 @@ * Two fields of a presentation are read here (see ViewerAdapter.subscribeView * in registry.js): * - `mountKey`, a number larger for each later mount, orders the mounts. A - * presentation without one counts as the latest mount; among several - * without, the one that began presenting last is. + * presentation without one counts as mounted when it began presenting: + * after every mount presenting before it, before any later mount, keyed + * or not. * - `actions.supersede()`, where present, is called on each presentation - * not drawn once the pick changes. It runs on a microtask, after the - * presentation that won has reached every subscriber: a subscriber never - * sees the superseded one withdraw before it sees the one replacing it. + * not drawn, whenever more than one presents. It runs on a microtask, + * after the presentation that won has reached every subscriber: a + * subscriber never sees the superseded one withdraw before it sees the + * one replacing it. * @param {Iterable<{subscribeView?: Function}>} viewers * @param {(view: ?object) => void} listener * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation, and when it began presenting. + // Each viewer's current presentation and its rank, {key, arrival}. const shown = new Map(); let arrivals = 0; + /** The largest mount key seen: a keyless mount ranks just after it. */ + let latestKey = -Infinity; let ready = false; let closed = false; let superseding = false; let last; /** Whether `a` was mounted after `b`. */ - const later = (a, b) => { - const key = ({ view }) => - Number.isFinite(view.mountKey) ? view.mountKey : Infinity; - const ka = key(a); - const kb = key(b); - return ka !== kb ? ka > kb : a.arrival > b.arrival; + const later = (a, b) => + a.key !== b.key ? a.key > b.key : a.arrival > b.arrival; + /** A new mount's rank: its key, or, without one, the latest key seen. */ + const rank = (view) => { + const keyed = Number.isFinite(view.mountKey); + if (keyed) latestKey = Math.max(latestKey, view.mountKey); + return { + key: keyed ? view.mountKey : latestKey, + // A keyed mount comes before a keyless one ranked on its key. + arrival: keyed ? 0 : ++arrivals, + }; }; // The others are not drawn: a mount still waiting on the view never // would be. @@ -48,10 +57,12 @@ export function subscribePhotoViewers(viewers, listener) { for (const entry of shown.values()) if (!next || later(entry, next)) next = entry; next = next?.view ?? null; - if (!ready || next === last) return; - last = next; - listener(next); - if (next && shown.size > 1 && !superseding) { + if (!ready) return; + if (next !== last) { + last = next; + listener(next); + } + if (last && shown.size > 1 && !superseding) { superseding = true; queueMicrotask(supersede); } @@ -64,7 +75,7 @@ export function subscribePhotoViewers(viewers, listener) { if (!view) shown.delete(viewer); else if (entry && entry.view.mountKey === view.mountKey) entry.view = view; - else shown.set(viewer, { view, arrival: ++arrivals }); + else shown.set(viewer, { view, ...rank(view) }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index f9b3f609d6..b27e315b78 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { createPhotoViewer } from './photoViewer.js'; import { subscribePhotoViewers } from './photoViewers.js'; /** @@ -92,7 +93,7 @@ test('every subscriber sees the earlier mount, then the later one, with no gap', for (const unsubscribe of unsubscribes) unsubscribe(); }); -test('a presentation without a mount key counts as the latest mount', () => { +test('a presentation without a mount key counts as mounted when it began presenting', async () => { const a = fakeViewer(); const b = fakeViewer(); const c = fakeViewer(); @@ -101,18 +102,72 @@ test('a presentation without a mount key counts as the latest mount', () => { shown.push(view), ); a.present(a.view(5)); - const keyless = { actions: {} }; + const keyless = b.view(undefined); b.present(keyless); assert.equal(shown.at(-1), keyless, 'after the keyed one'); - // A keyed mount presenting later does not take it back. - a.present(a.view(6)); - assert.equal(shown.at(-1), keyless); // Of two without, the one that began presenting last. - const newer = { actions: {} }; + const newer = c.view(undefined); c.present(newer); assert.equal(shown.at(-1), newer); b.present({ ...keyless, kind: 'flat' }); assert.equal(shown.at(-1), newer, 'presenting again is not a new mount'); + // A keyed mount made after them wins. + const latest = a.view(6); + a.present(latest); + assert.equal(shown.at(-1), latest); + await Promise.resolve(); + assert.ok(b.superseded > 0 && c.superseded > 0, 'the keyless ones are told'); + unsubscribe(); +}); + +test('a presentation that is not drawn is superseded even when the pick stays', async () => { + const a = fakeViewer(); + const b = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view)); + const later = b.view(2); + b.present(later); + // An earlier mount presents once the later one is drawn. + a.present(a.view(1)); + assert.deepEqual(shown, [null, later]); + await Promise.resolve(); + assert.equal(a.superseded, 1); + unsubscribe(); +}); + +test('a photo viewer mounting while a keyless presentation shows is drawn, and the keyless one superseded', async () => { + let superseded = 0; + const keyless = { + subscribeView(listener) { + listener({ actions: { supersede: () => superseded++ } }); + return () => {}; + }, + }; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: {}, + getPhoto: async () => null, + step: async () => null, + onStep() {}, + }); + const shown = []; + const element = { clientWidth: 400, clientHeight: 250 }; + const unsubscribe = subscribePhotoViewers([keyless, viewer], (view) => { + shown.push(view); + if (!view?.mountKey) return; + for (const name of ['root', 'picture', 'canvas', 'prev', 'next']) + view.actions.attach(name, element); + }); + const mounting = viewer.mount({}); + const outcome = await Promise.race([ + mounting.then(() => 'mounted'), + new Promise((resolve) => setTimeout(() => resolve('pending'), 50)), + ]); + assert.equal(outcome, 'mounted'); + assert.ok(Number.isFinite(shown.at(-1)?.mountKey), 'the mount is drawn'); + assert.ok(superseded >= 1, 'the keyless one is told'); + viewer.unmount(); unsubscribe(); }); diff --git a/src/layers/streetLevel/providers/kartaview/provider.test.mjs b/src/layers/streetLevel/providers/kartaview/provider.test.mjs index caf1cd3aef..bb8b167022 100644 --- a/src/layers/streetLevel/providers/kartaview/provider.test.mjs +++ b/src/layers/streetLevel/providers/kartaview/provider.test.mjs @@ -17,6 +17,7 @@ import { drawn, fakeHost, until, + resetPhotoView, } from '../../../../testSupport/kartaViewFakes.mjs'; import { bindStreetViewer, @@ -26,6 +27,9 @@ import { } from '../../../../testSupport/streetLevelFakes.mjs'; import { fakeDrawPort } from '../../../../testSupport/fakeDrawPort.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + /** A photo record `metres` east of (42.3314, -83.0458), in sequence `seq` at `index`. */ function photoRecord(id, { metres = 0, seq = '14010', index = 0 } = {}) { const lon = -83.0458 + metres / 82_300; diff --git a/src/layers/streetLevel/providers/kartaview/viewer.test.mjs b/src/layers/streetLevel/providers/kartaview/viewer.test.mjs index 9c6218d52c..05dabd27a0 100644 --- a/src/layers/streetLevel/providers/kartaview/viewer.test.mjs +++ b/src/layers/streetLevel/providers/kartaview/viewer.test.mjs @@ -5,8 +5,12 @@ import { drawn, fakeHost, until, + resetPhotoView, } from '../../../../testSupport/kartaViewFakes.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + const PHOTOS = { flat1: { id: 'flat1', diff --git a/src/layers/streetLevel/providers/panoramax/provider.test.mjs b/src/layers/streetLevel/providers/panoramax/provider.test.mjs index f26be6d023..99e3a92d77 100644 --- a/src/layers/streetLevel/providers/panoramax/provider.test.mjs +++ b/src/layers/streetLevel/providers/panoramax/provider.test.mjs @@ -18,6 +18,7 @@ import { drawn, fakeHost, until, + resetPhotoView, } from '../../../../testSupport/kartaViewFakes.mjs'; import { bindStreetViewer, @@ -31,6 +32,9 @@ import { stacItem, } from '../../../../testSupport/panoramaxFixtures.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + const ORIGIN = { lon: 2.3495, lat: 48.8874 }; /** A point `metres` east of ORIGIN. */ const east = (metres) => ({ diff --git a/src/layers/streetLevel/providers/panoramax/viewer.test.mjs b/src/layers/streetLevel/providers/panoramax/viewer.test.mjs index 185e9eeb21..ddd97fcc20 100644 --- a/src/layers/streetLevel/providers/panoramax/viewer.test.mjs +++ b/src/layers/streetLevel/providers/panoramax/viewer.test.mjs @@ -2,9 +2,16 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { PANORAMAX_SOURCES, createPanoramaxViewer } from './viewer.js'; import { normalizeItem } from './policy.js'; -import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs'; +import { + fakeHost, + until, + resetPhotoView, +} from '../../../../testSupport/kartaViewFakes.mjs'; import { stacItem } from '../../../../testSupport/panoramaxFixtures.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + const photo = (options) => normalizeItem(stacItem({ lon: 2.35, lat: 48.85, ...options })); diff --git a/src/layers/streetLevel/registry.js b/src/layers/streetLevel/registry.js index 177028d570..b332b61355 100644 --- a/src/layers/streetLevel/registry.js +++ b/src/layers/streetLevel/registry.js @@ -69,10 +69,10 @@ export function filtersOf(provider) { * presentation at once, then each new one, null while unmounted. One view * draws one viewer (photoViewers.js picks it), reading two fields: * `mountKey`, a number larger for each later mount (the later mount is - * drawn; a presentation without one counts as the latest), and - * `actions.supersede()`, called on a mount that is not drawn because a - * later one is (it should unmount, failing a mount still waiting to be - * drawn; an adapter without it is simply not drawn). + * drawn; a presentation without one counts as mounted when it began + * presenting), and `actions.supersede()`, called on a mount that is not + * drawn because a later one is (it should unmount, failing a mount still + * waiting to be drawn; an adapter without it is simply not drawn). * * @typedef {object} StreetPose * @property {string} providerId diff --git a/src/testSupport/kartaViewFakes.mjs b/src/testSupport/kartaViewFakes.mjs index c4b5ba5cce..5849e8f7d2 100644 --- a/src/testSupport/kartaViewFakes.mjs +++ b/src/testSupport/kartaViewFakes.mjs @@ -95,9 +95,22 @@ function resubscribe() { previous?.(); } +/** + * Start the shared view afresh, with no viewer: a test file calls it before + * each test, so a viewer left by an earlier test is not drawn with a later + * test's (nor superseded by it). A viewer it held is left without a view. + */ +export function resetPhotoView() { + shared.generation++; + shared.unsubscribe?.(); + shared.unsubscribe = null; + shared.viewers.clear(); + shared.draw = null; +} + /** * Draw a photo viewer with the shared view, alongside every other viewer - * given here (see `shared`). + * given here since the last `resetPhotoView()` (see `shared`). * @returns {() => void} Stop drawing it. */ export function drawPhotoViewer(viewer) { diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index 5f20b03faf..f30f86c6c7 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -101,11 +101,38 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); - assert.doesNotMatch(rest, /\.src\s*=[^=]/, 'a .src written on the page'); - // In loadImage, only on the off-page Image it creates. + // No property written through brackets (`picture['src'] = …`, + // `el[name] = …`), outside array destructuring declarations. + assert.doesNotMatch( + source.replace(/\b(?:const|let|var)\s*\[/g, ''), + /[\w$)\]]\s*\[[^[\]]*\]\s*=(?![=>])/, + 'a bracket write', + ); + const SRC = /\.src\s*=(?![=>])/g; + assert.doesNotMatch(rest, SRC, 'a .src written on the page'); + // In loadImage, only on the off-page Image it creates: `image` is bound + // once, to that Image, and never rebound or shadowed. assert.match(loader, /\bconst image = new Image\(\);/); - for (const [write] of loader.matchAll(/[\w$.\]]+\.src\s*=(?!=)/g)) - assert.match(write, /^image\.src\s*=$/, write); + assert.equal( + loader.match(/\b(?:const|let|var|function|class)\s+image\b/g)?.length, + 1, + 'one binding of image', + ); + for (const rebinding of [ + /(?])/, + /(?/, + /\((?:[^()]*[,{[\s(])?image\b[^()]*\)\s*=>/, + /\bfunction\b[^(]*\((?:[^)]*[,{[\s(])?image\b[^)]*\)/, + /\b(?:const|let|var)\s*[{[][^=]*\bimage\b/, + /\bcatch\s*\(\s*image\b/, + ]) + assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed'); + const writes = loader.match(SRC)?.length ?? 0; + assert.equal( + loader.match(/(?])/g)?.length ?? 0, + writes, + 'a .src written on something other than the Image', + ); const markup = template(VIEW); const opening = (name, attribute) => new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`); From 22485dcb01d3328e9f7f2dcecdd4f72af93d895b Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:23:42 -0800 Subject: [PATCH 10/24] Street Level photo viewer: a failed mount spares the next, stable keyless ranks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second review follow-ups: - A mount woken without being drawn unmounts only its own presentation: an earlier mount overtaken by a second mount of the same viewer fails as closed and leaves the second one mounted and presented. - A mount whose last view left fails only if no view has subscribed since; one subscribed in the same tick draws it. - Mount keys come from photoViewers.js's nextViewKey(), and a keyless presentation is stamped from the same counter when any picker first sees it, kept until it presents null: its rank no longer depends on the picker's lifetime or the order it subscribes in. - A canvas handed back while a panorama's open waits on its draw takes the panorama: the open builds its renderer there instead of falling back to the front view. A canvas the panorama moved off is not moved back to, so two views drawing their own cannot take it in turns. - The guard test also refuses compound writes (+=, ||=, ??=, &&=…), destructuring writes to properties, Object.assign (other than onto a new Error), Object.defineProperty and Reflect.set, and a catch binding that shadows loadImage's image. Nothing changes in the running app. Co-authored-by: Manjunath Paparaju --- src/layers/streetLevel/photoViewer.js | 68 +++++++--- src/layers/streetLevel/photoViewer.test.mjs | 126 +++++++++++++++++++ src/layers/streetLevel/photoViewers.js | 64 ++++++---- src/layers/streetLevel/photoViewers.test.mjs | 35 +++++- src/ui/kit/streetLevelPhotoControls.test.mjs | 39 ++++-- 5 files changed, 275 insertions(+), 57 deletions(-) diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index e2d8d14e29..8a6f2a97de 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -4,8 +4,14 @@ import { wrapDegrees, } from './panorama.js'; import { imageSize } from './imageSize.js'; +import { nextViewKey } from './photoViewers.js'; import { msg, t } from '../../i18n/index.js'; +// Each mount's and each canvas's key comes from `nextViewKey()`, never +// reused by any viewer: a view that sees one viewer unmount and another +// mount in the same tick still draws them fresh elements (a destroyed +// renderer leaves its canvas's context lost). + /** * EXPAND puts the viewer's wrap full screen, or (iPhone) opens it as a * popover. Each is tried on its own: a browser that cannot parse one @@ -36,14 +42,6 @@ function tooManyPixels(width, height) { ); } -/** - * Keys for each mount's and each canvas's elements, never reused by any - * viewer: a view that sees one viewer unmount and another mount in the same - * tick still draws them fresh elements (a destroyed renderer leaves its - * canvas's context lost). - */ -let viewKeys = 0; - /** Panorama texture widths: enough for a docked viewer, and for an expanded one. */ const PANO_MID_SIZE = Object.freeze([2048, 1024]); export const PANO_FULL_SIZE = Object.freeze([4096, 2048]); @@ -301,6 +299,13 @@ export function createPhotoViewer({ const canvasWaiters = new Set(); /** How many times the view has handed the canvas back (once per draw). */ let canvasDraws = 0; + /** + * Canvases the panorama moved off: one handed back again (a second view + * drawing its own) is not moved back to, so two views cannot take turns. + */ + const retiredCanvases = new WeakSet(); + /** The canvas moved while an open waited on its draw. */ + let canvasMoved = false; let renderer = null; /** WebGL failed once: 360° photos show their front view instead. */ let rendererFailed = false; @@ -496,7 +501,7 @@ export function createPhotoViewer({ // A lost canvas hands back its lost context: the view draws a new // element in its place and hands it back. canvas = null; - present({ canvasKey: ++viewKeys }); + present({ canvasKey: nextViewKey() }); reopen(); } @@ -507,8 +512,11 @@ export function createPhotoViewer({ */ function moveCanvas(element) { dropRenderer(); + retiredCanvases.add(canvas); canvas = element; - reopen(); + // An open waiting on the draw goes on, on the new canvas. + if (openingId !== null) canvasMoved = true; + else reopen(); } /** Let the renderer go, keeping the user's look for the photo's reopen. */ @@ -708,6 +716,7 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; + if (name === 'canvas' && retiredCanvases.has(element)) return; if (name === 'canvas' && renderer && canvas && element !== canvas) moveCanvas(element); else ELEMENTS[name]?.(element); @@ -731,7 +740,7 @@ export function createPhotoViewer({ }; presented = { host, - mountKey: ++viewKeys, + mountKey: nextViewKey(), providerId, label: t( '{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom', @@ -741,7 +750,7 @@ export function createPhotoViewer({ kind: undefined, src: null, fit: renderMode === 'fill' ? 'cover' : 'contain', - canvasKey: ++viewKeys, + canvasKey: nextViewKey(), dragging: false, prevLabel: t('Previous photo in this sequence (←)'), prevDisabled: true, @@ -916,8 +925,16 @@ export function createPhotoViewer({ // view draws it shown, at once or on a microtask, and hands the canvas // back then. const draws = canvasDraws; + canvasMoved = false; show('pano'); await drawnAfter(draws, signal); + // The view drew it on another canvas: the panorama goes there. + if (canvasMoved && seq === openSeq && !renderer && ensureRenderer()) { + const moved = restoreView?.id === target.id ? restoreView.view : null; + restoreView = null; + if (moved) renderer.setView(moved); + } + canvasMoved = false; // The last view left before drawing it: the canvas was never shown, and // nothing is drawn until a view is back. if (seq === openSeq && canvasDraws === draws && !viewListeners.size) { @@ -998,14 +1015,27 @@ export function createPhotoViewer({ throw new Error('Street Level photo viewer has no view to draw it'); // Resolves once the view drew the viewer, or it was unmounted, or its // last view left, meanwhile. - const drawn = new Promise((resolve) => rootWaiters.add(resolve)); + const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve)); + let drawn = waitRoot(); build(host); - if (!root) await drawn; - if (root) return; - // The last view left before drawing it: no view will. Unmounted, as - // when superseded, so a view subscribing later draws nothing. - if (presented) adapter.unmount(); - throw undrawn(); + // This mount's presentation: a later mount presents its own. + const mine = presented.actions; + for (;;) { + if (!root) await drawn; + const current = presented?.actions === mine; + if (root && current) return; + // Unmounted, superseded or mounted again: that is not this mount. + if (!current) throw undrawn(); + // Its last view left, and another subscribed since: it draws. + if (viewListeners.size) { + drawn = waitRoot(); + continue; + } + // No view will draw it. Unmounted, as when superseded, so a view + // subscribing later draws nothing. + adapter.unmount(); + throw undrawn(); + } }, /** Resolves once the photo is on screen and its pose was emitted. */ diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index ac3e252885..370ae53986 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -828,3 +828,129 @@ test('a viewer left by an earlier test is not superseded by a later test’s', a earlier.viewer.unmount(); later.viewer.unmount(); }); + +/** A panorama viewer whose renderers and flat loads the test reads. */ +function trackedViewer(options = {}) { + const renderers = []; + const loads = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => null, + onStep() {}, + load: async (url) => { + loads.push(url); + return { src: url }; + }, + createRenderer: (canvas) => { + const renderer = { + canvas, + images: [], + setImage: (image) => renderer.images.push(image.src), + setView() {}, + getView: () => ({ yaw: 0, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy() {}, + }; + renderers.push(renderer); + return renderer; + }, + ...options, + }); + return { viewer, renderers, loads }; +} + +/** Hand `parts` back to the viewer that presented `view`. */ +const attachAll = (view, parts) => { + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); +}; + +test('a mount overtaken by a second mount of the same viewer closes, and the second stays', async () => { + const { viewer } = trackedViewer(); + let latest = null; + const unsubscribe = viewer.subscribeView((view) => (latest = view)); + const first = viewer.mount({ id: 1 }); + const hostTwo = { id: 2 }; + const second = viewer.mount(hostTwo); + // The view draws on a later macrotask. + setTimeout(() => latest && attachAll(latest, elements()), 0); + await assert.rejects(first, /viewer was closed/); + await second; + assert.equal(latest?.host, hostTwo, 'the second mount is presented'); + viewer.unmount(); + unsubscribe(); +}); + +test('a mount whose view subscribes again in the same tick is drawn', async () => { + const { viewer } = trackedViewer(); + let latest = null; + const view = (next) => (latest = next); + let unsubscribe = viewer.subscribeView(view); + const mounting = viewer.mount({}); + // The view is replaced at once, and draws on a later macrotask. + unsubscribe(); + unsubscribe = viewer.subscribeView(view); + setTimeout(() => latest && attachAll(latest, elements()), 0); + await mounting; + assert.ok(latest, 'still presented'); + viewer.unmount(); + unsubscribe(); +}); + +test('a canvas handed back while a panorama’s open waits on its draw takes the panorama', async () => { + const { viewer, renderers, loads } = trackedViewer(); + const first = elements(); + const second = elements(); + let latest = null; + let hold = false; + const unsubscribe = viewer.subscribeView((view) => { + latest = view; + if (view && !hold) attachAll(view, first); + }); + await viewer.mount({}); + hold = true; + const opening = viewer.open('a'); + assert.ok(await until(() => latest?.kind === 'pano'), 'waiting on a draw'); + // The view draws it with a canvas of its own. + attachAll(latest, second); + await opening; + assert.equal(latest.kind, 'pano', 'not the front view'); + assert.deepEqual(loads, ['a-first'], 'no flat version loaded'); + assert.equal(renderers.at(-1).canvas, second.canvas); + assert.deepEqual(renderers.at(-1).images, ['a-first']); + viewer.unmount(); + unsubscribe(); +}); + +test('two views handing back canvases of their own do not take the panorama in turns', async () => { + let reopened = 0; + const { viewer, renderers } = trackedViewer({ + onReopen: (id) => { + reopened++; + if (reopened < 20) viewer.open(id).catch(() => {}); + }, + }); + const one = elements(); + const two = elements(); + const unsubscribes = [ + viewer.subscribeView((view) => view && attachAll(view, one)), + viewer.subscribeView((view) => view && attachAll(view, two)), + ]; + await viewer.mount({}); + await viewer.open('a'); + const built = renderers.length; + // Each presentation is drawn by both views. + for (const mode of ['fill', 'letterbox', 'fill']) { + viewer.setRenderMode(mode); + for (let i = 0; i < 5; i++) await tick(); + } + assert.equal(reopened, 0); + assert.equal(renderers.length, built, 'the panorama stays where it is'); + assert.deepEqual(renderers.at(-1).images, ['a-first']); + viewer.unmount(); + for (const unsubscribe of unsubscribes) unsubscribe(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index d8e0176a98..ed32dd5208 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,3 +1,22 @@ +/** The last key handed out by `nextViewKey()`. */ +let viewKeys = 0; + +/** + * A key no viewer or picker was ever given: photo viewers key their mounts + * and canvases with it, and a presentation without a mount key is stamped + * with one when first seen, so both rank on one scale. + */ +export function nextViewKey() { + return ++viewKeys; +} + +/** + * Each keyless viewer's current mount, `{actions, key}`: stamped once, by + * whichever picker sees it first, and kept until it presents null, so a + * picker made later ranks it the same. + */ +const keylessMounts = new WeakMap(); + /** * Receive the photo viewer to draw, out of several photo viewers mounting * in one host (see photoViewer.js): the one mounted last, whatever order @@ -8,10 +27,10 @@ * * Two fields of a presentation are read here (see ViewerAdapter.subscribeView * in registry.js): - * - `mountKey`, a number larger for each later mount, orders the mounts. A - * presentation without one counts as mounted when it began presenting: - * after every mount presenting before it, before any later mount, keyed - * or not. + * - `mountKey`, a number larger for each later mount (from `nextViewKey()`), + * orders the mounts. A presentation without one counts as mounted when + * any picker first saw it present: it is stamped with a `nextViewKey()` + * then, the same for every picker, however many are made later. * - `actions.supersede()`, where present, is called on each presentation * not drawn, whenever more than one presents. It runs on a microtask, * after the presentation that won has reached every subscriber: a @@ -22,27 +41,21 @@ * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation and its rank, {key, arrival}. + // Each viewer's current presentation and its rank, {view, key}. const shown = new Map(); - let arrivals = 0; - /** The largest mount key seen: a keyless mount ranks just after it. */ - let latestKey = -Infinity; let ready = false; let closed = false; let superseding = false; let last; - /** Whether `a` was mounted after `b`. */ - const later = (a, b) => - a.key !== b.key ? a.key > b.key : a.arrival > b.arrival; - /** A new mount's rank: its key, or, without one, the latest key seen. */ - const rank = (view) => { - const keyed = Number.isFinite(view.mountKey); - if (keyed) latestKey = Math.max(latestKey, view.mountKey); - return { - key: keyed ? view.mountKey : latestKey, - // A keyed mount comes before a keyless one ranked on its key. - arrival: keyed ? 0 : ++arrivals, - }; + /** A mount's rank: its key, or the stamp of its first presentation. */ + const rank = (viewer, view) => { + if (Number.isFinite(view.mountKey)) return view.mountKey; + let mount = keylessMounts.get(viewer); + if (!mount || mount.actions !== view.actions) { + mount = { actions: view.actions, key: nextViewKey() }; + keylessMounts.set(viewer, mount); + } + return mount.key; }; // The others are not drawn: a mount still waiting on the view never // would be. @@ -55,7 +68,7 @@ export function subscribePhotoViewers(viewers, listener) { const publish = () => { let next = null; for (const entry of shown.values()) - if (!next || later(entry, next)) next = entry; + if (!next || entry.key > next.key) next = entry; next = next?.view ?? null; if (!ready) return; if (next !== last) { @@ -71,11 +84,10 @@ export function subscribePhotoViewers(viewers, listener) { for (const viewer of viewers) { const unsubscribe = viewer?.subscribeView?.((view) => { if (closed) return; - const entry = shown.get(viewer); - if (!view) shown.delete(viewer); - else if (entry && entry.view.mountKey === view.mountKey) - entry.view = view; - else shown.set(viewer, { view, ...rank(view) }); + if (!view) { + shown.delete(viewer); + keylessMounts.delete(viewer); + } else shown.set(viewer, { view, key: rank(viewer, view) }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index b27e315b78..aa56b6b316 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createPhotoViewer } from './photoViewer.js'; -import { subscribePhotoViewers } from './photoViewers.js'; +import { nextViewKey, subscribePhotoViewers } from './photoViewers.js'; /** * A photo viewer whose presentations the test sends; `superseded` counts. @@ -10,6 +10,7 @@ import { subscribePhotoViewers } from './photoViewers.js'; */ function fakeViewer() { const listeners = new Set(); + let current = null; const viewer = { superseded: 0, view(mountKey) { @@ -19,11 +20,12 @@ function fakeViewer() { }; }, present(view) { + current = view; for (const listener of [...listeners]) listener(view); }, subscribeView(listener) { listeners.add(listener); - listener(null); + listener(current); return () => listeners.delete(listener); }, }; @@ -101,7 +103,7 @@ test('a presentation without a mount key counts as mounted when it began present const unsubscribe = subscribePhotoViewers([a, b, c], (view) => shown.push(view), ); - a.present(a.view(5)); + a.present(a.view(nextViewKey())); const keyless = b.view(undefined); b.present(keyless); assert.equal(shown.at(-1), keyless, 'after the keyed one'); @@ -112,7 +114,7 @@ test('a presentation without a mount key counts as mounted when it began present b.present({ ...keyless, kind: 'flat' }); assert.equal(shown.at(-1), newer, 'presenting again is not a new mount'); // A keyed mount made after them wins. - const latest = a.view(6); + const latest = a.view(nextViewKey()); a.present(latest); assert.equal(shown.at(-1), latest); await Promise.resolve(); @@ -186,3 +188,28 @@ test('a presentation without actions or supersede is drawn and passed over witho assert.equal(shown.at(-1).mountKey, 3); unsubscribe(); }); + +test('a keyless viewer on screen keeps its place when the picker is made again', async () => { + const keyed = fakeViewer(); + const keyless = fakeViewer(); + keyed.present(keyed.view(nextViewKey())); + const shown = []; + let unsubscribe = subscribePhotoViewers([keyless, keyed], (view) => + shown.push(view), + ); + const mounted = keyless.view(undefined); + keyless.present(mounted); + assert.equal(shown.at(-1), mounted); + await Promise.resolve(); + unsubscribe(); + // A new picker, the keyless viewer first: it is still the later mount. + const again = []; + unsubscribe = subscribePhotoViewers([keyless, keyed], (view) => + again.push(view), + ); + assert.equal(again.at(-1), mounted); + await Promise.resolve(); + assert.equal(keyless.superseded, 0, 'never told it is not drawn'); + assert.ok(keyed.superseded > 0); + unsubscribe(); +}); diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index f30f86c6c7..1c65279af4 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -79,6 +79,13 @@ test('the step buttons are not pressed toggles', () => { * the page: the one place a `.src` is written. */ const LOADER = /^export function loadImage\([\s\S]*?^}$/m; +// An assignment, plain or compound (`=`, `+=`, `||=`, `??=`, `**=`…), not +// a comparison or an arrow. +const ASSIGN = String.raw`\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|&&|\|\||\?\?)?=(?![=>])`; +const assigned = (target, flags = '') => + new RegExp(String.raw`${target}${ASSIGN}`, flags); +// A member or computed member: what a destructuring write must not target. +const MEMBER = /[\w$)\]]\s*(?:\.\s*[\w$]|\[)/; test('the photo viewer is drawn by its view, and its layer needs no Vue', () => { const source = read(VIEWER); @@ -96,19 +103,34 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /\.remove\(\)/, /\.(?:set|remove|toggle)Attribute(?:NS)?\(/, /\.(?:classList|className|dataset|style)\b/, - /\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/, - /\.(?:width|height|ariaLabel|id|value)\s*=[^=]/, + assigned( + String.raw`\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)`, + ), + assigned(String.raw`\.(?:width|height|ariaLabel|id|value)`), + // Properties written in bulk or by reflection (an Error's own fields + // aside). + /\bObject\.assign\(\s*(?!new Error\()/, + /\bObject\.definePropert(?:y|ies)\(/, + /\bReflect\.(?:set|defineProperty)\(/, /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); // No property written through brackets (`picture['src'] = …`, - // `el[name] = …`), outside array destructuring declarations. + // `el[name] ||= …`), outside array destructuring declarations. assert.doesNotMatch( source.replace(/\b(?:const|let|var)\s*\[/g, ''), - /[\w$)\]]\s*\[[^[\]]*\]\s*=(?![=>])/, + assigned(String.raw`[\w$)\]]\s*\[[^[\]]*\]`), 'a bracket write', ); - const SRC = /\.src\s*=(?![=>])/g; + // No destructuring write to a property (`[el.src] = …`, + // `({ a: el.id } = …)`); declarations bind names only. + for (const pattern of [ + /(?])/g, + /(?])/g, + ]) + for (const [write, targets] of source.matchAll(pattern)) + assert.doesNotMatch(targets, MEMBER, write); + const SRC = assigned(String.raw`\.src`, 'g'); assert.doesNotMatch(rest, SRC, 'a .src written on the page'); // In loadImage, only on the off-page Image it creates: `image` is bound // once, to that Image, and never rebound or shadowed. @@ -119,17 +141,18 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => 'one binding of image', ); for (const rebinding of [ - /(?])/, + assigned(String.raw`(?/, /\((?:[^()]*[,{[\s(])?image\b[^()]*\)\s*=>/, /\bfunction\b[^(]*\((?:[^)]*[,{[\s(])?image\b[^)]*\)/, /\b(?:const|let|var)\s*[{[][^=]*\bimage\b/, - /\bcatch\s*\(\s*image\b/, + /\bcatch\s*\([^)]*\bimage\b/, ]) assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed'); const writes = loader.match(SRC)?.length ?? 0; assert.equal( - loader.match(/(?])/g)?.length ?? 0, + loader.match(assigned(String.raw`(? Date: Thu, 19 Nov 2026 16:31:34 -0800 Subject: [PATCH 11/24] Street Level photo viewer: take a moved-off canvas back, and close a mount unmounted in its first draw MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A canvas the panorama moved off (a second view drew its own) is no longer ignored for good: its draws are counted, so an open waiting on one goes on, and once a single view is left its canvas is taken back. Before, after the second view left, the next 360° open waited forever and the panorama stayed on the departed view's canvas. A mount whose view unmounts it inside its first draw now fails as closed, as every other unmounted mount does, rather than with a TypeError. Both found in review; each new test fails without its fix. Co-authored-by: Manjunath Paparaju --- src/layers/streetLevel/photoViewer.js | 35 ++++++++++++----- src/layers/streetLevel/photoViewer.test.mjs | 42 +++++++++++++++++++++ 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index 8a6f2a97de..509ee48c75 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -247,7 +247,9 @@ export function panoSizeFor(canvasPixels, fovDeg) { * a panorama's open waiting on a draw when the last view leaves fails as * closed (the mount unmounts; the open leaves no photo shown). A view * handing back another canvas element than the renderer's (one subscribed - * since) gets the panorama drawn again on it, as after a lost context. + * since) gets the panorama drawn again on it, as after a lost context; + * while several views draw, a canvas the panorama moved off is not moved + * back to, and once one view is left its canvas is taken back. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -300,10 +302,12 @@ export function createPhotoViewer({ /** How many times the view has handed the canvas back (once per draw). */ let canvasDraws = 0; /** - * Canvases the panorama moved off: one handed back again (a second view - * drawing its own) is not moved back to, so two views cannot take turns. + * Canvases the panorama moved off while more than one view draws: one + * handed back again (a second view drawing its own) is not moved back to, + * so two views cannot take turns. Forgotten once a single view is left, + * so its canvas is taken back. */ - const retiredCanvases = new WeakSet(); + let retiredCanvases = new WeakSet(); /** The canvas moved while an open waited on its draw. */ let canvasMoved = false; let renderer = null; @@ -716,8 +720,16 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; - if (name === 'canvas' && retiredCanvases.has(element)) return; - if (name === 'canvas' && renderer && canvas && element !== canvas) + const retired = name === 'canvas' && retiredCanvases.has(element); + if (retired) { + // Another view still draws the panorama: this draw is counted, so + // an open waiting on it goes on, but the panorama stays put. + } else if ( + name === 'canvas' && + renderer && + canvas && + element !== canvas + ) moveCanvas(element); else ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); @@ -1018,8 +1030,10 @@ export function createPhotoViewer({ const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve)); let drawn = waitRoot(); build(host); - // This mount's presentation: a later mount presents its own. - const mine = presented.actions; + // This mount's presentation: a later mount presents its own. A view + // may have unmounted it already, inside its first draw. + const mine = presented?.actions; + if (!mine) throw undrawn(); for (;;) { if (!root) await drawn; const current = presented?.actions === mine; @@ -1125,7 +1139,10 @@ export function createPhotoViewer({ return () => { // The last view went: a mount or an open waiting on its draw fails // as closed. - if (viewListeners.delete(listener) && !viewListeners.size) { + if (!viewListeners.delete(listener)) return; + // One view left: the canvases moved off are its to hand back again. + if (viewListeners.size <= 1) retiredCanvases = new WeakSet(); + if (!viewListeners.size) { wake(rootWaiters); wake(canvasWaiters); } diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index 370ae53986..1f01117957 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -954,3 +954,45 @@ test('two views handing back canvases of their own do not take the panorama in t viewer.unmount(); for (const unsubscribe of unsubscribes) unsubscribe(); }); + +test('the panorama goes back to the one view left once a second view leaves', async () => { + const { viewer, renderers } = trackedViewer({ + onReopen: (id) => viewer.open(id).catch(() => {}), + }); + const one = elements(); + const two = elements(); + const unsubscribeOne = viewer.subscribeView( + (view) => view && attachAll(view, one), + ); + await viewer.mount({}); + await viewer.open('a'); + // A second view subscribes and draws its own canvas: the panorama moves. + const unsubscribeTwo = viewer.subscribeView( + (view) => view && attachAll(view, two), + ); + for (let i = 0; i < 5; i++) await tick(); + assert.equal(renderers.at(-1).canvas, two.canvas); + unsubscribeTwo(); + assert.ok( + await settles(viewer.open('b')), + 'the next open is not left waiting', + ); + for (let i = 0; i < 5; i++) await tick(); + assert.equal( + renderers.at(-1).canvas, + one.canvas, + 'the panorama is back on the view left', + ); + assert.equal(renderers.at(-1).images.at(-1), 'b-first'); + viewer.unmount(); + unsubscribeOne(); +}); + +test('a mount its view unmounts inside the first draw fails as closed', async () => { + const { viewer } = trackedViewer(); + const unsubscribe = viewer.subscribeView((view) => { + if (view) viewer.unmount(); + }); + await assert.rejects(viewer.mount({}), /Street-level viewer was closed/); + unsubscribe(); +}); From 80999ff00780d502acb040de3b849e84cee0764f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:36:54 -0800 Subject: [PATCH 12/24] Add the changelog entry for #1871 Co-authored-by: Manjunath Paparaju --- changelog.d/1871-street-level-photo-followups.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1871-street-level-photo-followups.md diff --git a/changelog.d/1871-street-level-photo-followups.md b/changelog.d/1871-street-level-photo-followups.md new file mode 100644 index 0000000000..e68357f915 --- /dev/null +++ b/changelog.d/1871-street-level-photo-followups.md @@ -0,0 +1,3 @@ +- Street Level's photo viewer settles every open and mount, draws one + viewer at a time and states its view contract (manjunath22466, + samehkhamis, #1871). From ff7b8e68c5b1f3b39421f71fc36fccf26be60087 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:56:10 -0800 Subject: [PATCH 13/24] Centre the phone Omnibar when no language picker sits beside it On a phone the field kept 60px on its right for the language picker even where the application shows none, so it sat left of centre. It now keeps 16px either side, and leaves the picker its room only while it is there. --- src/ui/views/panels/Omnibar.vue | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ui/views/panels/Omnibar.vue b/src/ui/views/panels/Omnibar.vue index 8e08b8d70e..9bdcd2e1c6 100644 --- a/src/ui/views/panels/Omnibar.vue +++ b/src/ui/views/panels/Omnibar.vue @@ -1347,10 +1347,14 @@ small { calc(var(--mobile-sheet-cover, 0px) + 6px) ); left: auto; - inset-inline: 16px 60px; + inset-inline: 16px; width: auto; transform: none; } +/* The language picker sits at the right edge beside the field; the field leaves it room. */ +:global(body.mobile-shell:has(#locale-picker) #gev-omnibar) { + inset-inline: 16px 60px; +} /* A lifted timeline leaves less map above the credits on short phones. */ @media (max-height: 480px) { :global(body.mobile-shell:has(#world-timeline) #gev-omnibar) { From 41e988606cdabe566553a6b3f810ac5a91f41752 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:56:19 -0800 Subject: [PATCH 14/24] Add the changelog entry for #1872 --- changelog.d/1872-omnibar-centred.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1872-omnibar-centred.md diff --git a/changelog.d/1872-omnibar-centred.md b/changelog.d/1872-omnibar-centred.md new file mode 100644 index 0000000000..d41b20d91e --- /dev/null +++ b/changelog.d/1872-omnibar-centred.md @@ -0,0 +1,3 @@ +- On a phone the search field is centred when no language picker sits beside + it, instead of keeping the picker's room empty on its right (samehkhamis, + #1872). From 84b60a92e0e50f3e585d1b1fb835c17c7c524a00 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 18:59:10 -0800 Subject: [PATCH 15/24] Read the weather texture limit and the reveal time in the body, not in a parameter default esbuild compiles an optional method call reached through an optional chain (`a?.b?.()`) in a parameter's default, for browsers it lowers optional chaining for (Chrome and Edge before 91), into code that reads a variable out of its scope. The weather shell's texture limit was read that way, so every satellite frame threw a ReferenceError in the built app and the layer showed "Weather imagery unavailable"; the leader and card reveal took their default time the same way. A test now refuses the form anywhere under src/. --- src/layers/weather/shellRendering.js | 13 +++- src/overlays/worldOverlayDraw.js | 24 +++---- src/parameterDefaults.test.mjs | 93 ++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+), 14 deletions(-) create mode 100644 src/parameterDefaults.test.mjs diff --git a/src/layers/weather/shellRendering.js b/src/layers/weather/shellRendering.js index 0391c2752f..06972473c5 100644 --- a/src/layers/weather/shellRendering.js +++ b/src/layers/weather/shellRendering.js @@ -177,13 +177,20 @@ export function createWeatherShell({ drawOf = findDraw, cameraOf = findCamera, frameOf = findFrame, - maxTextureSize = rendererOf(viewer)?.quality?.device?.().maxTextureSize ?? 0, + maxTextureSize, frameSource = null, }) { if (!Object.hasOwn(WEATHER_IMAGE_SIZES, product)) throw new TypeError('Unknown weather product'); - const size = fitTexture(WEATHER_IMAGE_SIZES[product], maxTextureSize); - const detailSize = fitTexture(WEATHER_DETAIL_SIZE, maxTextureSize); + // Read in the body, not as the parameter's default: an optional method call + // in a default parameter is compiled for older browsers into code that + // throws (esbuild). + const textureLimit = + maxTextureSize === undefined + ? (rendererOf(viewer)?.quality?.device?.().maxTextureSize ?? 0) + : maxTextureSize; + const size = fitTexture(WEATHER_IMAGE_SIZES[product], textureLimit); + const detailSize = fitTexture(WEATHER_DETAIL_SIZE, textureLimit); const infrared = product === 'clouds' || product === 'clouds-regional'; // Global infrared contrast depends on the requested extent, so a window would // not match the image around it; the globe host also shows one mosaic. diff --git a/src/overlays/worldOverlayDraw.js b/src/overlays/worldOverlayDraw.js index e5db5d5b7f..4a32b89437 100644 --- a/src/overlays/worldOverlayDraw.js +++ b/src/overlays/worldOverlayDraw.js @@ -709,29 +709,31 @@ function leaderDrawRatio(entry) { return Number.isFinite(ratio) ? Math.max(0.1, Math.min(0.9, ratio)) : 0.68; } -export function leaderRevealProgress( - entry, - timestamp = globalThis.performance?.now?.() ?? Date.now(), -) { +/** Now, for a reveal given no time. Not a parameter default: an optional + * method call in a default parameter is compiled for older browsers into code + * that throws (esbuild). */ +function revealNow() { + return globalThis.performance?.now?.() ?? Date.now(); +} + +export function leaderRevealProgress(entry, timestamp) { + const at = timestamp === undefined ? revealNow() : timestamp; const linear = Math.min( 1, - animationLinearProgress(entry, timestamp) / leaderDrawRatio(entry), + animationLinearProgress(entry, at) / leaderDrawRatio(entry), ); return 1 - Math.pow(1 - linear, 3); } -export function tacticalCardRevealAlpha( - entry, - timestamp = globalThis.performance?.now?.() ?? Date.now(), -) { +export function tacticalCardRevealAlpha(entry, timestamp) { if (!(Math.max(0, Number(entry?.leaderAnimationMs) || 0) > 0)) return 1; + const at = timestamp === undefined ? revealNow() : timestamp; const start = leaderDrawRatio(entry); const linear = Math.max( 0, Math.min( 1, - (animationLinearProgress(entry, timestamp) - start) / - Math.max(0.1, 1 - start), + (animationLinearProgress(entry, at) - start) / Math.max(0.1, 1 - start), ), ); return linear * linear * (3 - 2 * linear); diff --git a/src/parameterDefaults.test.mjs b/src/parameterDefaults.test.mjs new file mode 100644 index 0000000000..8314bc5138 --- /dev/null +++ b/src/parameterDefaults.test.mjs @@ -0,0 +1,93 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, readdirSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const SRC_ROOT = fileURLToPath(new URL('.', import.meta.url)); + +/** Every browser-built module under src/ — the test files are Node-only. */ +function browserModules(directory = SRC_ROOT) { + const files = []; + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const absolute = path.join(directory, entry.name); + if (entry.isDirectory()) files.push(...browserModules(absolute)); + else if ( + entry.isFile() && + entry.name.endsWith('.js') && + !entry.name.endsWith('.test.js') + ) + files.push(absolute); + } + return files.sort(); +} + +/** + * Whether `node` is an optional call of a method reached through an optional + * chain: `a?.b?.()`, `f()?.g?.h?.()`. The forms esbuild compiles correctly, + * `a?.b()` and `a.b?.()`, are not. + */ +function optionalMethodCall(node) { + if (!ts.isCallExpression(node) || !node.questionDotToken) return false; + const callee = node.expression; + const member = + ts.isPropertyAccessExpression(callee) || + ts.isElementAccessExpression(callee); + return member && (callee.flags & ts.NodeFlags.OptionalChain) !== 0; +} + +/** Such calls in `node`, a default's expression, outside nested functions. */ +function callsIn(node, found = []) { + if (ts.isFunctionLike(node)) return found; + if (optionalMethodCall(node)) found.push(node); + ts.forEachChild(node, (child) => callsIn(child, found)); + return found; +} + +/** The defaults of a parameter: its own and those inside a destructuring pattern. */ +function defaultsOf(binding, found = []) { + if (binding.initializer) found.push(binding.initializer); + if ( + ts.isObjectBindingPattern(binding.name) || + ts.isArrayBindingPattern(binding.name) + ) + for (const element of binding.name.elements) + if (ts.isBindingElement(element)) defaultsOf(element, found); + return found; +} + +test('no parameter default calls a method through an optional chain', () => { + // esbuild compiles `a?.b?.()` in a parameter's default, for the browsers a + // build still lowers optional chaining for (Chrome and Edge before 91), into + // code that reads a variable out of its scope: the call throws a + // ReferenceError in the built app, never under node:test. The weather shell + // read its texture limit this way, so every satellite frame failed. Compute + // such a value in the function's body instead. + const offenders = []; + for (const file of browserModules()) { + const source = ts.createSourceFile( + file, + readFileSync(file, 'utf8'), + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.JS, + ); + const visit = (node) => { + if (ts.isFunctionLike(node)) + for (const parameter of node.parameters ?? []) + for (const initializer of defaultsOf(parameter)) + for (const call of callsIn(initializer)) { + const { line } = source.getLineAndCharacterOfPosition( + call.getStart(source), + ); + offenders.push( + `${path.relative(SRC_ROOT, file)}:${line + 1} ${call.getText(source)}`, + ); + } + ts.forEachChild(node, visit); + }; + visit(source); + } + assert.deepEqual(offenders, []); +}); From 3e6d2165fd6c0400205a84d2bc33dfb13b9852f3 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 18:59:36 -0800 Subject: [PATCH 16/24] Changelog: #1873 --- changelog.d/1873-weather-texture-limit.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1873-weather-texture-limit.md diff --git a/changelog.d/1873-weather-texture-limit.md b/changelog.d/1873-weather-texture-limit.md new file mode 100644 index 0000000000..fdb351c1a2 --- /dev/null +++ b/changelog.d/1873-weather-texture-limit.md @@ -0,0 +1,4 @@ +- Satellite clouds draw again in a built app instead of showing "Weather + imagery unavailable": the weather shell read its texture limit in a + parameter default, which esbuild compiles for older browsers into code that + throws. A test now refuses the form under `src/` (samehkhamis, #1873). From e3a17c527bb0091a76cb91025d29cbfa5607f1d1 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 19:02:10 -0800 Subject: [PATCH 17/24] Parameter defaults test: name the forms that break, and read single-file components and .mjs modules too --- src/parameterDefaults.test.mjs | 42 +++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/src/parameterDefaults.test.mjs b/src/parameterDefaults.test.mjs index 8314bc5138..97e107b82e 100644 --- a/src/parameterDefaults.test.mjs +++ b/src/parameterDefaults.test.mjs @@ -7,26 +7,45 @@ import ts from 'typescript'; const SRC_ROOT = fileURLToPath(new URL('.', import.meta.url)); -/** Every browser-built module under src/ — the test files are Node-only. */ -function browserModules(directory = SRC_ROOT) { +/** Every module under src/ the build compiles: scripts and single-file + * components, not the Node-only tests. */ +function builtModules(directory = SRC_ROOT) { const files = []; for (const entry of readdirSync(directory, { withFileTypes: true })) { const absolute = path.join(directory, entry.name); - if (entry.isDirectory()) files.push(...browserModules(absolute)); + if (entry.isDirectory()) files.push(...builtModules(absolute)); else if ( entry.isFile() && - entry.name.endsWith('.js') && - !entry.name.endsWith('.test.js') + /\.(js|mjs|vue)$/.test(entry.name) && + !/\.test\.(js|mjs)$/.test(entry.name) ) files.push(absolute); } return files.sort(); } +/** The code of `file` to parse: a component's script blocks in place (every + * other character a space, so lines keep their numbers), else the file. */ +function scriptOf(file) { + const text = readFileSync(file, 'utf8'); + if (!file.endsWith('.vue')) return { code: text, kind: ts.ScriptKind.JS }; + const kept = text.replace(/[^\n]/g, ' ').split(''); + let kind = ts.ScriptKind.JS; + for (const match of text.matchAll(/]*)>([\s\S]*?)<\/script>/g)) { + if (/lang=["']ts["']/.test(match[1])) kind = ts.ScriptKind.TS; + const start = match.index + match[0].indexOf('>') + 1; + for (let i = 0; i < match[2].length; i += 1) + kept[start + i] = text[start + i]; + } + return { code: kept.join(''), kind }; +} + /** * Whether `node` is an optional call of a method reached through an optional - * chain: `a?.b?.()`, `f()?.g?.h?.()`. The forms esbuild compiles correctly, - * `a?.b()` and `a.b?.()`, are not. + * chain: `a?.b?.()`, `a.b?.c?.()`, `f()?.g?.()`. Of these esbuild breaks the + * ones whose optional property is read from a property or a call + * (`a.b?.c?.()`, `f()?.g?.()`); the rule is kept stricter than that, as such a + * value is as easily read in the body. `a?.b()` and `a.b?.()` are not matched. */ function optionalMethodCall(node) { if (!ts.isCallExpression(node) || !node.questionDotToken) return false; @@ -58,20 +77,21 @@ function defaultsOf(binding, found = []) { } test('no parameter default calls a method through an optional chain', () => { - // esbuild compiles `a?.b?.()` in a parameter's default, for the browsers a + // esbuild compiles `a.b?.c?.()` in a parameter's default, for the browsers a // build still lowers optional chaining for (Chrome and Edge before 91), into // code that reads a variable out of its scope: the call throws a // ReferenceError in the built app, never under node:test. The weather shell // read its texture limit this way, so every satellite frame failed. Compute // such a value in the function's body instead. const offenders = []; - for (const file of browserModules()) { + for (const file of builtModules()) { + const { code, kind } = scriptOf(file); const source = ts.createSourceFile( file, - readFileSync(file, 'utf8'), + code, ts.ScriptTarget.Latest, true, - ts.ScriptKind.JS, + kind, ); const visit = (node) => { if (ts.isFunctionLike(node)) From c9a78153ac2ea021d9c0f0fb704efdac00fb6e0d Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 19:21:10 -0800 Subject: [PATCH 18/24] globe.imagery.video: paint the test video red before recording starts The check recorded a canvas that stayed blank until its first 20 ms paint tick, so on a loaded runner the video's opening frames were dark and the pixel early in the segment read (28, 54) instead of red: main failed once after #1872 and passed on the runs around it. --- src/render/conformance/checks/ports.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 10062c4f67..1f28742747 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -5356,10 +5356,14 @@ export function portChecks() { const chunks = []; recorder.ondataavailable = (e) => chunks.push(e.data); let colour = '#ff0000'; - const paint = setInterval(() => { + const fill = () => { g.fillStyle = colour; g.fillRect(0, 0, 32, 32); - }, 20); + }; + // Red from the first recorded frame: a blank canvas until the first + // tick read dark early in the segment on a loaded runner. + fill(); + const paint = setInterval(fill, 20); const wait = (ms) => new Promise((done) => setTimeout(done, ms)); recorder.start(); await wait(1000); From edd51d58fdade570cf65d8b67049e9ce4066e8ea Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 19:45:20 -0800 Subject: [PATCH 19/24] Weather imagery and shells say what they show An imagery spec and a raster shell take an optional `shows`, such as 'clouds' or 'radar'. Drawing never depends on it; a renderer may use it to tell such a layer apart. The weather layer sets it for every product, 'clouds' for both cloud products. --- src/layers/weather/imageryOrder.js | 9 +++++++++ src/layers/weather/rendering.js | 4 +++- src/layers/weather/shellRendering.js | 2 ++ src/layers/weather/weather.test.mjs | 1 + src/render/contract/draw.d.ts | 2 ++ src/render/contract/globe.d.ts | 5 +++++ 6 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/layers/weather/imageryOrder.js b/src/layers/weather/imageryOrder.js index dc65fd47ed..521b0dde3f 100644 --- a/src/layers/weather/imageryOrder.js +++ b/src/layers/weather/imageryOrder.js @@ -3,6 +3,15 @@ * (wind), infrared, radar, then lightning, independent of enable order, and * above the port's other layers (zOrder 0). */ +/** What each product's imagery shows (the imagery's `shows`): both cloud products are clouds. */ +export const WEATHER_IMAGERY_SHOWS = Object.freeze({ + wind: 'wind', + clouds: 'clouds', + 'clouds-regional': 'clouds', + radar: 'radar', + lightning: 'lightning', +}); + export const WEATHER_IMAGERY_Z = Object.freeze({ wind: 1, clouds: 2, diff --git a/src/layers/weather/rendering.js b/src/layers/weather/rendering.js index 5c69c35742..cd5fe09733 100644 --- a/src/layers/weather/rendering.js +++ b/src/layers/weather/rendering.js @@ -1,5 +1,5 @@ import { weatherTileUrl, closeWeatherPixels } from './source.js'; -import { WEATHER_IMAGERY_Z } from './imageryOrder.js'; +import { WEATHER_IMAGERY_SHOWS, WEATHER_IMAGERY_Z } from './imageryOrder.js'; import { imageryHostStatus } from './imageryHost.js'; import { globeImageryHost } from './shellRendering.js'; import { drawMosaicTile, createFrameTileFetch } from './rasterTiles.js'; @@ -503,6 +503,7 @@ function createGlobeRendering({ drawMosaicTile(texture, rectangle, tile, canvas), admit, zOrder: WEATHER_IMAGERY_Z[snapshot.product], + shows: WEATHER_IMAGERY_SHOWS[snapshot.product], } : { kind: 'xyz', @@ -545,6 +546,7 @@ function createGlobeRendering({ } : {}), zOrder: WEATHER_IMAGERY_Z[snapshot.product], + shows: WEATHER_IMAGERY_SHOWS[snapshot.product], }; // A shown, transparent layer lets the renderer request staging tiles // while the last complete observation stays visible underneath it. diff --git a/src/layers/weather/shellRendering.js b/src/layers/weather/shellRendering.js index 06972473c5..9719bac78c 100644 --- a/src/layers/weather/shellRendering.js +++ b/src/layers/weather/shellRendering.js @@ -9,6 +9,7 @@ import { } from '../../render/rendererOf.js'; import { acquireWeatherImage } from './infraredImage.js'; import { imageryHostStatus } from './imageryHost.js'; +import { WEATHER_IMAGERY_SHOWS } from './imageryOrder.js'; import { WEATHER_DETAIL_SIZE, WEATHER_IMAGE_SIZES } from './source.js'; import { msg } from '../../i18n/index.js'; @@ -257,6 +258,7 @@ export function createWeatherShell({ heightM: height, alpha, detail: null, + shows: WEATHER_IMAGERY_SHOWS[product], }); fieldAlpha = alpha; owed = true; diff --git a/src/layers/weather/weather.test.mjs b/src/layers/weather/weather.test.mjs index bd69eaee9a..4975af9ec4 100644 --- a/src/layers/weather/weather.test.mjs +++ b/src/layers/weather/weather.test.mjs @@ -1006,6 +1006,7 @@ test('global infrared is acquired before staging and cropped from one processed assert.equal(provider.spec.kind, 'canvas'); assert.equal(provider.spec.maxLevel, 3); assert.equal(provider.spec.tileSize, 256); + assert.equal(provider.spec.shows, 'clouds'); assert.equal(provider.spec.tiling, 'geographic'); assert.deepEqual(provider.spec.rectangle, snapshot.bounds); const first = await provider.requestImage(0, 0, 0); diff --git a/src/render/contract/draw.d.ts b/src/render/contract/draw.d.ts index 11a69a433c..8191d78f2a 100644 --- a/src/render/contract/draw.d.ts +++ b/src/render/contract/draw.d.ts @@ -584,6 +584,8 @@ export type FieldSpec = */ detail?: { image: ImageRef; rectangle: GeoRect } | null; alpha?: number; + /** What the raster shows, as imagery's `shows`. */ + shows?: string; }; export interface FieldHandle extends Handle { diff --git a/src/render/contract/globe.d.ts b/src/render/contract/globe.d.ts index 38516e66e4..3e0be1b9fa 100644 --- a/src/render/contract/globe.d.ts +++ b/src/render/contract/globe.d.ts @@ -122,6 +122,11 @@ export interface ImagerySpec { ) => Promise | undefined; /** Draw order among imagery layers; higher draws on top. */ zOrder?: number; + /** + * What the imagery shows, such as `'clouds'` or `'radar'`. Drawing never + * depends on it; a renderer may use it to tell such a layer apart. + */ + shows?: string; } export interface TimedUrl { From f07f40271d8608169b69d9ff52cbf6151f438bb2 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 19:45:30 -0800 Subject: [PATCH 20/24] Changelog: #1875 --- changelog.d/1875-imagery-shows.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1875-imagery-shows.md diff --git a/changelog.d/1875-imagery-shows.md b/changelog.d/1875-imagery-shows.md new file mode 100644 index 0000000000..7c5feeb2c2 --- /dev/null +++ b/changelog.d/1875-imagery-shows.md @@ -0,0 +1,3 @@ +- Weather imagery and shells say what they show (`shows`, such as + `'clouds'`), so a renderer can tell such a layer apart; nothing draws + differently (samehkhamis, #1875). From 893bc5b5f324a98f4e922cc7f4b61a047e9c0034 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 20:15:49 -0800 Subject: [PATCH 21/24] The search dock sits above the World Timeline on desktop The bar takes the dock's floor and the dock, with the search field, rises by the bar's height while it shows, as the dock does outside the search layout. The bar no longer hides while search results or the chat and voice panels open, since they open upward from the dock and no longer cover it. --- docs/CURRENT-STATE.md | 8 +++++--- src/creditAttribution.test.mjs | 25 ++++++++++++++++++------ src/ui/hudSonarStyle.test.mjs | 35 ++++++++++++++++++++++++++-------- src/ui/styles/omnibar-dock.css | 34 +++++++++++---------------------- 4 files changed, 62 insertions(+), 40 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 6b218b17fc..cdac3d27b5 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1215,9 +1215,11 @@ every width, right to left it takes the bottom right at every width, and `src/ui/creditLineHeight.js` keeps its height in `--credit-line-height`: the coordinates (and, right to left, the Tactical readout) stay 6px above it however many lines it wraps onto, and the dock and World Timeline rise when -it is taller than their usual clearance. Narrower than 1120px the dock leaves -no room between the corners, so the coordinates and the readout sit above -the dock, and above the World Timeline while it shows. Outside that layout +it is taller than their usual clearance. The World Timeline takes the dock's +floor and the dock (with the Omnibar's field) sits above it, rising by the +bar's height while it shows, as the plain dock does. Narrower than 1120px the +dock leaves no room between the corners, so the coordinates and the readout +sit above the dock. Outside that layout Cesium's credit box wraps from 1200px, as before; the phone shell, clean view, recording and scene playback lay the line out themselves. The left rail treats the centered World Timeline and voice control as diff --git a/src/creditAttribution.test.mjs b/src/creditAttribution.test.mjs index 958578689d..c8a8a30a80 100644 --- a/src/creditAttribution.test.mjs +++ b/src/creditAttribution.test.mjs @@ -912,10 +912,12 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing' '#command-dock:has(#location-bar:not(.collapsed))', '#command-dock:has(#control-panel:not(.collapsed))', ]; - assert.equal( - omnibarVar('--world-timeline-lift'), - '0px', - 'the Omnibar layout holds the timeline lift at 0', + // The dock rises over the World Timeline by world-timeline.css's lift, as + // the plain dock does; the Omnibar scope leaves the lift alone. + assert.doesNotMatch( + fs.readFileSync(path.join(ROOT, 'src/ui/styles/omnibar-dock.css'), 'utf8'), + /--world-timeline-lift\s*:/, + 'the Omnibar layout leaves the timeline lift to world-timeline.css', ); for (const width of WIDTHS.filter((w) => w >= OMNIBAR_MIN_WIDTH)) { for (const height of HEIGHTS) { @@ -968,10 +970,21 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing' credit.part.startsWith(OMNIBAR_SCOPE), `the Omnibar owns the credit row at ${width}px`, ); - const dockBottom = omnibarPx( + // The dock rises over the World Timeline from the dock's floor, and + // the bar takes that floor: the floor is what clears the credit. + assert.equal( dock.decl.value, + 'var(--omnibar-dock-raised)', + `Omnibar dock bottom at ${width}px`, + ); + assert.equal( + omnibarVar('--omnibar-dock-raised').replace(/\s+/g, ' '), + 'calc( var(--omnibar-dock-bottom) + var(--world-timeline-lift, 0px) )', + ); + const dockBottom = omnibarPx( + 'var(--omnibar-dock-bottom)', height, - 'Omnibar dock bottom', + 'Omnibar dock floor', ); const creditTop = omnibarPx(credit.decl.value, height, 'Omnibar credit bottom') + diff --git a/src/ui/hudSonarStyle.test.mjs b/src/ui/hudSonarStyle.test.mjs index 0892e07480..c6074702a4 100644 --- a/src/ui/hudSonarStyle.test.mjs +++ b/src/ui/hudSonarStyle.test.mjs @@ -769,19 +769,38 @@ test('shared panel hooks affect only opted-in rail surfaces without overriding d ); }); -test('narrow Omnibar corners clear the World Timeline over the dock', () => { +test('the Omnibar dock sits above the World Timeline, and narrow corners clear the dock', () => { const css = read('./styles/omnibar-dock.css'); - const timeline = css.match( - /#world-timeline \{\s*bottom: calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px\);/, + // The bar takes the dock's floor; the dock and the field inside it rise by + // the bar's lift (world-timeline.css), as the plain dock does. + assert.match( + css, + /#world-timeline \{\s*bottom: var\(--omnibar-dock-bottom\);/, + ); + assert.match( + css, + /--omnibar-dock-raised: calc\(\s*var\(--omnibar-dock-bottom\) \+ var\(--world-timeline-lift, 0px\)\s*\);/, + ); + assert.match( + css, + /#command-dock \{[^}]*bottom: var\(--omnibar-dock-raised\);/, + ); + assert.match( + css, + /#gev-omnibar \{[^}]*bottom: calc\(var\(--omnibar-dock-raised\) \+ 11px\);/, + ); + assert.doesNotMatch(css, /--world-timeline-lift\s*:/); + const lift = read('./styles/world-timeline.css').match( + /body:has\(#world-timeline\) \{\s*--world-timeline-lift: (\d+)px;/, ); const height = read('./styles/world-timeline.css').match( /#world-timeline \{[^}]*\n {2}height: (\d+)px;/, ); + assert.ok(lift && height && Number(lift[1]) > Number(height[1])); const corners = css.match( - /&:has\(#world-timeline\) \{\s*--omnibar-coordinates-bottom: max\(\s*calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px \+ (\d+)px \+ (\d+)px\)/, + /--omnibar-coordinates-bottom: max\(\s*calc\(var\(--omnibar-dock-raised\) \+ (\d+)px \+ (\d+)px\)/, ); - assert.ok(timeline && height && corners); - assert.equal(Number(corners[1]), Number(timeline[1])); - assert.equal(Number(corners[2]), Number(height[1])); - assert.ok(Number(corners[3]) >= 6); + assert.ok(corners); + assert.equal(Number(corners[1]), 56); + assert.ok(Number(corners[2]) >= 6); }); diff --git a/src/ui/styles/omnibar-dock.css b/src/ui/styles/omnibar-dock.css index e9faafcdb2..6df613977f 100644 --- a/src/ui/styles/omnibar-dock.css +++ b/src/ui/styles/omnibar-dock.css @@ -8,11 +8,15 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( /* Clear of the attribution line under it, however many lines it wraps onto (--credit-line-height, src/ui/creditLineHeight.js). */ --omnibar-credits-clear: calc(1rem + var(--credit-line-height, 28px) + 6px); - /* The dock, and the World Timeline and narrow corners placed from it, + /* The World Timeline, and the dock and narrow corners placed from it, rise over a line wrapped taller than its usual one or two lines. */ --omnibar-dock-bottom: max(74px, calc(var(--omnibar-credits-clear) + 2px)); + /* The dock sits above the World Timeline, rising by its height + (--world-timeline-lift, world-timeline.css) as the plain dock does. */ + --omnibar-dock-raised: calc( + var(--omnibar-dock-bottom) + var(--world-timeline-lift, 0px) + ); --omnibar-coordinates-bottom: max(4.25rem, var(--omnibar-credits-clear)); - --world-timeline-lift: 0px; #intel-hud:is([data-variant='tactical'], [data-variant='minimal']) :is(.hud-top-left, .hud-top-right) { @@ -32,23 +36,14 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( } #world-timeline { - bottom: calc(var(--omnibar-dock-bottom) + 66px); + bottom: var(--omnibar-dock-bottom); width: var(--omnibar-dock-width); } - &:has(#gev-chat-panel:not([hidden]), #gev-voice-panel:not([hidden])) - #world-timeline, - &:has(#gev-omnibar.has-results):not( - :has(#gev-voice-control[data-assistant-mode='voice']) - ) - #world-timeline { - visibility: hidden; - } - #command-dock { --dock-voice-width: var(--omnibar-dock-width); top: auto; - bottom: var(--omnibar-dock-bottom); + bottom: var(--omnibar-dock-raised); z-index: 149; width: var(--omnibar-dock-width); max-width: none; @@ -197,7 +192,7 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( #gev-omnibar { top: auto; - bottom: calc(var(--omnibar-dock-bottom) + 11px); + bottom: calc(var(--omnibar-dock-raised) + 11px); left: 50%; width: calc(var(--omnibar-dock-width) - 120px); transform: translateX(-50%); @@ -235,7 +230,7 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( bottom: calc(100% + 11px); max-height: min( 360px, - max(0px, calc(100dvh - var(--omnibar-dock-bottom) - 144px)) + max(0px, calc(100dvh - var(--omnibar-dock-raised) - 144px)) ); overflow: auto; border-radius: 18px 18px 0 0; @@ -365,16 +360,9 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( rise above the dock. */ @media (max-width: 1119px) { --omnibar-coordinates-bottom: max( - calc(var(--omnibar-dock-bottom) + 56px + 10px), + calc(var(--omnibar-dock-raised) + 56px + 10px), var(--omnibar-credits-clear) ); - /* And above the World Timeline (42px tall) over the dock. */ - &:has(#world-timeline) { - --omnibar-coordinates-bottom: max( - calc(var(--omnibar-dock-bottom) + 66px + 42px + 10px), - var(--omnibar-credits-clear) - ); - } #intel-hud[data-variant='tactical'] .hud-bottom-right, &:where(html[dir='rtl'] *):not(.context-docked) #intel-hud[data-variant='tactical'] From 1cc06c021a8271cda9dd0380639966fd6d05e23f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 20:16:34 -0800 Subject: [PATCH 22/24] Changelog entry for #1876 --- changelog.d/1876-search-dock-above-timeline.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 changelog.d/1876-search-dock-above-timeline.md diff --git a/changelog.d/1876-search-dock-above-timeline.md b/changelog.d/1876-search-dock-above-timeline.md new file mode 100644 index 0000000000..50c810776d --- /dev/null +++ b/changelog.d/1876-search-dock-above-timeline.md @@ -0,0 +1,2 @@ +- On desktop the search dock sits above the World Timeline, which takes the + dock's floor (Sameh Khamis, @samehkhamis, #1876). From 9b10489454d48f3f05fd252f963e903bfd09bd6b Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 20:22:33 -0800 Subject: [PATCH 23/24] Keep a landed aircraft on the ground, not at its approach height A grounded row with no altitude fell back to the aircraft's sticky altitude, which straight after a landing is still the approach height. Military contacts then hung there for as long as they stayed on the ground (the grounded floor only ever raises a height); civil contacts held it until the ground cell under them warmed, which for a contact far from the viewer is never. The 3D model is ground-snapped on its own, so the plane dropped when the model took over. A grounded contact with no altitude now uses only an altitude it gave on the ground, else the ground fallback. Labels, the tracked readout and the follow distance read "On the ground" / no flight level instead of the approach altitude. --- src/layers/flights/queries.js | 4 ++- src/layers/flights/records.js | 17 ++++++++-- src/layers/flights/records.test.mjs | 44 +++++++++++++++++++++++--- src/layers/flights/tracking.js | 12 ++++++-- src/layers/military/queries.js | 13 +++++--- src/layers/military/records.js | 25 +++++++++------ src/layers/military/records.test.mjs | 46 ++++++++++++++++++++++++++++ src/layers/military/tracking.js | 10 ++++-- 8 files changed, 145 insertions(+), 26 deletions(-) diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 7ebb9feb12..681db5c9cf 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -546,7 +546,9 @@ export function createQueries({ object._labelCallsign = callsign; object._labelRegistration = registration; } - const altitude = info?.altitude; + // A grounded contact shows no flight level: its sticky `altitude` may + // still be the approach height. + const altitude = info?.onGround ? 0 : info?.altitude; if (object._altitude !== altitude) { object._altitude = altitude; object.metric = formatFlightLevel(altitude); // altitude is metres diff --git a/src/layers/flights/records.js b/src/layers/flights/records.js index eeb25a8cc1..1f2922606e 100644 --- a/src/layers/flights/records.js +++ b/src/layers/flights/records.js @@ -232,7 +232,13 @@ export class FlightRecords { surfaceM = geoidSurfaceLastResortM({ geoAltM: geo_alt, baroAltM: baro_alt, - priorRenderM: prevMeta?.renderAltitudeM, + // Only a height held ON THE GROUND counts as prior: straight after a + // landing the previous render height is the approach height, and + // holding it left the plane hanging there until a cell warmed — + // forever for a contact far from the viewer, whose cell is never + // queued (HAL-1032). + priorRenderM: + prevMeta?.onGround === true ? prevMeta.renderAltitudeM : null, geoidN, }); } @@ -266,10 +272,15 @@ export class FlightRecords { let renderAltitudeM; if (pickedAltM != null) { renderAltitudeM = pickedAltM; - } else if (Number.isFinite(prevMeta?.renderAltitudeM)) { + } else if ( + Number.isFinite(prevMeta?.renderAltitudeM) && + (!onGround || prevMeta.onGround === true) + ) { renderAltitudeM = prevMeta.renderAltitudeM; } else { - renderAltitudeM = alt; + // A grounded contact with nothing better sits at 0 m: `alt` is sticky, + // so after a landing it still holds the approach altitude. + renderAltitudeM = onGround ? 0 : alt; } // Field-test fix (WAKE01/RS46 class, 2026-07-06; widened round 3): // floor a low airborne contact's render height at the local coarse diff --git a/src/layers/flights/records.test.mjs b/src/layers/flights/records.test.mjs index 9ec4b74679..fdf067c72f 100644 --- a/src/layers/flights/records.test.mjs +++ b/src/layers/flights/records.test.mjs @@ -112,16 +112,52 @@ test('civil record owners isolate state and preserve partial, missing-poll and l ); }); -test('ground transitions preserve last render height while a surface cell is cold', () => { +test('a landing with a cold surface cell sits on the geoid, not at its approach height', () => { const store = records(); + store.geoidReady = true; store.receive(observation({ ellipsoidAltitudeM: 1040 }), view()); + // Every grounded poll, not just the first: a contact far from the viewer + // never has its cell warmed (HAL-1032). + for (let poll = 0; poll < 3; poll += 1) { + const next = store.receive( + observation({ + onGround: true, + baroAltitudeM: null, + positionTimeMs: 1700000010000 + poll * 10000, + }), + view(), + ); + assert.equal(next.groundFlipped, poll === 0); + assert.equal(next.meta.renderAltitudeM, 40); + assert.equal(next.meta.wasAirborne, true); + } +}); + +test('a landing before the geoid loads sits at 0 m, not at its approach height', () => { + const store = records(); + store.receive(observation({ baroAltitudeM: 1539 }), view()); const next = store.receive( observation({ onGround: true, baroAltitudeM: null }), view(), ); - assert.equal(next.groundFlipped, true); - assert.equal(next.meta.renderAltitudeM, 1040); - assert.equal(next.meta.wasAirborne, true); + assert.equal(next.meta.renderAltitudeM, 0); +}); + +test('a parked contact whose surface cell goes cold holds its ground height', () => { + let floor = 312; + const store = new FlightRecords({ + geoidHeight: () => 40, + cachedGroundFloor: () => floor, + floorAltitudeM: (altitude) => altitude, + approxDistanceKm: () => 0, + fleetModels: () => null, + }); + store.geoidReady = true; + const grounded = () => + store.receive(observation({ onGround: true, baroAltitudeM: null }), view()); + assert.equal(grounded().meta.renderAltitudeM, 312); + floor = null; + assert.equal(grounded().meta.renderAltitudeM, 312); }); test('complete snapshots age out vanished aircraft and retain position-less ones unless landed', () => { diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index d4aa51a710..0ab27b03ea 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -900,13 +900,19 @@ export function createTracking({ // the ICAO hex, so a callsign-less enriched contact heads its readout with // the tail number rather than raw hex. const cs = parts.queries._contactLabel(icao24, info); - const altFt = Math.round((info.altitude || 0) * 3.28084); + const altFt = info.onGround + ? null + : Math.round((info.altitude || 0) * 3.28084); // Flight levels are an aviation code; feet and knots read in the active // language ("0 фт · 1 уз"). const quantity = (value, unit) => `${formatNumber(value, { useGrouping: false })} ${unitLabel(unit)}`; const fl = - altFt >= 18000 ? `FL${Math.round(altFt / 100)}` : quantity(altFt, 'ft'); + altFt == null + ? t('On the ground') + : altFt >= 18000 + ? `FL${Math.round(altFt / 100)}` + : quantity(altFt, 'ft'); const spd = info.velocity ? quantity(Math.round(info.velocity * 1.944), 'kts') : ''; @@ -1164,7 +1170,7 @@ export function createTracking({ // viewFrom — behind + above, distance scaled to altitude — for a readable // initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.) const followRange = Math.min( - Math.max((info.altitude || 1500) * 1.1 + 2500, 3000), + Math.max((info.onGround ? 0 : info.altitude || 1500) * 1.1 + 2500, 3000), 30000, ); const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55); diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index 8b14315781..048b4d2a05 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -194,9 +194,12 @@ export function createQueries({ lon: num(info?.rawLon), // altitudeFt is the sticky barometric/MSL aviation field — converted to // meters here for shape parity with the flights layer. - altitudeM: Number.isFinite(info?.altitudeFt) - ? info.altitudeFt * 0.3048 - : null, + // A grounded contact reports only an altitude it gave on the ground. + altitudeM: info?.onGround + ? (info.groundAltitudeM ?? null) + : Number.isFinite(info?.altitudeFt) + ? info.altitudeFt * 0.3048 + : null, speedMps: num(info?.speedMps), heading: num(info?.track), verticalRateMps: num(info?.verticalRateMps), @@ -510,7 +513,9 @@ export function createQueries({ // TR-3B, not the airframe underneath it. const klass = tr3bTypeLabel(icao24, info?.type || 'MIL'); if (object.klass !== klass) object.klass = klass; - const altitudeFt = info?.altitudeFt ?? 0; + // A grounded contact shows no flight level, like the civil layer; its + // sticky altitudeFt may still be the approach height. + const altitudeFt = info?.onGround ? 0 : (info?.altitudeFt ?? 0); if (object._altitudeFt !== altitudeFt) { object._altitudeFt = altitudeFt; // military metadata stores altitudeFt (feet); the helper takes metres diff --git a/src/layers/military/records.js b/src/layers/military/records.js index 23581c3456..cefa1773da 100644 --- a/src/layers/military/records.js +++ b/src/layers/military/records.js @@ -70,19 +70,25 @@ export class MilitaryFlightRecords { this.missingPolls.delete(icao24); const prevMeta = this.data.get(icao24); // adsb.lol/readsb reports GROUND traffic as alt_baro === "ground" (no - // separate boolean). Grounded planes fall back to their last known - // altitude (field elevation is unknowable here), else 0 m — never the - // 3 km airborne default (a parked plane must not float). + // separate boolean). Grounded planes fall back to an altitude they + // reported while on the ground (field elevation is unknowable here), + // else 0 m — never the 3 km airborne default, and never the last + // AIRBORNE altitude: `altitudeFt` is sticky across the landing, so it + // still holds the approach height, and the icon would hang there while + // the ground-snapped model sits on the field (a parked plane must not + // float). `groundAltitudeM` is that ground-only altitude: set by a + // grounded report that carries one, held while grounded, dropped on + // takeoff. const onGround = aircraft.onGround; const altitudeFt = aircraft.baroAltitudeM == null ? null : aircraft.baroAltitudeM / 0.3048; + const groundAltitudeM = onGround + ? (aircraft.baroAltitudeM ?? + (prevMeta?.onGround === true ? prevMeta.groundAltitudeM : null) ?? + null) + : null; const altitudeM = - aircraft.baroAltitudeM ?? - (onGround - ? Number.isFinite(prevMeta?.altitudeFt) - ? prevMeta.altitudeFt * 0.3048 - : 0 - : 3048); + aircraft.baroAltitudeM ?? (onGround ? (groundAltitudeM ?? 0) : 3048); const verticalRateMps = aircraft.verticalRateMps; const callsign = aircraft.callsign; const type = aircraft.typeCode; @@ -198,6 +204,7 @@ export class MilitaryFlightRecords { registration: stickyText(registration, prevMeta?.registration), operator: stickyText(operator, prevMeta?.operator), altitudeFt: stickyNumber(altitudeFt, prevMeta?.altitudeFt, null), + groundAltitudeM, // geoAltitudeM/renderAltitudeM are ADDITIVE fields alongside the // untouched aviation `altitudeFt` — never rename/replace it (labels, // the FL readout, and the landed-fast-cull heuristic all still read diff --git a/src/layers/military/records.test.mjs b/src/layers/military/records.test.mjs index bbea594d87..9348574487 100644 --- a/src/layers/military/records.test.mjs +++ b/src/layers/military/records.test.mjs @@ -65,6 +65,52 @@ test('military ground records leave model-owned placement alone and warm the sam assert.deepEqual(unowned.floorWarmPoints, owned.floorWarmPoints); }); +test('a military contact that lands with no altitude sits on the ground, not at its last airborne height', () => { + for (const [modelOwnsVisual, expected] of [ + [false, 201.5], + [true, 0], + ]) { + const records = store(); + records.receive( + observation({ baroAltitudeM: 1539 }), + context({ modelOwnsVisual }), + ); + // Every grounded report, not just the first after the landing. + for (let poll = 0; poll < 3; poll += 1) { + const landed = records.receive( + observation({ onGround: true, baroAltitudeM: null, speedMps: 4.6 }), + context({ modelOwnsVisual }), + ); + assert.equal(landed.meta.renderAltitudeM, expected); + // The aviation readout keeps the last reported altitude, as before. + assert.equal(landed.meta.altitudeFt, 1539 / 0.3048); + } + } +}); + +test('a grounded military contact holds a ground altitude it reported earlier', () => { + const records = store(); + records.receive( + observation({ onGround: true, baroAltitudeM: 320 }), + context({ modelOwnsVisual: true }), + ); + for (let poll = 0; poll < 2; poll += 1) { + const next = records.receive( + observation({ onGround: true, baroAltitudeM: null }), + context({ modelOwnsVisual: true }), + ); + assert.equal(next.meta.renderAltitudeM, 320); + } + // Airborne again: that ground altitude is forgotten, so the next landing + // without an altitude starts from the ground, not from it. + records.receive(observation({ baroAltitudeM: 900 }), context()); + const relanded = records.receive( + observation({ onGround: true, baroAltitudeM: null }), + context({ modelOwnsVisual: true }), + ); + assert.equal(relanded.meta.renderAltitudeM, 0); +}); + test('military records keep bounded partial retention and release metadata only after removal admission', () => { const first = store(); const second = store(); diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index f1ffefcd7d..03e0c40b4c 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -365,7 +365,9 @@ export function createTracking({ parts.queries._toCleanText(info?.registration) || t('Reg unknown'); const operator = parts.queries._toCleanText(info?.operator) || t('Operator unknown'); - const altitude = parts.queries._formatAltitude(info?.altitudeFt); + const altitude = info?.onGround + ? t('On the ground') + : parts.queries._formatAltitude(info?.altitudeFt); const speedKt = info?.speedMps ? Math.round(info.speedMps * 1.944) : null; const tail = speedKt ? `${altitude} · ${speedKt} kt` : altitude; return [ @@ -1124,7 +1126,11 @@ export function createTracking({ // renderer's default follow distance is far too tight. It gets a calibrated // viewFrom — behind + above, distance scaled to altitude — for a readable // initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.) - const altM = info?.altitudeFt ? info.altitudeFt * 0.3048 : 1500; + const altM = info?.onGround + ? 0 + : info?.altitudeFt + ? info.altitudeFt * 0.3048 + : 1500; const followRange = Math.min(Math.max(altM * 1.1 + 2500, 3000), 30000); const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55); From 2dd26de768d011b3bd724f3252bff02f62e567f6 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 20:22:43 -0800 Subject: [PATCH 24/24] Add the changelog entry for #1877 --- changelog.d/1877-landed-aircraft-on-ground.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 changelog.d/1877-landed-aircraft-on-ground.md diff --git a/changelog.d/1877-landed-aircraft-on-ground.md b/changelog.d/1877-landed-aircraft-on-ground.md new file mode 100644 index 0000000000..a53cf27fb0 --- /dev/null +++ b/changelog.d/1877-landed-aircraft-on-ground.md @@ -0,0 +1,4 @@ +- A plane that lands and is reported on the ground with no altitude stays on + the ground, instead of hanging at its approach height until it takes off + or its 3D model appears; its labels read "On the ground" (samehkhamis, + #1877).