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). diff --git a/changelog.d/1869-kit-sweep-final-scan.md b/changelog.d/1869-kit-sweep-final-scan.md new file mode 100644 index 0000000000..bcdfc9d9ff --- /dev/null +++ b/changelog.d/1869-kit-sweep-final-scan.md @@ -0,0 +1,3 @@ +- The view scan now forbids any hand-written button, Material glyph, + checkbox or range in the views, and any control built in script + (manjunath22466, samehkhamis, #1869). 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). 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). 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). 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). 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). 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). 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). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index a6320958e1..826183c127 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 @@ -1201,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 @@ -6354,8 +6370,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 @@ -8867,6 +8884,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/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index bbe5450990..aa2909df10 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -84,6 +84,21 @@ Home and End), since each of Core's groups keeps its own keyboard policy, and once and asks for a change only when it lands on another option. Every segmented group in Core is a `UiSegmented`; the old `segmentedControl.js` adapter is gone. +No view hand-writes a control the kit has: every button in an SFC outside +the kit is a `UiButton`, `UiCloseButton` or another kit control, every +Material Symbols glyph a `UiIcon`, every checkbox a `UiCheckbox`, every +select a `UiSelect`, and every range a `UiSlider` except the radio +tuner's and the world timeline's, for the reasons given below. No module +outside the kit, and no SFC's script, builds a button, select, field or +Material glyph in script or writes one as markup in a string, apart from +the globe panel's standalone page (`src/tools/globePanel.js`), plain HTML +a host serves with no Vue or kit, whose Expand and Open buttons are +written as markup (`src/ui/kit/viewControls.test.mjs` pins all of it). +The native fields left are the text, number, password and file inputs +and the two text areas (the chat's message box and the scene dialog's +multiline field) the kit has no control for, and the search fields whose +surfaces this document names. The scene dialog's single-line field takes +its type from its caller, which passes text-like types only. `UiButton` adds `pressedClass`, Core's class on a pressed toggle (most use `active`); its pressed classes toggle through `classList`, so a class other code adds (a voice highlight) survives a press. Every pressed toggle (a diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 07557b3c71..de208048ea 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", @@ -5536,6 +5540,7 @@ "src/data/entityContext.js", "src/ui/stores/entityCard.js", "src/ui/entityContextBridge.js", + "src/data/locate.js", "src/render/cesium/cardPreviews.js" ], "external": [ @@ -5978,6 +5983,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/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/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/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/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..681db5c9cf 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, @@ -545,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 @@ -778,6 +781,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/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 52221f6d6e..048b4d2a05 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, @@ -193,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), @@ -509,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 @@ -651,6 +657,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/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); diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index c9b9f48a11..509ee48c75 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]); @@ -159,6 +157,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. @@ -228,13 +236,20 @@ 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, 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; + * 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. @@ -284,6 +299,17 @@ 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; + /** + * 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. + */ + let 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; @@ -396,22 +422,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() { @@ -469,6 +501,30 @@ 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: nextViewKey() }); + 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(); + retiredCanvases.add(canvas); + canvas = element; + // 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. */ + function dropRenderer() { const lost = renderer; renderer = null; // The new renderer starts facing the photo's heading: keep the user's look. @@ -479,11 +535,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); @@ -665,9 +720,23 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; - ELEMENTS[name]?.(element); + 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); - if (name === 'canvas') wake(canvasWaiters); + if (name === 'canvas') { + canvasDraws++; + wake(canvasWaiters); + } }, keydown: current(onKeyDown), pointerdown: current(onPointerDown), @@ -683,7 +752,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', @@ -693,7 +762,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, @@ -865,9 +934,27 @@ 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; + canvasMoved = false; show('pano'); - await nextDraw(signal); + 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) { + image.close?.(); + photo = null; + show(null); + throw undrawn(); + } if (seq !== openSeq || !renderer) { image.close?.(); if (seq !== openSeq) return false; @@ -916,7 +1003,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); @@ -937,12 +1025,31 @@ 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. - const drawn = new Promise((resolve) => rootWaiters.add(resolve)); + // Resolves once the view drew the viewer, or it was unmounted, or its + // last view left, meanwhile. + const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve)); + let drawn = waitRoot(); build(host); - if (!root) await drawn; - // Unmounted or superseded before the view drew it. - if (!root) throw new Error('Street-level viewer was closed'); + // 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; + 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. */ @@ -1029,7 +1136,17 @@ export function createPhotoViewer({ subscribeView(listener) { viewListeners.add(listener); listener(presented); - return () => viewListeners.delete(listener); + return () => { + // The last view went: a mount or an open waiting on its draw fails + // as closed. + 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); + } + }; }, }; return adapter; diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index 97c8bf4000..1f01117957 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 }, @@ -636,3 +643,356 @@ 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('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; + 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'); + 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(); + 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(); +}); + +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(); +}); + +/** 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(); +}); + +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(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index ecf4eab5a1..ed32dd5208 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,37 +1,93 @@ +/** 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, 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 (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 + * 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 its rank, {view, key}. const shown = new Map(); let ready = false; + let closed = false; + let superseding = false; let last; + /** 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. + 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; - 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(); + for (const entry of shown.values()) + if (!next || entry.key > next.key) next = entry; + next = next?.view ?? null; + if (!ready) return; + if (next !== last) { + last = next; + listener(next); + } + if (last && 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; + 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); @@ -40,6 +96,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..aa56b6b316 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -1,6 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { subscribePhotoViewers } from './photoViewers.js'; +import { createPhotoViewer } from './photoViewer.js'; +import { nextViewKey, subscribePhotoViewers } from './photoViewers.js'; /** * A photo viewer whose presentations the test sends; `superseded` counts. @@ -9,6 +10,7 @@ import { subscribePhotoViewers } from './photoViewers.js'; */ function fakeViewer() { const listeners = new Set(); + let current = null; const viewer = { superseded: 0, view(mountKey) { @@ -18,18 +20,19 @@ 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); }, }; 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 +43,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 +58,158 @@ 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 mounted when it began presenting', async () => { + 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(nextViewKey())); + const keyless = b.view(undefined); + b.present(keyless); + assert.equal(shown.at(-1), keyless, 'after the keyed one'); + // Of two without, the one that began presenting last. + 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(nextViewKey()); + 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(); +}); + +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(); +}); + +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/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 b74cfcdc99..b332b61355 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 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/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/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 0391c2752f..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'; @@ -177,13 +178,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. @@ -250,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/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..97e107b82e --- /dev/null +++ b/src/parameterDefaults.test.mjs @@ -0,0 +1,113 @@ +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 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(...builtModules(absolute)); + else if ( + entry.isFile() && + /\.(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?.()`, `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; + 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?.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 builtModules()) { + const { code, kind } = scriptOf(file); + const source = ts.createSourceFile( + file, + code, + ts.ScriptTarget.Latest, + true, + kind, + ); + 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, []); +}); 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); 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 { diff --git a/src/testSupport/kartaViewFakes.mjs b/src/testSupport/kartaViewFakes.mjs index 83ed5f38f5..5849e8f7d2 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,58 @@ 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?.(); +} + +/** + * 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 since the last `resetPhotoView()` (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 +131,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 +214,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 +222,7 @@ export function drawPhotoViewer(viewer) { queued = false; draw(pending); }); - }); + }; } /** diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index c086cefd84..655540c924 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -118,6 +118,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, @@ -129,6 +131,7 @@ export class StyleManager extends ShellFacade { initialShareCode = null, localePicker = true, homeView = null, + startLayers = [], } = {}, ) { super(); @@ -257,6 +260,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/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/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/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/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index be1d65a8b5..1c65279af4 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -74,10 +74,27 @@ 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; +// 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); + 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/, @@ -86,10 +103,59 @@ 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*=[^=]/, + 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. + assert.doesNotMatch( + source.replace(/\b(?:const|let|var)\s*\[/g, ''), + assigned(String.raw`[\w$)\]]\s*\[[^[\]]*\]`), + 'a bracket write', + ); + // 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. + assert.match(loader, /\bconst image = new Image\(\);/); + assert.equal( + loader.match(/\b(?:const|let|var|function|class)\s+image\b/g)?.length, + 1, + '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*\([^)]*\bimage\b/, + ]) + assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed'); + const writes = loader.match(SRC)?.length ?? 0; + assert.equal( + loader.match(assigned(String.raw`(? new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`); diff --git a/src/ui/kit/viewControls.test.mjs b/src/ui/kit/viewControls.test.mjs index 81ff7a7ca4..7ef7d42ba2 100644 --- a/src/ui/kit/viewControls.test.mjs +++ b/src/ui/kit/viewControls.test.mjs @@ -1,10 +1,14 @@ // The kit's every-control claims in docs/VUE-MIGRATION.md, read from every -// SFC outside the kit: every select is a UiSelect, every pressed toggle a -// UiButton with `pressed` (no template hand-writes `aria-pressed` on any -// element, as an attribute or inside a `v-bind` object, apart from the -// exceptions below), and every close, dismiss and clear button a -// UiCloseButton. -// Controls built in script are not read here. +// SFC outside the kit: every button is a kit button, every select a +// UiSelect, every checkbox a UiCheckbox, every range a UiSlider apart from +// the two named below, and every Material Symbols glyph a UiIcon; every +// pressed toggle is a UiButton with `pressed` (no template hand-writes +// `aria-pressed` on any element, as an attribute or inside a `v-bind` +// object, apart from the exceptions below), and every close, dismiss and +// clear button a UiCloseButton. Outside the kit, no module (nor an SFC's +// script) builds a button, select, field or Material glyph in script, or +// writes one as markup in a string, apart from the globe panel's standalone +// page named below. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync, readdirSync } from 'node:fs'; @@ -69,6 +73,59 @@ const HAND_WRITTEN_CLOSE = new RegExp( const tidy = (markup) => markup.replace(/\s+/g, ' '); +// The two ranges that stay native, by file (docs/VUE-MIGRATION.md says why). +const NATIVE_RANGES = { + 'src/ui/views/panels/RadioTuner.vue': 1, + 'src/ui/views/panels/WorldTimeline.vue': 1, +}; +const RAW_BUTTON = /`, 'gi'); +// An attribute and its value, read from the tag rather than other values. +const ATTRIBUTE = /([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'/>]+)))?/g; +/** + * A tag's `type`: written, bound to a quoted literal (`:type="'checkbox'"`), + * or named in a `v-bind` object; null when it is bound to anything else. + */ +function inputType(attrs) { + for (const m of attrs.matchAll(ATTRIBUTE)) { + const name = m[1].toLowerCase(); + const value = m[2] ?? m[3] ?? m[4] ?? ''; + if (name === 'type') return value.toLowerCase(); + if (name === ':type' || name === 'v-bind:type') { + const literal = /^\s*(['`])([^'`]*)\1\s*$/.exec(value); + if (literal) return literal[2].toLowerCase(); + } + if (name === 'v-bind' || name === ':') { + const named = /\btype\s*:\s*(['`])([^'`]*)\1/.exec(value); + if (named) return named[2].toLowerCase(); + } + } + return null; +} + +/** Hand-written buttons in an SFC's template. */ +const rawButtons = (source) => + [...template(source).matchAll(RAW_BUTTON)].map((m) => m[0]); + +/** Tags in an SFC's template that draw a Material glyph by hand. */ +function materialGlyphs(source) { + const found = []; + for (const m of template(source).matchAll(ANY_TAG)) + if (!/^ + [...template(source).matchAll(INPUT_TAG)] + .filter((m) => inputType(m[1]) === type) + .map((m) => tidy(m[0])); + /** Raw selects in an SFC's template. */ const rawSelects = (source) => [...template(source).matchAll(RAW_SELECT)].map((m) => m[0]); @@ -134,6 +191,82 @@ test('the scans find each hand-written control', () => { assert.equal(handWrittenCloses(markup).length, 0, markup); }); +test('the scans find each hand-written button, glyph, checkbox and range', () => { + for (const markup of [ + '', + '', + ]) + assert.equal(rawButtons(markup).length, 1, markup); + for (const markup of [ + '', + '', + '', + ]) + assert.equal(rawButtons(markup).length, 0, markup); + + for (const markup of [ + '', + '', + '', + '', + ]) + assert.equal(materialGlyphs(markup).length, 1, markup); + for (const markup of [ + '', + '', + '', + ]) + assert.equal(materialGlyphs(markup).length, 0, markup); + + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 1, + ); + assert.equal( + nativeInputs( + '', + 'range', + ).length, + 1, + ); + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 0, + ); + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 0, + ); + for (const markup of [ + ``, + ``, + ``, + '', + '', + ]) + assert.equal(nativeInputs(markup, 'checkbox').length, 1, markup); + assert.equal( + nativeInputs('', 'checkbox') + .length, + 0, + ); + assert.equal( + materialGlyphs( + ``, + ).length, + 1, + ); +}); + test('the views are read: the scan reaches the views and skips the kit', () => { const files = views.map((view) => view.file); assert.ok(files.includes('src/ui/views/panels/ChatPanel.vue')); @@ -169,3 +302,138 @@ test('no view hand-writes a close button; each is a UiCloseButton', () => { found.push(`${file}: ${markup}`); assert.deepEqual(found, []); }); + +test('every button in the views is a kit button', () => { + const found = []; + for (const { file, source } of views) + for (const markup of rawButtons(source)) found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every Material Symbols glyph in the views is a UiIcon', () => { + const found = []; + for (const { file, source } of views) + for (const markup of materialGlyphs(source)) + found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every checkbox in the views is a UiCheckbox', () => { + const found = []; + for (const { file, source } of views) + for (const markup of nativeInputs(source, 'checkbox')) + found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every range in the views is a UiSlider apart from the two named', () => { + const counts = {}; + for (const { file, source } of views) { + const n = nativeInputs(source, 'range').length; + if (n) counts[file] = n; + } + assert.deepEqual(counts, NATIVE_RANGES); +}); + +// The globe panel's standalone page: plain HTML a host serves, with no Vue +// and no kit, so its two buttons are written as markup. +const STRING_MARKUP_PAGES = new Set(['src/tools/globePanel.js']); + +/** + * Every module under src outside the kit, tests and test support, and every + * SFC's script blocks, as `{ file, source }`. + */ +function scriptSources(directory = SRC_ROOT) { + const found = []; + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const absolute = path.join(directory, entry.name); + const file = path.relative(REPO_ROOT, absolute).split(path.sep).join('/'); + if (entry.isDirectory()) { + if ( + path.relative(KIT_ROOT, absolute) !== '' && + entry.name !== 'testSupport' + ) + found.push(...scriptSources(absolute)); + } else if ( + !entry.isFile() || + /\.test\.(?:js|mjs|ts)$|Fixture\.mjs$/.test(entry.name) + ) { + continue; + } else if (/\.(?:js|mjs|ts)$/.test(entry.name)) { + found.push({ file, source: readFileSync(absolute, 'utf8') }); + } else if (entry.name.endsWith('.vue')) { + const blocks = [ + ...readFileSync(absolute, 'utf8').matchAll( + /]*>([\s\S]*?)<\/script\s*>/g, + ), + ]; + found.push({ file, source: blocks.map((m) => m[1]).join('\n') }); + } + } + return found; +} + +const SCRIPT_CONTROL = + /\bcreateElement(?:NS)?\(\s*(?:[^,)]*,\s*)?['"`](?:button|select|input|textarea)['"`]/gi; +const SCRIPT_GLYPH = + /['"`][^'"`]*\bmaterial-symbols-(?:outlined|rounded|sharp|\$\{)/g; +const STRING_MARKUP = /<(?:button|select|input|textarea)\b/gi; + +/** A source with its comments blanked, line numbers kept. */ +const uncommented = (source) => + source + .replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:'"`\\])\/\/[^\n]*/g, '$1'); + +/** Each match in a source, as `file:line: text`. */ +function hits(file, source, pattern) { + return [...source.matchAll(pattern)].map((m) => { + const line = source.slice(0, m.index).split('\n').length; + return `${file}:${line}: ${source.split('\n')[line - 1].trim()}`; + }); +} + +test('no module outside the kit builds a control or Material glyph in script', () => { + const sees = (pattern, text) => [...text.matchAll(pattern)].length > 0; + assert.ok( + sees(SCRIPT_CONTROL, "const b = document.createElement('button');"), + ); + assert.ok(sees(SCRIPT_CONTROL, 'doc.createElement("INPUT")')); + assert.ok( + sees(SCRIPT_CONTROL, "someDocument.createElement(\n 'button',\n);"), + ); + assert.ok(!sees(SCRIPT_CONTROL, "document.createElement('div')")); + assert.ok( + sees(SCRIPT_GLYPH, "span.className = 'material-symbols-outlined';"), + ); + assert.ok(sees(SCRIPT_GLYPH, 'el.className = `material-symbols-${style}`;')); + assert.ok( + !sees(SCRIPT_GLYPH, 'ctx.font = \'24px "Material Symbols Outlined"\';'), + ); + assert.ok(sees(STRING_MARKUP, "host.innerHTML = '';")); + 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, 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`, + ); + } +}); 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( 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/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); 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/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'] 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 }} + 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) {