From 28ee3bfc3748c60af1dba027a655fe344b1ea168 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 6 Nov 2026 00:47:52 +0000 Subject: [PATCH 001/138] Keep app shortcuts off Cmd/Ctrl/Alt combos; F collapses the layer panel like its button --- src/ui/applicationShell.js | 1 + src/ui/applicationShortcuts.js | 5 +++++ src/ui/displayBindings.js | 4 ++-- src/ui/visualInput.test.mjs | 14 ++++++++++++-- 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index ac921b34b5..1e4daaefdb 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -542,6 +542,7 @@ export class StyleManager extends ShellFacade { _toggleOrbit: (...args) => this._toggleOrbit(...args), toggleCleanView: (...args) => this.toggleCleanView(...args), _toggleCctvEnabled: (...args) => this._toggleCctvEnabled(...args), + _togglePanel: (panelId) => this._panelChrome._togglePanel(panelId), _setBloomEnabled: (...args) => this._setBloomEnabled(...args), _setBloomIntensity: (...args) => this._setBloomIntensity(...args), _setSharpenEnabled: (...args) => this._setSharpenEnabled(...args), diff --git a/src/ui/applicationShortcuts.js b/src/ui/applicationShortcuts.js index 57214a570d..d83e0caab2 100644 --- a/src/ui/applicationShortcuts.js +++ b/src/ui/applicationShortcuts.js @@ -27,6 +27,11 @@ export function bindApplicationShortcuts({ event.target?.matches?.('select, input, textarea') || event.target === searchInput; if (isFormControl && event.key !== 'Escape') return; + // Browser and OS shortcuts (Cmd+C, Ctrl+F, Alt+1…) are not ours. + if (event.metaKey || event.ctrlKey || event.altKey) { + if (event.key === 'Escape') actions.dismissSearch(); + return; + } if (STYLE_KEYS[event.key]) actions.setStyle(STYLE_KEYS[event.key]); if (event.key === 'Escape') actions.dismissSearch(); diff --git a/src/ui/displayBindings.js b/src/ui/displayBindings.js index 73c4fbee68..5a00dc6631 100644 --- a/src/ui/displayBindings.js +++ b/src/ui/displayBindings.js @@ -64,8 +64,8 @@ export class DisplayBindings { }, toggleOrbit: () => this._toggleOrbit(), toggleCleanView: () => this.toggleCleanView(), - toggleLayers: () => - document.getElementById('data-panel').classList.toggle('active'), + // Same collapse as the panel's own button, so its rail entry stays. + toggleLayers: () => this._togglePanel('data-panel'), cycleDetection: () => { this.shareLinkManager?.claimRestoreLane?.('visual'); this.claimDetection(); diff --git a/src/ui/visualInput.test.mjs b/src/ui/visualInput.test.mjs index d49a19bda0..82ca6beccd 100644 --- a/src/ui/visualInput.test.mjs +++ b/src/ui/visualInput.test.mjs @@ -117,9 +117,19 @@ test('the supplied search target retains editing even without form markup', () = assert.deepEqual(f.calls, [['dismissSearch']]); }); -test('shortcut extraction does not change repeat or modifier policy', () => { +test('browser shortcuts with Cmd, Ctrl or Alt never reach app shortcuts', () => { const f = shortcuts(); - f.press('h', new Element(), { repeat: true, ctrlKey: true }); + for (const modifier of ['metaKey', 'ctrlKey', 'altKey']) + for (const key of ['1', 'h', 'o', 'v', 'f', 'd', 'c']) + f.press(key, new Element(), { [modifier]: true }); + assert.deepEqual(f.calls, []); + f.press('Escape', new Element(), { metaKey: true }); + assert.deepEqual(f.calls, [['dismissSearch']]); +}); + +test('a held key still repeats its shortcut', () => { + const f = shortcuts(); + f.press('h', new Element(), { repeat: true }); assert.deepEqual(f.calls, [['toggleHud']]); }); From d3904b9503b203d7541f8f29f362c9e4efc7e720 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Fri, 6 Nov 2026 11:59:27 +0000 Subject: [PATCH 002/138] Changelog: 1598 fragment --- changelog.d/1598-shortcuts-modifier-keys.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 changelog.d/1598-shortcuts-modifier-keys.md diff --git a/changelog.d/1598-shortcuts-modifier-keys.md b/changelog.d/1598-shortcuts-modifier-keys.md new file mode 100644 index 0000000000..80c30dde51 --- /dev/null +++ b/changelog.d/1598-shortcuts-modifier-keys.md @@ -0,0 +1,5 @@ +- Keep single-key app shortcuts off Cmd, Ctrl and Alt combinations, so Cmd+F, + Cmd+C and Cmd+R reach the browser instead of hiding the layer panel or + switching layers on. `F` now collapses the layer panel the way its button + does, instead of hiding the panel and the button that brings it back + (asturksever, #1598). From a8ac8eeb9b9a0e1e1f009b480327724e521fe273 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Mon, 16 Nov 2026 17:55:29 +0530 Subject: [PATCH 003/138] feat(earthquakes): select quakes by click and show their details Clicking a quake's disc selects it and shows a card with its magnitude and USGS class, a class meter with the depth band, place, UTC time and source. With a USGS event id the card opens the event page. Clicking a magnitude label, the part a far view can hit, also flies the camera to the quake. The selection joins the shared context selection, so "what's selected" answers with it. The selected disc is painted with a gradient that fades to its outer circle, and wavy contour lines run out from the marker for three cycles while it is on screen, then rest as still contours, so a parked camera returns to idle. A feed refresh updates the selection in place without restarting the lines or taking back the shared selection. The package takes input, picking, context, focus, the opener, the painter and the translator by injection; without them it draws as before. --- docs/CURRENT-STATE.md | 23 + scripts/format-scope.json | 3 + scripts/package-boundaries.json | 2 + src/app/layers/earthquakeRipples.js | 381 ++++++++++++++ src/app/layers/earthquakeRipples.test.mjs | 420 +++++++++++++++ src/app/layers/earthquakes.js | 44 +- src/i18n/locales/ar.json | 11 + src/i18n/locales/de.json | 11 + src/i18n/locales/es.json | 11 + src/i18n/locales/fr.json | 11 + src/i18n/locales/he.json | 11 + src/i18n/locales/it.json | 11 + src/i18n/locales/ja.json | 11 + src/i18n/locales/pt.json | 11 + src/i18n/locales/ru.json | 11 + src/i18n/locales/sv.json | 11 + src/i18n/locales/uk.json | 11 + src/i18n/locales/zh-CN.json | 11 + src/i18n/locales/zh-Hant.json | 11 + src/layers/earthquakes/index.js | 397 ++++++++++++-- src/layers/earthquakes/model.js | 292 +++++++++++ src/layers/earthquakes/selection.test.mjs | 610 ++++++++++++++++++++++ src/navigationPolicy.js | 1 + src/worldFocus.js | 3 + src/worldFocus.test.mjs | 7 +- 25 files changed, 2292 insertions(+), 34 deletions(-) create mode 100644 src/app/layers/earthquakeRipples.js create mode 100644 src/app/layers/earthquakeRipples.test.mjs create mode 100644 src/layers/earthquakes/selection.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 811e2a1fd6..5a3af0a5b9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1851,6 +1851,19 @@ feed's place, cut to 40 characters (`earthquakeMarkLabel` in `src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon Islands`, or `M6.4` with no place). +Clicking a quake's disc selects it; clicking its magnitude label (what a far +view can hit) also flies the camera there through the world-focus request +(`earthquake` framing in `src/worldFocus.js`). The selected quake shows a card +(`describeEarthquake`): magnitude and USGS class (`M5.5 · Moderate`), a +six-step class meter with the depth band, place, UTC time and source; with a +USGS event id the card opens that event's page. The selection is also the +shared context selection, so "what's selected" answers with it. Its disc is +painted with a gradient fading to the outer circle and wavy contour lines +(shaped by the quake's id, never crossing) under the labels. The package takes +clicks, picking, context, focus, the opener, the painter and the translator by +injection (`src/app/layers/earthquakes.js`); without input and picking it draws +and takes no clicks, and its labels stay non-interactive. + Air quality (`./layers/air-quality`) draws its station discs as one renderer draw set of ground-clamped fills and reads the view through the camera port; it no longer reaches Cesium, so a caller handing it a Cesium viewer, @@ -8165,6 +8178,16 @@ on it. per frame, it holds NO continuous-render hold — the governor stays idle with earthquakes on, and the manager's `layer-tick` / `layer-visibility` requests carry new data to the screen. Pinned in `src/data/earthquakes.test.mjs`. + The one animation is the selected quake's contour lines + (`src/app/layers/earthquakeRipples.js`), painted on the world overlay, not + the ground set: they ask for frames for `RIPPLE_ACTIVE_CYCLES` (3) runs out + to the disc's edge after a selection (about 14 s), only while the disc is on + screen, then rest as still contours and ask for none. A parked camera with a + quake selected therefore returns to idle. A feed refresh updates the + selected quake in place: it neither runs the contours again nor takes back + a shared selection made since; only a click or a label's activation does. + Selecting fades that one disc's flat fill once (an `upsert`, not per frame) + under the painted gradient. - **Geocode framing has an off-centre sanity gate.** A viewport that is both bigger than any city (>300 km diagonal) and not centred on its own geocoded location (anchor >15% of the diagonal from the centroid) is replaced by a diff --git a/scripts/format-scope.json b/scripts/format-scope.json index e474377e12..1069652db2 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -434,6 +434,9 @@ "src/layers/earthquakes/model.js", "src/layers/earthquakes/source.js", "src/layers/earthquakes/ownership.test.mjs", + "src/layers/earthquakes/selection.test.mjs", + "src/app/layers/earthquakeRipples.js", + "src/app/layers/earthquakeRipples.test.mjs", "src/layers/perimeters/index.js", "src/layers/perimeters/records.js", "src/layers/perimeters/source.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 4147d8f6cd..4b4d0e9776 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -4060,6 +4060,7 @@ "src/app/layers/bikeshare.js", "src/app/layers/cctv.js", "src/app/layers/cyclones.js", + "src/app/layers/earthquakeRipples.js", "src/app/layers/earthquakes.js", "src/app/layers/firms.js", "src/app/layers/flights.js", @@ -5466,6 +5467,7 @@ "src/app/layers/bikeshare.js", "src/app/layers/cctv.js", "src/app/layers/cyclones.js", + "src/app/layers/earthquakeRipples.js", "src/app/layers/earthquakes.js", "src/app/layers/firms.js", "src/app/layers/flights.js", diff --git a/src/app/layers/earthquakeRipples.js b/src/app/layers/earthquakeRipples.js new file mode 100644 index 0000000000..31f3557c44 --- /dev/null +++ b/src/app/layers/earthquakeRipples.js @@ -0,0 +1,381 @@ +import { registerWorldOverlayPaintLane } from '../../overlays/worldOverlay.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { + earthquakeContourRings, + earthquakeContourScale, + earthquakeContourShape, + earthquakeRippleRings, + EARTHQUAKE_RIPPLE_PERIOD_MS, +} from '../../layers/earthquakes/model.js'; + +/** Points around each contour line: smooth at the largest disc on screen. */ +export const RIPPLE_RING_SEGMENTS = 96; +/** An index contour's width, and every other line's. */ +const INDEX_WIDTH_PX = 2; +const LINE_WIDTH_PX = 1.1; +/** + * The overlay lane the lines paint in: the magnitude labels' own. A lane's + * custom painters run before its entries, so the lines sit under the labels + * and under the selected quake's card. + */ +export const RIPPLE_PAINT_LANE = 'ambient-label'; +/** + * The selected disc's fill, [offset, alpha] from the epicentre (0) to its + * outer circle (1): strongest in the middle, fading out to nothing at the + * edge. + */ +export const DISC_FADE = Object.freeze([ + [0, 0.42], + [0.35, 0.26], + [0.75, 0.1], + [1, 0], +]); +/** + * Each contour wave's fill, out to its own line: clear inside, tinting + * toward the line; times the wave's own fade. + */ +export const WAVE_FADE = Object.freeze([ + [0, 0], + [0.55, 0], + [1, 0.2], +]); + +/** + * `rgb(r,g,b)` (or `rgba`) as a function of alpha, for gradient stops; any + * other colour keeps its own alpha. + */ +export function cssWithAlpha(color) { + const m = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(color)); + if (!m) return () => color; + const rgb = `${m[1]},${m[2]},${m[3]}`; + return (alpha) => `rgba(${rgb},${Math.max(0, Math.min(1, alpha))})`; +} + +/** + * How many times the lines run out to the edge after a quake is selected + * before they rest as still contours and stop asking for frames: earthquakes + * otherwise hold no render (docs/CURRENT-STATE.md, "Earthquake discs are + * STATIC geometry"), and a quake can stay selected for hours. + */ +export const RIPPLE_ACTIVE_CYCLES = 3; + +let reducedMotionQuery; +/** + * The viewer's reduced-motion setting, live: the media query is kept, so a + * change mid-session is read at the next paint and tick. + */ +const reducedMotion = () => { + try { + reducedMotionQuery ??= + globalThis.matchMedia?.('(prefers-reduced-motion: reduce)') ?? null; + return reducedMotionQuery?.matches === true; + } catch { + return false; + } +}; + +/** + * The selected earthquake's contour lines, painted on the world overlay: + * wavy closed lines, shaped by the quake's id (earthquakeContourShape), run + * from the marker out to the disc's edge and fade there, one after another, + * for RIPPLE_ACTIVE_CYCLES runs after a quake is selected and only while it + * is on screen, then rest as still contours. They never cross, and every third is + * a heavier index contour, as on a topographic map. Nothing is drawn, and no + * frame is asked for, while no quake is selected. With reduced motion the + * lines hold still. + * + * A line is drawn in the tangent plane at the epicentre: at the largest + * disc (M6, 64 km) it sits about 320 m above the curved ground at its edge + * (64² / 2R), about 1.5 px off the drawn disc at the 220 km, -45° framing a + * label click flies to (900 px tall, 35° field of view); less for smaller + * quakes, as the offset grows with the square of the radius. + * @param {object} [deps] + * @param {Function} [deps.registerLane] `registerWorldOverlayPaintLane`. + * @param {() => number} [deps.now] Steady clock, ms. + * @param {(cb: Function) => number} [deps.requestFrame] + * @param {(handle: number) => void} [deps.cancelFrame] + * @param {() => boolean} [deps.prefersReducedMotion] + * @returns {{show: Function, hide: Function, dispose: Function}} + */ +export function createEarthquakeRipples({ + registerLane = registerWorldOverlayPaintLane, + now = () => globalThis.performance?.now?.() ?? Date.now(), + requestFrame = (cb) => globalThis.requestAnimationFrame?.(cb) ?? null, + cancelFrame = (handle) => globalThis.cancelAnimationFrame?.(handle), + prefersReducedMotion = reducedMotion, +} = {}) { + let lane = null; + let target = null; + let frameHandle = null; + // When the running lines settle into still contours (the selection's + // bound), and whether the last paint found the quake on screen. + let startedAt = 0; + let settlesAt = 0; + let onScreen = false; + /** Whether the lines run now: in the window, and motion allowed. */ + const running = () => now() < settlesAt && !prefersReducedMotion(); + // Unit offsets around the line in the epicentre's tangent plane, packed + // x, y, z per point: north·cos + east·sin. + const offsets = new Float64Array((RIPPLE_RING_SEGMENTS + 1) * 3); + const angles = new Float64Array(RIPPLE_RING_SEGMENTS + 1); + for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) + angles[i] = (2 * Math.PI * i) / RIPPLE_RING_SEGMENTS; + + // Screen points, reused every frame. + const at = { x: 0, y: 0 }; + const centerAt = { x: 0, y: 0 }; + const eastAt = { x: 0, y: 0 }; + const northAt = { x: 0, y: 0 }; + + /** Project an ECEF point to CSS pixels; false when it is behind the eye. */ + function project(frame, px, py, pz, out) { + const m = frame.viewProjectionMatrix; + const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; + if (w <= 0) return false; + out.x = + ((m[0] * px + m[4] * py + m[8] * pz + m[12]) / w / 2 + 0.5) * frame.width; + out.y = + (0.5 - (m[1] * px + m[5] * py + m[9] * pz + m[13]) / w / 2) * + frame.height; + return true; + } + + /** + * Trace one closed line at `fraction` of the disc's radius (`shaped`: + * as a contour, else the disc's own circle). True when all of it is in + * front of the eye, so it can be filled. + */ + function trace(frame, fraction, shaped) { + const { ctx } = frame; + const center = target.center; + const reach = fraction * target.radiusM; + ctx.beginPath(); + let pen = false; + let whole = true; + for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) { + // The last point repeats the first angle, so the line closes. + const r = shaped + ? reach * earthquakeContourScale(target.shape, angles[i], fraction) + : reach; + const visible = project( + frame, + center.x + offsets[i * 3] * r, + center.y + offsets[i * 3 + 1] * r, + center.z + offsets[i * 3 + 2] * r, + at, + ); + if (!visible) { + pen = false; + whole = false; + continue; + } + if (pen) ctx.lineTo(at.x, at.y); + else ctx.moveTo(at.x, at.y); + pen = true; + } + return whole; + } + + /** + * Fill the traced path with a radial gradient laid on the ground: the + * canvas places a path when it is traced and a gradient when it fills, so + * under the disc's ground-to-screen transform the gradient's circle + * becomes the disc's ellipse on screen while the path stays exact. + * @param {Array<[number, number]>} stops [offset, alpha], out to `reach`. + */ + function fillGround(ctx, reach, stops) { + ctx.save(); + ctx.transform( + eastAt.x - centerAt.x, + eastAt.y - centerAt.y, + northAt.x - centerAt.x, + northAt.y - centerAt.y, + centerAt.x, + centerAt.y, + ); + const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, reach); + for (const [offset, alpha] of stops) + gradient.addColorStop(offset, target.rgba(alpha)); + ctx.fillStyle = gradient; + ctx.globalAlpha = 1; + ctx.fill(); + ctx.restore(); + } + + /** + * Whether any of the disc is in the viewport: its centre's screen point, + * padded by its larger screen radius (or, seen edge-on, the centre alone). + */ + function discOnScreen(frame, c, e, n) { + if (!Number.isFinite(c.x) || !Number.isFinite(c.y)) return false; + const pad = Math.max( + Math.hypot(e.x - c.x, e.y - c.y) || 0, + Math.hypot(n.x - c.x, n.y - c.y) || 0, + ); + return ( + c.x + pad >= 0 && + c.x - pad <= frame.width && + c.y + pad >= 0 && + c.y - pad <= frame.height + ); + } + + function paint(frame) { + if (!target) return; + const { ctx } = frame; + const center = target.center; + onScreen = false; + if (frame.occluder?.isPointVisible?.(center) === false) return; + const R = target.radiusM; + // The disc's ground frame on screen: its centre, and a radius east and + // north. Seen edge-on (or partly behind the eye) it is not filled. + const centerOk = project(frame, center.x, center.y, center.z, centerAt); + const eastOk = project( + frame, + center.x + target.east.x * R, + center.y + target.east.y * R, + center.z + target.east.z * R, + eastAt, + ); + const northOk = project( + frame, + center.x + target.north.x * R, + center.y + target.north.y * R, + center.z + target.north.z * R, + northAt, + ); + let fills = centerOk && eastOk && northOk; + if (fills) { + const area = + (eastAt.x - centerAt.x) * (northAt.y - centerAt.y) - + (eastAt.y - centerAt.y) * (northAt.x - centerAt.x); + fills = Math.abs(area) > 1; + } + onScreen = + centerOk && + discOnScreen( + frame, + centerAt, + eastOk ? eastAt : centerAt, + northOk ? northAt : centerAt, + ); + // The disc: strongest at the epicentre, fading out to its outer circle. + if (fills && trace(frame, 1, false)) fillGround(ctx, 1, DISC_FADE); + const animate = running(); + const rings = animate + ? earthquakeRippleRings(now() - startedAt) + : earthquakeContourRings(); + // Brought back into view while the window lasts: run again. + if (animate && onScreen && frameHandle === null && lane) + frameHandle = requestFrame(tick); + ctx.strokeStyle = target.color; + ctx.lineJoin = 'round'; + for (const { fraction, alpha, index } of rings) { + if (!(alpha > 0.01)) continue; + const whole = trace(frame, fraction, true); + // Each wave: clear inside, tinting toward its own line, as it fades. + if (fills && whole) + fillGround( + ctx, + fraction, + WAVE_FADE.map(([offset, a]) => [offset, a * alpha]), + ); + ctx.lineWidth = index ? INDEX_WIDTH_PX : LINE_WIDTH_PX; + ctx.globalAlpha = alpha; + ctx.stroke(); + } + ctx.globalAlpha = 1; + } + + /** Ask for one more frame while the lines run (one request at a time). */ + function tick() { + frameHandle = null; + if (!target || !lane) return; + // Settled, or out of sight: one last paint draws the still contours + // (or nothing), and no more frames are asked for. A paint that finds it + // on screen again inside the window starts the frames again. + if (!running() || !onScreen) { + lane.requestPaint(); + return; + } + lane.requestPaint(); + frameHandle = requestFrame(tick); + } + + function stopFrames() { + if (frameHandle !== null) cancelFrame(frameHandle); + frameHandle = null; + } + + /** + * Run the contour lines around one quake, replacing any other. + * @param {{id: string, lon: number, lat: number, radiusM: number, color: string}} next + * @param {{restart?: boolean}} [options] `restart: false` updates the + * same quake in place (a feed refresh) without running it again. + */ + function show(next, { restart = true } = {}) { + if ( + !next || + !Number.isFinite(next.lon) || + !Number.isFinite(next.lat) || + !(next.radiusM > 0) + ) { + hide(); + return; + } + const sameQuake = target?.id === next.id; + const lon = (next.lon * Math.PI) / 180; + const lat = (next.lat * Math.PI) / 180; + const [sinLon, cosLon] = [Math.sin(lon), Math.cos(lon)]; + const [sinLat, cosLat] = [Math.sin(lat), Math.cos(lat)]; + for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) { + const [c, s] = [Math.cos(angles[i]), Math.sin(angles[i])]; + offsets[i * 3] = c * -sinLat * cosLon + s * -sinLon; + offsets[i * 3 + 1] = c * -sinLat * sinLon + s * cosLon; + offsets[i * 3 + 2] = c * cosLat; + } + target = { + id: next.id, + center: fromDegrees(next.lon, next.lat), + radiusM: next.radiusM, + color: next.color || 'rgb(255,165,0)', + shape: earthquakeContourShape(next.id), + rgba: cssWithAlpha(next.color || 'rgb(255,165,0)'), + // Angle 0 is north and a quarter turn is east (see `offsets`). + north: { x: offsets[0], y: offsets[1], z: offsets[2] }, + east: { + x: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3], + y: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 1], + z: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 2], + }, + }; + if (restart || !sameQuake) { + startedAt = now(); + settlesAt = + startedAt + RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS; + // Assume it is in view until a paint says otherwise. + onScreen = true; + } + lane ??= registerLane(RIPPLE_PAINT_LANE, paint, { + id: 'earthquake-ripples', + }); + lane.setActive(true); + lane.requestPaint(); + if (running() && frameHandle === null) frameHandle = requestFrame(tick); + } + + function hide() { + stopFrames(); + if (!target) return; + target = null; + lane?.setActive(false); + } + + function dispose() { + hide(); + lane?.unregister(); + lane = null; + } + + return { show, hide, dispose }; +} diff --git a/src/app/layers/earthquakeRipples.test.mjs b/src/app/layers/earthquakeRipples.test.mjs new file mode 100644 index 0000000000..e97b9f00a8 --- /dev/null +++ b/src/app/layers/earthquakeRipples.test.mjs @@ -0,0 +1,420 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + DISC_FADE, + cssWithAlpha, + RIPPLE_ACTIVE_CYCLES, + RIPPLE_PAINT_LANE, + RIPPLE_RING_SEGMENTS, + createEarthquakeRipples, +} from './earthquakeRipples.js'; +import { + EARTHQUAKE_RIPPLE_PERIOD_MS, + EARTHQUAKE_RIPPLE_RINGS, +} from '../../layers/earthquakes/model.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; + +/** A paint lane, frame clock and canvas the test steps by hand. */ +function harness({ reducedMotion = false } = {}) { + let motionReduced = reducedMotion; + const lanes = []; + const frames = new Map(); + let nextFrame = 1; + let clock = 0; + const ripples = createEarthquakeRipples({ + registerLane(laneId, painter, options) { + const lane = { + laneId, + painter, + options, + active: false, + paints: 0, + unregistered: false, + setActive(next) { + lane.active = next; + }, + requestPaint() { + lane.paints++; + }, + unregister() { + lane.unregistered = true; + }, + }; + lanes.push(lane); + return lane; + }, + now: () => clock, + requestFrame(cb) { + const handle = nextFrame++; + frames.set(handle, cb); + return handle; + }, + cancelFrame: (handle) => frames.delete(handle), + prefersReducedMotion: () => motionReduced, + }); + const strokes = []; + const fills = []; + let path = null; + const ctx = { + globalAlpha: 1, + beginPath() { + path = { moves: 0, lines: 0 }; + }, + moveTo() { + path.moves++; + }, + lineTo() { + path.lines++; + }, + stroke() { + strokes.push({ + ...path, + alpha: ctx.globalAlpha, + color: ctx.strokeStyle, + width: ctx.lineWidth, + }); + }, + // Fills record their path, gradient and the transform they fill under. + saved: 0, + transformed: null, + save() { + ctx.saved++; + }, + restore() { + ctx.saved--; + ctx.transformed = null; + }, + transform(...args) { + ctx.transformed = args; + }, + createRadialGradient(...circles) { + const gradient = { circles, stops: [] }; + gradient.addColorStop = (offset, color) => + gradient.stops.push([offset, color]); + return gradient; + }, + fill() { + fills.push({ + ...path, + gradient: ctx.fillStyle, + transform: ctx.transformed, + }); + }, + }; + // w = 1 everywhere: every point is in front of the eye. + const matrix = new Float64Array(16); + matrix[0] = 1e-7; + matrix[5] = 1e-7; + matrix[15] = 1; + const frame = (visible = true) => ({ + ctx, + width: 800, + height: 600, + viewProjectionMatrix: matrix, + occluder: { isPointVisible: () => visible }, + }); + return { + ripples, + lanes, + frames, + strokes, + fills, + frame, + matrix, + setReducedMotion(next) { + motionReduced = next; + }, + advance(ms) { + clock += ms; + }, + /** Run the pending animation frames once. */ + step() { + const pending = [...frames.entries()]; + frames.clear(); + for (const [, cb] of pending) cb(); + }, + }; +} + +const target = { + id: 'ak1', + lon: -153.3, + lat: 60, + radiusM: 32000, + color: 'rgb(255,0,0)', +}; + +test('nothing is registered or animated until a quake is selected', () => { + const h = harness(); + assert.equal(h.lanes.length, 0); + assert.equal(h.frames.size, 0); + h.ripples.hide(); + assert.equal(h.frames.size, 0); +}); + +test('a selected quake animates one ring set, one frame request at a time', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + assert.equal(lane.laneId, RIPPLE_PAINT_LANE); + assert.equal(RIPPLE_PAINT_LANE, 'ambient-label', 'under the labels'); + assert.equal(lane.active, true); + assert.equal(h.frames.size, 1); + h.ripples.show({ ...target, id: 'ak2' }); + assert.equal(h.lanes.length, 1, 'the lane is reused'); + assert.equal(h.frames.size, 1, 'still one frame loop'); + const before = lane.paints; + h.step(); + h.step(); + assert.equal(lane.paints, before + 2, 'one repaint per frame'); + assert.equal(h.frames.size, 1); + + h.advance(600); + lane.painter(h.frame()); + // At 600 ms every line is between the marker and the edge, so all draw. + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + assert.deepEqual( + h.strokes.map((stroke) => stroke.width), + [2, 1.1, 1.1, 2, 1.1, 1.1], + 'every third line is an index contour', + ); + for (const stroke of h.strokes) { + assert.equal(stroke.moves, 1, 'one unbroken ring'); + assert.equal(stroke.lines, RIPPLE_RING_SEGMENTS); + assert.equal(stroke.color, 'rgb(255,0,0)'); + assert.ok(stroke.alpha > 0 && stroke.alpha <= 1); + } + + h.ripples.hide(); + assert.equal(lane.active, false); + assert.equal(h.frames.size, 0, 'no frames asked for once hidden'); + h.strokes.length = 0; + lane.painter(h.frame()); + assert.equal(h.strokes.length, 0); +}); + +test('rings are skipped behind the globe and broken behind the eye', () => { + const h = harness(); + h.ripples.show(target); + h.advance(600); + const [lane] = h.lanes; + lane.painter(h.frame(false)); + assert.equal(h.strokes.length, 0, 'epicentre over the horizon'); + + // Points with negative x fall behind the eye: each ring breaks there. + const frame = h.frame(); + frame.viewProjectionMatrix[3] = 1e-6; + const center = fromDegrees(target.lon, target.lat); + frame.viewProjectionMatrix[15] = -1e-6 * center.x; + lane.painter(frame); + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + for (const stroke of h.strokes) + assert.ok(stroke.lines < RIPPLE_RING_SEGMENTS, 'part of each ring hidden'); +}); + +test('reduced motion draws still contour rings and asks for no frames', () => { + const h = harness({ reducedMotion: true }); + h.ripples.show(target); + assert.equal(h.frames.size, 0); + assert.equal(h.lanes[0].paints, 1, 'painted once'); + h.lanes[0].painter(h.frame()); + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7)); +}); + +test('an unusable target hides the rings; dispose releases the lane', () => { + const h = harness(); + h.ripples.show(target); + h.ripples.show({ ...target, radiusM: 0 }); + assert.equal(h.lanes[0].active, false); + assert.equal(h.frames.size, 0); + h.ripples.dispose(); + assert.equal(h.lanes[0].unregistered, true); + // Shown again after dispose, it registers a fresh lane. + h.ripples.show(target); + assert.equal(h.lanes.length, 2); + h.ripples.dispose(); +}); + +test('contour lines are wavy, the same for a quake every time, and inside the disc', () => { + const h = harness(); + h.ripples.show(target); + h.advance(600); + // An identity-like projection: screen x, y follow ECEF y, z, so the + // distance from the projected epicentre measures each point's radius. + const frame = h.frame(); + const m = frame.viewProjectionMatrix; + m[0] = 0; + m[5] = 0; + m[4] = 1e-6; + m[9] = 1e-6; + const points = []; + const ctx = frame.ctx; + const record = (x, y) => points.at(-1).push([x, y]); + ctx.beginPath = () => points.push([]); + ctx.moveTo = record; + ctx.lineTo = record; + ctx.stroke = () => {}; + h.lanes[0].painter(frame); + const center = fromDegrees(target.lon, target.lat); + const cx = (center.y * 1e-6 * 0.5 + 0.5) * 800; + const cy = (0.5 - center.z * 1e-6 * 0.5) * 600; + const spread = (line) => { + const radii = line.map(([x, y]) => Math.hypot(x - cx, y - cy)); + return Math.max(...radii) / Math.min(...radii); + }; + // The disc's outer circle first (filled, not stroked), then each line. + assert.equal(points.length, EARTHQUAKE_RIPPLE_RINGS + 1); + points.shift(); + assert.ok( + points.every((line) => spread(line) > 1.05), + 'not circles: each line dents in and out', + ); + for (const line of points) { + const [first, last] = [line[0], line.at(-1)]; + assert.ok( + Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6, + 'closed', + ); + } +}); + +test('the disc fades out to its outer circle; each wave fills with a fade', () => { + const h = harness(); + h.ripples.show(target); + h.advance(600); + // A projection where east and north span the screen: the disc is seen + // from above, so its ground frame can be filled. + const frame = h.frame(); + const m = frame.viewProjectionMatrix; + m[0] = 0; + m[5] = 0; + m[4] = 1e-6; + m[9] = 1e-6; + h.lanes[0].painter(frame); + assert.equal(h.fills.length, 1 + EARTHQUAKE_RIPPLE_RINGS); + const [disc, ...waves] = h.fills; + assert.equal(disc.lines, RIPPLE_RING_SEGMENTS, 'the whole outer circle'); + assert.deepEqual(disc.gradient.circles, [0, 0, 0, 0, 0, 1]); + assert.deepEqual( + disc.gradient.stops, + DISC_FADE.map(([offset, alpha]) => [offset, `rgba(255,0,0,${alpha})`]), + ); + assert.equal(disc.gradient.stops.at(-1)[1], 'rgba(255,0,0,0)', 'fades out'); + assert.ok(disc.transform, 'filled under the ground-to-screen transform'); + assert.equal(h.fills.length, waves.length + 1); + for (const wave of waves) { + const reach = wave.gradient.circles[5]; + assert.ok(reach > 0 && reach < 1, 'out to its own line'); + assert.equal(wave.gradient.stops[0][1], 'rgba(255,0,0,0)', 'clear inside'); + } + // The transforms were undone: nothing leaks into the labels' painting. + assert.equal(frame.ctx.saved, 0); + // Seen edge-on, the ground frame has no area: lines only, no fills. + h.fills.length = 0; + m[9] = 0; + m[5] = 0; + h.lanes[0].painter(frame); + assert.equal(h.fills.length, 0); +}); + +test('cssWithAlpha turns rgb into rgba stops', () => { + assert.equal(cssWithAlpha('rgb(255,165,0)')(0.25), 'rgba(255,165,0,0.25)'); + assert.equal(cssWithAlpha('rgba(1, 2, 3, 0.5)')(2), 'rgba(1,2,3,1)'); + assert.equal(cssWithAlpha('red')(0.3), 'red'); +}); + +test('the lines run a bounded time after a selection, then rest without frames', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + const window = RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS; + assert.ok(window <= 15_000, 'about a quarter of a minute at most'); + let frames = 0; + for (let t = 0; t < window * 3; t += 16) { + if (!h.frames.size) break; + lane.painter(h.frame()); + h.advance(16); + h.step(); + frames++; + } + assert.equal(h.frames.size, 0, 'no frame asked for once settled'); + assert.ok(frames <= Math.ceil(window / 16) + 2, `bounded: ${frames} frames`); + // At rest the lines hold still as readable contours. + h.strokes.length = 0; + lane.painter(h.frame()); + assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS); + assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7)); + // A parked camera repainting the overlay does not start them again. + lane.painter(h.frame()); + assert.equal(h.frames.size, 0); + // A new selection runs again. + h.ripples.show({ ...target, id: 'ak2' }); + assert.equal(h.frames.size, 1); + h.ripples.dispose(); +}); + +test('off screen the frames stop; back in view inside the window they resume', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + // Behind the globe. + lane.painter(h.frame(false)); + const paints = lane.paints; + h.step(); + assert.equal(h.frames.size, 0, 'stopped while out of sight'); + assert.equal(lane.paints, paints + 1, 'one last paint, then none'); + h.step(); + assert.equal(lane.paints, paints + 1); + // Panned away: the disc is far off the viewport. + h.ripples.show(target); + const away = h.frame(); + away.viewProjectionMatrix[12] = 50; + lane.painter(away); + h.step(); + assert.equal(h.frames.size, 0); + // The camera brings it back while the window lasts. + away.viewProjectionMatrix[12] = 0; + lane.painter(h.frame()); + assert.equal(h.frames.size, 1, 'resumed'); + h.ripples.dispose(); +}); + +test('turning reduced motion on mid-run stills the lines and stops the frames', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + lane.painter(h.frame()); + h.setReducedMotion(true); + h.step(); + assert.equal(h.frames.size, 0); + h.strokes.length = 0; + lane.painter(h.frame()); + assert.ok( + h.strokes.every((stroke) => stroke.alpha === 0.7), + 'still', + ); + // Turned off again within the window: the next paint runs them again. + h.setReducedMotion(false); + lane.painter(h.frame()); + assert.equal(h.frames.size, 1); + h.ripples.dispose(); +}); + +test('a refresh of the same quake does not run a settled selection again', () => { + const h = harness(); + h.ripples.show(target); + const [lane] = h.lanes; + h.advance(RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS + 1); + lane.painter(h.frame()); + h.step(); + assert.equal(h.frames.size, 0, 'settled'); + h.ripples.show({ ...target, radiusM: 40000 }, { restart: false }); + assert.equal(h.frames.size, 0, 'a refresh keeps it at rest'); + lane.painter(h.frame()); + assert.equal(h.frames.size, 0); + // A different quake, or a user's restart, runs again. + h.ripples.show({ ...target, id: 'other' }, { restart: false }); + assert.equal(h.frames.size, 1); + h.ripples.dispose(); +}); diff --git a/src/app/layers/earthquakes.js b/src/app/layers/earthquakes.js index ae6bc1b63a..dc56448d35 100644 --- a/src/app/layers/earthquakes.js +++ b/src/app/layers/earthquakes.js @@ -1,6 +1,46 @@ import { createEarthquakesLayer } from '../../layers/earthquakes/index.js'; import { overlayHost } from './overlayHost.js'; -/** Wire earthquake observations to the application overlay host. */ +import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js'; +import { inputFor } from '../../input/dispatcher.js'; +import * as picking from '../../data/pickRegistry.js'; +import * as context from '../../data/contextStore.js'; +import { isPointerFree } from '../../data/inputOwnership.js'; +import { requestWorldFocus } from '../../worldFocus.js'; +import { createEarthquakeRipples } from './earthquakeRipples.js'; +import { formatDate, formatNumber, t } from '../../i18n/index.js'; + +const EVENT_TIME = Object.freeze({ + day: 'numeric', + month: 'short', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + timeZone: 'UTC', + timeZoneName: 'short', +}); + +/** The clicked quake's card text, in the page's language. */ +export const earthquakeCardText = Object.freeze({ + t, + formatTime: (time) => formatDate(time, EVENT_TIME), + formatDepth: (km) => formatNumber(km, { maximumFractionDigits: 1 }), +}); + +/** + * Wire earthquake observations to the application overlay host, and its + * discs to the globe's clicks: a clicked quake shows its detail card. + */ export function createApplicationEarthquakes(options) { - return createEarthquakesLayer({ overlayHost, ...options }); + return createEarthquakesLayer({ + overlayHost: { ...overlayHost, hitTest: hitTestWorldOverlay }, + input: (viewer) => inputFor(viewer), + picking, + context, + pointer: { isPointerFree }, + openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), + focus: { requestWorldFocus }, + ripples: createEarthquakeRipples(), + text: earthquakeCardText, + ...options, + }); } diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 15b8414c54..246a9d36fc 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -647,6 +647,16 @@ "UNAVAILABLE": "غير متاح", "Live Flights": "تتبّع الرحلات المباشر", "Earthquakes (24h)": "الزلازل (24 ساعة)", + "earthquake|Minor": "طفيف", + "earthquake|Light": "خفيف", + "earthquake|Moderate": "معتدل", + "earthquake|Strong": "قوي", + "earthquake|Major": "كبير", + "earthquake|Great": "هائل", + "earthquake|Shallow": "ضحل", + "earthquake|Intermediate": "متوسط العمق", + "earthquake|Deep": "عميق", + "{km} km deep": "على عمق {km} كم", "No selected data layers": "لا توجد طبقات بيانات محددة", "Cleared {count} data layers": { "zero": "لم تُمسح أي طبقة بيانات ({count})", @@ -2154,6 +2164,7 @@ "Exit cockpit to fly to a target": "اخرج من القمرة للانتقال إلى هدف", "Exit cockpit to fly to a vessel": "اخرج من القمرة للانتقال إلى سفينة", "Exit cockpit to fly to a fire": "اخرج من القمرة للانتقال إلى حريق", + "Exit cockpit to fly to an earthquake": "اخرج من القمرة للانتقال إلى زلزال", "Exit cockpit to fly to a route": "اخرج من القمرة للانتقال إلى مسار", "Exit cockpit to fly to a file": "اخرج من القمرة للانتقال إلى ملف", "Exit cockpit to fly to a scene": "اخرج من القمرة للانتقال إلى مشهد", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 3d1caeab42..d7900f7789 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -634,6 +634,16 @@ "Live Flights": "Live-Flüge", "Military Flights": "Militärflüge", "Earthquakes (24h)": "Erdbeben (24 h)", + "earthquake|Minor": "Schwach", + "earthquake|Light": "Leicht", + "earthquake|Moderate": "Mittel", + "earthquake|Strong": "Stark", + "earthquake|Major": "Schwer", + "earthquake|Great": "Gewaltig", + "earthquake|Shallow": "Flach", + "earthquake|Intermediate": "Mitteltief", + "earthquake|Deep": "Tief", + "{km} km deep": "{km} km tief", "Satellites": "Satelliten", "Place names": "Ortsnamen", "Space Missions (30d)": "Raummissionen (30 T)", @@ -2058,6 +2068,7 @@ "Exit cockpit to fly to a target": "Cockpit verlassen, um zu einem Ziel zu fliegen", "Exit cockpit to fly to a vessel": "Cockpit verlassen, um zu einem Schiff zu fliegen", "Exit cockpit to fly to a fire": "Cockpit verlassen, um zu einem Brand zu fliegen", + "Exit cockpit to fly to an earthquake": "Cockpit verlassen, um zu einem Erdbeben zu fliegen", "Exit cockpit to fly to a route": "Cockpit verlassen, um zu einer Route zu fliegen", "Exit cockpit to fly to a file": "Cockpit verlassen, um zu einer Datei zu fliegen", "Exit cockpit to fly to a scene": "Cockpit verlassen, um zu einer Szene zu fliegen", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 729e19c280..124e4288cf 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -526,6 +526,16 @@ "UNAVAILABLE": "NO DISPONIBLE", "Live Flights": "Vuelos en vivo", "Earthquakes (24h)": "Terremotos (24 h)", + "earthquake|Minor": "Menor", + "earthquake|Light": "Ligero", + "earthquake|Moderate": "Moderado", + "earthquake|Strong": "Fuerte", + "earthquake|Major": "Mayor", + "earthquake|Great": "Gran", + "earthquake|Shallow": "Superficial", + "earthquake|Intermediate": "Intermedio", + "earthquake|Deep": "Profundo", + "{km} km deep": "{km} km de profundidad", "No selected data layers": "No hay capas de datos seleccionadas", "Cleared {count} data layers": { "one": "Se limpió {count} capa de datos", @@ -2599,6 +2609,7 @@ "Exit cockpit to fly to a target": "Sal de la cabina para volar a un objetivo", "Exit cockpit to fly to a vessel": "Sal de la cabina para volar a un buque", "Exit cockpit to fly to a fire": "Sal de la cabina para volar a un incendio", + "Exit cockpit to fly to an earthquake": "Sal de la cabina para volar a un terremoto", "Exit cockpit to fly to a route": "Sal de la cabina para volar a una ruta", "Exit cockpit to fly to a file": "Sal de la cabina para volar a un archivo", "Exit cockpit to fly to a scene": "Sal de la cabina para volar a una escena", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 8e0ce68982..0edb2993d9 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1479,6 +1479,7 @@ "Exit cockpit to fly to a target": "Quittez le cockpit pour rejoindre une cible", "Exit cockpit to fly to a vessel": "Quittez le cockpit pour rejoindre un navire", "Exit cockpit to fly to a fire": "Quittez le cockpit pour rejoindre un incendie", + "Exit cockpit to fly to an earthquake": "Quittez le cockpit pour rejoindre un séisme", "Exit cockpit to fly to a route": "Quittez le cockpit pour rejoindre un itinéraire", "Exit cockpit to fly to a file": "Quittez le cockpit pour rejoindre un fichier", "Exit cockpit to fly to a scene": "Quittez le cockpit pour rejoindre une scène", @@ -1937,6 +1938,16 @@ "Live Flights": "Vols en direct", "Military Flights": "Vols militaires", "Earthquakes (24h)": "Séismes (24 h)", + "earthquake|Minor": "Mineur", + "earthquake|Light": "Léger", + "earthquake|Moderate": "Modéré", + "earthquake|Strong": "Fort", + "earthquake|Major": "Majeur", + "earthquake|Great": "Exceptionnel", + "earthquake|Shallow": "Superficiel", + "earthquake|Intermediate": "Intermédiaire", + "earthquake|Deep": "Profond", + "{km} km deep": "{km} km de profondeur", "Satellites": "Satellites", "Place names": "Noms de lieux", "Space Missions (30d)": "Missions spatiales (30 j)", diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index a7b5f29e03..3f8afe847f 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -1373,6 +1373,7 @@ "Exit cockpit to fly to a target": "צא מתא הטייס כדי לטוס אל מטרה", "Exit cockpit to fly to a vessel": "צא מתא הטייס כדי לטוס אל אונייה", "Exit cockpit to fly to a fire": "צא מתא הטייס כדי לטוס אל שריפה", + "Exit cockpit to fly to an earthquake": "צא מתא הטייס כדי לטוס אל רעידת אדמה", "Exit cockpit to fly to a sighting": "צא מתא הטייס כדי לטוס אל תצפית", "Exit cockpit to fly to a sighting area": "צא מתא הטייס כדי לטוס אל אזור תצפית", "Exit cockpit to fly to a route": "צא מתא הטייס כדי לטוס אל מסלול", @@ -1789,6 +1790,16 @@ "Live Flights": "טיסות חיות", "Military Flights": "טיסות צבאיות", "Earthquakes (24h)": "רעידות אדמה (24 שע׳)", + "earthquake|Minor": "קל מאוד", + "earthquake|Light": "קל", + "earthquake|Moderate": "בינוני", + "earthquake|Strong": "חזק", + "earthquake|Major": "חזק מאוד", + "earthquake|Great": "עצום", + "earthquake|Shallow": "רדוד", + "earthquake|Intermediate": "עומק בינוני", + "earthquake|Deep": "עמוק", + "{km} km deep": "בעומק {km} ק״מ", "Satellites": "לוויינים", "Space Missions (30d)": "משימות חלל (30 יום)", "Street Traffic": "תנועה ברחובות", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 00338746f1..a94460c494 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1479,6 +1479,7 @@ "Exit cockpit to fly to a target": "Esci dal cockpit per volare a un obiettivo", "Exit cockpit to fly to a vessel": "Esci dal cockpit per volare a una nave", "Exit cockpit to fly to a fire": "Esci dal cockpit per volare a un incendio", + "Exit cockpit to fly to an earthquake": "Esci dal cockpit per volare a un terremoto", "Exit cockpit to fly to a route": "Esci dal cockpit per volare a un percorso", "Exit cockpit to fly to a file": "Esci dal cockpit per volare a un file", "Exit cockpit to fly to a scene": "Esci dal cockpit per volare a una scena", @@ -1937,6 +1938,16 @@ "Live Flights": "Voli live", "Military Flights": "Voli militari", "Earthquakes (24h)": "Terremoti (24 h)", + "earthquake|Minor": "Minore", + "earthquake|Light": "Leggero", + "earthquake|Moderate": "Moderato", + "earthquake|Strong": "Forte", + "earthquake|Major": "Maggiore", + "earthquake|Great": "Grande", + "earthquake|Shallow": "Superficiale", + "earthquake|Intermediate": "Intermedio", + "earthquake|Deep": "Profondo", + "{km} km deep": "{km} km di profondità", "Satellites": "Satelliti", "Place names": "Nomi dei luoghi", "Space Missions (30d)": "Missioni spaziali (30 g)", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 4dfdd5f213..05e31a9414 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -1441,6 +1441,7 @@ "Exit cockpit to fly to a target": "ターゲットへ移動するにはコックピットを終了してください", "Exit cockpit to fly to a vessel": "船舶へ移動するにはコックピットを終了してください", "Exit cockpit to fly to a fire": "火災へ移動するにはコックピットを終了してください", + "Exit cockpit to fly to an earthquake": "地震へ移動するにはコックピットを終了してください", "Exit cockpit to fly to a route": "ルートへ移動するにはコックピットを終了してください", "Exit cockpit to fly to a file": "ファイルの位置へ移動するにはコックピットを終了してください", "Exit cockpit to fly to a scene": "シーンへ移動するにはコックピットを終了してください", @@ -1869,6 +1870,16 @@ "Live Flights": "ライブフライト", "Military Flights": "軍用機", "Earthquakes (24h)": "地震(24時間)", + "earthquake|Minor": "微小", + "earthquake|Light": "軽微", + "earthquake|Moderate": "中規模", + "earthquake|Strong": "強い", + "earthquake|Major": "大規模", + "earthquake|Great": "巨大", + "earthquake|Shallow": "浅発", + "earthquake|Intermediate": "やや深発", + "earthquake|Deep": "深発", + "{km} km deep": "深さ {km} km", "Satellites": "衛星", "Place names": "地名", "Space Missions (30d)": "宇宙ミッション(30日)", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index ae3ec81c4f..79e2b34045 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -1479,6 +1479,7 @@ "Exit cockpit to fly to a target": "Saia da cabine para voar até um alvo", "Exit cockpit to fly to a vessel": "Saia da cabine para voar até uma embarcação", "Exit cockpit to fly to a fire": "Saia da cabine para voar até um incêndio", + "Exit cockpit to fly to an earthquake": "Saia da cabine para voar até um terremoto", "Exit cockpit to fly to a route": "Saia da cabine para voar até uma rota", "Exit cockpit to fly to a file": "Saia da cabine para voar até um arquivo", "Exit cockpit to fly to a scene": "Saia da cabine para voar até uma cena", @@ -1937,6 +1938,16 @@ "Live Flights": "Voos ao vivo", "Military Flights": "Voos militares", "Earthquakes (24h)": "Terremotos (24 h)", + "earthquake|Minor": "Menor", + "earthquake|Light": "Leve", + "earthquake|Moderate": "Moderado", + "earthquake|Strong": "Forte", + "earthquake|Major": "Maior", + "earthquake|Great": "Grande", + "earthquake|Shallow": "Raso", + "earthquake|Intermediate": "Intermediário", + "earthquake|Deep": "Profundo", + "{km} km deep": "{km} km de profundidade", "Satellites": "Satélites", "Place names": "Nomes de lugares", "Space Missions (30d)": "Missões espaciais (30 d)", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 36c3a20571..9261174229 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -631,6 +631,16 @@ "Live Flights": "Рейсы онлайн", "Military Flights": "Военные рейсы", "Earthquakes (24h)": "Землетрясения (24 ч)", + "earthquake|Minor": "Слабое", + "earthquake|Light": "Лёгкое", + "earthquake|Moderate": "Умеренное", + "earthquake|Strong": "Сильное", + "earthquake|Major": "Мощное", + "earthquake|Great": "Катастрофическое", + "earthquake|Shallow": "Мелкофокусное", + "earthquake|Intermediate": "Среднефокусное", + "earthquake|Deep": "Глубокофокусное", + "{km} km deep": "глубина {km} км", "Satellites": "Спутники", "Place names": "Названия мест", "Space Missions (30d)": "Космические миссии (30 дн.)", @@ -2645,6 +2655,7 @@ "Exit cockpit to fly to a target": "Выйдите из кабины, чтобы перелететь к цели", "Exit cockpit to fly to a vessel": "Выйдите из кабины, чтобы перелететь к судну", "Exit cockpit to fly to a fire": "Выйдите из кабины, чтобы перелететь к пожару", + "Exit cockpit to fly to an earthquake": "Выйдите из кабины, чтобы перелететь к землетрясению", "Exit cockpit to fly to a route": "Выйдите из кабины, чтобы перелететь к маршруту", "Exit cockpit to fly to a file": "Выйдите из кабины, чтобы перелететь к файлу", "Exit cockpit to fly to a scene": "Выйдите из кабины, чтобы перелететь к сцене", diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 60ad8724ec..f7d6f81964 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -591,6 +591,16 @@ "Live Flights": "Liveflyg", "Military Flights": "Militärflyg", "Earthquakes (24h)": "Jordbävningar (24 h)", + "earthquake|Minor": "Mindre", + "earthquake|Light": "Lätt", + "earthquake|Moderate": "Måttlig", + "earthquake|Strong": "Kraftig", + "earthquake|Major": "Stor", + "earthquake|Great": "Mycket stor", + "earthquake|Shallow": "Grund", + "earthquake|Intermediate": "Medeldjup", + "earthquake|Deep": "Djup", + "{km} km deep": "{km} km djup", "Satellites": "Satelliter", "Space Missions (30d)": "Rymduppdrag (30 d)", "Street Traffic": "Gatutrafik", @@ -1980,6 +1990,7 @@ "Exit cockpit to fly to a target": "Lämna cockpiten för att flyga till ett mål", "Exit cockpit to fly to a vessel": "Lämna cockpiten för att flyga till ett fartyg", "Exit cockpit to fly to a fire": "Lämna cockpiten för att flyga till en brand", + "Exit cockpit to fly to an earthquake": "Lämna cockpiten för att flyga till en jordbävning", "Exit cockpit to fly to a route": "Lämna cockpiten för att flyga till en rutt", "Exit cockpit to fly to a file": "Lämna cockpiten för att flyga till en fil", "Exit cockpit to fly to a scene": "Lämna cockpiten för att flyga till en scen", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index 3231f3322a..8e6d2bfaf3 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -1497,6 +1497,7 @@ "Exit cockpit to fly to a target": "Вийдіть із кабіни, щоб перелетіти до цілі", "Exit cockpit to fly to a vessel": "Вийдіть із кабіни, щоб перелетіти до судна", "Exit cockpit to fly to a fire": "Вийдіть із кабіни, щоб перелетіти до пожежі", + "Exit cockpit to fly to an earthquake": "Вийдіть із кабіни, щоб перелетіти до землетрусу", "Exit cockpit to fly to a route": "Вийдіть із кабіни, щоб перелетіти до маршруту", "Exit cockpit to fly to a file": "Вийдіть із кабіни, щоб перелетіти до файлу", "Exit cockpit to fly to a scene": "Вийдіть із кабіни, щоб перелетіти до сцени", @@ -1970,6 +1971,16 @@ "Live Flights": "Рейси онлайн", "Military Flights": "Військові рейси", "Earthquakes (24h)": "Землетруси (24 год)", + "earthquake|Minor": "Слабкий", + "earthquake|Light": "Легкий", + "earthquake|Moderate": "Помірний", + "earthquake|Strong": "Сильний", + "earthquake|Major": "Потужний", + "earthquake|Great": "Катастрофічний", + "earthquake|Shallow": "Мілкофокусний", + "earthquake|Intermediate": "Середньофокусний", + "earthquake|Deep": "Глибокофокусний", + "{km} km deep": "глибина {km} км", "Satellites": "Супутники", "Place names": "Назви місць", "Space Missions (30d)": "Космічні місії (30 дн)", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 1851c62306..8ea38dc97d 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1415,6 +1415,7 @@ "Exit cockpit to fly to a target": "请先退出座舱,再飞往目标", "Exit cockpit to fly to a vessel": "请先退出座舱,再飞往船舶", "Exit cockpit to fly to a fire": "请先退出座舱,再飞往火点", + "Exit cockpit to fly to an earthquake": "请先退出座舱,再飞往地震", "Exit cockpit to fly to a route": "请先退出座舱,再飞往路线", "Exit cockpit to fly to a file": "请先退出座舱,再飞往文件位置", "Exit cockpit to fly to a scene": "请先退出座舱,再飞往场景", @@ -1844,6 +1845,16 @@ "Live Flights": "实时航班", "Military Flights": "军用航班", "Earthquakes (24h)": "地震(24 小时)", + "earthquake|Minor": "微弱", + "earthquake|Light": "轻微", + "earthquake|Moderate": "中等", + "earthquake|Strong": "强烈", + "earthquake|Major": "重大", + "earthquake|Great": "巨大", + "earthquake|Shallow": "浅源", + "earthquake|Intermediate": "中源", + "earthquake|Deep": "深源", + "{km} km deep": "震源深度 {km} km", "Satellites": "卫星", "Place names": "地名", "Space Missions (30d)": "太空任务(30 天)", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 88e759c66e..81999dbadb 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -1410,6 +1410,7 @@ "Exit cockpit to fly to a target": "請先退出座艙,再飛往目標", "Exit cockpit to fly to a vessel": "請先退出座艙,再飛往船舶", "Exit cockpit to fly to a fire": "請先退出座艙,再飛往火點", + "Exit cockpit to fly to an earthquake": "請先退出座艙,再飛往地震", "Exit cockpit to fly to a route": "請先退出座艙,再飛往路線", "Exit cockpit to fly to a file": "請先退出座艙,再飛往文件位置", "Exit cockpit to fly to a scene": "請先退出座艙,再飛往場景", @@ -1836,6 +1837,16 @@ "Live Flights": "實時航班", "Military Flights": "軍用航班", "Earthquakes (24h)": "地震(24 小時)", + "earthquake|Minor": "微弱", + "earthquake|Light": "輕微", + "earthquake|Moderate": "中等", + "earthquake|Strong": "強烈", + "earthquake|Major": "重大", + "earthquake|Great": "巨大", + "earthquake|Shallow": "淺源", + "earthquake|Intermediate": "中源", + "earthquake|Deep": "深源", + "{km} km deep": "震源深度 {km} km", "Satellites": "衛星", "Place names": "地名", "Space Missions (30d)": "太空任務(30 天)", diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 90d70e9a90..37cd2e8cae 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -11,6 +11,11 @@ import { selectEarthquakeOverlayCohort, mapAnalystRecord, earthquakeCoverage, + earthquakeMarkLabel, + earthquakeMagnitudeTitle, + earthquakeZoomLabel, + earthquakeDiscRadiusM, + describeEarthquake, } from './model.js'; export * from './model.js'; export { createUsgsEarthquakeSource } from './source.js'; @@ -25,6 +30,18 @@ const msg = (text) => text; * as `Hit.set`. */ export const EARTHQUAKE_DISC_SET_ID = 'earthquakes'; +export const EARTHQUAKES_LAYER_ID = 'earthquakes'; +/** The overlay source the clicked quake's detail card is shown in. */ +export const EARTHQUAKE_CARD_SOURCE_ID = 'earthquake-card'; +/** A disc's item id is this prefix and the event's stable id. */ +const PICK_PREFIX = 'earthquake:'; +/** The selected quake's flat fill, faint under the painted gradient. */ +const SELECTED_DISC_ALPHA = 0.04; +const CARD_HOST_OPTIONS = Object.freeze({ + cohortLimit: 1, + collisionCapacity: 1, + moving: false, +}); let instances = 0; /** @@ -33,8 +50,42 @@ let instances = 0; * The discs are one renderer draw set (`drawOf(viewer)`), made at `init`. * Given a Cesium viewer with no renderer bound, the * caller loads the package's `./render/cesium/unbound` export first. + * + * Clicking a disc shows that quake's detail card and selects it in the + * shared context. The application gives the click and selection services; + * without `input` and `picking` the discs are drawn but take no clicks. + * @param {object} options + * @param {object} options.source Snapshot source. + * @param {object} options.overlayHost World-overlay host (`hitTest` lets + * the card be clicked). + * @param {(viewer: object) => {onClick: Function}} [options.input] The + * viewer's click dispatcher. + * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function, + * registerPickOwner: Function, unregisterPickOwner: Function}} [options.picking] + * @param {{registerEntityContext: Function, selectEntityContext: Function, + * clearSelectedEntityContextForLayer: Function, + * getContextStore: Function}} [options.context] Shared selection store. + * @param {{isPointerFree: () => boolean}} [options.pointer] + * @param {(url: string) => void} [options.openExternal] + * @param {{requestWorldFocus: (detail: object) => boolean}} [options.focus] + * The camera transfer a clicked magnitude label asks for. + * @param {{show: (target: {id: string, lon: number, lat: number, + * radiusM: number, color: string}) => void, hide: () => void}} [options.ripples] + * The selected quake's animated contour rings. + * @param {object} [options.text] Card formatters (see describeEarthquake). */ -export function createEarthquakesLayer({ source, overlayHost } = {}) { +export function createEarthquakesLayer({ + source, + overlayHost, + input = null, + picking = null, + context = null, + pointer = null, + openExternal = null, + focus = null, + ripples = null, + text = undefined, +} = {}) { if (typeof source?.getSnapshot !== 'function') throw new TypeError('Earthquakes require a snapshot source'); if (!overlayHost) throw new TypeError('Earthquakes require an overlay host'); @@ -60,6 +111,270 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _marksKey = key; worldClock.coverageChanged(); }; + // The drawn events by stable id, for clicks; the selected one's id, card + // and the context record it was published as. + let _eventById = new Map(); + let _selectedId = null; + let _selectedCardId = null; + let _selectedLink = null; + let _contextId = null; + let _clickHandler = null; + const canSelect = () => Boolean(input && picking); + // The disc whose flat fill is faded while the painter draws its gradient. + let _fadedDiscId = null; + + /** + * A quake's disc: filled on the ground, with static axes (re-tessellating + * clamped ground geometry every frame is what once cost 30 fps). No + * outline: clamped to the ground, Cesium never drew one. A selected + * quake's disc is all but clear: the ripples painter fills it with a + * gradient instead, and the faint fill keeps it pickable. + */ + function discItem(event, faded = false) { + const radius = earthquakeDiscRadiusM(event.mag); + const [r, g, b] = depthColor(event.depthKm || 0); + const fillAlpha = faded + ? SELECTED_DISC_ALPHA + : event.mag >= 5.0 + ? 0.4 + : 0.3; + return { + id: `${PICK_PREFIX}${event.stableId}`, + geometry: { + kind: 'ellipse', + center: { lon: event.lon, lat: event.lat }, + semiMajor: radius, + semiMinor: radius, + }, + fill: [r, g, b, fillAlpha], + height: 'clampGround', + clampTo: 'both', + }; + } + + /** Fade one disc's flat fill (and restore the one faded before). */ + function fadeDisc(stableId) { + if (!ripples || !_discs || _fadedDiscId === stableId) return; + const changed = []; + const before = _eventById.get(_fadedDiscId); + if (before) changed.push(discItem(before, false)); + const next = _eventById.get(stableId); + if (next) changed.push(discItem(next, true)); + _fadedDiscId = next ? stableId : null; + if (changed.length) _discs.upsert(changed); + } + + /** The drawn event a pick id names, or null. */ + function eventOfPickId(pickId) { + if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX)) + return null; + return _eventById.get(pickId.slice(PICK_PREFIX.length)) ?? null; + } + + /** The drawn event a click's draw hit is on: an item of this layer's set. */ + function pickedEvent(hit) { + if (!hit || hit.surface || !_discs || hit.set !== _discs.id) return null; + return eventOfPickId(hit.id); + } + + /** + * Show the selected quake's card, context and contours. `user`: a click or + * a label's activation, which claims the shared selection and runs the + * contours again; a feed refresh only brings them up to date, so it never + * takes back a selection made since, nor restarts the animation. + */ + function publishCard({ user = false } = {}) { + const event = _selectedId ? _eventById.get(_selectedId) : null; + if (!_enabled || !event) { + clearSelection(); + return; + } + const { title, details, link, accessibilityLabel } = describeEarthquake( + event, + text, + ); + _selectedLink = link && openExternal ? link : null; + const card = { + id: `earthquake-card:${event.stableId}`, + selected: true, + // Always hit-testable (the host only hit-tests interactive entries), + // so a click on a card with no link keeps it rather than falling + // through to the ground under it and clearing the selection. + interactive: true, + title, + details, + accent: depthAccent(event.depthKm || 0), + priority: Number.MAX_SAFE_INTEGER, + gapPx: 15, + verticalOnly: true, + placement: 'above', + stateless: true, + horizonCull: true, + position: fromDegrees(event.lon, event.lat), + }; + if (_selectedLink) { + const target = _selectedLink; + card.accessibilityLabel = accessibilityLabel; + card.activate = () => { + openExternal(target); + return true; + }; + } + _selectedCardId = card.id; + overlayHost.setEntries( + EARTHQUAKE_CARD_SOURCE_ID, + [card], + CARD_HOST_OPTIONS, + ); + overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, true); + publishContext(event, user); + fadeDisc(event.stableId); + ripples?.show?.( + { + id: event.stableId, + lon: event.lon, + lat: event.lat, + radiusM: earthquakeDiscRadiusM(event.mag), + color: depthAccent(event.depthKm || 0), + }, + { restart: user }, + ); + } + + /** + * Select the event in the shared context store, so "what's selected" + * (voice, the Cockpit) answers with it, as a clicked fire does. + */ + function publishContext(event, select) { + if (!context) return; + const id = `${PICK_PREFIX}${event.stableId}`; + try { + if (_contextId && _contextId !== id) + context.getContextStore().entities.delete(_contextId); + const carrier = { show: true }; + context.registerEntityContext(carrier, { + id, + layerId: EARTHQUAKES_LAYER_ID, + layerName: layer.name, + source: 'USGS', + // Hidden with the layer: the context store reads its `show`. + dataSource: _discs, + targetPosition: fromDegrees(event.lon, event.lat), + // i18n-ignore: English entity label, as the analyst records are + label: `Earthquake · ${earthquakeMarkLabel(event)}`, + latitude: event.lat, + longitude: event.lon, + properties: { + magnitude: event.mag, + depthKm: event.depthKm ?? null, + place: event.place ?? null, + time: Number.isFinite(event.time) + ? new Date(event.time).toISOString() + : null, + usgsId: event.usgsId ?? null, + }, + }); + _contextId = id; + if (select) context.selectEntityContext(carrier); + } catch { + // No context store (no window): the card still shows. + } + } + + function clearContext() { + if (!context || !_contextId) return; + try { + context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID); + context.getContextStore().entities.delete(_contextId); + } catch { + // store unavailable: nothing to clean + } + _contextId = null; + } + + function clearSelection() { + const had = _selectedId || _selectedCardId; + _selectedId = null; + _selectedCardId = null; + _selectedLink = null; + clearContext(); + ripples?.hide?.(); + fadeDisc(null); + if (had) + overlayHost.setEntries(EARTHQUAKE_CARD_SOURCE_ID, [], CARD_HOST_OPTIONS); + } + + function installClickHandler() { + if (!canSelect() || _clickHandler || !_viewer) return; + picking.registerPickOwner?.( + EARTHQUAKES_LAYER_ID, + (pickedId) => _enabled && eventOfPickId(pickedId) !== null, + ); + // A viewer with no renderer input bound takes no clicks. + let clicks = null; + try { + clicks = input(_viewer) ?? null; + } catch { + clicks = null; + } + if (!clicks) return; + _clickHandler = clicks.onClick((click) => { + if (!_enabled || (pointer && !pointer.isPointerFree())) return; + const at = click.screenPosition; + const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { + sourceId: EARTHQUAKE_CARD_SOURCE_ID, + }); + if (cardHit && cardHit.entryId === _selectedCardId) { + if (_selectedLink) openExternal(_selectedLink); + return; + } + // Another layer's pick (an aircraft, a camera) is not this layer's, + // even under a magnitude label: that layer handles it, and this card + // stays. Checked before the labels, as the fire layer does. + const pickId = click.topHit + ? (picking.resolvePickId(click.topHit) ?? null) + : null; + if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId)) + return; + // A magnitude label is what a far view (the whole globe) can click: + // it selects the quake and flies to it. + const labelHit = overlayHost.hitTest?.(at?.x, at?.y, { + sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID, + }); + if (labelHit && _eventById.has(labelHit.entryId)) { + selectAndFocus(labelHit.entryId); + return; + } + const event = pickedEvent(click.drawHit ?? click.topHit); + if (event) { + _selectedId = event.stableId; + publishCard({ user: true }); + return; + } + clearSelection(); + }); + } + + /** Select a drawn quake, show its card, and ask the camera to go there. */ + function selectAndFocus(stableId) { + const event = _eventById.get(stableId); + if (!_enabled || !event) return false; + _selectedId = stableId; + publishCard({ user: true }); + focus?.requestWorldFocus?.({ + kind: 'earthquake', + id: `${PICK_PREFIX}${stableId}`, + label: earthquakeMagnitudeTitle(event.mag), + position: fromDegrees(event.lon, event.lat), + }); + return true; + } + + function removeClickHandler() { + _clickHandler?.(); + _clickHandler = null; + picking?.unregisterPickOwner?.(EARTHQUAKES_LAYER_ID); + } const layer = { id: 'earthquakes', @@ -93,6 +408,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { // layer has no per-frame animator to keep the render loop alive for. if (_discs) _discs.show = true; overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true); + installClickHandler(); coverageChanged(); }, @@ -101,6 +417,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _request = null; _enabled = false; if (_discs) _discs.show = false; + removeClickHandler(); + clearSelection(); + overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID); + overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false); overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); coverageChanged(); @@ -132,41 +452,52 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { time, } of rows) { count++; - const baseRadius = Math.pow(2, mag) * 1000; - const color = depthColor(depthKm || 0); - const [r, g, b] = color; - const isSignificant = mag >= 5.0; - const fillAlpha = isSignificant ? 0.4 : 0.3; - const position = fromDegrees(lon, lat); - nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat }); - // A filled disc on the ground, with static axes: re-tessellating - // clamped ground geometry every frame is what once cost 30 fps. - // No outline: clamped to the ground, Cesium never drew one. - nextDiscs.push({ - id: `earthquake:${stableId}`, - geometry: { - kind: 'ellipse', - center: { lon, lat }, - semiMajor: baseRadius, - semiMinor: baseRadius, - }, - fill: [r, g, b, fillAlpha], - height: 'clampGround', - clampTo: 'both', - }); - overlayEntries.push( - createEarthquakeOverlayEntry({ - id: String(stableId), - position, - magnitude: mag, - accent: depthAccent(depthKm || 0), - }), + const event = { + stableId: String(stableId), + usgsId, + mag, + place, + time, + depthKm, + lon, + lat, + }; + nextEvents.push(event); + nextDiscs.push( + discItem(event, Boolean(ripples) && event.stableId === _selectedId), ); + const label = createEarthquakeOverlayEntry({ + id: String(stableId), + position, + magnitude: mag, + accent: depthAccent(depthKm || 0), + }); + if (canSelect()) { + const id = String(stableId); + label.interactive = true; + label.accessibilityLabel = earthquakeZoomLabel( + { mag, place }, + text, + ); + label.activate = () => selectAndFocus(id); + } + overlayEntries.push(label); } + // Bigger quakes first, so a small quake inside a big one's disc is + // drawn, and picked, on top of it. + nextDiscs.sort((a, b) => b.geometry.semiMajor - a.geometry.semiMajor); _discs.set(nextDiscs); _events = nextEvents; + _eventById = new Map( + nextEvents.map((event) => [event.stableId, event]), + ); + _fadedDiscId = + ripples && _eventById.has(_selectedId) ? _selectedId : null; + // A selected quake still in the feed keeps its card, refreshed; one + // that left the 24 h window loses it. + if (_selectedId) publishCard(); coverageChanged(); if (_enabled) { overlayHost.setEntries( @@ -199,13 +530,19 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { destroy(viewer = _viewer) { _request?.abort(); _request = null; + removeClickHandler(); + clearSelection(); + ripples?.dispose?.(); _viewer = null; _enabled = false; + overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID); + overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false); overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); _discs?.dispose(); _discs = null; _events = []; + _eventById = new Map(); _uncover?.(); _uncover = null; _marksKey = null; diff --git a/src/layers/earthquakes/model.js b/src/layers/earthquakes/model.js index 25570e7243..228758c011 100644 --- a/src/layers/earthquakes/model.js +++ b/src/layers/earthquakes/model.js @@ -123,6 +123,298 @@ export function createEarthquakeOverlayEntry({ }; } +/** Where USGS publishes one event's page, its event id appended. */ +export const USGS_EVENT_PAGE_URL = + 'https://earthquake.usgs.gov/earthquakes/eventpage/'; + +/** + * The USGS page for an event id, or null when there is no usable id (a + * fallback `event-N` id never names a USGS page, and is never sent). + * @param {unknown} usgsId + * @returns {string|null} + */ +export function earthquakeEventLink(usgsId) { + const id = + typeof usgsId === 'string' || typeof usgsId === 'number' + ? String(usgsId).trim() + : ''; + return /^[A-Za-z0-9_-]{1,64}$/.test(id) + ? `${USGS_EVENT_PAGE_URL}${id}` + : null; +} + +// The package carries no i18n: with no translator given, the card stays +// English, its `{name}` slots filled in. +const english = (text, values) => + String(text).replace(/\{(\w+)\}/g, (all, key) => + values && Object.hasOwn(values, key) ? String(values[key]) : all, + ); +const utcMinute = (time) => + `${new Date(time).toISOString().slice(0, 16).replace('T', ' ')} UTC`; +const oneDecimal = (value) => String(Math.round(value * 10) / 10); + +/** + * The detail card one clicked earthquake shows: its magnitude as the title, + * then where, when and how deep, and the source. With a USGS event id the + * card opens that event's page. + * @param {{mag: number, place?: string|null, time?: number|null, + * depthKm?: number|null, usgsId?: string|null}} event + * @param {object} [text] The application's formatters. + * @param {(text: string, values?: object) => string} [text.t] Translator. + * @param {(time: number) => string} [text.formatTime] An event time. + * @param {(value: number) => string} [text.formatDepth] A depth in km. + * @returns {{title: string, details: string[], link: string|null, + * accessibilityLabel: string}} + */ +export function describeEarthquake( + event, + { t = english, formatTime = utcMinute, formatDepth = oneDecimal } = {}, +) { + const details = []; + // Severity at a glance, right under the title: the class meter, then + // where in the crust it broke. + const glance = [earthquakeSeverityMeter(event?.mag)]; + if (Number.isFinite(event?.depthKm)) { + glance.push( + `${earthquakeDepthBandName(event.depthKm, t)} · ${t('{km} km deep', { + km: formatDepth(event.depthKm), + })}`, + ); + } + details.push(glance.join(' ')); + const place = + typeof event?.place === 'string' + ? event.place.replace(/\s+/g, ' ').trim() + : ''; + if (place) details.push(place); + if (Number.isFinite(event?.time)) details.push(formatTime(event.time)); + details.push(t('Source: {value}', { value: 'USGS' })); + const link = earthquakeEventLink(event?.usgsId); + if (link) details.push(t('Click the card to open the source ↗')); + const title = `${earthquakeMagnitudeTitle(event?.mag)} · ${earthquakeSeverityName( + event?.mag, + t, + )}`; + return { + title, + details, + link, + accessibilityLabel: t('Open the source for {title}', { title }), + }; +} + +/** + * USGS's magnitude classes, weakest first: minor (under 4; the feed starts + * at M2.5), light, moderate, strong, major, great (8 and up). + */ +export const EARTHQUAKE_SEVERITY_LEVELS = 6; + +/** + * A magnitude's USGS class, 0 (minor) to 5 (great). + * @param {number} magnitude + * @returns {number} + */ +export function earthquakeSeverityLevel(magnitude) { + const mag = Number(magnitude); + if (!Number.isFinite(mag) || mag < 4) return 0; + return Math.min(EARTHQUAKE_SEVERITY_LEVELS - 1, Math.floor(mag) - 3); +} + +/** A magnitude's class, as a word in the page's language. */ +export function earthquakeSeverityName(magnitude, t = english) { + switch (earthquakeSeverityLevel(magnitude)) { + case 5: + return t('Great', { context: 'earthquake' }); + case 4: + return t('Major', { context: 'earthquake' }); + case 3: + return t('Strong', { context: 'earthquake' }); + case 2: + return t('Moderate', { context: 'earthquake' }); + case 1: + return t('Light', { context: 'earthquake' }); + default: + return t('Minor', { context: 'earthquake' }); + } +} + +/** + * The class as a six-step meter, one filled block per class up to this one: + * `■■□□□□` for a light quake. Plain text, so the card shows it as it is. + * @param {number} magnitude + * @returns {string} + */ +export function earthquakeSeverityMeter(magnitude) { + const filled = earthquakeSeverityLevel(magnitude) + 1; + return '■'.repeat(filled) + '□'.repeat(EARTHQUAKE_SEVERITY_LEVELS - filled); +} + +/** + * The depth band the disc's colour shows, as a word: shallow (under 70 km, + * red), intermediate (to 300 km, orange), deep (yellow). + */ +export function earthquakeDepthBandName(depthKm, t = english) { + const band = depthBand(depthKm); + if (band === SHALLOW) return t('Shallow', { context: 'earthquake' }); + if (band === INTERMEDIATE) + return t('Intermediate', { context: 'earthquake' }); + return t('Deep', { context: 'earthquake' }); +} + +/** + * A quake's disc radius on the ground, in metres: it doubles with each + * magnitude step (about 5.7 km at M2.5, 32 km at M5, 64 km at M6). + * @param {number} magnitude + * @returns {number} + */ +export const earthquakeDiscRadiusM = (magnitude) => + Math.pow(2, magnitude) * 1000; + +/** How many contour lines run out from a selected quake at once. */ +export const EARTHQUAKE_RIPPLE_RINGS = 6; +/** How long one contour line takes from the marker to the disc's edge. */ +export const EARTHQUAKE_RIPPLE_PERIOD_MS = 4800; +/** Every this many lines one is an index contour, drawn heavier. */ +export const EARTHQUAKE_INDEX_CONTOUR_EVERY = 3; + +/** + * How far a contour line dents in from the circle, as a share of its + * radius. Kept with the drift below so nested lines never cross: a line's + * radius grows with `fraction` faster than its dents move (see + * earthquakeContourScale). + */ +export const EARTHQUAKE_CONTOUR_WOBBLE = 0.24; +const CONTOUR_HARMONICS = Object.freeze([2, 3, 5]); +const CONTOUR_WEIGHTS = Object.freeze([1, 0.6, 0.3]); +const CONTOUR_MAX_DRIFT = 1.5; + +/** A stable 32-bit hash of a string (FNV-1a). */ +function hashString(text) { + let h = 0x811c9dc5; + for (const ch of String(text ?? '')) { + h ^= ch.codePointAt(0); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +/** + * One quake's contour shape: a few harmonics around the circle, each with + * its own phase and a drift that turns it as a line runs outward, seeded by + * the quake's id so the same quake always draws the same contours. + * @param {string} seed The quake's stable id. + * @returns {ReadonlyArray<{harmonic: number, weight: number, phase: number, drift: number}>} + */ +export function earthquakeContourShape(seed) { + let state = hashString(seed) || 1; + // xorshift32: a small, stable stream from the seed. + const next = () => { + state ^= state << 13; + state ^= state >>> 17; + state ^= state << 5; + return (state >>> 0) / 0x100000000; + }; + return Object.freeze( + CONTOUR_HARMONICS.map((harmonic, i) => + Object.freeze({ + harmonic, + weight: CONTOUR_WEIGHTS[i], + phase: next() * 2 * Math.PI, + drift: (next() * 2 - 1) * CONTOUR_MAX_DRIFT, + }), + ), + ); +} + +/** + * Where a contour line runs at `angle` (radians), as a share of a circle of + * the same `fraction`: between 1 - EARTHQUAKE_CONTOUR_WOBBLE and 1, so the + * outermost line never leaves the disc. The dents turn as `fraction` grows, + * and no faster than the line grows, so lines never cross: with wobble A + * and drift D, d(fraction · scale)/d(fraction) ≥ 1 - A - A·D/2 > 0. + * @param {ReturnType} shape + * @param {number} angle + * @param {number} fraction 0 at the marker, 1 at the disc's edge. + * @returns {number} + */ +export function earthquakeContourScale(shape, angle, fraction) { + let sum = 0; + let total = 0; + for (const { harmonic, weight, phase, drift } of shape) { + sum += weight * Math.sin(harmonic * angle + phase + drift * fraction); + total += weight; + } + const n = total > 0 ? sum / total : 0; + return 1 - (EARTHQUAKE_CONTOUR_WOBBLE * (1 - n)) / 2; +} + +/** + * The selected quake's contour lines at a time: each runs from the marker + * (`fraction` 0) out to the disc's edge (1), evenly staggered, fading in + * just after it starts and out as it reaches the edge; every + * EARTHQUAKE_INDEX_CONTOUR_EVERY-th is an index contour. Pure: the painter + * gives the clock. + * @param {number} timeMs Any steady clock, in milliseconds. + * @param {{count?: number, periodMs?: number}} [options] + * @returns {Array<{fraction: number, alpha: number, index: boolean}>} + */ +export function earthquakeRippleRings( + timeMs, + { + count = EARTHQUAKE_RIPPLE_RINGS, + periodMs = EARTHQUAKE_RIPPLE_PERIOD_MS, + } = {}, +) { + const phase = Number.isFinite(timeMs) && periodMs > 0 ? timeMs / periodMs : 0; + const rings = []; + for (let k = 0; k < count; k++) { + const fraction = (((phase + k / count) % 1) + 1) % 1; + rings.push({ + fraction, + alpha: earthquakeRippleAlpha(fraction), + index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0, + }); + } + return rings; +} + +/** + * Still contour lines, for viewers who ask for reduced motion: the same + * lines as the animation, held evenly spaced out to the edge. + * @param {number} [count] + * @returns {Array<{fraction: number, alpha: number, index: boolean}>} + */ +export function earthquakeContourRings(count = EARTHQUAKE_RIPPLE_RINGS) { + const rings = []; + for (let k = 1; k <= count; k++) + rings.push({ + fraction: k / count, + alpha: 0.7, + index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0, + }); + return rings; +} + +const RIPPLE_FADE_IN = 0.12; +/** A ring's opacity where it is: in from 0 near the marker, out to 0 at the edge. */ +function earthquakeRippleAlpha(fraction) { + if (fraction <= 0 || fraction >= 1) return 0; + return fraction < RIPPLE_FADE_IN + ? fraction / RIPPLE_FADE_IN + : (1 - fraction) / (1 - RIPPLE_FADE_IN); +} + +/** + * What a magnitude label says to assistive technology: activating it zooms + * to the quake (`Zoom to M5.0 · 42 km SW of Anchorage, Alaska`). + * @param {{mag: number, place?: string|null}} event + * @param {{t?: (text: string, values?: object) => string}} [text] + * @returns {string} + */ +export function earthquakeZoomLabel(event, { t = english } = {}) { + return t('Zoom to {name}', { name: earthquakeMarkLabel(event) }); +} + /** Keep the largest events, with stable identity as the tie-break. */ export function selectEarthquakeOverlayCohort( entries, diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs new file mode 100644 index 0000000000..568d6cc4e1 --- /dev/null +++ b/src/layers/earthquakes/selection.test.mjs @@ -0,0 +1,610 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; +import * as picking from '../../data/pickRegistry.js'; +import { + EARTHQUAKE_CARD_SOURCE_ID, + EARTHQUAKE_OVERLAY_SOURCE_ID, + createEarthquakesLayer, + describeEarthquake, + earthquakeEventLink, + earthquakeRippleRings, + earthquakeContourRings, + earthquakeContourShape, + earthquakeContourScale, + EARTHQUAKE_CONTOUR_WOBBLE, + EARTHQUAKE_RIPPLE_PERIOD_MS, + earthquakeSeverityName, + earthquakeSeverityMeter, + earthquakeDepthBandName, +} from './index.js'; + +const quake = (id, extra = {}) => ({ + stableId: id, + usgsId: id, + lon: -153.3, + lat: 60.0, + depthKm: 112.4, + mag: 2.5, + place: '42 km W of Fixture, Alaska', + time: Date.UTC(2026, 10, 13, 15, 37), + ...extra, +}); + +/** A layer whose globe clicks, card hits and context store the test drives. */ +function harness(rows, { context = null, ripples = null } = {}) { + let snapshot = rows; + const handlers = []; + const opened = []; + const cards = []; + const visible = new Map(); + const labels = []; + const focused = []; + // What the overlay hit test finds under the click, per source. + const overlayHits = new Map(); + const viewer = {}; + const { draw } = bindFakeDraw(viewer); + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => snapshot }, + overlayHost: { + setEntries(sourceId, entries) { + if (sourceId === EARTHQUAKE_CARD_SOURCE_ID) cards.push(entries); + if (sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) labels.push(entries); + }, + setVisible: (sourceId, show) => visible.set(sourceId, show), + clearSource() {}, + // As the real host does, only an interactive entry painted now is hit. + hitTest(_x, _y, { sourceId }) { + const hit = overlayHits.get(sourceId); + const painted = + sourceId === EARTHQUAKE_CARD_SOURCE_ID ? cards.at(-1) : labels.at(-1); + const entry = painted?.find((e) => e.id === hit?.entryId); + return hit && entry?.interactive === true ? hit : null; + }, + }, + input: () => ({ + onClick(callback) { + const handler = { callback, destroyed: false }; + handlers.push(handler); + return () => { + handler.destroyed = true; + }; + }, + }), + picking, + context, + ripples, + pointer: { isPointerFree: () => true }, + openExternal: (url) => opened.push(url), + focus: { + requestWorldFocus: (detail) => { + focused.push(detail); + return true; + }, + }, + }); + layer.init(viewer); + const discs = () => draw.find('earthquakes:'); + const live = () => handlers.filter((h) => !h.destroyed); + return { + layer, + viewer, + opened, + cards, + visible, + focused, + handlers, + discs, + setRows(next) { + snapshot = next; + }, + /** Click a quake's disc (by stable id), something else, or the map. */ + click(hit) { + for (const { callback } of live()) + callback({ + screenPosition: { x: 10, y: 10 }, + topHit: hit, + drawHit: hit && !hit.surface ? hit : null, + }); + }, + clickDisc(id) { + this.click({ set: discs().spec.id, id: `earthquake:${id}` }); + }, + clickCard(entryId) { + this.clickOverlay(EARTHQUAKE_CARD_SOURCE_ID, entryId); + }, + /** Click a magnitude label, as the overlay host paints it. */ + clickLabel(id) { + this.clickOverlay(EARTHQUAKE_OVERLAY_SOURCE_ID, id); + }, + clickOverlay(sourceId, entryId) { + this.clickOverlayWith(sourceId, entryId, null); + }, + /** Click an overlay entry with `hit` drawn under the same pixel. */ + clickOverlayWith(sourceId, entryId, hit) { + overlayHits.set(sourceId, { sourceId, entryId }); + this.click(hit); + overlayHits.delete(sourceId); + }, + lastCard: () => cards.at(-1), + lastLabels: () => labels.at(-1), + }; +} + +test('clicking a quake disc shows its detail card; empty map clears it', async () => { + const h = harness([quake('ak1'), quake('ak2', { mag: 4.1 })]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + assert.equal(h.cards.length, 0, 'no card before a click'); + + h.clickDisc('ak2'); + const [card] = h.lastCard(); + assert.equal(card.id, 'earthquake-card:ak2'); + assert.equal(card.title, 'M4.1 · Light'); + assert.deepEqual(card.details, [ + '■■□□□□ Intermediate · 112.4 km deep', + '42 km W of Fixture, Alaska', + '2026-11-13 15:37 UTC', + 'Source: USGS', + 'Click the card to open the source ↗', + ]); + assert.equal(card.interactive, true); + assert.equal(card.accessibilityLabel, 'Open the source for M4.1 · Light'); + assert.equal(h.visible.get(EARTHQUAKE_CARD_SOURCE_ID), true); + + h.click(null); + assert.deepEqual(h.lastCard(), [], 'a click on the map clears the card'); + h.layer.destroy(); +}); + +test('the card opens the USGS event page, from a click or the keyboard', async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.clickCard('earthquake-card:ak1'); + assert.deepEqual(h.opened, [ + 'https://earthquake.usgs.gov/earthquakes/eventpage/ak1', + ]); + assert.equal(h.lastCard()[0].activate(), true); + assert.equal(h.opened.length, 2); + assert.equal(h.lastCard().length, 1, 'opening the source keeps the card'); + h.layer.destroy(); +}); + +test('a quake with no USGS id gets a card with no link', async () => { + const h = harness([quake('event-1', { usgsId: null })]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('event-1'); + const [card] = h.lastCard(); + assert.equal(card.interactive, true, 'hit-testable, so a click keeps it'); + assert.equal(card.activate, undefined); + assert.equal(card.accessibilityLabel, undefined, 'no action to offer'); + assert.ok(!card.details.some((line) => line.includes('Click the card'))); + h.clickCard(card.id); + assert.deepEqual(h.opened, []); + assert.equal(h.lastCard()[0].id, card.id, 'the card stays'); + h.layer.destroy(); +}); + +test("another layer's pick leaves the card; its own pick ids are claimed", async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + assert.equal(picking.findPickOwner('earthquake:ak1'), 'earthquakes'); + assert.equal(picking.findPickOwner('earthquake:gone'), null); + picking.registerPickOwner('test-other', (id) => id === 'plane-1'); + try { + h.clickDisc('ak1'); + const before = h.cards.length; + h.click({ set: 'flights:1', id: 'plane-1' }); + assert.equal(h.cards.length, before, 'the card stays'); + // A pick of the same id from another set is not a quake. + h.click({ set: 'other:1', id: 'earthquake:ak1' }); + assert.deepEqual(h.lastCard(), []); + } finally { + picking.unregisterPickOwner('test-other'); + h.layer.destroy(); + } + assert.equal(picking.findPickOwner('earthquake:ak1'), null); +}); + +test('a refresh keeps the selected quake while it is in the feed', async () => { + const h = harness([quake('ak1'), quake('ak2')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.setRows([quake('ak1', { mag: 2.7 }), quake('ak2')]); + await h.layer.update(h.viewer); + assert.equal( + h.lastCard()[0].title, + 'M2.7 · Minor', + 'the card follows the feed', + ); + h.setRows([quake('ak2')]); + await h.layer.update(h.viewer); + assert.deepEqual(h.lastCard(), [], 'a quake that left the feed loses it'); + h.layer.destroy(); +}); + +test('disable removes the click handler and the card', async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.layer.disable(h.viewer); + assert.deepEqual(h.lastCard(), []); + assert.equal( + h.handlers.every((handler) => handler.destroyed), + true, + ); + assert.equal(picking.findPickOwner('earthquake:ak1'), null); + h.layer.enable(h.viewer); + assert.equal( + h.handlers.filter((handler) => !handler.destroyed).length, + 1, + 'one handler again, not two', + ); + h.layer.destroy(); +}); + +test('a small quake inside a big one is drawn on top of it', async () => { + const h = harness([quake('small', { mag: 2.6 }), quake('big', { mag: 6 })]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + assert.deepEqual( + [...h.discs().items.keys()], + ['earthquake:big', 'earthquake:small'], + ); + h.layer.destroy(); +}); + +test('the clicked quake is the selected context, cleared with the card', async () => { + const entities = new Map(); + const calls = []; + const context = { + getContextStore: () => ({ entities }), + registerEntityContext(carrier, metadata) { + entities.set(metadata.id, { ...metadata, entity: carrier }); + }, + selectEntityContext: (carrier) => calls.push(['select', carrier]), + clearSelectedEntityContextForLayer: (layerId) => + calls.push(['clear', layerId]), + }; + const h = harness([quake('ak1'), quake('ak2')], { context }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const record = entities.get('earthquake:ak1'); + assert.equal(record.layerId, 'earthquakes'); + assert.equal(record.label, 'Earthquake · M2.5 · 42 km W of Fixture, Alaska'); + assert.equal(record.properties.usgsId, 'ak1'); + assert.equal(record.dataSource.show, true, 'hidden with the discs'); + assert.equal(calls.at(-1)[0], 'select'); + h.clickDisc('ak2'); + assert.deepEqual([...entities.keys()], ['earthquake:ak2'], 'one record'); + h.click(null); + assert.equal(entities.size, 0); + assert.deepEqual(calls.at(-1), ['clear', 'earthquakes']); + h.layer.destroy(); +}); + +test('without click services the layer draws and takes no clicks', async () => { + const viewer = {}; + bindFakeDraw(viewer); + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => [quake('ak1')] }, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + layer.init(viewer); + layer.enable(viewer); + assert.equal(await layer.update(viewer), true); + assert.equal(picking.findPickOwner('earthquake:ak1'), null); + layer.destroy(); +}); + +test('describeEarthquake translates through the given formatters', () => { + const card = describeEarthquake(quake('ak1', { place: ' far away ' }), { + t: (text, values) => `<${text}>${JSON.stringify(values ?? {})}`, + formatTime: () => 'TIME', + formatDepth: (km) => `~${km}`, + }); + assert.equal(card.title, 'M2.5 · {"context":"earthquake"}'); + assert.deepEqual(card.details, [ + '■□□□□□ {"context":"earthquake"} · <{km} km deep>{"km":"~112.4"}', + 'far away', + 'TIME', + '{"value":"USGS"}', + '{}', + ]); + const bare = describeEarthquake({ mag: 3, place: null, time: null }); + assert.equal(bare.title, 'M3.0 · Minor'); + assert.deepEqual(bare.details, ['■□□□□□', 'Source: USGS']); + assert.equal(bare.link, null); +}); + +test('severity follows the USGS magnitude classes; depth bands the disc colours', () => { + const cases = [ + [2.5, 'Minor', '■□□□□□'], + [3.99, 'Minor', '■□□□□□'], + [4, 'Light', '■■□□□□'], + [5.4, 'Moderate', '■■■□□□'], + [6.1, 'Strong', '■■■■□□'], + [7.8, 'Major', '■■■■■□'], + [8.2, 'Great', '■■■■■■'], + [9.5, 'Great', '■■■■■■'], + [Number.NaN, 'Minor', '■□□□□□'], + ]; + for (const [mag, name, meter] of cases) { + assert.equal(earthquakeSeverityName(mag), name, String(mag)); + assert.equal(earthquakeSeverityMeter(mag), meter, String(mag)); + } + assert.equal(earthquakeDepthBandName(10), 'Shallow'); + assert.equal(earthquakeDepthBandName(69.9), 'Shallow'); + assert.equal(earthquakeDepthBandName(70), 'Intermediate'); + assert.equal(earthquakeDepthBandName(299), 'Intermediate'); + assert.equal(earthquakeDepthBandName(300), 'Deep'); +}); + +test('earthquakeEventLink accepts only plain USGS ids', () => { + assert.equal( + earthquakeEventLink('us7000abcd'), + 'https://earthquake.usgs.gov/earthquakes/eventpage/us7000abcd', + ); + for (const bad of [null, '', ' ', '../x', 'a/b', 'a?b=1', 'x'.repeat(65)]) + assert.equal(earthquakeEventLink(bad), null, String(bad)); +}); + +test('clicking a magnitude label selects the quake and flies to it', async () => { + const h = harness([ + quake('ak1'), + quake('jp1', { mag: 5, lon: 142, lat: 38 }), + ]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + const label = h.lastLabels().find((entry) => entry.id === 'jp1'); + assert.equal(label.interactive, true, 'labels take clicks'); + assert.equal( + label.accessibilityLabel, + 'Zoom to M5.0 · 42 km W of Fixture, Alaska', + ); + + h.clickLabel('jp1'); + assert.equal(h.lastCard()[0].id, 'earthquake-card:jp1'); + assert.equal(h.focused.length, 1); + const [detail] = h.focused; + assert.equal(detail.kind, 'earthquake'); + assert.equal(detail.id, 'earthquake:jp1'); + assert.equal(detail.label, 'M5.0'); + assert.ok( + Math.hypot(detail.position.x, detail.position.y, detail.position.z) > 6e6, + ); + + // The keyboard path does the same. + assert.equal( + h + .lastLabels() + .find((e) => e.id === 'ak1') + .activate(), + true, + ); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1'); + assert.equal(h.focused.at(-1).id, 'earthquake:ak1'); + + // A disc click only selects: the camera stays where it is. + h.clickDisc('jp1'); + assert.equal(h.focused.length, 2); + assert.equal(h.lastCard()[0].id, 'earthquake-card:jp1'); + + // A label id the layer no longer draws is not a quake. + h.clickLabel('gone'); + assert.deepEqual(h.lastCard(), []); + assert.equal(h.focused.length, 2); + h.layer.destroy(); +}); + +test('without click services the labels stay non-interactive', async () => { + const viewer = {}; + bindFakeDraw(viewer); + const published = []; + const layer = createEarthquakesLayer({ + source: { getSnapshot: async () => [quake('ak1')] }, + overlayHost: { + setEntries: (_source, entries) => published.push(entries), + setVisible() {}, + clearSource() {}, + }, + }); + layer.init(viewer); + layer.enable(viewer); + await layer.update(viewer); + const [label] = published.at(-1); + assert.equal(label.interactive, false); + assert.equal(label.activate, undefined); + layer.destroy(); +}); + +test('the selected quake runs contour rings to its disc edge; clearing stops them', async () => { + const calls = []; + const ripples = { + show: (target) => calls.push(['show', target]), + hide: () => calls.push(['hide']), + dispose: () => calls.push(['dispose']), + }; + const h = harness( + [quake('ak1', { mag: 5, depthKm: 10 }), quake('ak2', { mag: 3 })], + { ripples }, + ); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const shown = calls.findLast(([kind]) => kind === 'show')[1]; + assert.deepEqual(shown, { + id: 'ak1', + lon: -153.3, + lat: 60, + radiusM: 32000, + color: 'rgb(255,0,0)', + }); + assert.equal( + h.discs().items.get('earthquake:ak1').geometry.semiMajor, + shown.radiusM, + 'the rings end at the disc edge', + ); + h.clickDisc('ak2'); + assert.equal(calls.findLast(([kind]) => kind === 'show')[1].radiusM, 8000); + h.click(null); + assert.deepEqual(calls.at(-1), ['hide']); + h.clickDisc('ak1'); + h.layer.disable(h.viewer); + assert.deepEqual(calls.at(-1), ['hide']); + h.layer.destroy(); + assert.deepEqual(calls.at(-1), ['dispose']); +}); + +test('ripple rings run from the marker to the edge, staggered, fading at both ends', () => { + const rings = earthquakeRippleRings(0, { count: 3, periodMs: 3000 }); + assert.deepEqual( + rings.map(({ fraction }) => Number(fraction.toFixed(4))), + [0, 0.3333, 0.6667], + ); + assert.equal(rings[0].alpha, 0, 'a ring at the marker is not yet seen'); + // Each ring moves outward with time and wraps back to the marker. + const later = earthquakeRippleRings(1000, { count: 3, periodMs: 3000 }); + assert.ok(later[1].fraction > rings[1].fraction); + assert.ok(later[2].fraction < rings[2].fraction, 'the outer ring wrapped'); + for (let t = 0; t < 6000; t += 37) + for (const { fraction, alpha } of earthquakeRippleRings(t)) { + assert.ok(fraction >= 0 && fraction < 1); + assert.ok(alpha >= 0 && alpha <= 1); + } + const near = (f) => + earthquakeRippleRings(f * EARTHQUAKE_RIPPLE_PERIOD_MS, { count: 1 })[0] + .alpha; + assert.ok(near(0.99) < 0.02, 'fades out at the edge'); + assert.ok(near(0.12) > 0.999, 'fully in just after the start'); + assert.deepEqual( + earthquakeContourRings(3).map(({ fraction }) => fraction), + [1 / 3, 2 / 3, 1], + ); +}); + +test('a quake keeps its own contour shape; nested lines never cross', () => { + const a = earthquakeContourShape('us7000abcd'); + assert.deepEqual( + earthquakeContourShape('us7000abcd'), + a, + 'same id, same shape', + ); + assert.notDeepEqual(earthquakeContourShape('ak2026xyz'), a); + for (const id of ['us7000abcd', 'ak2026xyz', 'event-1', '']) { + const shape = earthquakeContourShape(id); + for (let i = 0; i < 180; i++) { + const angle = (2 * Math.PI * i) / 180; + let previous = 0; + for (let step = 1; step <= 200; step++) { + const fraction = step / 200; + const scale = earthquakeContourScale(shape, angle, fraction); + assert.ok(scale <= 1 + 1e-12, 'never past the disc edge'); + assert.ok(scale >= 1 - EARTHQUAKE_CONTOUR_WOBBLE - 1e-12); + const reach = fraction * scale; + assert.ok(reach > previous, `${id}: lines cross at ${angle}`); + previous = reach; + } + } + } +}); + +test("the selected quake's flat disc fades under its gradient and comes back", async () => { + const ripples = { show() {}, hide() {}, dispose() {} }; + const h = harness([quake('ak1', { mag: 5 }), quake('ak2')], { ripples }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + const alpha = (id) => h.discs().items.get(`earthquake:${id}`).fill[3]; + assert.equal(alpha('ak1'), 0.4); + h.clickDisc('ak1'); + assert.equal(alpha('ak1'), 0.04, 'faint, still pickable'); + h.clickDisc('ak2'); + assert.equal(alpha('ak1'), 0.4, 'restored'); + assert.equal(alpha('ak2'), 0.04); + // A refresh keeps the selected disc faded. + await h.layer.update(h.viewer); + assert.equal(alpha('ak2'), 0.04); + assert.equal(alpha('ak1'), 0.4); + h.click(null); + assert.equal(alpha('ak2'), 0.3); + h.layer.destroy(); +}); + +test('without the ripples painter the selected disc keeps its fill', async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + assert.equal(h.discs().items.get('earthquake:ak1').fill[3], 0.3); + h.layer.destroy(); +}); + +test('a feed refresh neither retakes the selection nor restarts the contours', async () => { + const calls = []; + const shows = []; + const entities = new Map(); + const context = { + getContextStore: () => ({ entities }), + registerEntityContext(carrier, metadata) { + entities.set(metadata.id, { ...metadata, entity: carrier }); + }, + selectEntityContext: () => calls.push('select'), + clearSelectedEntityContextForLayer: () => calls.push('clear'), + }; + const ripples = { + show: (target, options) => shows.push(options), + hide() {}, + dispose() {}, + }; + const h = harness([quake('ak1', { mag: 4 })], { context, ripples }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + assert.deepEqual(calls, ['select']); + assert.deepEqual(shows, [{ restart: true }]); + // Another layer's selection happens here; then the feed refreshes. + h.setRows([quake('ak1', { mag: 4.3 })]); + await h.layer.update(h.viewer); + assert.deepEqual(calls, ['select'], 'not selected again by a refresh'); + assert.deepEqual(shows.at(-1), { restart: false }); + assert.equal( + entities.get('earthquake:ak1').label, + 'Earthquake · M4.3 · 42 km W of Fixture, Alaska', + 'the record is kept up to date', + ); + // Clicking it again is the user's: it selects and runs again. + h.clickDisc('ak1'); + assert.deepEqual(calls, ['select', 'select']); + assert.deepEqual(shows.at(-1), { restart: true }); + h.layer.destroy(); +}); + +test("another layer's object over a magnitude label takes the click", async () => { + const h = harness([quake('ak1')]); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); + try { + // The click lands on the label and on a plane drawn there. + h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak1', { + set: 'flights:1', + id: 'plane-9', + }); + assert.equal(h.cards.length, 0, 'the quake is not selected'); + assert.equal(h.focused.length, 0, 'and the camera stays'); + // The label alone still selects and flies. + h.clickLabel('ak1'); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1'); + assert.equal(h.focused.length, 1); + } finally { + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + } +}); diff --git a/src/navigationPolicy.js b/src/navigationPolicy.js index d9e0e1757d..077cfb8d45 100644 --- a/src/navigationPolicy.js +++ b/src/navigationPolicy.js @@ -24,6 +24,7 @@ const COCKPIT_REFUSALS = Object.freeze({ target: msg('Exit cockpit to fly to a target'), vessel: msg('Exit cockpit to fly to a vessel'), fire: msg('Exit cockpit to fly to a fire'), + earthquake: msg('Exit cockpit to fly to an earthquake'), sighting: msg('Exit cockpit to fly to a sighting'), 'sighting-area': msg('Exit cockpit to fly to a sighting area'), train: msg('Exit cockpit to fly to a train'), diff --git a/src/worldFocus.js b/src/worldFocus.js index af50b2f30b..cf9e2fb90f 100644 --- a/src/worldFocus.js +++ b/src/worldFocus.js @@ -18,6 +18,9 @@ export const WORLD_FOCUS_FRAMING = Object.freeze({ // A stopped train's one fly-to, and the frame a moving train is followed // in (src/layers/rail/follow.js): the train and the track either side. train: Object.freeze({ radiusM: 200, rangeM: 2500, pitchDeg: -35 }), + // A clicked quake's magnitude label: its disc (2^M km across, so about + // 11 km at M2.5 and 128 km at M6) and the ground around it. + earthquake: Object.freeze({ radiusM: 20000, rangeM: 220000, pitchDeg: -45 }), 'sighting-area': Object.freeze({ radiusM: 11000, rangeM: 60000, diff --git a/src/worldFocus.test.mjs b/src/worldFocus.test.mjs index 2f90c5b6f9..8512a969d4 100644 --- a/src/worldFocus.test.mjs +++ b/src/worldFocus.test.mjs @@ -209,6 +209,7 @@ test('fires frame wider than vessels — a fire is read by its surroundings', () test('every framing is a real oblique standoff, not a nadir or an inside-out sphere', () => { const kinds = Object.keys(WORLD_FOCUS_FRAMING); assert.deepEqual(kinds.sort(), [ + 'earthquake', 'fire', 'sighting', 'sighting-area', @@ -232,8 +233,10 @@ test('every framing is a real oblique standoff, not a nadir or an inside-out sph framing.rangeM > framing.radiusM, `${kind}: range ${framing.rangeM} must stand off outside radius ${framing.radiusM}`, ); - // An obscured sighting frames its entire 0.2° privacy cell. - const maximumRange = kind === 'sighting-area' ? 60000 : 10000; + // An obscured sighting frames its entire 0.2° privacy cell, and a quake + // its disc, up to 128 km across at M6. + const maximumRange = + { 'sighting-area': 60000, earthquake: 250000 }[kind] ?? 10000; assert.ok( framing.rangeM <= maximumRange, `${kind}: range must fit its surface extent, got ${framing.rangeM}`, From 0a8899d4393a821a75cb723e4dedcf06df937e93 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Mon, 16 Nov 2026 19:47:06 +0530 Subject: [PATCH 004/138] test(camera): compare recorded camera traces within platform roundoff The camera golden test compared the recorded traces byte for byte, so it failed on arm64, where trigonometry differs from the committed traces in the last bits (at most 2.1e-9 m on a height, 33 of 1,530 numbers). Compare structure, keys, array lengths, counters and the viewport exactly, and other numbers within 1e-8 m for positions and heights and 1e-14 otherwise; a self-test rejects larger errors, NaN, null, strings and missing or extra keys. The pose test compares pitch by its sine within 1e-12, as the conformance suite does, and checks the canonical range. The golden file and production camera code are unchanged. --- src/render/cesium/cameraGoldens.test.mjs | 73 +++++++++++++++++++++--- src/render/cesium/cameraPort.test.mjs | 11 +++- 2 files changed, 75 insertions(+), 9 deletions(-) diff --git a/src/render/cesium/cameraGoldens.test.mjs b/src/render/cesium/cameraGoldens.test.mjs index 774b0a0114..91ca593516 100644 --- a/src/render/cesium/cameraGoldens.test.mjs +++ b/src/render/cesium/cameraGoldens.test.mjs @@ -2,15 +2,72 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { recordCameraGoldens } from './cameraGoldens.js'; +import { near } from '../conformance/expect.js'; + +// The recorder is deterministic, but platforms can differ in the last bits +// of trigonometric arithmetic. Keep structure and discrete values exact. +function compareTrace(actual, expected, path = []) { + const label = path.join('.'); + if (typeof expected === 'number') { + const key = path.at(-1); + if (['step', 'frames', 'count'].includes(key) || path[0] === 'viewport') { + assert.equal(actual, expected, label); + return; + } + const metres = + path.at(-2) === 'position' || + key === 'height' || + (path.at(-2) === 'view' && Number(key) >= 12 && Number(key) <= 14); + near(actual, expected, metres ? 1e-8 : 1e-14, label); + return; + } + if (expected !== null && typeof expected === 'object') { + assert.ok(actual !== null && typeof actual === 'object', label); + assert.equal(Array.isArray(actual), Array.isArray(expected), label); + assert.deepEqual(Object.keys(actual), Object.keys(expected), label); + if (Array.isArray(expected)) + assert.equal(actual.length, expected.length, label); + for (const key of Object.keys(expected)) + compareTrace(actual[key], expected[key], [...path, key]); + return; + } + assert.equal(actual, expected, label); +} test('the committed camera traces are what the installed Cesium records', async () => { - const committed = readFileSync( - new URL('../conformance/goldens/camera.json', import.meta.url), - 'utf8', - ); - const recorded = `${JSON.stringify(await recordCameraGoldens(), null, 2)}\n`; - assert.ok( - recorded === committed, - 'goldens/camera.json is out of date: run node scripts/record-camera-goldens.mjs and review the diff', + const committed = JSON.parse( + readFileSync( + new URL('../conformance/goldens/camera.json', import.meta.url), + 'utf8', + ), ); + compareTrace(await recordCameraGoldens(), committed); +}); + +test('trace comparison tolerates only numeric roundoff, preserving structure and counters', () => { + const expected = { + position: { x: 1000 }, + pitch: 0.3, + frames: 2, + values: [1], + label: 'pose', + }; + compareTrace( + { ...expected, position: { x: 1000 + 2e-9 }, pitch: 0.3 + 1e-16 }, + expected, + ); + for (const actual of [ + { ...expected, extra: true }, + { ...expected, values: [] }, + { ...expected, position: { x: 1000 + 2e-8 } }, + { ...expected, pitch: 0.3 + 2e-14 }, + { ...expected, frames: 2 + 1e-15 }, + { ...expected, pitch: NaN }, + { ...expected, pitch: null }, + { ...expected, pitch: '0.3' }, + { ...expected, label: 'other' }, + ]) + assert.throws(() => compareTrace(actual, expected)); + const { label, ...missing } = expected; + assert.throws(() => compareTrace(missing, expected)); }); diff --git a/src/render/cesium/cameraPort.test.mjs b/src/render/cesium/cameraPort.test.mjs index 967ff1f761..9d81e928fa 100644 --- a/src/render/cesium/cameraPort.test.mjs +++ b/src/render/cesium/cameraPort.test.mjs @@ -416,7 +416,16 @@ test('a pose measures heading, pitch and roll as Cesium does, and leaves the cam const pitch = camera.pitch; const roll = camera.roll; assert.equal(pose.heading, heading, `heading ${k}`); - assert.ok(Math.abs(pose.pitch - pitch) < 1e-12, `pitch ${k}`); + assert.ok( + pose.pitch >= -Math.PI / 2 && pose.pitch <= Math.PI / 2, + `canonical pitch ${k}`, + ); + // Near vertical, acos amplifies last-bit direction differences. Match + // the conformance suite's well-conditioned pitch comparison. + assert.ok( + Math.abs(Math.sin(pose.pitch) - Math.sin(pitch)) < 1e-12, + `pitch ${k}`, + ); const turn = Math.abs(pose.roll - roll); assert.ok(Math.min(turn, 2 * Math.PI - turn) < 1e-12, `roll ${k}`); } From 9f698779be6644c2b626c30290d5542bf3ae04f7 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Mon, 16 Nov 2026 19:47:15 +0530 Subject: [PATCH 005/138] test(track): follow the shared 3D toggle and draw-port trails The tracked aircraft now takes its model under the same 3D toggle as the fleet, and trails are drawn through draw-port line sets rather than viewer entities, so the tracking regression read a contract that no longer exists. Arm the toggle in the model scenarios and observe the trail head through the draw port. A trail check with too few frames now fails instead of skipping, and a missing tracked model before the exit check is an error. --- scripts/track-regression.mjs | 88 +++++++++++++++++++++++------------- 1 file changed, 57 insertions(+), 31 deletions(-) diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs index 4e163cd398..3e8e6f62d1 100644 --- a/scripts/track-regression.mjs +++ b/scripts/track-regression.mjs @@ -1619,19 +1619,48 @@ async function main() { // The fixture planes repeat one position, so the icon holds and draws no // head. Fly the tracked one east for this check; the display runs 30 s // behind, so give it time to reach the moving reports. - await evalPage((icao) => { + await evalPage(async (icao) => { + const { rendererOf } = await import(`${window.__gevQaSourceBase || '/src'}/render/rendererOf.js`); + const app = window.__godsEyeView; + const fl = app.dataManager.layers.get('flights').module; + // Observe this selection's actual draw-port submissions: trails no + // longer live in viewer.entities. Disabling destroys the reused trail + // set, so this selection creates one the probe can identify. + await app.dataManager.setEnabled('flights', false); + const draw = rendererOf(app.viewer).draw; + const createLines = draw.lines; + let head = null; + let trail = null; + draw.lines = function (spec) { + const set = createLines.call(this, spec); + if (!spec.id.startsWith('trail:')) return set; + draw.lines = createLines; + trail = set; + const upsert = set.upsert; + set.upsert = function (items) { + const result = upsert.call(this, items); + for (const item of items) + if (/^gev-trail:\d+:head$/.test(item.id)) head = item; + return result; + }; + const clear = set.clear; + set.clear = function () { head = null; return clear.call(this); }; + const dispose = set.dispose; + set.dispose = function () { head = null; trail = null; return dispose.call(this); }; + return set; + }; + window.__qaTrailHead = () => trail?.show && head?.show !== false ? head?.positions : null; + window.__qaRestoreTrailProbe = () => { draw.lines = createLines; }; + await app.dataManager.setEnabled('flights', true); + if (!fl.trackById(icao)) throw new Error('trail fixture could not reselect its aircraft'); const f = window.__SYNTH.flights.find((p) => p.icao === icao); f.moveFromMs = Date.now(); }, trackedIcao); await sleep(55_000); const headSamples = await sampleFrames(page, 40, (icao) => { - const viewer = window.__godsEyeView.viewer; const fl = window.__godsEyeView.dataManager.layers.get('flights').module; - const ent = viewer.trackedEntity; - const time = viewer.clock.currentTime; - const head = viewer.entities.values.find((e) => String(e.id).startsWith('gev-trail:fl-head-')); - const line = head?.polyline?.positions?.getValue(time); - const drawn = ent?.position?.getValue(time); + const line = window.__qaTrailHead(); + const drawn = window.__qaFollowed()?.position?.(); if (!line?.length || !drawn) return null; const end = line[line.length - 1]; const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z); @@ -1677,10 +1706,8 @@ async function main() { for (let i = 0; i < 8; i++) { await sleep(600); betweenFrames.push(await evalPage((icao) => { - const viewer = window.__godsEyeView.viewer; - const head = viewer.entities.values.find((e) => String(e.id).startsWith('gev-trail:fl-head-')); - const line = head?.polyline?.positions?.getValue(viewer.clock.currentTime); - const drawn = viewer.trackedEntity?.position?.getValue(viewer.clock.currentTime); + const line = window.__qaTrailHead(); + const drawn = window.__qaFollowed()?.position?.(); if (!line?.length || !drawn) return null; const end = line[line.length - 1]; return Math.hypot(end.x - drawn.x, end.y - drawn.y, end.z - drawn.z); @@ -1694,10 +1721,11 @@ async function main() { f.lon += (f.vel * (Date.now() - f.moveFromMs)) / 1000 / (111320 * Math.cos((f.lat * Math.PI) / 180)); delete f.moveFromMs; + window.__qaRestoreTrailProbe(); }, trackedIcao); const headUsable = headSamples.values.filter((v) => v != null); if (headUsable.length < 10) { - skip('trail head: ends at the drawn icon on every frame', + record('trail head: ends at the drawn icon on every frame', false, `only ${headUsable.length} frames with a drawn head (timedOut=${headSamples.timedOut})`); } else { const worst = Math.max(...headUsable.map((v) => v.end)); @@ -3661,6 +3689,9 @@ async function main() { } while (Date.now() < fleetClampDeadline && (!Number.isFinite(fleetH) || fleetH < seeded + 1)); if (!fl.trackById('aaa097')) return { error: 'trackById(aaa097) failed' }; + // The tracked contact obeys the same 3D toggle as the fleet. Arm it + // before testing the cold-ground gate and the warm model handoff. + fl.setParams({ models3d: true }); await window.__dfSettle(1500); // Read the tracked entity's rendered height plus the floor under it and // the sensor value the data APIs report, at whatever regime the camera @@ -3750,6 +3781,7 @@ async function main() { }; const trackedEntity = window.__qaFollowed(); const trackedModel = findOwnModel(); + if (!trackedModel) return { error: 'tracked model absent before exit' }; const achievedOut = await window.__dfZoomAbove(window.__dfRegime.exit + 5000); const zoomedOut = await window.__dfObserveTrackedExit({ scene: v.scene, trackedEntity, trackedModel, getTrackedModel: findOwnModel, @@ -3888,10 +3920,8 @@ async function main() { // the tracked billboard becomes the visual again. Gating the clamp on // model EXISTENCE put the burial straight back in exactly that state. // - // This scenario also pins the toggle contract itself. The DISPLAY-rail - // "3D" toggle stays OFF for the whole block on purpose: it governs the - // FLEET's draw-call budget only, and the tracked contact must still take - // its model on zoom without the operator arming anything. + // The tracked contact obeys the shared 3D toggle. Keep it enabled + // while zoom alone hands the visual between model and billboard. const dfRetained = await evalPage(async () => { const v = window.__godsEyeView.viewer; const Cesium = await import('/node_modules/cesium/Build/Cesium/index.js'); @@ -3904,13 +3934,13 @@ async function main() { // and there would otherwise hand an open skin to the seeded scenarios // that follow; closing an already-closed skin is inert. try { - // Toggle OFF throughout — the tracked model must not need it. - fl.setParams({ models3d: false }); - const toggleOff = fl.getParams().models3d === false; + // Arm the shared toggle so the zoom regime can retain a hidden model. + fl.setParams({ models3d: true }); + const toggleOn = fl.getParams().models3d === true; if (!fl.trackById('aaa097')) return { error: 'trackById(aaa097) failed' }; await window.__dfSettle(600); // Below the ENTER ceiling (trackById re-frames to the close follow - // range): the tracked model arrives on zoom alone, toggle still off. + // range): the tracked model arrives on zoom alone, 3D enabled. const belowH = await window.__dfZoomBelow(window.__dfRegime.enter - 20000); const withModel = await window.__dfAwaitTrackedModel('aaa097', 20000); // Same split as the regime scenario: a browser with no usable GLB @@ -3960,7 +3990,7 @@ async function main() { const ent2 = window.__qaFollowed()?.position?.(); const c2 = ent2 ? window.__dfCarto(ent2) : null; const out = { - toggleOff, + toggleOn, enter: window.__dfRegime.enter, exit: window.__dfRegime.exit, belowH, @@ -3995,23 +4025,19 @@ async function main() { record('display-floor/T7: while the tracked MODEL is the visual, the clamp stands aside', !dfRetained.error && dfRetained.modelsRenderingBelow > 0, dfRetained.error - || `${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering at ${(dfRetained.belowH / 1000).toFixed(0)} km with the 3D toggle OFF; entity at ${Number(dfRetained.withModelH).toFixed(1)} m (ground-snap owns it)`); + || `${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering at ${(dfRetained.belowH / 1000).toFixed(0)} km with the 3D toggle ON; entity at ${Number(dfRetained.withModelH).toFixed(1)} m (ground-snap owns it)`); - // The toggle contract after auto-3D (2026-08-20): the DISPLAY-rail "3D" - // switch owns the FLEET only. The tracked contact's model is default-on - // and decided purely by camera distance, so with the toggle OFF it is - // SHOWN below the enter ceiling and handed back above the exit ceiling — - // and handed back by HIDING, not destroying, which is the retained state - // the floor pin below depends on. - record('display-floor/regime: the 3D toggle governs the FLEET only — the tracked model follows the zoom', - !dfRetained.error && dfRetained.toggleOff === true + // With 3D enabled, zooming out hides rather than destroys the + // tracked model: the retained state the floor check depends on. + record('display-floor/regime: with 3D enabled the tracked model follows the zoom', + !dfRetained.error && dfRetained.toggleOn === true && dfRetained.modelsRenderingBelow > 0 && dfRetained.belowH < dfRetained.enter && dfRetained.shownModelsAbove === 0 && dfRetained.hiddenModelsAbove > 0 && dfRetained.aboveH > dfRetained.exit, dfRetained.error - || `toggle OFF throughout: at ${(dfRetained.belowH / 1000).toFixed(0)} km (< ${(dfRetained.enter / 1000).toFixed(0)} km enter) ${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering; at ${(dfRetained.aboveH / 1000).toFixed(0)} km (> ${(dfRetained.exit / 1000).toFixed(1)} km exit) ${dfRetained.shownModelsAbove} shown / ${dfRetained.hiddenModelsAbove} retained-hidden`); + || `toggle ON throughout: at ${(dfRetained.belowH / 1000).toFixed(0)} km (< ${(dfRetained.enter / 1000).toFixed(0)} km enter) ${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering; at ${(dfRetained.aboveH / 1000).toFixed(0)} km (> ${(dfRetained.exit / 1000).toFixed(1)} km exit) ${dfRetained.shownModelsAbove} shown / ${dfRetained.hiddenModelsAbove} retained-hidden`); record('display-floor: a retained-but-hidden tracked model does NOT suppress the floor', Number.isFinite(dfRetained.afterSeedH) From b2bc15e763d3aa3ce6aaea14f9be1353ea74459c Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Mon, 16 Nov 2026 19:47:30 +0530 Subject: [PATCH 006/138] fix(earthquakes): keep quake discs out of pick ownership Registering quake discs as pick owners changed how other layers read a click anywhere over a quake: sibling layers yield to owned picks before their own card hit-tests and treat an owned pick as not empty space. A fire card drawn over a large quake could not be clicked and the quake beneath was selected, radio near-miss taps found nothing, and a followed aircraft kept its camera while the quake took the shared selection. Leave the discs unregistered, as drone airspace and fire perimeters do, so a disc reads as empty space to other layers. The quake handler finds its own discs by draw set, reads the click's resolved hit, and yields when another layer's card or label is the topmost overlay entry. Another layer's object under the quake card or a label takes the click before either is read, so a click on the card over an aircraft does not also open the USGS page. A feed refresh inside the contour window no longer asks for a frame while the disc is off screen. --- docs/CURRENT-STATE.md | 6 ++ src/app/layers/earthquakeRipples.js | 5 +- src/layers/earthquakes/index.js | 41 +++++--- src/layers/earthquakes/selection.test.mjs | 117 ++++++++++++++++++++-- 4 files changed, 144 insertions(+), 25 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 5a3af0a5b9..07f2e8f891 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1863,6 +1863,12 @@ painted with a gradient fading to the outer circle and wavy contour lines clicks, picking, context, focus, the opener, the painter and the translator by injection (`src/app/layers/earthquakes.js`); without input and picking it draws and takes no clicks, and its labels stay non-interactive. +Quake discs are deliberately not registered in the pick-ownership registry, +like drone airspace and fire perimeters: sibling layers read a disc as empty +space, so their cards, near-miss taps and deselection work over a quake as +before. When another layer's card or label is painted over a disc (a fire card +on a large quake), the quake handler yields to it rather than selecting the +quake beneath. Air quality (`./layers/air-quality`) draws its station discs as one renderer draw set of ground-clamped fills and reads the view through the camera port; it diff --git a/src/app/layers/earthquakeRipples.js b/src/app/layers/earthquakeRipples.js index 31f3557c44..c761eee0fe 100644 --- a/src/app/layers/earthquakeRipples.js +++ b/src/app/layers/earthquakeRipples.js @@ -361,7 +361,10 @@ export function createEarthquakeRipples({ }); lane.setActive(true); lane.requestPaint(); - if (running() && frameHandle === null) frameHandle = requestFrame(tick); + // A refresh while the disc is out of sight asks for no frame; a paint + // that finds it on screen again starts them (a restart sets onScreen). + if (running() && onScreen && frameHandle === null) + frameHandle = requestFrame(tick); } function hide() { diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 37cd2e8cae..cd4b0ca1c3 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -60,8 +60,7 @@ let instances = 0; * the card be clicked). * @param {(viewer: object) => {onClick: Function}} [options.input] The * viewer's click dispatcher. - * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function, - * registerPickOwner: Function, unregisterPickOwner: Function}} [options.picking] + * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function}} [options.picking] * @param {{registerEntityContext: Function, selectEntityContext: Function, * clearSelectedEntityContextForLayer: Function, * getContextStore: Function}} [options.context] Shared selection store. @@ -306,10 +305,12 @@ export function createEarthquakesLayer({ function installClickHandler() { if (!canSelect() || _clickHandler || !_viewer) return; - picking.registerPickOwner?.( - EARTHQUAKES_LAYER_ID, - (pickedId) => _enabled && eventOfPickId(pickedId) !== null, - ); + // Deliberately NOT registered in the pick-ownership registry, like drone + // airspace and fire perimeters: siblings yield to owned picks before + // their own card hit-tests and treat an owned pick as not empty space, + // so claiming these large discs would make their cards inert and their + // selections stick anywhere over a quake. Unowned, a disc reads as + // empty space to them; this handler finds its own discs by draw set. // A viewer with no renderer input bound takes no clicks. let clicks = null; try { @@ -321,6 +322,23 @@ export function createEarthquakesLayer({ _clickHandler = clicks.onClick((click) => { if (!_enabled || (pointer && !pointer.isPointerFree())) return; const at = click.screenPosition; + // Another layer's card or label painted on top (a fire's card over a + // quake disc) is that layer's click: the disc under it is background. + const topEntry = overlayHost.hitTest?.(at?.x, at?.y); + if ( + topEntry && + topEntry.sourceId !== EARTHQUAKE_CARD_SOURCE_ID && + topEntry.sourceId !== EARTHQUAKE_OVERLAY_SOURCE_ID + ) + return; + // Another layer's pick (an aircraft, a camera) is not this layer's, + // even under this layer's card or a magnitude label: that layer acts + // on the click itself, and this card stays. Checked before the card + // and the labels, as the fire layer does. + const hit = click.hit; + const pickId = picking.resolvePickId(hit); + if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId)) + return; const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID, }); @@ -328,14 +346,6 @@ export function createEarthquakesLayer({ if (_selectedLink) openExternal(_selectedLink); return; } - // Another layer's pick (an aircraft, a camera) is not this layer's, - // even under a magnitude label: that layer handles it, and this card - // stays. Checked before the labels, as the fire layer does. - const pickId = click.topHit - ? (picking.resolvePickId(click.topHit) ?? null) - : null; - if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId)) - return; // A magnitude label is what a far view (the whole globe) can click: // it selects the quake and flies to it. const labelHit = overlayHost.hitTest?.(at?.x, at?.y, { @@ -345,7 +355,7 @@ export function createEarthquakesLayer({ selectAndFocus(labelHit.entryId); return; } - const event = pickedEvent(click.drawHit ?? click.topHit); + const event = pickedEvent(hit); if (event) { _selectedId = event.stableId; publishCard({ user: true }); @@ -373,7 +383,6 @@ export function createEarthquakesLayer({ function removeClickHandler() { _clickHandler?.(); _clickHandler = null; - picking?.unregisterPickOwner?.(EARTHQUAKES_LAYER_ID); } const layer = { diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs index 568d6cc4e1..4a5e70412a 100644 --- a/src/layers/earthquakes/selection.test.mjs +++ b/src/layers/earthquakes/selection.test.mjs @@ -42,6 +42,8 @@ function harness(rows, { context = null, ripples = null } = {}) { const focused = []; // What the overlay hit test finds under the click, per source. const overlayHits = new Map(); + // Another layer's interactive entry painted on top, if any. + let foreignTop = null; const viewer = {}; const { draw } = bindFakeDraw(viewer); const layer = createEarthquakesLayer({ @@ -54,7 +56,15 @@ function harness(rows, { context = null, ripples = null } = {}) { setVisible: (sourceId, show) => visible.set(sourceId, show), clearSource() {}, // As the real host does, only an interactive entry painted now is hit. - hitTest(_x, _y, { sourceId }) { + hitTest(_x, _y, { sourceId } = {}) { + // Unfiltered, as the host answers: another layer's entry on top + // first, else this layer's own. + if (!sourceId) + return ( + foreignTop ?? + this.hitTest(_x, _y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID }) ?? + this.hitTest(_x, _y, { sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID }) + ); const hit = overlayHits.get(sourceId); const painted = sourceId === EARTHQUAKE_CARD_SOURCE_ID ? cards.at(-1) : labels.at(-1); @@ -99,11 +109,12 @@ function harness(rows, { context = null, ripples = null } = {}) { snapshot = next; }, /** Click a quake's disc (by stable id), something else, or the map. */ - click(hit) { + click(hit, resolvedHit = hit) { for (const { callback } of live()) callback({ screenPosition: { x: 10, y: 10 }, topHit: hit, + hit: resolvedHit, drawHit: hit && !hit.surface ? hit : null, }); }, @@ -120,10 +131,16 @@ function harness(rows, { context = null, ripples = null } = {}) { clickOverlay(sourceId, entryId) { this.clickOverlayWith(sourceId, entryId, null); }, - /** Click an overlay entry with `hit` drawn under the same pixel. */ - clickOverlayWith(sourceId, entryId, hit) { - overlayHits.set(sourceId, { sourceId, entryId }); + /** Click another layer's card painted on top, with `hit` under it. */ + clickForeignCard(sourceId, entryId, hit) { + foreignTop = { sourceId, entryId }; this.click(hit); + foreignTop = null; + }, + /** Click an overlay entry with `hit` drawn under the same pixel. */ + clickOverlayWith(sourceId, entryId, hit, resolvedHit = hit) { + overlayHits.set(sourceId, { sourceId, entryId }); + this.click(hit, resolvedHit); overlayHits.delete(sourceId); }, lastCard: () => cards.at(-1), @@ -188,12 +205,15 @@ test('a quake with no USGS id gets a card with no link', async () => { h.layer.destroy(); }); -test("another layer's pick leaves the card; its own pick ids are claimed", async () => { +test("another layer's pick leaves the card; discs stay unowned, as area layers do", async () => { const h = harness([quake('ak1')]); h.layer.enable(h.viewer); await h.layer.update(h.viewer); - assert.equal(picking.findPickOwner('earthquake:ak1'), 'earthquakes'); - assert.equal(picking.findPickOwner('earthquake:gone'), null); + // Like drone airspace and fire perimeters, the discs are not registered: + // siblings read a disc as empty space, so their cards and deselection + // work over a quake (a fire card, a radio near-miss, a followed plane). + assert.equal(picking.findPickOwner('earthquake:ak1'), null); + assert.equal(picking.isOwnedByOtherLayer('firms', 'earthquake:ak1'), false); picking.registerPickOwner('test-other', (id) => id === 'plane-1'); try { h.clickDisc('ak1'); @@ -608,3 +628,84 @@ test("another layer's object over a magnitude label takes the click", async () = h.layer.destroy(); } }); + +test('a touch-expanded quake hit selects its disc without flying', async () => { + const h = harness([quake('ak1')]); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.click(null, { set: h.discs().spec.id, id: 'earthquake:ak1' }); + assert.equal(h.lastCard()?.[0]?.id, 'earthquake-card:ak1'); + assert.equal(h.focused.length, 0); + } finally { + h.layer.destroy(); + } +}); + +test('a touch-expanded sibling hit takes precedence over a quake label', async () => { + const h = harness([quake('ak1'), quake('ak2')]); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); + h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', null, { + set: 'flights:1', + id: 'plane-9', + }); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1'); + assert.equal(h.focused.length, 0); + } finally { + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + } +}); + +test("another layer's card over a quake disc takes the click, and the disc yields", async () => { + const h = harness([quake('ak1', { mag: 6 })]); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + // A fire's card painted over the disc: the disc is what the scene picks. + h.clickForeignCard('firms', 'fire:x', { + set: h.discs().spec.id, + id: 'earthquake:ak1', + }); + assert.equal(h.cards.length, 0, 'the quake is not selected'); + assert.equal(h.focused.length, 0); + // The same disc with nothing painted over it selects the quake. + h.clickDisc('ak1'); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1'); + } finally { + h.layer.destroy(); + } +}); + +test("another layer's object under the quake card takes the click", async () => { + const h = harness([quake('ak1')]); + picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const card = h.lastCard()[0]; + // The card is painted over a plane: the flight layer acts on the click, + // so the card neither opens its link nor changes. + overlayHitCard(h, card.id, { set: 'flights:1', id: 'plane-9' }); + assert.deepEqual(h.opened, []); + assert.equal(h.lastCard()[0].id, card.id, 'the card stays'); + // Over open ground the card opens the USGS page. + h.clickCard(card.id); + assert.deepEqual(h.opened, [ + 'https://earthquake.usgs.gov/earthquakes/eventpage/ak1', + ]); + } finally { + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + } +}); + +/** Click this layer's card with `hit` (another layer's object) under it. */ +function overlayHitCard(h, entryId, hit) { + h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, entryId, hit); +} From f6314884f7ebe03295d0a72f5f65555c042ffcfd Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Mon, 16 Nov 2026 21:13:32 +0530 Subject: [PATCH 007/138] fix(overlays): keep painted hit rectangles until the next paint Every overlay change cleared the world overlay's hit rectangles at once, and only the next paint rebuilt them. When one click subscriber published its selection card, every later subscriber in the same click saw no overlay at all, so the outcome of a click depended on listener order: a card or label painted over another layer's item could lose to that item, or both acted. Hit rectangles now stay what is painted on screen until the next paint rebuilds them, so every subscriber reads the overlay the user clicked, and a paint that draws nothing clears them. --- src/overlays/worldOverlay.js | 11 ++++++----- src/overlays/worldOverlay.test.mjs | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js index 39a3f626cc..bb0d2d33f1 100644 --- a/src/overlays/worldOverlay.js +++ b/src/overlays/worldOverlay.js @@ -884,7 +884,9 @@ function invalidateHost({ solve = true, layout = false } = {}) { if (layout) _occludersDirty = true; _canvasNeedsClear = true; _paintRectCount = 0; - _hitRectCount = 0; + // Hit rectangles stay what is painted on screen until the next paint + // rebuilds them: every click subscriber reads the same overlay, even after + // an earlier one republishes entries in that click (a selection card). _paintRectByKey.clear(); requestOverlayRender(); } @@ -2783,10 +2785,9 @@ function drawWorldOverlay() { resetFrameDiagnostics(); _solveDirty = false; if (_canvasNeedsClear || _detectionSurfaceNeedsClear) clearCanvas(); - if (_accessibilitySignature) { - _hitRectCount = 0; - syncAccessibleActions(); - } + // Nothing is painted now, so nothing can be hit. + _hitRectCount = 0; + if (_accessibilitySignature) syncAccessibleActions(); syncPaintVisibility(false); return; } diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs index 4b27e73aeb..d64d065978 100644 --- a/src/overlays/worldOverlay.test.mjs +++ b/src/overlays/worldOverlay.test.mjs @@ -1936,6 +1936,25 @@ test('paint rectangles publish from a pool and topmost interactive lookup wins', env.cleanup(); }); +test('hit rectangles stay what is painted until the next paint, through a republish in the same click', () => { + const env = installMockEnvironment(); + initWorldOverlay(env.viewer); + setOverlayEntries('cards', [selectedEntry('card', { interactive: true })]); + env.postRender.raise(); + assert.equal(hitTestWorldOverlay(200, 120)?.entryId, 'card'); + // An earlier click subscriber publishes its own selection card: later + // subscribers in the same click still see what the user clicked on. + setOverlayEntries('other', [selectedEntry('elsewhere', { interactive: true })]); + clearOverlaySource('cards'); + assert.equal(hitTestWorldOverlay(200, 120)?.entryId, 'card'); + assert.equal(hitTestWorldOverlay(200, 120, { sourceId: 'cards' })?.entryId, 'card'); + // The next paint shows the change, and the hit test follows it. + env.postRender.raise(); + assert.equal(hitTestWorldOverlay(200, 120, { sourceId: 'cards' }), null); + assert.equal(hitTestWorldOverlay(200, 120)?.entryId, 'elsewhere'); + env.cleanup(); +}); + test('CCTV stable frame slots gate ambient chrome and wire the exact host hit rectangle', () => { const env = installMockEnvironment({ width: 500, height: 400, dpr: 1 }); initWorldOverlay(env.viewer); From 959698cff94bc08530f6dc0b6f4aeea5a84a02a3 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Mon, 16 Nov 2026 21:13:42 +0530 Subject: [PATCH 008/138] fix(drone-airspace, perimeters): yield area clicks to cards painted on top Drone airspace and fire perimeters select a zone or incident from any shape hit, so a quake card or magnitude label painted over one made both layers act on a single click: the quake opened its USGS page or flew to the quake while the area was selected too. Fire and vessel cards over an area did the same. The areas now stand aside when another layer's card or label is the topmost overlay entry, the rule the quake handler already follows for cards painted over its discs. Deselection and every other path are unchanged. Items of layers that never act on clicks no longer matter: the quake card and labels keep working over air-quality stations, traffic lines and OSM places. --- docs/CURRENT-STATE.md | 12 +- src/layers/droneAirspace/index.js | 9 ++ src/layers/droneAirspace/ownership.test.mjs | 37 +++++ src/layers/earthquakes/selection.test.mjs | 169 ++++++++++++++++++++ src/layers/perimeters/index.js | 9 ++ src/layers/perimeters/ownership.test.mjs | 37 +++++ 6 files changed, 272 insertions(+), 1 deletion(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 07f2e8f891..f68d179b8b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1868,7 +1868,17 @@ like drone airspace and fire perimeters: sibling layers read a disc as empty space, so their cards, near-miss taps and deselection work over a quake as before. When another layer's card or label is painted over a disc (a fire card on a large quake), the quake handler yields to it rather than selecting the -quake beneath. +quake beneath. The same rule holds the other way: drone airspace and fire +perimeters do not select a zone or incident from a shape hit while another +layer's card or label is the topmost overlay entry, so a quake card or +magnitude label over one of them acts once, as the quake's. Items of layers +that never act on clicks (air-quality stations, traffic lines, OSM places) do +not block the quake card or labels. A bare area click with nothing painted on +top still selects the area and clears the quake selection. These rules hold in any +listener order because world-overlay hit rectangles are what is painted on +screen until the next paint: an overlay change (a click subscriber publishing +its selection card) no longer clears them mid-click, and a paint that draws +nothing clears them (`src/overlays/worldOverlay.js`). Air quality (`./layers/air-quality`) draws its station discs as one renderer draw set of ground-clamped fills and reads the view through the camera port; it diff --git a/src/layers/droneAirspace/index.js b/src/layers/droneAirspace/index.js index 8bb8b72423..2e64bafd37 100644 --- a/src/layers/droneAirspace/index.js +++ b/src/layers/droneAirspace/index.js @@ -139,6 +139,15 @@ export function createDroneAirspaceLayer({ const picked = event.topHit; const zoneId = picked ? pickedZoneId(event.drawHit) : null; if (zoneId) { + // Another layer's card or label painted over the zone (a quake's + // card or magnitude label, a fire card) is that layer's click: under + // it the zone is background, as it is to siblings, so it stays as is. + const top = overlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + {}, + ); + if (top && top.sourceId !== DRONE_AIRSPACE_OVERLAY_SOURCE_ID) return; _selectedId = zoneId; publishSelectedCard(); return; diff --git a/src/layers/droneAirspace/ownership.test.mjs b/src/layers/droneAirspace/ownership.test.mjs index 3dbb16a583..b6e4cbdcb2 100644 --- a/src/layers/droneAirspace/ownership.test.mjs +++ b/src/layers/droneAirspace/ownership.test.mjs @@ -143,6 +143,43 @@ test('clicking a zone publishes its card; empty space clears it', async () => { assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0); }); +// Another layer's card or label painted over the area (a quake's card or +// magnitude label) is that layer's click: the area under it stands aside. +test("another layer's overlay on top keeps a click off the area", async () => { + let pickResult = null; + let foreignOnTop = false; + const h = harness( + { getSnapshot: async () => [row] }, + { + pick: () => pickResult, + // Unfiltered: the topmost entry of any source. + cardHit: (_x, _y, options) => + foreignOnTop && !options?.sourceId + ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' } + : null, + }, + ); + await h.layer.update(h.viewer); + pickResult = zonePick('drone-airspace:310:0'); + foreignOnTop = true; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0); + // With nothing painted over it, the same click selects the area. + foreignOnTop = false; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal( + h.overlay.entries.get('drone-airspace')[0].id, + 'drone-airspace-card:310', + ); + // An overlay on top never clears an existing selection either. + foreignOnTop = true; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal( + h.overlay.entries.get('drone-airspace')[0].id, + 'drone-airspace-card:310', + ); +}); + test('late refresh cannot publish after disable or destroy', async () => { for (const action of ['disable', 'destroy']) { let resolve, signal; diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs index 4a5e70412a..ad8765b05d 100644 --- a/src/layers/earthquakes/selection.test.mjs +++ b/src/layers/earthquakes/selection.test.mjs @@ -2,6 +2,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import * as picking from '../../data/pickRegistry.js'; +import { fakeInput } from '../../input/testDoubles.mjs'; +import { createDroneAirspaceLayer } from '../droneAirspace/index.js'; import { EARTHQUAKE_CARD_SOURCE_ID, EARTHQUAKE_OVERLAY_SOURCE_ID, @@ -709,3 +711,170 @@ test("another layer's object under the quake card takes the click", async () => function overlayHitCard(h, entryId, hit) { h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, entryId, hit); } + +for (const kind of ['card', 'label']) { + for (const areaFirst of [false, true]) { + test(`quake ${kind} over an unowned area takes the click once (${areaFirst ? 'area' : 'quake'} handler first)`, async () => { + let sceneHit = null; + let painted = null; + const viewer = { + scene: { pick: () => (sceneHit ? { id: sceneHit } : null) }, + }; + const { draw, unbind } = bindFakeDraw(viewer); + const input = fakeInput(viewer); + const entries = new Map(); + const opened = []; + const focused = []; + // As the real host does, hits are what was last painted: a card a + // subscriber publishes during a click changes nothing for the others + // until the next paint, so the outcome cannot depend on their order. + let screen = new Map(); + const paint = () => { + screen = new Map(entries); + }; + const host = { + setEntries: (source, rows) => entries.set(source, rows), + setVisible() {}, + clearSource: (source) => entries.delete(source), + hitTest(_x, _y, { sourceId } = {}) { + if (!painted || (sourceId && sourceId !== painted.sourceId)) + return null; + const entry = screen + .get(painted.sourceId) + ?.find((e) => e.id === painted.entryId); + return entry?.interactive ? { ...painted, entry } : null; + }, + }; + const click = () => { + paint(); + input.click(); + }; + const q = createEarthquakesLayer({ + source: { getSnapshot: async () => [quake('ak1')] }, + overlayHost: host, + input: () => input.input, + picking, + openExternal: (url) => opened.push(url), + focus: { requestWorldFocus: (detail) => focused.push(detail) }, + }); + const area = createDroneAirspaceLayer({ + source: { + getSnapshot: async () => [ + { + stableId: '310', + name: 'Fixture area', + typeCode: 'P', + type: 'Prohibited', + lowerAltitude: 'SFC', + upperAltitude: '18000', + polygons: [ + [ + [ + [-153.4, 59.9], + [-153.2, 59.9], + [-153.2, 60.1], + [-153.4, 59.9], + ], + ], + ], + }, + ], + }, + overlayHost: host, + inputFor: () => input.input, + picking, + }); + const layers = areaFirst ? [area, q] : [q, area]; + try { + for (const layer of layers) { + layer.init(viewer); + layer.enable(viewer); + await layer.update(viewer); + } + const ownHit = { + set: draw.find('earthquakes:').spec.id, + id: 'earthquake:ak1', + }; + const areaSet = [...draw.sets.values()].find( + (set) => + set.spec.id.startsWith('drone-airspace:') && + set.spec.id.endsWith(':fills'), + ); + const areaHit = { set: areaSet.spec.id, id: 'drone-airspace:310:0' }; + assert.equal(picking.findPickOwner(areaHit.id), null); + sceneHit = ownHit; + click(); + assert.equal( + entries.get('earthquake-card')[0].id, + 'earthquake-card:ak1', + ); + assert.equal(entries.get('drone-airspace')?.length ?? 0, 0); + painted = { + sourceId: + kind === 'card' + ? EARTHQUAKE_CARD_SOURCE_ID + : EARTHQUAKE_OVERLAY_SOURCE_ID, + entryId: kind === 'card' ? 'earthquake-card:ak1' : 'ak1', + }; + sceneHit = areaHit; + click(); + // The quake's card or label painted on top takes the click; the + // zone under it is background and stands aside: one action. + assert.equal( + entries.get('drone-airspace')?.length ?? 0, + 0, + 'the area under the overlay is not selected', + ); + assert.equal( + entries.get('earthquake-card')[0].id, + 'earthquake-card:ak1', + 'the quake card stays', + ); + assert.equal(opened.length, kind === 'card' ? 1 : 0); + assert.equal(focused.length, kind === 'label' ? 1 : 0); + // The same painted action works over its own disc and over open ground. + for (const hit of [ownHit, null]) { + sceneHit = hit; + click(); + } + assert.equal(opened.length, kind === 'card' ? 3 : 0); + assert.equal(focused.length, kind === 'label' ? 3 : 0); + // With no overlay the area is selected and the quake deselects. + painted = null; + sceneHit = areaHit; + click(); + assert.equal(entries.get('drone-airspace')?.length, 1); + assert.equal(entries.get('earthquake-card')?.length ?? 0, 0); + } finally { + for (const layer of layers) layer.destroy(); + input.destroy(); + unbind(); + } + }); + } +} + +// Layers that never act on clicks still draw pickable items (air quality +// stations, traffic heat lines, OSM places). They are not a click target, so +// the quake card and labels painted over them keep working. +test('quake card and label work over pickable items no layer acts on', async () => { + const h = harness([quake('ak1'), quake('ak2', { mag: 4 })]); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const decorative = [ + { set: 'air-quality-markers:1', id: 'aq:station-1' }, + { set: 'traffic:1:heat', id: 'traffic:segment-9' }, + { set: 'osm-places:1:points', id: 'osm:node-3' }, + ]; + for (const hit of decorative) { + h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', hit); + } + assert.equal(h.opened.length, decorative.length, 'the card opens USGS'); + h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', decorative[1]); + assert.equal(h.focused.at(-1)?.id, 'earthquake:ak2', 'the label flies'); + } finally { + h.layer.destroy(); + } +}); diff --git a/src/layers/perimeters/index.js b/src/layers/perimeters/index.js index 3a5a180c48..017e7ab46c 100644 --- a/src/layers/perimeters/index.js +++ b/src/layers/perimeters/index.js @@ -230,6 +230,15 @@ export function createFirePerimetersLayer({ const picked = event.topHit; const incidentId = picked ? pickedIncidentId(event.drawHit) : null; if (incidentId) { + // Another layer's card or label painted over the perimeter (a + // quake's card or magnitude label, a fire card) is that layer's + // click: under it the perimeter is background, so it stays as is. + const top = overlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + {}, + ); + if (top && top.sourceId !== PERIMETER_OVERLAY_SOURCE_ID) return; abortLinkVerification(); _selectedId = incidentId; publishSelectedCard(); diff --git a/src/layers/perimeters/ownership.test.mjs b/src/layers/perimeters/ownership.test.mjs index 61cfde2bbf..9f11d5b177 100644 --- a/src/layers/perimeters/ownership.test.mjs +++ b/src/layers/perimeters/ownership.test.mjs @@ -243,6 +243,43 @@ test('clicking a perimeter publishes its incident card; empty space clears it', assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0); }); +// Another layer's card or label painted over the area (a quake's card or +// magnitude label) is that layer's click: the area under it stands aside. +test("another layer's overlay on top keeps a click off the area", async () => { + let pickResult = null; + let foreignOnTop = false; + const h = harness( + { getSnapshot: async () => [row] }, + { + pick: () => pickResult, + // Unfiltered: the topmost entry of any source. + cardHit: (_x, _y, options) => + foreignOnTop && !options?.sourceId + ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' } + : null, + }, + ); + await h.layer.update(h.viewer); + pickResult = perimeterPick('fire-perimeter:2026-NMGNF-000123:0'); + foreignOnTop = true; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0); + // With nothing painted over it, the same click selects the area. + foreignOnTop = false; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal( + h.overlay.entries.get('fire-perimeters')[0].id, + 'fire-perimeter-card:2026-NMGNF-000123', + ); + // An overlay on top never clears an existing selection either. + foreignOnTop = true; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal( + h.overlay.entries.get('fire-perimeters')[0].id, + 'fire-perimeter-card:2026-NMGNF-000123', + ); +}); + test('disable removes the click handler, pick ownership, and any card', async () => { const h = harness( { getSnapshot: async () => [row] }, From 836daf82b3797632b9beb66586dec27cb88cf16c Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Tue, 17 Nov 2026 01:32:47 +0530 Subject: [PATCH 009/138] fix(overlays): let only the topmost painted card act on a click Card handlers hit-tested only their own source, so a card buried under another layer's card still acted, and a click on a selected quake card over a vessel or fire card made both layers act. Vessels, FIRMS, wildlife, news, ghost maps and shipwrecks now read the unfiltered topmost painted entry: their own card acts only when it is on top, and a click on another layer's card is that layer's, so it neither acts here nor clears a selection. A top news or wildlife card still acts over another layer's scene item, so it never goes dead over a flight trail or a directions route; a registered marker under a foreign card is still its layer's to select. --- src/data/aisLiveVessels.test.mjs | 32 +++++++++- src/data/firmsInteraction.test.mjs | 45 +++++++++++++- src/layers/firms/selection.js | 4 +- src/layers/ghostMaps/index.js | 10 ++- src/layers/ghostMaps/lifecycle.test.mjs | 51 ++++++++++++++++ src/layers/news/index.js | 10 +-- src/layers/news/layer.test.mjs | 61 ++++++++++++++++++- src/layers/shipwrecks/index.js | 13 ++-- src/layers/shipwrecks/index.test.mjs | 46 +++++++++++++- src/layers/vessels/selection.js | 10 ++- .../wildlifeSightings/ownership.test.mjs | 5 +- src/layers/wildlifeSightings/selection.js | 17 ++---- .../wildlifeSightings/selection.test.mjs | 43 ++++++++++++- src/ui/wildlifeSightingCard.test.mjs | 6 +- 14 files changed, 310 insertions(+), 43 deletions(-) diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index 1b091ec4f7..b2ea95ceb1 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -1847,12 +1847,17 @@ test('vessel interaction wire: a vessel with an id and no MMSI is selected by cl * only publishes rects for `interactive` entries, so a stub returning a hit is * the same contract a painted, actionable card presents. */ -function hostWithCardHit(entryId) { +function hostWithCardHit(entryId, topHit) { return { setEntries() {}, setVisible() {}, clearSource() {}, - hitTest: () => (entryId ? { sourceId: 'ais-live-vessels', entryId } : null), + hitTest: (_x, _y, { sourceId } = {}) => + !sourceId && topHit + ? topHit + : entryId + ? { sourceId: 'ais-live-vessels', entryId } + : null, }; } @@ -1914,6 +1919,29 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact } }); +test('vessel interaction wire: a covered card yields while a real vessel pick still focuses', () => { + for (const ownPick of [false, true]) { + const harness = installWireHarness(ownPick ? { id: makeRecord().mmsi } : null); + const requests = []; + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(`vessel:${harness.record.mmsi}`, { + sourceId: 'earthquakes', entryId: 'quake:cover', + }), + ); + try { + harness.handler.click({ position: { x: 10, y: 20 } }); + assert.equal(requests.length, ownPick ? 1 : 0); + assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi); + } finally { + _setVesselOverlayHostForTest(null); + harness.cleanup(); + } + } +}); + test('vessel interaction wire: an unknown card id preserves selection and never flies', () => { const harness = installWireHarness({ primitive: {}, diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index ddd5f9b034..55413c1d85 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -58,6 +58,7 @@ function harness({ fires = [makeFire()], picked = null, cardHit = null, + topCard = null, cameraPosition = null, withDataSource = false, withGlobe = false, @@ -85,7 +86,12 @@ function harness({ setEntries: (sourceId, entries) => published.push(...entries), setVisible() {}, clearSource() {}, - hitTest: () => (cardHit ? { sourceId: 'firms', entryId: cardHit } : null), + hitTest: (_x, _y, { sourceId } = {}) => + !sourceId && topCard + ? topCard + : cardHit + ? { sourceId: 'firms', entryId: cardHit } + : null, }, }); @@ -153,6 +159,9 @@ function harness({ (record) => record.kind === 'icons' && !record.disposed, ), click: () => input.click({ x: 400, y: 300 }), + cover: (hit) => { + topCard = hit; + }, cleanup() { Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection; if (hadWindow) globalThis.window = priorWindow; @@ -308,7 +317,11 @@ test('far-side detections cannot consume the bounded ambient-card cohort', () => test('clicking a fire sprite selects it and requests the camera transfer', () => { const fire = makeFire(); - const h = harness({ fires: [fire], picked: glowPick('firms-7') }); + const h = harness({ + fires: [fire], + picked: glowPick('firms-7'), + topCard: { sourceId: 'earthquakes', entryId: 'quake:cover' }, + }); try { h.click(); assert.equal(h.requests.length, 1); @@ -355,6 +368,34 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => { } }); +test('a covered fire card does not act, and keeps an existing selection', () => { + const fire = makeFire(); + const h = harness({ + fires: [fire], + cardHit: `fire:${fireDetectionKey(fire)}`, + }); + try { + // Covered by another layer's card from the start: nothing selects or flies. + h.cover({ sourceId: 'earthquakes', entryId: 'quake:cover' }); + h.click(); + assert.equal(h.requests.length, 0); + assert.equal(h.layer.getSelectedInfo(), null); + // Uncovered, the card selects; covered again, the click is the other + // layer's and leaves that selection alone. + h.cover(null); + h.click(); + assert.equal(h.requests.length, 1); + const selected = h.layer.getSelectedInfo(); + assert.ok(selected); + h.cover({ sourceId: 'earthquakes', entryId: 'quake:cover' }); + h.click(); + assert.equal(h.requests.length, 1); + assert.deepEqual(h.layer.getSelectedInfo(), selected); + } finally { + h.cleanup(); + } +}); + // The voice model reads these labels as data (track_entity, get_entity_context, // pointer_context); the voice card translates them where it shows them. test('fire labels stay English data in a translated interface', () => { diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index db80cef722..edbae6734b 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -49,11 +49,9 @@ export function createSelection({ const cardHit = overlayHost.hitTest?.( event.screenPosition?.x, event.screenPosition?.y, - { - sourceId: FIRMS_OVERLAY_SOURCE_ID, - }, ); if (cardHit) { + if (cardHit.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return; const carded = layerState._fireByCardId.get(cardHit.entryId); if (carded) selectAndFocusFire(carded); return; diff --git a/src/layers/ghostMaps/index.js b/src/layers/ghostMaps/index.js index 9332622411..d2378de613 100644 --- a/src/layers/ghostMaps/index.js +++ b/src/layers/ghostMaps/index.js @@ -710,9 +710,11 @@ export function createGhostMapsLayer({ const cardHit = overlayHost.hitTest?.( event.screenPosition?.x, event.screenPosition?.y, - { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID }, ); - if (cardHit && cardHit.entryId === _selectedCardId) { + if ( + cardHit?.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID && + cardHit.entryId === _selectedCardId + ) { if (_selectedLink && openExternal) openExternal(_selectedLink); return; } @@ -729,6 +731,10 @@ export function createGhostMapsLayer({ if (pickId && picking.isOwnedByOtherLayer(GHOSTMAPS_LAYER_ID, pickId)) return; } + // A covered card must neither open its source nor clear the selection. + // A marker of ours under that card was already selected by the pick + // check before this one. + if (cardHit) return; if (_selectedKey) { clearSelection(); render(); diff --git a/src/layers/ghostMaps/lifecycle.test.mjs b/src/layers/ghostMaps/lifecycle.test.mjs index 7bba31645d..ea4f99bed7 100644 --- a/src/layers/ghostMaps/lifecycle.test.mjs +++ b/src/layers/ghostMaps/lifecycle.test.mjs @@ -642,3 +642,54 @@ test('narrowing to a window the loaded data covers clears a failed wider reload' assert.equal(layer.getStats().error, null); assert.equal(layer.getStats().count, 1); }); + +test('a covered selected card yields while genuine GhostMaps markers still select', async (t) => { + const cards = []; + const opened = []; + let painted = []; + const { layer, viewer, click } = fixture(t, { + reports: [ + { + name: 'First', + description: 'Source', + }, + { + name: 'Second', + description: 'Source', + }, + ], + controls: { + overlayHost: { + setEntries: (_id, entries) => cards.push(entries), + hitTest: (_x, _y, { sourceId } = {}) => + painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null, + }, + picking: { resolvePickId: (picked) => picked }, + openExternal: (url) => opened.push(url), + }, + }); + await layer.update(viewer); + click('ghostmaps:cip:0:0'); + const first = cards.at(-1)[0]; + const foreign = { + sourceId: 'earthquake-card', + entryId: 'earthquake-card:ak1', + }; + painted = [foreign, { sourceId: 's2-ghostmaps', entryId: first.id }]; + click(null); + assert.deepEqual(opened, []); + assert.equal(cards.at(-1)[0].id, first.id); + click('ghostmaps:cip:1:0'); + const second = cards.at(-1)[0]; + assert.notEqual( + second.id, + first.id, + 'an actual marker still selects beneath the foreign card', + ); + painted = [{ sourceId: 's2-ghostmaps', entryId: second.id }]; + click(null); + assert.deepEqual(opened, ['https://example.com/second']); + painted = []; + click(null); + assert.deepEqual(cards.at(-1), [], 'bare map still clears the selection'); +}); diff --git a/src/layers/news/index.js b/src/layers/news/index.js index 4ad5826c27..7e5e9a7eae 100644 --- a/src/layers/news/index.js +++ b/src/layers/news/index.js @@ -1348,10 +1348,10 @@ export function createNewsLayer({ clickOff = inputFor(viewer).onClick((event) => { const at = event?.screenPosition; if (!enabled || destroyed || !isPointerFree() || !at) return; - const card = hitTestOverlay(at.x, at.y, { - sourceId: NEWS_OVERLAY_SOURCE_ID, - }); - if (card?.entry?.activate) { + // The topmost painted entry decides: our own card acts; one covered by + // another layer's card does not. + const card = hitTestOverlay(at.x, at.y); + if (card?.sourceId === NEWS_OVERLAY_SOURCE_ID && card.entry?.activate) { card.entry.activate(); return; } @@ -1408,6 +1408,8 @@ export function createNewsLayer({ return; } if (id && isOwnedByOtherLayer(NEWS_LAYER_ID, id)) return; + // Another layer's card on top is that layer's click, not empty map. + if (card) return; if (selectedId && !picked?.id) layer.setParams({ clear: true }); }); } diff --git a/src/layers/news/layer.test.mjs b/src/layers/news/layer.test.mjs index 9804011d77..0070b6b773 100644 --- a/src/layers/news/layer.test.mjs +++ b/src/layers/news/layer.test.mjs @@ -5,6 +5,13 @@ import { fromDegrees } from '../../geo/ellipsoid.js'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; import { NEWS_KEY_PROVIDERS, createNewsLayer } from './index.js'; +import { + findPickOwner, + registerPickOwner, + unregisterPickOwner, +} from '../../data/pickRegistry.js'; +// Registers the shared `gev-trail:` no-op owner, as the app does. +import '../../data/trailRenderer.js'; import { getSelectedEntityContext } from '../../data/contextStore.js'; const NOW = Date.parse('2026-10-28T10:00:00Z'); @@ -51,6 +58,7 @@ function fixture( now = () => NOW, quality, pictureCards, + hitTestOverlay = () => null, } = {}, ) { const calls = { feed: [], hotspots: 0, outline: 0 }; @@ -141,7 +149,7 @@ function fixture( source, overlayHost, inputFor: () => input, - hitTestOverlay: () => null, + hitTestOverlay, now, matchMedia: () => ({ matches: reduced }), getViewCentre: () => centre(), @@ -1285,6 +1293,57 @@ test('a click on a marker selects its report, on a beacon chooses its hotspot, o assert.equal(clickHandlers.size, 0); }); +test('a covered news card yields; the top news card acts over a flight trail', async (t) => { + let hits = []; + const { layer, items, entries, click, flights } = fixture(t, { + height: 500_000, + hitTestOverlay: (_x, _y, { sourceId } = {}) => + hits.find((hit) => !sourceId || hit.sourceId === sourceId) || null, + }); + layer.enable(); + await layer.update(); + await flush(); + const marker = [...items('points'), ...items('icons')].find((item) => + String(item.id).startsWith('news:report:major~'), + ); + click({ set: 'news:1:points', id: marker.id, surface: false }); + const card = entries.flat().find((entry) => entry.activate); + assert.ok(card, 'an actionable news card was published'); + let activations = 0; + const activate = card.activate; + card.activate = () => { + activations++; + return activate(); + }; + hits = [ + { sourceId: 'earthquakes', entryId: 'quake:cover' }, + { sourceId: 'news', entry: card }, + ]; + const before = layer.getRowControls().feed; + const flightCount = flights.length; + click(null); + assert.equal(activations, 0, 'a covered news card does not activate'); + assert.equal(layer.getRowControls().feed.selected.id, 'major'); + assert.deepEqual(layer.getRowControls().feed.filters, before.filters); + assert.equal(flights.length, flightCount); + layer.setParams({ clear: true }); + click({ set: 'news:1:points', id: marker.id, surface: false }); + assert.equal(layer.getRowControls().feed.selected.id, 'major'); + hits.shift(); + click(null); + assert.equal(activations, 1, 'the unobscured news card acts once'); + // A flight trail is registered so every layer reads a click on it as a + // no-op (src/data/trailRenderer.js). Under the top news card it must not + // make the card dead. + assert.equal(findPickOwner('gev-trail:fl-a1b2c3:head'), 'trails'); + click({ + set: 'trail:1:lines', + id: 'gev-trail:fl-a1b2c3:head', + surface: false, + }); + assert.equal(activations, 2, 'the news card acts over a flight trail'); +}); + test('zoomed out, a hotspot is one beacon; off, nothing draws; destroyed, the sets go', async (t) => { const { layer, items } = fixture(t); assert.deepEqual(items('points'), []); diff --git a/src/layers/shipwrecks/index.js b/src/layers/shipwrecks/index.js index c2c2db2814..c8eff42cb7 100644 --- a/src/layers/shipwrecks/index.js +++ b/src/layers/shipwrecks/index.js @@ -278,10 +278,11 @@ export function createShipwrecksLayer({ _clickHandler = clicks.onClick((click) => { if (pointer && !pointer.isPointerFree()) return; const at = click.screenPosition; - const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { - sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID, - }); - if (cardHit && cardHit.entryId === _selectedCardId) { + const cardHit = overlayHost.hitTest?.(at?.x, at?.y); + if ( + cardHit?.sourceId === SHIPWRECKS_OVERLAY_SOURCE_ID && + cardHit.entryId === _selectedCardId + ) { if (_selectedLink) openExternal(_selectedLink); return; } @@ -299,6 +300,10 @@ export function createShipwrecksLayer({ } if (pickId && picking.isOwnedByOtherLayer(SHIPWRECKS_LAYER_ID, pickId)) return; + // A covered card must neither open its source nor clear the selection. + // A marker of ours under that card was already selected by the pick + // check before this one. + if (cardHit) return; if (_selectedId) { clearSelection(); render(); diff --git a/src/layers/shipwrecks/index.test.mjs b/src/layers/shipwrecks/index.test.mjs index 7d69f2b457..6209129caa 100644 --- a/src/layers/shipwrecks/index.test.mjs +++ b/src/layers/shipwrecks/index.test.mjs @@ -36,7 +36,7 @@ function deferred() { return { promise, resolve }; } -function harness({ snapshots, now = () => 1 } = {}) { +function harness({ snapshots, now = () => 1, cardHit = () => null } = {}) { const cards = []; const handlers = []; const opened = []; @@ -59,7 +59,7 @@ function harness({ snapshots, now = () => 1 } = {}) { overlayHost: { setEntries: (_source, entries) => cards.push(entries), setVisible() {}, - hitTest: () => null, + hitTest: cardHit, }, // The globe's clicks: one listener per click handler installed. input: () => ({ @@ -393,3 +393,45 @@ test('the page deadline subtracts the newest available source age from the limit ); assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults'); }); + +test('a covered selected card yields while genuine wreck markers still select', async () => { + let painted = []; + const h = harness({ + snapshots: [ + snapshot([ + wreck('a', { url: 'https://example.com/a' }), + wreck('b', { url: 'https://example.com/b' }), + ]), + ], + cardHit: (_x, _y, { sourceId } = {}) => + painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null, + }); + try { + h.layer.enable(); + await h.layer.update(); + const click = () => h.handlers[0].click({ screenPosition: { x: 1, y: 1 } }); + h.pick('a'); + click(); + const first = h.lastCard()[0]; + painted = [ + { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }, + { sourceId: 'shipwrecks', entryId: first.id }, + ]; + h.pick(null); + click(); + assert.deepEqual(h.opened, []); + assert.equal(h.lastCard()[0].id, first.id); + h.pick('b'); + click(); + assert.equal(h.lastCard()[0].id, 'shipwreck-card:b'); + painted = [{ sourceId: 'shipwrecks', entryId: 'shipwreck-card:b' }]; + h.pick(null); + click(); + assert.deepEqual(h.opened, ['https://example.com/b']); + painted = []; + click(); + assert.deepEqual(h.lastCard(), [], 'bare map still clears the selection'); + } finally { + h.layer.destroy(); + } +}); diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index 7f8ddab832..f236aebf7e 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -68,14 +68,12 @@ export function createSelection({ ? vesselState._vesselOverlayHost.hitTest?.( event.screenPosition?.x, event.screenPosition?.y, - { - ...(cycloneBackground - ? {} - : { sourceId: VESSEL_OVERLAY_SOURCE_ID }), - }, ) : null; - if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID) + if ( + (cardHit && cardHit.sourceId !== VESSEL_OVERLAY_SOURCE_ID) || + (cycloneBackground && !cardHit) + ) return; if (!record && cardHit) { const id = String(cardHit.entryId || '').startsWith('vessel:') diff --git a/src/layers/wildlifeSightings/ownership.test.mjs b/src/layers/wildlifeSightings/ownership.test.mjs index 057c805196..ebe4b75e58 100644 --- a/src/layers/wildlifeSightings/ownership.test.mjs +++ b/src/layers/wildlifeSightings/ownership.test.mjs @@ -196,8 +196,9 @@ function harness( }, setVisible: (id, value) => overlay.visible.set(id, value), clearSource: (id) => overlay.entries.delete(id), - hitTest: (_x, _y, { sourceId }) => - cardHit?.sourceId === sourceId ? cardHit : null, + // As the host does: unfiltered, the topmost entry. + hitTest: (_x, _y, { sourceId } = {}) => + !sourceId || cardHit?.sourceId === sourceId ? cardHit : null, }, input: () => ({ onClick(fn) { diff --git a/src/layers/wildlifeSightings/selection.js b/src/layers/wildlifeSightings/selection.js index dc0b7c126c..368497c539 100644 --- a/src/layers/wildlifeSightings/selection.js +++ b/src/layers/wildlifeSightings/selection.js @@ -483,17 +483,10 @@ export function createSelection({ state, services, parts }) { if (!state.enabled || services.pointer?.isPointerFree?.() === false) return; const at = click.screenPosition; - const hit = - overlay?.hitTest?.(at?.x, at?.y, { - sourceId: WILDLIFE_SELECTED_SOURCE_ID, - }) || - overlay?.hitTest?.(at?.x, at?.y, { - sourceId: WILDLIFE_OVERLAY_SOURCE_ID, - }) || - overlay?.hitTest?.(at?.x, at?.y, { - sourceId: WILDLIFE_LABEL_SOURCE_ID, - }); - if (hit) { + // The topmost painted entry decides: our own card or label acts; one + // covered by another layer's card does not. + const hit = overlay?.hitTest?.(at?.x, at?.y); + if (hit && sourceIds.includes(hit.sourceId)) { hit.entry?.activate?.(); return; } @@ -516,6 +509,8 @@ export function createSelection({ state, services, parts }) { services.picking?.isOwnedByOtherLayer?.('wildlife-sightings', id) ) return; + // Another layer's card on top is that layer's click, not empty map. + if (hit) return; clearAndRebuild(); }); } diff --git a/src/layers/wildlifeSightings/selection.test.mjs b/src/layers/wildlifeSightings/selection.test.mjs index bf623526bb..f7da089369 100644 --- a/src/layers/wildlifeSightings/selection.test.mjs +++ b/src/layers/wildlifeSightings/selection.test.mjs @@ -21,6 +21,7 @@ function fixture(sighting = row, extraServices = {}) { const seen = []; const painted = new Set(); let hit = null; + let coveringHit = null; let projections = 0; let click; const state = { @@ -49,8 +50,12 @@ function fixture(sighting = row, extraServices = {}) { setEntries: (id, value) => entries.set(id, value), clearSource: (id) => entries.delete(id), setVisible() {}, - hitTest: (_x, _y, { sourceId }) => - hit?.sourceId === sourceId ? hit : null, + hitTest: (_x, _y, { sourceId } = {}) => + sourceId + ? hit?.sourceId === sourceId + ? hit + : null + : coveringHit || hit, }, now: () => row.observedAt + 60_000, project: (_scene, anchor) => { @@ -94,6 +99,9 @@ function fixture(sighting = row, extraServices = {}) { ?.find((entry) => entry.id === entryId); hit = entry ? { sourceId, entryId, entry } : null; }, + cover(value) { + coveringHit = value; + }, paint(ids) { painted.clear(); for (const id of ids) painted.add(id); @@ -179,6 +187,37 @@ test('selected photo and name cards use the selected lane, select on click and n } }); +test('a covered sighting label yields; the top label acts over trails and other scene items', () => { + const f = fixture(row, { + // Registered owners, as the app has them: an aircraft, and the flight + // trails every layer reads as a no-op (src/data/trailRenderer.js). + picking: { + isOwnedByOtherLayer: (_layer, id) => + id === 'other:aircraft' || String(id).startsWith('gev-trail:'), + }, + }); + f.selection.install(); + f.selection.refreshAmbient(); + f.hit('wildlife-sightings-labels', 'wildlife-sightings-label:inat:123'); + f.click(null); + assert.equal(f.flights.length, 1); + f.cover({ sourceId: 'earthquakes', entryId: 'quake:cover' }); + f.click(null); + assert.equal(f.flights.length, 1); + assert.equal(f.state.selectedRow, row); + f.click(); + assert.equal(f.flights.length, 2, 'an actual sighting remains selectable'); + f.cover(null); + // The top label acts over a flight trail: never a dead click. + f.click('gev-trail:fl-a1b2c3:head'); + assert.equal(f.flights.length, 3, 'the label acts over a flight trail'); + // And over another layer's scene item, as on main. + f.click('other:aircraft'); + assert.equal(f.flights.length, 4, 'the top label acts'); + assert.equal(f.state.selectedRow, row); + f.selection.remove(); +}); + test('nearby duplicate display names yield to painted cards and higher-ranked labels using cached screens', () => { const low = { ...row, diff --git a/src/ui/wildlifeSightingCard.test.mjs b/src/ui/wildlifeSightingCard.test.mjs index 731897a6a2..96f9d06c33 100644 --- a/src/ui/wildlifeSightingCard.test.mjs +++ b/src/ui/wildlifeSightingCard.test.mjs @@ -128,8 +128,10 @@ function fixture( now: () => NOW, overlayHost: { setEntries: (id, entries) => overlays.set(id, entries), - hitTest: (_x, _y, { sourceId }) => - hit?.sourceId === sourceId ? hit : null, + // As the host does: unfiltered, the topmost entry; filtered, only + // an entry of that source. + hitTest: (_x, _y, { sourceId } = {}) => + hit && (!sourceId || hit.sourceId === sourceId) ? hit : null, }, input: () => ({ onClick(fn) { From 133d022b29b9a7b6cf8ca636a0bfcb22a1424906 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Tue, 17 Nov 2026 01:33:06 +0530 Subject: [PATCH 010/138] fix(picking): arbitrate card clicks over passive and background shapes Flight trails register their ids so every layer reads a trail click as a no-op, and the directions route claims its line and markers though it acts only on its maneuver steps. The quake card and magnitude labels yielded to any registered owner, so over a trail or a route they did nothing. Pick owners can now name the picks they never act on (registerPickOwner(..., { passive })); isActedOnByOtherLayer leaves those out while isOwnedByOtherLayer is unchanged, so they are still not empty space. Submarine cables and rocket launches acted on any scene pick, so a card or label over a cable or a launch marker made both layers act. Both now stand aside when a world-overlay entry is under the click, as drone airspace and fire perimeters do through the top-entry check. Each of these layers, and the quake discs, registers its shapes with registerCardBackground. CCTV asks isCardBackground instead of matching other layers' set and id formats, so a live top CCTV card acts once over any of them, while unknown identified objects and registered owners still block it. --- docs/CURRENT-STATE.md | 26 +++- scripts/format-scope.json | 2 + src/app/layers/rocketLaunches.js | 3 +- src/app/layers/submarineCables.js | 6 +- src/data/cctv.test.mjs | 11 +- src/data/directions.test.mjs | 41 ++++++ src/data/pickRegistry.js | 87 +++++++++++- src/data/pickRegistry.test.mjs | 109 +++++++++++++-- src/data/trailRenderer.js | 8 +- src/layers/cctv/lifecycle.js | 48 ++++--- src/layers/cctv/lifecycle.test.mjs | 131 ++++++++++++++++++ src/layers/directions/index.js | 3 + src/layers/droneAirspace/index.js | 22 +-- src/layers/droneAirspace/ownership.test.mjs | 34 ++++- src/layers/earthquakes/index.js | 33 ++++- src/layers/earthquakes/selection.test.mjs | 55 +++++++- src/layers/launches/clickYield.test.mjs | 77 ++++++++++ src/layers/launches/lifecycle.js | 24 ++++ src/layers/perimeters/index.js | 21 +-- src/layers/perimeters/ownership.test.mjs | 41 +++++- src/layers/submarineCables/index.js | 3 + src/layers/submarineCables/interaction.js | 29 +++- .../submarineCables/interaction.test.mjs | 89 ++++++++++++ 23 files changed, 825 insertions(+), 78 deletions(-) create mode 100644 src/layers/launches/clickYield.test.mjs create mode 100644 src/layers/submarineCables/interaction.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f68d179b8b..fff1716a8f 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1874,11 +1874,33 @@ layer's card or label is the topmost overlay entry, so a quake card or magnitude label over one of them acts once, as the quake's. Items of layers that never act on clicks (air-quality stations, traffic lines, OSM places) do not block the quake card or labels. A bare area click with nothing painted on -top still selects the area and clears the quake selection. These rules hold in any -listener order because world-overlay hit rectangles are what is painted on +top still selects the area and clears the quake selection. These rules hold in +any listener order because world-overlay hit rectangles are what is painted on screen until the next paint: an overlay change (a click subscriber publishing its selection card) no longer clears them mid-click, and a paint that draws nothing clears them (`src/overlays/worldOverlay.js`). +Card consumers resolve the unfiltered top painted entry before acting, so a +covered vessel, fire, wildlife, news, CCTV, perimeter, ghost-map or shipwreck +card does not act alongside the card above it; drone-airspace shapes use the +same top-entry check (their cards are not interactive). A top news or wildlife +card still acts over another layer's scene item, as before, so a card over a +flight trail (registered as a no-op for every layer) or a directions route is +never a dead click. A click on another layer's card does not activate a covered +card of these layers or clear their selection; a marker of theirs under that +card is still theirs to select. Flight trails and the directions route line and +markers are passive pick owners (`registerPickOwner(…, { passive })`): still +not empty space (`isOwnedByOtherLayer`), but `isActedOnByOtherLayer` leaves +them out, so the quake card and magnitude labels act over them. Directions +selects only its maneuver steps, though any other click still clears a selected +step. Fire, vessel and CCTV cards over a trail or the route stay as they were +(no action). Submarine cables and rocket launches, whose own overlays are not +interactive, stand aside when any overlay entry is under the click, so a card +or label over a cable or a launch marker acts once. Layers whose shapes stand +aside like this (drone airspace, fire perimeters, quake discs, cables, +launches) register them with `registerCardBackground`, and a live top CCTV card +acts over any shape `isCardBackground` names; unknown identified objects and +registered foreign owners still block it. An empty-map click keeps its existing +deselection behavior. Air quality (`./layers/air-quality`) draws its station discs as one renderer draw set of ground-clamped fills and reads the view through the camera port; it diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 1069652db2..e41531fc57 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -435,6 +435,8 @@ "src/layers/earthquakes/source.js", "src/layers/earthquakes/ownership.test.mjs", "src/layers/earthquakes/selection.test.mjs", + "src/layers/submarineCables/interaction.test.mjs", + "src/layers/launches/clickYield.test.mjs", "src/app/layers/earthquakeRipples.js", "src/app/layers/earthquakeRipples.test.mjs", "src/layers/perimeters/index.js", diff --git a/src/app/layers/rocketLaunches.js b/src/app/layers/rocketLaunches.js index af60bd3b62..44ed64ead6 100644 --- a/src/app/layers/rocketLaunches.js +++ b/src/app/layers/rocketLaunches.js @@ -2,11 +2,12 @@ import { createRocketLaunchesLayer } from '../../layers/launches/index.js'; import * as geometry from '../../celestialRing.js'; import * as overlays from '../../overlays/worldOverlay.js'; import * as render from '../../renderGovernor.js'; +import * as picking from '../../data/pickRegistry.js'; /** Construct one layer using the application scene owners and a supplied source. */ export function createApplicationLaunches({ source, satellites }) { return createRocketLaunchesLayer({ source, - services: { satellites, geometry, overlays, render }, + services: { satellites, geometry, overlays, render, picking }, }); } diff --git a/src/app/layers/submarineCables.js b/src/app/layers/submarineCables.js index 1f6dd7d817..5b19b8cf10 100644 --- a/src/app/layers/submarineCables.js +++ b/src/app/layers/submarineCables.js @@ -1,9 +1,13 @@ import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js'; import { overlayHost } from './overlayHost.js'; +import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js'; +import * as picking from '../../data/pickRegistry.js'; /** Wire cable source geometry to the application overlay host. */ export function createApplicationCables(options) { return createSubmarineCableLayer({ - overlayHost, + // Hit-testing lets a card painted over a cable keep its click. + overlayHost: { ...overlayHost, hitTest: hitTestWorldOverlay }, + picking, mapStackEventTarget: typeof window !== 'undefined' ? window : null, ...options, }); diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index 35a634c6cf..4fb15c6903 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -1022,10 +1022,6 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat componentFunctionSource(cctvLayer.init), /_cctvOverlayHost\.hitTest/, ); - assert.match( - componentFunctionSource(cctvLayer.init), - /sourceId: CCTV_OVERLAY_SOURCE_ID/, - ); assert.match( componentFunctionSource(cctvLayer.init), /activateCctvCameraFromWorldClick\(cameraId, setActiveCamera\)/, @@ -1157,11 +1153,8 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and ); const initSource = componentFunctionSource(cctvLayer.init); - assert.ok( - initSource.indexOf('if (pickedId !== null) return') < - initSource.indexOf('_cctvOverlayHost.hitTest'), - 'every identified sibling must win before an overlapping CCTV card hit test', - ); + // The real init-bound click route, including identified-object barriers, + // is exercised in layers/cctv/lifecycle.test.mjs. assert.match(initSource, /activeCameraId: _activeCameraId/); assert.match(initSource, /calibrationMode: _calibrationMode/); }); diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs index ddd144e81f..6657c0a27e 100644 --- a/src/data/directions.test.mjs +++ b/src/data/directions.test.mjs @@ -28,6 +28,8 @@ import { createApplicationDirectionsLayer, } from './directions.js'; import { GROUND_FLOOR_LIFT_M } from './groundFloor.js'; +import { isActedOnByOtherLayer, isOwnedByOtherLayer } from './pickRegistry.js'; +import { fakeInput } from '../input/testDoubles.mjs'; import { instructionFor } from './routeSteps.js'; import { setLocale } from '../i18n/index.js'; import { @@ -465,6 +467,45 @@ function ownershipFixture(t) { }); } +// Directions acts only on its maneuver steps. The route line and the A/B +// markers are passive picks: still not empty space to other layers, but a +// card painted over them (a quake card) keeps its click. +test('enabled, directions owns its picks and acts only on its steps', (t) => { + ownershipFixture(t); + const viewer = { + scene: { + pick: () => null, + canvas: { clientWidth: 100, clientHeight: 100 }, + }, + }; + const input = fakeInput(viewer); + t.after(() => input.destroy()); + directionsLayer.enable(viewer); + try { + for (const id of [ + 'directions:route', + 'directions:marker:a', + 'directions:step:3', + ]) + assert.equal(isOwnedByOtherLayer('earthquakes', id), true, id); + assert.equal( + isActedOnByOtherLayer('earthquakes', 'directions:route'), + false, + ); + assert.equal( + isActedOnByOtherLayer('earthquakes', 'directions:marker:a'), + false, + ); + assert.equal( + isActedOnByOtherLayer('earthquakes', 'directions:step:3'), + true, + ); + } finally { + directionsLayer.disable(viewer); + } + assert.equal(isOwnedByOtherLayer('earthquakes', 'directions:route'), false); +}); + test('placing an endpoint takes the pointer, and every exit path gives it back', (t) => { ownershipFixture(t); diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js index 95243c02ee..e6807e1e7c 100644 --- a/src/data/pickRegistry.js +++ b/src/data/pickRegistry.js @@ -26,6 +26,19 @@ const isSurface = (hit) => !hit || hit.surface === true; /** @type {Map boolean>} layerId -> ownership predicate */ const _owners = new Map(); +/** + * Owners that claim picks but never act on a click on them (flight trails, a + * directions route line): `true` for all of an owner's picks, or a predicate + * naming which. Their picks are still not empty space to other layers. + * @type {Map boolean)>} + */ +const _passive = new Map(); +/** + * Layers whose shapes are background to any card painted over them: their + * click handlers stand aside under a card, so the card's layer may act there. + * @type {Map boolean>} + */ +const _cardBackgrounds = new Map(); /** * A hit's canonical pick id, for the ownership scan: its item's id. Layers' @@ -47,11 +60,17 @@ export function resolvePickId(hit) { * @param {string} layerId - Owning layer id (e.g. 'flights'). * @param {(pickedId: string) => boolean} predicate - Returns true when the * picked primitive/entity id belongs to this layer. + * @param {{passive?: boolean | ((pickedId: string) => boolean)}} [options] + * `passive`: the layer never acts on a click on these picks (all of them, + * or those the predicate names). See {@link isActedOnByOtherLayer}. * @returns {void} */ -export function registerPickOwner(layerId, predicate) { +export function registerPickOwner(layerId, predicate, { passive } = {}) { if (!layerId || typeof predicate !== 'function') return; _owners.set(layerId, predicate); + if (passive === true || typeof passive === 'function') + _passive.set(layerId, passive); + else _passive.delete(layerId); } /** @@ -61,6 +80,7 @@ export function registerPickOwner(layerId, predicate) { */ export function unregisterPickOwner(layerId) { _owners.delete(layerId); + _passive.delete(layerId); } /** @@ -99,6 +119,31 @@ export function isOwnedByOtherLayer(layerId, pickedId) { return false; } +/** + * True when some OTHER registered layer owns the picked id and acts on a + * click on it: {@link isOwnedByOtherLayer} without passive owners. A card + * painted over a passive pick (a flight trail) is still the card's click. + * @param {string} layerId - The asking layer's id (excluded from the scan). + * @param {string} pickedId - Picked primitive/entity id. + * @returns {boolean} + */ +export function isActedOnByOtherLayer(layerId, pickedId) { + if (!pickedId) return false; + for (const [ownerId, predicate] of _owners) { + if (ownerId === layerId) continue; + try { + if (!predicate(pickedId)) continue; + const passive = _passive.get(ownerId); + if (passive === true) continue; + if (typeof passive === 'function' && passive(pickedId)) continue; + return true; + } catch { + // a broken predicate must never break click handling + } + } + return false; +} + /** * Resolve a moving-contact click without letting map tiles hide a nearby touch * target. Exact picks always win; only a coarse primary pointer may expand a @@ -145,3 +190,43 @@ export function pickContact(query, position, options = {}) { } return picked; } + +/** + * Registers a layer's unowned shapes that stand aside for a card painted over + * them (its click handler returns when a world-overlay entry is on top). + * @param {string} layerId - Registering layer id. + * @param {(hit: import('../render/contract/query').Hit) => boolean} predicate + * True when a click's draw hit is one of this layer's shapes. + * @returns {void} + */ +export function registerCardBackground(layerId, predicate) { + if (!layerId || typeof predicate !== 'function') return; + _cardBackgrounds.set(layerId, predicate); +} + +/** + * Removes a layer's card-background predicate (call when its clicks stop). + * @param {string} layerId - Registering layer id. + * @returns {void} + */ +export function unregisterCardBackground(layerId) { + _cardBackgrounds.delete(layerId); +} + +/** + * True when a click's draw hit is a shape whose layer stands aside for a card + * painted over it, so that card may act on the click. + * @param {import('../render/contract/query').Hit|null|undefined} hit + * @returns {boolean} + */ +export function isCardBackground(hit) { + if (isSurface(hit)) return false; + for (const predicate of _cardBackgrounds.values()) { + try { + if (predicate(hit)) return true; + } catch { + // a broken predicate must never break click handling + } + } + return false; +} diff --git a/src/data/pickRegistry.test.mjs b/src/data/pickRegistry.test.mjs index 924c956692..bcc1876f07 100644 --- a/src/data/pickRegistry.test.mjs +++ b/src/data/pickRegistry.test.mjs @@ -15,8 +15,13 @@ import { registerPickOwner, unregisterPickOwner, isOwnedByOtherLayer, + isActedOnByOtherLayer, resolvePickId, pickContact, + findPickOwner, + registerCardBackground, + unregisterCardBackground, + isCardBackground, } from './pickRegistry.js'; // --------------------------------------------------------------------------- @@ -49,8 +54,11 @@ test('resolvePickId: the map and nothing → null', () => { // --------------------------------------------------------------------------- test('ownership: sibling layers recognize each other via String-coerced ids', () => { - const points = new Map([[25544, {}], [43013, {}]]); // satellites: numeric keys - const vessels = new Map([['367123450', {}]]); // AIS: string id keys + const points = new Map([ + [25544, {}], + [43013, {}], + ]); // satellites: numeric keys + const vessels = new Map([['367123450', {}]]); // AIS: string id keys registerPickOwner('satellites', (pickedId) => { const norad = Number(pickedId); return Number.isFinite(norad) && points.has(norad); @@ -58,9 +66,15 @@ test('ownership: sibling layers recognize each other via String-coerced ids', () registerPickOwner('ais-live-vessels', (pickedId) => vessels.has(pickedId)); try { // Flights asking about a satellite pick (raw numeric id → String upstream) - assert.equal(isOwnedByOtherLayer('flights', resolvePickId(item('sat:1', '25544'))), true); + assert.equal( + isOwnedByOtherLayer('flights', resolvePickId(item('sat:1', '25544'))), + true, + ); // Flights asking about a vessel pick (an icon row id: the vessel's id) - assert.equal(isOwnedByOtherLayer('flights', resolvePickId(item('ais:1', '367123450'))), true); + assert.equal( + isOwnedByOtherLayer('flights', resolvePickId(item('ais:1', '367123450'))), + true, + ); // A layer never owns its own pick via the sibling scan assert.equal(isOwnedByOtherLayer('satellites', '25544'), false); // Unknown ids belong to nobody @@ -73,7 +87,9 @@ test('ownership: sibling layers recognize each other via String-coerced ids', () }); test('ownership: a throwing predicate never breaks click handling', () => { - registerPickOwner('broken', () => { throw new Error('boom'); }); + registerPickOwner('broken', () => { + throw new Error('boom'); + }); registerPickOwner('cctv', (pickedId) => pickedId === 'atx-cam-3'); try { assert.equal(isOwnedByOtherLayer('flights', 'atx-cam-3'), true); @@ -121,6 +137,49 @@ function query(picked, drillPick = () => assert.fail('must not drill')) { }; } +test('ownership: passive owners still own their picks but act on none of them', () => { + registerPickOwner('test-trails', (id) => id.startsWith('trail:'), { + passive: true, + }); + registerPickOwner('test-route', (id) => id.startsWith('route:'), { + passive: (id) => !id.startsWith('route:step:'), + }); + registerPickOwner('test-plane', (id) => id === 'plane:1'); + registerPickOwner('test-broken', () => { + throw new Error('broken'); + }); + try { + assert.equal( + isOwnedByOtherLayer('cards', 'trail:9'), + true, + 'not empty space', + ); + assert.equal(isActedOnByOtherLayer('cards', 'trail:9'), false); + assert.equal(isActedOnByOtherLayer('cards', 'route:line'), false); + assert.equal(isActedOnByOtherLayer('cards', 'route:step:3'), true); + assert.equal(isActedOnByOtherLayer('cards', 'plane:1'), true); + assert.equal( + isActedOnByOtherLayer('test-plane', 'plane:1'), + false, + 'never the asker', + ); + assert.equal(isActedOnByOtherLayer('cards', null), false); + // Registering again without the option makes the owner act. + registerPickOwner('test-trails', (id) => id.startsWith('trail:')); + assert.equal(isActedOnByOtherLayer('cards', 'trail:9'), true); + // Unregistering drops the option with the predicate. + registerPickOwner('test-trails', (id) => id.startsWith('trail:'), { + passive: true, + }); + unregisterPickOwner('test-trails'); + registerPickOwner('test-trails', (id) => id.startsWith('trail:')); + assert.equal(isActedOnByOtherLayer('cards', 'trail:9'), true); + } finally { + for (const id of ['test-trails', 'test-route', 'test-plane', 'test-broken']) + unregisterPickOwner(id); + } +}); + test('touch contact pick expands only a surface miss, bounded to 8 hits in 14 CSS pixels', (t) => { primaryPointer(t, true); contactOwners(t); @@ -141,10 +200,14 @@ test("touch contact pick uses the click's own pick and drill", (t) => { contactOwners(t); const contact = item('flights:1', 'civil'); const asked = []; - const found = pickContact(query(null), { x: 1, y: 1 }, { - picked: null, - drill: (...args) => (asked.push(args), [contact]), - }); + const found = pickContact( + query(null), + { x: 1, y: 1 }, + { + picked: null, + drill: (...args) => (asked.push(args), [contact]), + }, + ); assert.equal(found, contact); assert.deepEqual(asked, [[8, 14, 14]]); }); @@ -177,7 +240,13 @@ test('touch expansion stops at an unowned item and respects the drill bound', (t [...Array(8).fill(item('notes:1', 'x')), item('flights:1', 'civil')], [], ]) - assert.equal(pickContact(query(SURFACE, () => hits), { x: 1, y: 1 }), SURFACE); + assert.equal( + pickContact( + query(SURFACE, () => hits), + { x: 1, y: 1 }, + ), + SURFACE, + ); }); test('fine primary pointers keep the exact mouse pick without a drill', (t) => { @@ -197,3 +266,23 @@ test('touch picking tolerates a failing drill and preserves empty sky', (t) => { ]) assert.equal(pickContact(query(null, drillPick), { x: 1, y: 1 }), null); }); + +test('card backgrounds: a registered shape, never the map, and safe to break', () => { + const shape = { set: 'zones:1:fills', id: 'zone:1', surface: false }; + assert.equal(isCardBackground(shape), false); + registerCardBackground('test-zones', (hit) => hit.set === shape.set); + registerCardBackground('test-broken', () => { + throw new Error('broken predicate'); + }); + try { + assert.equal(isCardBackground(shape), true); + assert.equal(isCardBackground({ ...shape, set: 'other:1' }), false); + assert.equal(isCardBackground({ surface: true }), false); + assert.equal(isCardBackground(null), false); + assert.equal(findPickOwner(shape.id), null, 'not an owner'); + } finally { + unregisterCardBackground('test-zones'); + unregisterCardBackground('test-broken'); + } + assert.equal(isCardBackground(shape), false); +}); diff --git a/src/data/trailRenderer.js b/src/data/trailRenderer.js index 06c8581318..1c8f6dc598 100644 --- a/src/data/trailRenderer.js +++ b/src/data/trailRenderer.js @@ -36,8 +36,12 @@ import { registerPickOwner } from './pickRegistry.js'; // plane being tracked. Claiming the 'gev-trail:' id namespace makes // isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op // everywhere. Registered once at module load; the predicate is pure. -registerPickOwner('trails', (pickedId) => - String(pickedId).startsWith('gev-trail:'), +// Passive: no layer acts on a trail click, so a card painted over a trail +// still takes its click (isActedOnByOtherLayer). +registerPickOwner( + 'trails', + (pickedId) => String(pickedId).startsWith('gev-trail:'), + { passive: true }, ); /** @type {number} Uniquifier for trail set and line ids. */ diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 233a2b38e7..fec21a0549 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -23,8 +23,13 @@ export function createLifecycle({ source, }) { const { activateCctvCameraFromWorldClick } = services.activation; - const { resolvePickId, registerPickOwner, unregisterPickOwner } = - services.picking; + const { + resolvePickId, + registerPickOwner, + unregisterPickOwner, + isOwnedByOtherLayer, + isCardBackground, + } = services.picking; const { onFocusTargetAppear } = services.focus; const { releaseContinuousRender } = services.render; @@ -401,23 +406,32 @@ export function createLifecycle({ ); return; } - // Any identified scene object owns this click even if its layer does not - // register a shared pick predicate. This keeps selectable siblings ahead - // of an overlapping CCTV card while ID-less globe/terrain/tile surfaces - // remain eligible for true empty-space deselection. - const pickedId = resolvePickId(picked); - if (pickedId !== null) return; - // Item A (owner round 2): the scene pick found no camera — try the - // painted ambient cards. The cards canvas is pointer-events:none (this - // handler owns the events), so a click landing on a card's rect selects - // its camera exactly like a click on the icon. Click positions - // and the recorded rects are both CSS px — direct comparison. - const cardId = layerState._cctvOverlayHost.hitTest( + // Cards use the last-painted top hit, never an obscured card from + // our own source. Actual camera icons above keep their normal route. + const cardHit = layerState._cctvOverlayHost.hitTest( event.screenPosition.x, event.screenPosition.y, - { sourceId: CCTV_OVERLAY_SOURCE_ID }, - )?.entryId; - if (cardId && layerState._recordById.has(cardId)) { + {}, + ); + const cardId = + cardHit?.sourceId === CCTV_OVERLAY_SOURCE_ID && + layerState._recordById.has(cardHit.entryId) + ? cardHit.entryId + : null; + const pickedId = resolvePickId(picked); + const hit = event.drawHit; + // A live top CCTV card acts over shapes whose layers stand aside + // for a painted card (drone zones, fire perimeters, quake discs, + // cables, launch markers), as each registers them. Unknown + // identified objects and registered owners remain barriers. + const cardBackground = + cardId && + typeof pickedId === 'string' && + !isOwnedByOtherLayer?.('cctv', pickedId) && + Boolean(isCardBackground?.(hit)); + if (pickedId !== null && !cardBackground) return; + if (cardHit && cardHit.sourceId !== CCTV_OVERLAY_SOURCE_ID) return; + if (cardId) { activateCctvCameraFromWorldClick( cardId, parts.selection.setActiveCamera, diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index 205997721b..c1ffdb4da8 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -1,6 +1,10 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createLifecycle } from './lifecycle.js'; +import { createSelection } from './selection.js'; +import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; +import { fakeInput } from '../../input/testDoubles.mjs'; +import * as picking from '../../data/pickRegistry.js'; import { bindRenderer } from '../../render/rendererOf.js'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; @@ -72,3 +76,130 @@ test('the view listeners follow the camera port and let go on teardown', () => { assert.deepEqual(counts(second.camera), [0, 0]); assert.equal(state._viewListenerCamera, null); }); + +test('world clicks respect the painted top card and registered card backgrounds', async (t) => { + const noop = () => {}; + const { viewer } = viewerWithCamera(); + let picked = null; + viewer.scene = { + canvas: {}, + pick: () => (picked ? { id: picked } : undefined), + }; + const input = fakeInput(viewer); + const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }; + const foreignCard = { + sourceId: 'earthquake-card', + entryId: 'earthquake-card:qa', + }; + let painted = []; + const actions = []; + const state = { + _cctvOverlayHost: { + hitTest: (_x, _y, options = {}) => + painted.find( + (hit) => !options.sourceId || hit.sourceId === options.sourceId, + ) ?? null, + }, + }; + const parts = { + calibration: { loadCalibrationStore: () => new Map() }, + catalog: { + loadCameraSources: async () => [], + buildCatalogFromSources: () => [], + seedCatalog: () => [], + }, + ground: { + resolveGroundPriors: async () => [], + currentSurfaceRegime: () => 'terrain-globe', + }, + cards: { teardownAmbientCards: noop }, + projection: { clearProjectionOverlay: noop }, + geometryQueue: { stopGeometryLoadQueue: noop }, + rendering: { + createCameraIcons: noop, + refreshHorizonCulling: () => false, + refreshCoverageStyles: noop, + extractPickedCameraId: (hit) => + hit?.set === 'cctv:fixture' ? hit.id : null, + }, + hover: { handleHoverMove: noop }, + health: { syncHealthState: async () => {} }, + presentation: { notifyListeners: noop }, + }; + const services = { + sprites: {}, + focus: {}, + render: {}, + picking, + activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) }, + }; + parts.selection = createSelection({ state, services, parts }); + parts.selection.deactivateActiveCamera = () => actions.push('clear'); + const lifecycle = createLifecycle({ state, services, parts }); + t.after(() => { + state._clickSubscription?.(); + lifecycle.detachViewListeners(); + input.destroy(); + picking.unregisterPickOwner('area-control'); + picking.unregisterCardBackground('area-fixture'); + }); + await lifecycle.methods.init(viewer); + state._enabled = true; + state._activeCameraId = 'cam-1'; + state._recordById.set('cam-1', { camera: { id: 'cam-1' } }); + const click = (hit, cards, expected) => { + picked = hit; + painted = cards; + actions.length = 0; + input.tap(); + assert.deepEqual(actions, expected, JSON.stringify({ hit, cards })); + }; + const drone = { + set: 'drone-airspace:1:fills', + id: 'drone-airspace:zone:0', + surface: false, + }; + const perimeter = { + set: 'fire-perimeters:1:lines', + id: 'fire-perimeter:incident:0', + surface: false, + }; + const quake = { set: 'earthquakes:1', id: 'earthquake:q1', surface: false }; + const cable = { set: 'submarine-cables:1:lines', id: 'c:0', surface: false }; + const launch = { + set: 'launches:1:markers', + id: 'rocket-x:1', + surface: false, + }; + const backgrounds = [drone, perimeter, quake, cable, launch]; + // Each of those layers registers its own shapes this way (their tests + // check the real predicates); CCTV only asks the registry. + picking.registerCardBackground('area-fixture', (hit) => + backgrounds.some((b) => b.set === hit.set && b.id === hit.id), + ); + for (const area of backgrounds) { + click(area, [ownCard], ['cam-1']); + click(area, [], []); + click(area, [foreignCard, ownCard], []); + } + for (const hit of [ + { set: 'flights:1', id: 'aircraft', surface: false }, + { set: '', id: 'unregistered-local-entity', surface: false }, + { set: '', id: '', surface: false }, + { ...drone, set: 'unrelated:1:fills' }, + { ...drone, id: 'unregistered-local-entity' }, + ]) + click(hit, [ownCard], []); + picking.registerPickOwner('area-control', (id) => id === drone.id); + click(drone, [ownCard], []); + picking.unregisterPickOwner('area-control'); + click(null, [foreignCard, ownCard], []); + click(null, [ownCard], ['cam-1']); + click(null, [], ['clear']); + click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []); + click( + { set: 'cctv:fixture', id: 'cam-1' }, + [foreignCard, ownCard], + ['cam-1'], + ); +}); diff --git a/src/layers/directions/index.js b/src/layers/directions/index.js index 54ec30c095..873eac5041 100644 --- a/src/layers/directions/index.js +++ b/src/layers/directions/index.js @@ -1672,10 +1672,13 @@ export function createDirectionsLayer({ services, source }) { _overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, true); _overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, true); _installClickHandler(viewer); + // Only the maneuver steps act on a click; the route line and the A/B + // markers are passive, so a card painted over them keeps its click. services.picking.registerPickOwner( 'directions', (pickedId) => typeof pickedId === 'string' && pickedId.startsWith('directions:'), + { passive: (pickedId) => !pickedId.startsWith('directions:step:') }, ); syncRenderHold(); }, diff --git a/src/layers/droneAirspace/index.js b/src/layers/droneAirspace/index.js index 2e64bafd37..1e359b8d9b 100644 --- a/src/layers/droneAirspace/index.js +++ b/src/layers/droneAirspace/index.js @@ -129,25 +129,26 @@ export function createDroneAirspaceLayer({ // so claiming these large ground polygons would make FIRMS/vessel/CCTV // cards inert anywhere over a zone. Unowned, our picks read as // "empty space" to siblings — the same contract as fire perimeters. + // Our shapes stand aside for a card painted over them (below), so that + // card's layer may act on the click; without a hit-test they cannot. + if (overlayHost?.hitTest) + picking?.registerCardBackground?.( + layer.id, + (hit) => pickedZoneId(hit) !== null, + ); _clickSubscription = inputFor(_viewer).onClick((event) => { const cardHit = overlayHost.hitTest?.( event.screenPosition?.x, event.screenPosition?.y, - { sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID }, ); + // Only the top painted card owns the click; this area's shapes are + // background when another layer has painted a card or label over them. + if (cardHit && cardHit.sourceId !== DRONE_AIRSPACE_OVERLAY_SOURCE_ID) + return; if (cardHit && cardHit.entryId === _selectedCardId) return; const picked = event.topHit; const zoneId = picked ? pickedZoneId(event.drawHit) : null; if (zoneId) { - // Another layer's card or label painted over the zone (a quake's - // card or magnitude label, a fire card) is that layer's click: under - // it the zone is background, as it is to siblings, so it stays as is. - const top = overlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - {}, - ); - if (top && top.sourceId !== DRONE_AIRSPACE_OVERLAY_SOURCE_ID) return; _selectedId = zoneId; publishSelectedCard(); return; @@ -166,6 +167,7 @@ export function createDroneAirspaceLayer({ function removeClickHandler() { _clickSubscription?.(); _clickSubscription = null; + picking?.unregisterCardBackground?.(layer.id); } function clearSelection() { diff --git a/src/layers/droneAirspace/ownership.test.mjs b/src/layers/droneAirspace/ownership.test.mjs index b6e4cbdcb2..306fd32c55 100644 --- a/src/layers/droneAirspace/ownership.test.mjs +++ b/src/layers/droneAirspace/ownership.test.mjs @@ -17,6 +17,7 @@ const liveSet = (draw, suffix) => function harness(source, { pick = () => null, cardHit = () => null } = {}) { const overlay = { entries: new Map(), visible: null }; const owners = new Map(); + const backgrounds = new Map(); const viewer = { scene: { pick } }; const { draw } = bindFakeDraw(viewer); const input = fakeInput(viewer); @@ -47,6 +48,9 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) { String(pickedId).startsWith('other-layer:'), registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate), unregisterPickOwner: (layerId) => owners.delete(layerId), + registerCardBackground: (layerId, predicate) => + backgrounds.set(layerId, predicate), + unregisterCardBackground: (layerId) => backgrounds.delete(layerId), }, }); layer.init(viewer); @@ -61,6 +65,7 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) { overlay, clicks, owners, + backgrounds, }; } @@ -153,6 +158,8 @@ test("another layer's overlay on top keeps a click off the area", async () => { { pick: () => pickResult, // Unfiltered: the topmost entry of any source. + // As the host does: drone-airspace cards are not interactive, so only + // another layer's card painted on top is ever hit. cardHit: (_x, _y, options) => foreignOnTop && !options?.sourceId ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' } @@ -171,13 +178,20 @@ test("another layer's overlay on top keeps a click off the area", async () => { h.overlay.entries.get('drone-airspace')[0].id, 'drone-airspace-card:310', ); - // An overlay on top never clears an existing selection either. + // An overlay on top covers the selected area's card. foreignOnTop = true; h.clicks.handler({ position: { x: 10, y: 10 } }); assert.equal( h.overlay.entries.get('drone-airspace')[0].id, 'drone-airspace-card:310', ); + pickResult = null; + h.clicks.handler({ position: { x: 10, y: 10 } }); + assert.equal( + h.overlay.entries.get('drone-airspace')[0].id, + 'drone-airspace-card:310', + 'the foreground overlay preserves selection over bare map too', + ); }); test('late refresh cannot publish after disable or destroy', async () => { @@ -270,3 +284,21 @@ test('a boundary change alone redraws the zone; identical geometry does not', as assert.notDeepEqual(redrawn.positions, first.positions); assert.ok(h.layer.getAnalystRecords()[0].lon > -76.6); }); + +// A card painted over the area may act there (a live CCTV card): the layer +// names its own drawn shapes, and only while it takes clicks. +test('enabled, the zone shapes register as card background', async () => { + const h = harness({ getSnapshot: async () => [row] }); + await h.layer.update(h.viewer); + const isBackground = h.backgrounds.get('drone-airspace'); + const own = { + set: h.fills().spec.id, + id: 'drone-airspace:310:0', + surface: false, + }; + assert.equal(isBackground(own), true); + assert.equal(isBackground({ ...own, set: 'other:1:fills' }), false); + assert.equal(isBackground({ ...own, id: 'other-layer:x' }), false); + h.layer.disable(h.viewer); + assert.equal(h.backgrounds.has('drone-airspace'), false); +}); diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index cd4b0ca1c3..898ea6c9a5 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -60,7 +60,11 @@ let instances = 0; * the card be clicked). * @param {(viewer: object) => {onClick: Function}} [options.input] The * viewer's click dispatcher. - * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function}} [options.picking] + * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function, + * isActedOnByOtherLayer?: Function, registerCardBackground?: Function, + * unregisterCardBackground?: Function}} [options.picking] The pick + * registry; with the card-background pair, a card painted over a disc + * (a CCTV card) may act on the click. * @param {{registerEntityContext: Function, selectEntityContext: Function, * clearSelectedEntityContextForLayer: Function, * getContextStore: Function}} [options.context] Shared selection store. @@ -319,6 +323,14 @@ export function createEarthquakesLayer({ clicks = null; } if (!clicks) return; + // Our discs stand aside for another layer's card painted over them + // (below), so that card's layer may act on the click; without a + // hit-test they cannot. + if (overlayHost?.hitTest) + picking.registerCardBackground?.( + EARTHQUAKES_LAYER_ID, + (hit) => pickedEvent(hit) !== null, + ); _clickHandler = clicks.onClick((click) => { if (!_enabled || (pointer && !pointer.isPointerFree())) return; const at = click.screenPosition; @@ -331,14 +343,16 @@ export function createEarthquakesLayer({ topEntry.sourceId !== EARTHQUAKE_OVERLAY_SOURCE_ID ) return; - // Another layer's pick (an aircraft, a camera) is not this layer's, - // even under this layer's card or a magnitude label: that layer acts - // on the click itself, and this card stays. Checked before the card - // and the labels, as the fire layer does. + // Another layer's pick that it acts on (an aircraft, a camera) is not + // this layer's, even under this layer's card or a magnitude label: + // that layer takes the click, and this card stays. A passive owner's + // pick (a flight trail, a directions route) acts for nobody, so the + // card or label over it keeps the click. const hit = click.hit; const pickId = picking.resolvePickId(hit); - if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId)) - return; + const actedOn = + picking.isActedOnByOtherLayer ?? picking.isOwnedByOtherLayer; + if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId)) return; const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID, }); @@ -355,6 +369,10 @@ export function createEarthquakesLayer({ selectAndFocus(labelHit.entryId); return; } + // A passive owner's pick with nothing of ours over it is still not + // empty space: leave the selection alone, as every layer does. + if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId)) + return; const event = pickedEvent(hit); if (event) { _selectedId = event.stableId; @@ -383,6 +401,7 @@ export function createEarthquakesLayer({ function removeClickHandler() { _clickHandler?.(); _clickHandler = null; + picking?.unregisterCardBackground?.(EARTHQUAKES_LAYER_ID); } const layer = { diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs index ad8765b05d..528ff6fbe3 100644 --- a/src/layers/earthquakes/selection.test.mjs +++ b/src/layers/earthquakes/selection.test.mjs @@ -2,6 +2,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import * as picking from '../../data/pickRegistry.js'; +// Registers the shared `gev-trail:` owner as passive, as the app does. +import '../../data/trailRenderer.js'; import { fakeInput } from '../../input/testDoubles.mjs'; import { createDroneAirspaceLayer } from '../droneAirspace/index.js'; import { @@ -250,12 +252,17 @@ test('a refresh keeps the selected quake while it is in the feed', async () => { h.layer.destroy(); }); -test('disable removes the click handler and the card', async () => { +test('disable removes the click handler, card background and the card', async () => { const h = harness([quake('ak1')]); h.layer.enable(h.viewer); await h.layer.update(h.viewer); h.clickDisc('ak1'); + // A drawn disc is background to a card painted over it (a CCTV card). + const disc = { set: h.discs().spec.id, id: 'earthquake:ak1' }; + assert.equal(picking.isCardBackground(disc), true); + assert.equal(picking.isCardBackground({ ...disc, set: 'other:1' }), false); h.layer.disable(h.viewer); + assert.equal(picking.isCardBackground(disc), false); assert.deepEqual(h.lastCard(), []); assert.equal( h.handlers.every((handler) => handler.destroyed), @@ -878,3 +885,49 @@ test('quake card and label work over pickable items no layer acts on', async () h.layer.destroy(); } }); + +// Flight trails and a directions route line are registered owners that act +// on no click. Under the quake card or a magnitude label they must not make +// the click dead; a layer that acts (an aircraft) still takes it. +test('quake card and label act over a flight trail and a directions route', async () => { + const h = harness([quake('ak1'), quake('ak2', { mag: 4 })]); + picking.registerPickOwner( + 'test-directions', + (id) => String(id).startsWith('directions:'), + { passive: (id) => !id.startsWith('directions:step:') }, + ); + picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + const trail = { set: 'trail:1:lines', id: 'gev-trail:fl-a1b2c3:head' }; + const route = { set: 'directions:1:route', id: 'directions:route' }; + assert.equal(picking.findPickOwner(trail.id), 'trails'); + h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', trail); + h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', route); + assert.equal(h.opened.length, 2, 'the card opens USGS over both'); + h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', trail); + assert.equal(h.focused.at(-1)?.id, 'earthquake:ak2', 'the label flies'); + // A route step acts for directions: it takes the click. + const focusedBefore = h.focused.length; + h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak1', { + set: 'directions:1:steps', + id: 'directions:step:2', + }); + assert.equal(h.focused.length, focusedBefore, 'a step takes the click'); + // So does an aircraft under the card. + h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak2', { + set: 'flights:1', + id: 'plane-9', + }); + assert.equal(h.opened.length, 2); + // A plain click on a trail is still not empty space: the card stays. + h.click(trail); + assert.equal(h.lastCard()[0].id, 'earthquake-card:ak2'); + } finally { + picking.unregisterPickOwner('test-directions'); + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + } +}); diff --git a/src/layers/launches/clickYield.test.mjs b/src/layers/launches/clickYield.test.mjs new file mode 100644 index 0000000000..9004e10c19 --- /dev/null +++ b/src/layers/launches/clickYield.test.mjs @@ -0,0 +1,77 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createLifecycle } from './lifecycle.js'; +import { fakeInput } from '../../input/testDoubles.mjs'; +import * as picking from '../../data/pickRegistry.js'; + +/** Any part method is a no-op unless the test supplies it. */ +const stubs = (given = {}) => + new Proxy(given, { + get: (target, key) => (key in target ? target[key] : () => undefined), + }); + +// Mission overlays are not interactive: an overlay entry under the pointer is +// another layer's card or label painted over the mission (a quake label), and +// that layer takes the click, so the mission is not also selected. +test('a card painted over a launch marker keeps its click; with none the mission selects', () => { + const viewer = { + scene: { + pick: () => null, + canvas: { clientWidth: 100, clientHeight: 100 }, + }, + }; + const input = fakeInput(viewer); + let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }; + const selected = []; + const state = { _launches: [{ id: 'L1' }], _enabled: false }; + const { methods: lifecycle } = createLifecycle({ + state, + services: { + render: { holdContinuousRender() {}, releaseContinuousRender() {} }, + overlays: { hitTestWorldOverlay: () => top }, + picking, + }, + parts: { + panel: stubs(), + overlays: stubs(), + launchPad: stubs(), + orbitRendering: stubs(), + replay: stubs(), + ingestion: stubs(), + rendering: stubs({ + missionsShown: () => true, + missionHitsAt: () => [{ id: 'mission:L1' }], + launchIdFromPicks: (hits) => + hits.some((hit) => hit?.id === 'mission:L1') ? 'L1' : null, + }), + selection: stubs({ setSelectedMission: (id) => selected.push(id) }), + }, + source: {}, + }); + try { + // init installs the click handler; enable would start a feed load. + lifecycle.init(viewer); + state._enabled = true; + input.click(); + assert.deepEqual(selected, [], 'the mission stands aside'); + top = null; + input.click(); + assert.deepEqual( + selected, + ['L1'], + 'with no card on top, the mission selects', + ); + // So a card on top (a live CCTV card) may act over the mission instead. + const mission = { set: 'launches:1:markers', id: 'mission:L1' }; + assert.equal(picking.isCardBackground(mission), true); + assert.equal(picking.isCardBackground({ ...mission, id: 'x' }), false); + state._enabled = false; + assert.equal(picking.isCardBackground(mission), false); + state._inputSubscription(); + state._enabled = true; + assert.equal(picking.isCardBackground(mission), false); + } finally { + state._inputSubscription?.(); + input.destroy(); + } +}); diff --git a/src/layers/launches/lifecycle.js b/src/layers/launches/lifecycle.js index 5266763814..c326b78847 100644 --- a/src/layers/launches/lifecycle.js +++ b/src/layers/launches/lifecycle.js @@ -4,6 +4,8 @@ import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js'; import { worldClock } from '../../time/worldClock.js'; const HOVER_PICK_INTERVAL_MS = 120; +/** Our id in the pick registry's card backgrounds. */ +const CARD_BACKGROUND_ID = 'rocket-launches'; /** * Bound hover picking independently of precise click selection. A move inside @@ -200,8 +202,29 @@ export function createLifecycle({ layerState._orbitMatches = 0; parts.overlays.clearMissionOverlaySources(); const input = inputFor(viewer); + // Our mission items stand aside for a card painted over them (below), + // so that card's layer may act on the click; without a hit-test they + // cannot. + if (services.overlays?.hitTestWorldOverlay) + services.picking?.registerCardBackground?.( + CARD_BACKGROUND_ID, + (hit) => + layerState._enabled && + parts.rendering.missionsShown() && + parts.rendering.launchIdFromPicks([hit]) !== null, + ); const unsubscribeClick = input.onClick((event) => { if (!layerState._enabled || !parts.rendering.missionsShown()) return; + // Mission overlays are not interactive, so any overlay entry hit + // here is another layer's card or label painted over the click: that + // layer's click, not a mission's. + if ( + services.overlays?.hitTestWorldOverlay?.( + event.screenPosition?.x, + event.screenPosition?.y, + ) + ) + return; // The click's pick position (CSS px), as the click picked it. const launchId = parts.rendering.launchIdFromPicks( parts.rendering.missionHitsAt(event.position, 12), @@ -221,6 +244,7 @@ export function createLifecycle({ layerState._inputSubscription = () => { unsubscribeClick(); unsubscribeHover(); + services.picking?.unregisterCardBackground?.(CARD_BACKGROUND_ID); }; // Apply horizon visibility before the renderer draws and picks. // A postRender write is one frame late and can remain visibly stale when diff --git a/src/layers/perimeters/index.js b/src/layers/perimeters/index.js index 017e7ab46c..d973f8d6d7 100644 --- a/src/layers/perimeters/index.js +++ b/src/layers/perimeters/index.js @@ -215,14 +215,23 @@ export function createFirePerimetersLayer({ // so claiming these large ground polygons would make FIRMS/vessel/CCTV // cards inert anywhere over a perimeter. Unowned, our picks read as // "empty space" to siblings — the pre-existing behavior for the globe. + // Our shapes stand aside for a card painted over them (below), so that + // card's layer may act on the click; without a hit-test they cannot. + if (overlayHost?.hitTest) + picking?.registerCardBackground?.( + layer.id, + (hit) => pickedIncidentId(hit) !== null, + ); _clickSubscription = inputFor(_viewer).onClick((event) => { // A click on the incident card itself opens its InciWeb page (when the // incident has one) and never disturbs the selection. const cardHit = overlayHost.hitTest?.( event.screenPosition?.x, event.screenPosition?.y, - { sourceId: PERIMETER_OVERLAY_SOURCE_ID }, ); + // Only the top painted card owns the click; this area's shapes are + // background when another layer has painted a card or label over them. + if (cardHit && cardHit.sourceId !== PERIMETER_OVERLAY_SOURCE_ID) return; if (cardHit && cardHit.entryId === _selectedCardId) { if (_selectedLink && openExternal) openExternal(_selectedLink); return; @@ -230,15 +239,6 @@ export function createFirePerimetersLayer({ const picked = event.topHit; const incidentId = picked ? pickedIncidentId(event.drawHit) : null; if (incidentId) { - // Another layer's card or label painted over the perimeter (a - // quake's card or magnitude label, a fire card) is that layer's - // click: under it the perimeter is background, so it stays as is. - const top = overlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - {}, - ); - if (top && top.sourceId !== PERIMETER_OVERLAY_SOURCE_ID) return; abortLinkVerification(); _selectedId = incidentId; publishSelectedCard(); @@ -261,6 +261,7 @@ export function createFirePerimetersLayer({ function removeClickHandler() { _clickSubscription?.(); _clickSubscription = null; + picking?.unregisterCardBackground?.(layer.id); } function clearSelection() { diff --git a/src/layers/perimeters/ownership.test.mjs b/src/layers/perimeters/ownership.test.mjs index 9f11d5b177..bd0533a28b 100644 --- a/src/layers/perimeters/ownership.test.mjs +++ b/src/layers/perimeters/ownership.test.mjs @@ -27,6 +27,7 @@ function harness( ) { const overlay = { entries: new Map(), visible: null }; const owners = new Map(); + const backgrounds = new Map(); const opened = []; const viewer = { scene: { pick } }; const { draw } = bindFakeDraw(viewer); @@ -58,6 +59,9 @@ function harness( String(pickedId).startsWith('other-layer:'), registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate), unregisterPickOwner: (layerId) => owners.delete(layerId), + registerCardBackground: (layerId, predicate) => + backgrounds.set(layerId, predicate), + unregisterCardBackground: (layerId) => backgrounds.delete(layerId), }, inciwebSource: inciwebIndex ? { getIndex: async () => inciwebIndex } @@ -77,6 +81,7 @@ function harness( overlay, clicks, owners, + backgrounds, opened, }; } @@ -316,12 +321,16 @@ test('a matched incident card carries the InciWeb line and click-through', async }, ]; let cardHitResult = null; + let foreignOnTop = false; const h = harness( { getSnapshot: async () => [{ ...row, name: 'Fixture' }] }, { pick: () => null, inciwebIndex, - cardHit: () => cardHitResult, + cardHit: (_x, _y, options) => + foreignOnTop && !options?.sourceId + ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' } + : cardHitResult, }, ); await h.layer.update(h.viewer); @@ -336,9 +345,15 @@ test('a matched incident card carries the InciWeb line and click-through', async const entries = h.overlay.entries.get('fire-perimeters'); assert.equal(entries[0].details.at(-1), 'InciWeb ↗ · click card to open'); - // Clicking the card itself opens the InciWeb page. - cardHitResult = { entryId: entries[0].id }; + // A selected card covered by a quake card cannot open its hidden link. + cardHitResult = { sourceId: 'fire-perimeters', entryId: entries[0].id }; h.viewer.scene.pick = () => null; + foreignOnTop = true; + h.clicks.handler({ position: { x: 12, y: 12 } }); + assert.deepEqual(h.opened, []); + assert.equal(h.overlay.entries.get('fire-perimeters')[0].id, entries[0].id); + // Removing the foreground card makes the incident card actionable again. + foreignOnTop = false; h.clicks.handler({ position: { x: 12, y: 12 } }); assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']); assert.equal( @@ -365,7 +380,7 @@ test('an unmatched incident renders no InciWeb line and card clicks stay inert', entries[0].details.some((line) => line.includes('InciWeb')), false, ); - cardHitResult = { entryId: entries[0].id }; + cardHitResult = { sourceId: 'fire-perimeters', entryId: entries[0].id }; h.viewer.scene.pick = () => null; h.clicks.handler({ position: { x: 12, y: 12 } }); assert.deepEqual(h.opened, []); @@ -679,3 +694,21 @@ test('a failed refresh after a stale snapshot reads as the failure, not stale', assert.equal(h.layer.getStats().stale, false); assert.equal(h.layer.getStats().error, 'WFIGS HTTP 502'); }); + +// A card painted over the area may act there (a live CCTV card): the layer +// names its own drawn shapes, and only while it takes clicks. +test('enabled, the perimeter shapes register as card background', async () => { + const h = harness({ getSnapshot: async () => [row] }); + await h.layer.update(h.viewer); + const isBackground = h.backgrounds.get('fire-perimeters'); + const own = { + set: h.fills().spec.id, + id: 'fire-perimeter:2026-NMGNF-000123:0', + surface: false, + }; + assert.equal(isBackground(own), true); + assert.equal(isBackground({ ...own, set: 'other:1:fills' }), false); + assert.equal(isBackground({ ...own, id: 'other-layer:x' }), false); + h.layer.disable(h.viewer); + assert.equal(h.backgrounds.has('fire-perimeters'), false); +}); diff --git a/src/layers/submarineCables/index.js b/src/layers/submarineCables/index.js index e38e69bf31..de47082b0f 100644 --- a/src/layers/submarineCables/index.js +++ b/src/layers/submarineCables/index.js @@ -8,6 +8,7 @@ import { inputFor as defaultInputFor } from '../../input/dispatcher.js'; export function createSubmarineCableLayer({ source, overlayHost, + picking = null, inputFor = defaultInputFor, mapStackEventTarget = null, sweepClock = defaultSweepClock, @@ -23,6 +24,8 @@ export function createSubmarineCableLayer({ parts, source, inputFor, + overlayHost, + picking, mapStackEventTarget, }; parts.rendering = createRendering(context); diff --git a/src/layers/submarineCables/interaction.js b/src/layers/submarineCables/interaction.js index de7470da27..823020e16e 100644 --- a/src/layers/submarineCables/interaction.js +++ b/src/layers/submarineCables/interaction.js @@ -1,15 +1,40 @@ import { toRadians } from '../../geo/vector.js'; import { cameraOf } from '../../render/rendererOf.js'; -export function createInteraction({ state, parts, inputFor }) { +const CARD_BACKGROUND_ID = 'submarine-cables'; + +export function createInteraction({ + state, + parts, + inputFor, + overlayHost, + picking, +}) { function beginInteraction(viewer) { if (state._clickSubscription) return; - state._clickSubscription = inputFor(viewer).onClick((event) => { + // Our cables stand aside for a card painted over them (below), so that + // card's layer may act on the click; without a hit-test they cannot. + if (overlayHost?.hitTest) + picking?.registerCardBackground?.( + CARD_BACKGROUND_ID, + (hit) => state._enabled && Boolean(resolvePickRecord(hit)?.reference), + ); + const unsubscribe = inputFor(viewer).onClick((event) => { if (!state._enabled) return; + // Cable labels are not interactive, so any overlay entry hit here is + // another layer's card or label painted over the cable: its click. + if ( + overlayHost?.hitTest?.(event.screenPosition?.x, event.screenPosition?.y) + ) + return; const record = resolvePickRecord(event.drawHit); if (!record?.reference) return; flyToReference(viewer, record.reference); }); + state._clickSubscription = () => { + unsubscribe(); + picking?.unregisterCardBackground?.(CARD_BACKGROUND_ID); + }; } /** diff --git a/src/layers/submarineCables/interaction.test.mjs b/src/layers/submarineCables/interaction.test.mjs new file mode 100644 index 0000000000..79282c02e8 --- /dev/null +++ b/src/layers/submarineCables/interaction.test.mjs @@ -0,0 +1,89 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createInteraction } from './interaction.js'; +import * as picking from '../../data/pickRegistry.js'; + +/** The cable click handler, with its click and overlay seams faked. */ +function harness({ overlayTop = null } = {}) { + let onClick = null; + const picked = []; + let top = overlayTop; + const interaction = createInteraction({ + state: { _enabled: true, _clickSubscription: null }, + parts: { + rendering: { + pickInfo: (hit) => { + picked.push(hit); + return null; + }, + }, + }, + inputFor: () => ({ + onClick: (fn) => { + onClick = fn; + return () => (onClick = null); + }, + }), + overlayHost: { hitTest: () => top }, + }); + interaction.beginInteraction({}); + return { + picked, + setTop: (next) => { + top = next; + }, + click: () => + onClick({ + screenPosition: { x: 5, y: 5 }, + drawHit: { set: 'c', id: 'x' }, + }), + }; +} + +// Cable labels are not interactive: an overlay entry under the pointer is +// another layer's card or label painted over the cable (a quake card), and +// that layer takes the click, so the cable does not also fly the camera. +test('a card painted over a cable keeps its click; with none the cable reads the pick', () => { + const h = harness({ + overlayTop: { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }, + }); + h.click(); + assert.equal(h.picked.length, 0, 'the cable stands aside'); + h.setTop(null); + h.click(); + assert.equal( + h.picked.length, + 1, + 'with no card on top, the cable reads its pick', + ); +}); + +// So a card on top (a live CCTV card) may act over the cable instead. +test('while it takes clicks, a drawn cable registers as card background', () => { + const state = { _enabled: true, _clickSubscription: null }; + const interaction = createInteraction({ + state, + parts: { + rendering: { + pickInfo: (hit) => + hit?.set === 'cables:1' ? { reference: { lon: 1, lat: 2 } } : null, + }, + }, + inputFor: () => ({ onClick: () => () => {} }), + overlayHost: { hitTest: () => null }, + picking, + }); + interaction.beginInteraction({}); + const cable = { set: 'cables:1', id: 'cable:0' }; + try { + assert.equal(picking.isCardBackground(cable), true); + assert.equal(picking.isCardBackground({ set: 'other:1', id: 'x' }), false); + state._enabled = false; + assert.equal(picking.isCardBackground(cable), false); + state._enabled = true; + state._clickSubscription(); + assert.equal(picking.isCardBackground(cable), false); + } finally { + state._clickSubscription?.(); + } +}); From 830c980ca6a60b7d812ab5f2a65728621f295c4c Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Tue, 17 Nov 2026 13:18:32 +0530 Subject: [PATCH 011/138] fix(touch): give each tap to the layer that acts on it On a coarse pointer the dispatcher can name a contact near the tap instead of the exact pick. Only flights, military, vessels, radio and Street Level act on such a contact, so they now register as expanded pick owners, and a quake card or label yields only to them. A FIRMS fire or CCTV camera reached only as a nearby contact no longer swallows a quake card, a quake label or a vessel's own card tap, and FIRMS and CCTV cards yield to a contact whose layer does act on it. Radio and Street Level also pick through their own windows. A station or Street Level item found only there, not as the touch contact, yields to another layer's card painted over it, and Street Level takes its own touch contact beyond its narrower window. Fire, CCTV and vessel cards now act over a passive owner's pick (a flight trail, the directions route), as the quake card does. The Context panel leaves a passive route, or a fire or camera reached only as a nearby contact, to the card painted over it. --- docs/CURRENT-STATE.md | 27 +++- scripts/format-scope.json | 2 + src/app/layers/streetLevel.js | 4 +- src/data/aisLiveVessels.test.mjs | 73 +++++++++- src/data/firmsInteraction.test.mjs | 115 +++++++++++++++ src/data/pickOwnerExpanded.test.mjs | 165 ++++++++++++++++++++++ src/data/pickRegistry.js | 25 +++- src/data/pickRegistry.test.mjs | 34 +++++ src/data/pickedContext.js | 28 +++- src/data/pickedContext.test.mjs | 52 ++++++- src/layers/cctv/lifecycle.js | 22 ++- src/layers/cctv/lifecycle.test.mjs | 35 +++++ src/layers/earthquakes/index.js | 6 +- src/layers/earthquakes/selection.test.mjs | 156 +++++++++++++++----- src/layers/firms/selection.js | 25 +++- src/layers/flights/lifecycle.js | 8 ++ src/layers/military/lifecycle.js | 8 ++ src/layers/news/layer.test.mjs | 6 +- src/layers/radio/interaction.js | 21 ++- src/layers/radio/interaction.test.mjs | 39 +++++ src/layers/streetLevel/selection.js | 25 +++- src/layers/streetLevel/selection.test.mjs | 135 ++++++++++++++++++ src/layers/vessels/lifecycle.js | 6 +- src/layers/vessels/selection.js | 38 ++++- src/ui/entityContextBridge.js | 8 +- src/ui/entityContextBridge.test.mjs | 101 +++++++++++++ 26 files changed, 1095 insertions(+), 69 deletions(-) create mode 100644 src/data/pickOwnerExpanded.test.mjs create mode 100644 src/ui/entityContextBridge.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 23029867b3..f492bedce2 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2055,6 +2055,25 @@ painted with a gradient fading to the outer circle and wavy contour lines clicks, picking, context, focus, the opener, the painter and the translator by injection (`src/app/layers/earthquakes.js`); without input and picking it draws and takes no clicks, and its labels stay non-interactive. +On a coarse pointer, a nearby FIRMS or CCTV icon that requires an exact hit +does not swallow a quake card or label tap, or a tap on a vessel's own card. +Owners that pick nearby contacts register as `expanded` pick owners: flights, +military aircraft, vessels, radio and Street Level, and a quake card or label +yields to one the shared touch contact (14 px) reaches. Flights, military and +vessels act on that contact, and so do radio and Street Level, which also pick +through their own windows (17 and 9 px). A station or Street Level item found +only through that window, not as the exact hit or the touch contact, yields to +another layer's card or label painted over it, so a quake card or label beside +one acts alone, with a mouse or a coarse pointer. Fire and CCTV cards in turn +yield to a touch contact whose layer acts on it. The aircraft a layer already +tracks and Street Level's position marker are passive picks, since a click on +either does nothing. Fire, CCTV and vessel cards, like the quake's, act over a +passive owner's pick (a flight trail, the directions route); with no card +there, that pick still leaves a selection alone. Context +(`src/ui/entityContextBridge.js`) names what a click identifies, except under a +world-overlay card or label when the item's owner does not act on that hit +(`cardKeepsClick` in `src/data/pickedContext.js`): a passive route, or a fire +or camera reached only as a nearby contact. The card takes that click. Quake discs are deliberately not registered in the pick-ownership registry, like drone airspace and fire perimeters: sibling layers read a disc as empty space, so their cards, near-miss taps and deselection work over a quake as @@ -2082,10 +2101,10 @@ card of these layers or clear their selection; a marker of theirs under that card is still theirs to select. Flight trails and the directions route line and markers are passive pick owners (`registerPickOwner(…, { passive })`): still not empty space (`isOwnedByOtherLayer`), but `isActedOnByOtherLayer` leaves -them out, so the quake card and magnitude labels act over them. Directions -selects only its maneuver steps, though any other click still clears a selected -step. Fire, vessel and CCTV cards over a trail or the route stay as they were -(no action). Submarine cables and rocket launches, whose own overlays are not +them out, so the quake card and magnitude labels act over them, as do fire, +vessel and CCTV cards. Directions selects only its maneuver steps, though any +other click still clears a selected step. Submarine cables and rocket +launches, whose own overlays are not interactive, stand aside when any overlay entry is under the click, so a card or label over a cable or a launch marker acts once. Layers whose shapes stand aside like this (drone airspace, fire perimeters, quake discs, cables, diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 82643e508d..993e64a297 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -439,6 +439,8 @@ "src/layers/earthquakes/ownership.test.mjs", "src/layers/earthquakes/selection.test.mjs", "src/layers/submarineCables/interaction.test.mjs", + "src/data/pickOwnerExpanded.test.mjs", + "src/ui/entityContextBridge.test.mjs", "src/layers/launches/clickYield.test.mjs", "src/app/layers/earthquakeRipples.js", "src/app/layers/earthquakeRipples.test.mjs", diff --git a/src/app/layers/streetLevel.js b/src/app/layers/streetLevel.js index 3b7c7cc0b9..964d495300 100644 --- a/src/app/layers/streetLevel.js +++ b/src/app/layers/streetLevel.js @@ -6,6 +6,7 @@ import { createPanoramaxProvider } from '../../layers/streetLevel/providers/pano import * as picking from '../../data/pickRegistry.js'; import * as scenePick from '../../data/scenePick.js'; import * as render from '../../renderGovernor.js'; +import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js'; /** The browser Maps key the scene was started with (src/app/scene.js). */ const googleApiKey = () => globalThis.window?.__GOOGLE_MAPS_API_KEY__ || null; @@ -35,6 +36,7 @@ export function createApplicationStreetLevel({ }) { return createStreetLevelLayer({ providers, - services: { picking, scenePick, render }, + // Hit-testing lets a card painted over a near miss keep its click. + services: { picking, scenePick, render, overlayHit: hitTestWorldOverlay }, }); } diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index b2ea95ceb1..25747f257c 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -1012,7 +1012,7 @@ function makeCesiumEvent() { }; } -function installWireHarness(picked, stateOverrides = {}) { +function installWireHarness(picked, stateOverrides = {}, sceneExtras = {}) { const hadWindow = Object.hasOwn(globalThis, 'window'); const hadDocument = Object.hasOwn(globalThis, 'document'); const priorWindow = globalThis.window; @@ -1038,7 +1038,7 @@ function installWireHarness(picked, stateOverrides = {}) { }, }; const viewer = { - scene: { pick: () => picked }, + scene: { pick: () => picked, ...sceneExtras }, }; const input = fakeInput(viewer); // The camera port other layers follow through, with no pose to read; its @@ -1993,6 +1993,75 @@ test('vessel interaction wire: a sibling-owned pick wins without selection mutat } }); +// A trail acts for nobody: the vessel's card painted over it still selects, +// and a bare trail pick stays a no-op that keeps the selection. +test('vessel interaction wire: a card over a trail selects; a bare trail is a no-op', () => { + for (const carded of [true, false]) { + const harness = installWireHarness( + { id: 'gev-trail:fl-a1b2c3:head' }, + { selectedRecord: null }, + ); + const requests = []; + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(carded ? `vessel:${harness.record.mmsi}` : null), + ); + try { + harness.handler.click({ position: { x: 10, y: 20 } }); + assert.equal(requests.length, carded ? 1 : 0, `card: ${carded}`); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi ?? null, + carded ? harness.record.mmsi : null, + ); + } finally { + _setVesselOverlayHostForTest(null); + harness.cleanup(); + } + } +}); + +// A coarse tap on the vessel's card finds a fire nearby through the shared +// touch contact. The fire layer acts only on exact hits, so the card keeps the +// tap; an exact fire pick under the card still belongs to the fire. +test('vessel interaction wire: a coarse near miss of an exact-only item keeps the card tap', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const fire = 'fire:near-miss'; + registerPickOwner('test-exact-fires', (pickedId) => pickedId === fire); + t.after(() => unregisterPickOwner('test-exact-fires')); + for (const exact of [false, true]) { + const harness = installWireHarness( + exact ? { id: fire } : null, + { selectedRecord: null }, + { drillPick: () => [{ id: fire }] }, + ); + const requests = []; + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(`vessel:${harness.record.mmsi}`), + ); + try { + harness.handler.click({ position: { x: 10, y: 20 } }); + assert.equal(requests.length, exact ? 0 : 1, `exact fire: ${exact}`); + assert.equal( + aisLiveVesselsLayer.getSelectedInfo()?.mmsi ?? null, + exact ? null : harness.record.mmsi, + ); + } finally { + _setVesselOverlayHostForTest(null); + harness.cleanup(); + } + } +}); + for (const card of ['live', 'stale', 'absent', 'covered']) { test(`vessel interaction wire: ${card} foreground card over registered cyclone`, () => { const id = 'cyclone:fixture:cone:0'; diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index 55413c1d85..0bdf158f98 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -63,6 +63,7 @@ function harness({ withDataSource = false, withGlobe = false, feed = null, + drilled = null, } = {}) { const hadWindow = Object.hasOwn(globalThis, 'window'); const priorWindow = globalThis.window; @@ -112,6 +113,7 @@ function harness({ const viewer = { scene: { pick, + ...(drilled ? { drillPick: () => drilled } : {}), canvas: { clientWidth: 1280, clientHeight: 800 }, camera: cameraPosition ? { positionWC: cameraPosition } : undefined, globe: { ellipsoid: Cesium.Ellipsoid.WGS84 }, @@ -162,6 +164,9 @@ function harness({ cover: (hit) => { topCard = hit; }, + setPicked: (next) => { + picked = next; + }, cleanup() { Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection; if (hadWindow) globalThis.window = priorWindow; @@ -461,6 +466,116 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) { }); } +// A passive owner's pick (a directions route, a flight trail) acts for nobody: +// a fire card over it still takes the click, and with no card the pick is +// still not empty space, so the selection stays. +test('a fire card acts over a passive pick; the bare pick leaves the selection', () => { + const fire = makeFire(); + registerPickOwner('test-route', (pickedId) => pickedId === 'route:line', { + passive: true, + }); + const carded = harness({ + fires: [fire], + picked: { id: 'route:line' }, + cardHit: `fire:${fireDetectionKey(fire)}`, + }); + try { + carded.click(); + assert.equal(carded.requests.length, 1, 'the card acts over the route'); + assert.ok(carded.layer.getSelectedInfo()); + } finally { + carded.cleanup(); + } + const bare = harness({ fires: [fire], picked: { id: 'route:line' } }); + try { + bare.click(); + assert.equal(bare.requests.length, 0); + assert.equal( + bare.layer.getSelectedInfo(), + null, + 'nothing to clear or pick', + ); + } finally { + bare.cleanup(); + unregisterPickOwner('test-route'); + } +}); + +// A coarse tap on a fire card finds an aircraft nearby through the shared +// touch contact. The flights layer acts on that contact, so the card yields: +// one action, not two. +test('a fire card yields to a touch contact its layer acts on', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const fire = makeFire(); + registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1', { + expanded: true, + }); + t.after(() => unregisterPickOwner('test-planes')); + const h = harness({ + fires: [fire], + drilled: [{ id: 'plane:1' }], + cardHit: `fire:${fireDetectionKey(fire)}`, + }); + try { + h.click(); + assert.equal(h.requests.length, 0, 'the aircraft takes the tap'); + assert.equal(h.layer.getSelectedInfo(), null); + } finally { + h.cleanup(); + } +}); + +// A touch contact whose layer acts only on exact hits does not take the tap +// from our card; with no card, a coarse tap near an aircraft still clears. +test('a fire card keeps a tap whose contact does not act; bare taps still clear', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const fire = makeFire(); + registerPickOwner('test-cameras', (pickedId) => pickedId === 'cam:1'); + registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1', { + expanded: true, + }); + t.after(() => { + unregisterPickOwner('test-cameras'); + unregisterPickOwner('test-planes'); + }); + const carded = harness({ + fires: [fire], + drilled: [{ id: 'cam:1' }], + cardHit: `fire:${fireDetectionKey(fire)}`, + }); + try { + carded.click(); + assert.equal(carded.requests.length, 1, 'the card acts'); + } finally { + carded.cleanup(); + } + const bare = harness({ + fires: [fire], + picked: glowPick('firms-7'), + drilled: [{ id: 'plane:1' }], + }); + try { + bare.click(); + assert.ok(bare.layer.getSelectedInfo(), 'a fire is selected'); + // Nothing exact now; the touch contact is an aircraft, with no card. + bare.setPicked(null); + bare.click(); + assert.equal(bare.layer.getSelectedInfo(), null, 'the bare tap clears'); + } finally { + bare.cleanup(); + } +}); + test('a stale card id resolves to nothing instead of an arbitrary fire', () => { const h = harness({ picked: { primitive: {}, content: {}, featureId: 0 }, diff --git a/src/data/pickOwnerExpanded.test.mjs b/src/data/pickOwnerExpanded.test.mjs new file mode 100644 index 0000000000..83ab4afa79 --- /dev/null +++ b/src/data/pickOwnerExpanded.test.mjs @@ -0,0 +1,165 @@ +/** + * Which pick owners select nearby contacts. A coarse tap's shared contact + * hit (`pickContact`) can land on a contact near an exact miss; only owners + * whose click handlers act on such a hit, or on their own pick window, + * register `expanded`, so a quake card or label yields to them and not to + * exact-only owners (FIRMS, CCTV). Each case runs the layer's own + * registration code (its enable or install step) with stand-in services. + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createLifecycle as createFlightLifecycle } from '../layers/flights/lifecycle.js'; +import { createLifecycle as createMilitaryLifecycle } from '../layers/military/lifecycle.js'; +import { createLifecycle as createVesselLifecycle } from '../layers/vessels/lifecycle.js'; +import { createInteraction as createRadioInteraction } from '../layers/radio/interaction.js'; +import { createSelection as createStreetSelection } from '../layers/streetLevel/selection.js'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { STREET_LEVEL_LAYER_ID } from '../layers/streetLevel/policy.js'; +import * as picking from './pickRegistry.js'; + +/** + * A stand-in for any collaborator: every property is another stand-in and + * every call returns one, except the keys `given` names. Not a thenable. + */ +function stub(given = {}) { + return new Proxy(function stand() {}, { + get(target, key) { + if (key in given) return given[key]; + if (key === 'then' || typeof key === 'symbol') return undefined; + return stub(); + }, + set(target, key, value) { + given[key] = value; + return true; + }, + apply: () => stub(), + }); +} + +/** Picking services that record each registration's options. */ +function recordingPicking() { + const registered = new Map(); + return { + registered, + services: { + ...picking, + registerPickOwner(layerId, predicate, options) { + registered.set(layerId, options ?? {}); + picking.registerPickOwner(layerId, predicate, options); + }, + }, + }; +} + +function withDocument(t) { + const previous = globalThis.document; + globalThis.document = { + body: { classList: { contains: () => false } }, + addEventListener() {}, + removeEventListener() {}, + }; + t.after(() => { + if (previous === undefined) delete globalThis.document; + else globalThis.document = previous; + }); +} + +/** A quake card over `pickedId` reached as a nearby touch contact. */ +const actsOnNearbyHit = (pickedId) => + picking.isActedOnByOtherLayer('earthquakes', pickedId, { expanded: true }); + +for (const [name, layerId, create] of [ + ['flights', 'flights', createFlightLifecycle], + ['military', 'military', createMilitaryLifecycle], +]) { + test(`${name} registers its aircraft as acting on nearby touch hits`, (t) => { + withDocument(t); + const { registered, services } = recordingPicking(); + const flightState = stub({ + _icons: { show: false, has: (id) => id === `${name}-1` }, + records: { geoidReady: true }, + timeline: null, + _trackedIcao: null, + }); + const { methods: lifecycle } = create({ + flightState, + services: stub({ picking: services }), + parts: stub(), + layer: stub(), + resolveAsset: () => '', + }); + t.after(() => picking.unregisterPickOwner(layerId)); + lifecycle.enable({}); + assert.equal(registered.get(layerId)?.expanded, true); + assert.equal(actsOnNearbyHit(`${name}-1`), true); + // A click on the aircraft already tracked is ignored, so it is passive. + flightState._trackedIcao = `${name}-1`; + assert.equal(actsOnNearbyHit(`${name}-1`), false); + }); +} + +test('vessels register their icons as acting on nearby touch hits', (t) => { + withDocument(t); + const { registered, services } = recordingPicking(); + const state = { + feed: { enabled: true, sessionId: 1 }, + records: { byId: new Map([['vessel-1', {}]]) }, + viewer: {}, + }; + const created = createVesselLifecycle({ + vesselState: stub({ state, _geoidReady: true }), + services: stub({ picking: services }), + parts: stub(), + }); + const lifecycle = created.methods ?? created; + t.after(() => picking.unregisterPickOwner('ais-live-vessels')); + lifecycle.enable({}); + assert.equal(registered.get('ais-live-vessels')?.expanded, true); + assert.equal(actsOnNearbyHit('vessel-1'), true); +}); + +test('radio registers its stations as acting on nearby touch hits', (t) => { + const { registered, services } = recordingPicking(); + const viewer = { scene: { canvas: new EventTarget(), pick: () => null } }; + const input = fakeInput(viewer); + const state = { _viewer: viewer, _clickSubscription: null }; + const interaction = createRadioInteraction({ + state, + services: { picking: services, overlays: stub() }, + parts: stub(), + }); + t.after(() => { + interaction.removeInteraction(); + input.destroy(); + }); + interaction.installInteraction(); + assert.equal(registered.get('radio')?.expanded, true); + assert.equal(actsOnNearbyHit('radio:kexp'), true); + interaction.removeInteraction(); + assert.equal(actsOnNearbyHit('radio:kexp'), false); +}); + +test('Street Level registers its picks as acting on nearby touch hits', (t) => { + withDocument(t); + const { registered, services } = recordingPicking(); + const viewer = { scene: { canvas: new EventTarget(), pick: () => null } }; + const input = fakeInput(viewer); + const state = { services: { picking: services }, clickSubscription: null }; + const selection = createStreetSelection({ + state, + parts: stub({ + router: { + ownsPick: (id) => id === 'mly:seq-1', + resolve: (id) => (id === 'mly:seq-1' ? { id, instance: {} } : null), + }, + }), + }); + t.after(() => { + state.clickSubscription?.(); + picking.unregisterPickOwner(STREET_LEVEL_LAYER_ID); + input.destroy(); + }); + selection.install(viewer); + assert.equal(registered.get(STREET_LEVEL_LAYER_ID)?.expanded, true); + assert.equal(actsOnNearbyHit('mly:seq-1'), true); +}); diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js index e6807e1e7c..b16264f71f 100644 --- a/src/data/pickRegistry.js +++ b/src/data/pickRegistry.js @@ -33,6 +33,8 @@ const _owners = new Map(); * @type {Map boolean)>} */ const _passive = new Map(); +/** Owners whose click handlers also select nearby contacts. */ +const _expanded = new Set(); /** * Layers whose shapes are background to any card painted over them: their * click handlers stand aside under a card, so the card's layer may act there. @@ -60,14 +62,22 @@ export function resolvePickId(hit) { * @param {string} layerId - Owning layer id (e.g. 'flights'). * @param {(pickedId: string) => boolean} predicate - Returns true when the * picked primitive/entity id belongs to this layer. - * @param {{passive?: boolean | ((pickedId: string) => boolean)}} [options] + * @param {{passive?: boolean | ((pickedId: string) => boolean), expanded?: boolean}} [options] * `passive`: the layer never acts on a click on these picks (all of them, * or those the predicate names). See {@link isActedOnByOtherLayer}. + * `expanded`: preserve precedence for handlers that select nearby contacts, + * through the shared contact hit or their own pick window. * @returns {void} */ -export function registerPickOwner(layerId, predicate, { passive } = {}) { +export function registerPickOwner( + layerId, + predicate, + { passive, expanded = false } = {}, +) { if (!layerId || typeof predicate !== 'function') return; _owners.set(layerId, predicate); + if (expanded) _expanded.add(layerId); + else _expanded.delete(layerId); if (passive === true || typeof passive === 'function') _passive.set(layerId, passive); else _passive.delete(layerId); @@ -80,6 +90,7 @@ export function registerPickOwner(layerId, predicate, { passive } = {}) { */ export function unregisterPickOwner(layerId) { _owners.delete(layerId); + _expanded.delete(layerId); _passive.delete(layerId); } @@ -125,12 +136,18 @@ export function isOwnedByOtherLayer(layerId, pickedId) { * painted over a passive pick (a flight trail) is still the card's click. * @param {string} layerId - The asking layer's id (excluded from the scan). * @param {string} pickedId - Picked primitive/entity id. + * @param {{expanded?: boolean}} [options] A nearby rather than exact hit: + * only owners whose handlers select nearby contacts take precedence. * @returns {boolean} */ -export function isActedOnByOtherLayer(layerId, pickedId) { +export function isActedOnByOtherLayer( + layerId, + pickedId, + { expanded = false } = {}, +) { if (!pickedId) return false; for (const [ownerId, predicate] of _owners) { - if (ownerId === layerId) continue; + if (ownerId === layerId || (expanded && !_expanded.has(ownerId))) continue; try { if (!predicate(pickedId)) continue; const passive = _passive.get(ownerId); diff --git a/src/data/pickRegistry.test.mjs b/src/data/pickRegistry.test.mjs index bcc1876f07..1a27752646 100644 --- a/src/data/pickRegistry.test.mjs +++ b/src/data/pickRegistry.test.mjs @@ -158,6 +158,40 @@ test('ownership: passive owners still own their picks but act on none of them', assert.equal(isActedOnByOtherLayer('cards', 'route:line'), false); assert.equal(isActedOnByOtherLayer('cards', 'route:step:3'), true); assert.equal(isActedOnByOtherLayer('cards', 'plane:1'), true); + assert.equal( + isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }), + false, + ); + registerPickOwner('test-plane', (id) => id === 'plane:1', { + expanded: true, + }); + assert.equal( + isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }), + true, + ); + registerPickOwner('test-plane', (id) => id === 'plane:1', { + expanded: true, + passive: true, + }); + assert.equal( + isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }), + false, + ); + registerPickOwner('test-plane', (id) => id === 'plane:1'); + assert.equal( + isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }), + false, + ); + registerPickOwner('test-plane', (id) => id === 'plane:1', { + expanded: true, + }); + unregisterPickOwner('test-plane'); + registerPickOwner('test-plane', (id) => id === 'plane:1'); + assert.equal( + isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }), + false, + ); + assert.equal( isActedOnByOtherLayer('test-plane', 'plane:1'), false, diff --git a/src/data/pickedContext.js b/src/data/pickedContext.js index 8957c5a24b..ed23d093ff 100644 --- a/src/data/pickedContext.js +++ b/src/data/pickedContext.js @@ -1,6 +1,10 @@ import { getContextStore, isContextRecordActive } from './contextStore.js'; import { readEntityRecord } from './entityRecords.js'; -import { findPickOwner, resolvePickId } from './pickRegistry.js'; +import { + findPickOwner, + isActedOnByOtherLayer, + resolvePickId, +} from './pickRegistry.js'; /** * Resolve a pick (the contract's `Hit`, as `pickAt` in @@ -123,3 +127,25 @@ export function resolvePickedContext(picked, { dataManager = null } = {}) { altitudeM: finite(found?.altitudeM), }; } + +/** + * Whether a world-overlay card or label under a click keeps it from the item + * the click names, because that item's owner does not act on this hit: a + * passive owner (a directions route) acts on none, and an owner that acts + * only on exact hits (a fire, a camera) does not act on a coarse pointer's + * nearby contact (`hit` is not the exact `topHit`). The card's layer takes + * such a click (quake, fire, camera, vessel, news and wildlife cards act over + * it; an inert card, such as a selected drone-zone card, does nothing), so + * Context leaves the item; owners that act on it (an aircraft, a vessel, a + * directions step) still name it. + * @param {{hit?: object|null, topHit?: object|null}} click + * @param {boolean} underCard Whether a world-overlay entry is under it. + * @returns {boolean} + */ +export function cardKeepsClick(click, underCard) { + if (!underCard || !click?.hit) return false; + const pickId = resolvePickId(click.hit); + if (!pickId) return false; + const expanded = pickId !== resolvePickId(click.topHit ?? null); + return !isActedOnByOtherLayer('', pickId, { expanded }); +} diff --git a/src/data/pickedContext.test.mjs b/src/data/pickedContext.test.mjs index 4b452e0cab..70ed704b4d 100644 --- a/src/data/pickedContext.test.mjs +++ b/src/data/pickedContext.test.mjs @@ -12,7 +12,7 @@ globalThis.dispatchEvent ||= () => true; const { registerEntityContext } = await import('./contextStore.js'); const { registerPickOwner, unregisterPickOwner, findPickOwner } = await import('./pickRegistry.js'); -const { resolvePickedContext, pickedKindForLayer } = await import('./pickedContext.js'); +const { resolvePickedContext, pickedKindForLayer, cardKeepsClick } = await import('./pickedContext.js'); function manager({ enabled = new Set(['flights', 'local-datacenters']), modules = {} } = {}) { return { @@ -97,3 +97,53 @@ test('disabled layers, trails and empty picks never resolve', () => { assert.equal(resolvePickedContext(hit('unknown'), { dataManager: manager() }), null); assert.equal(pickedKindForLayer('ais-live-vessels'), 'vessel'); }); + +test('a card keeps a click from items whose layer does not act on that hit', (t) => { + registerPickOwner('test-fires', (id) => id === 'fire:1'); + registerPickOwner('test-planes', (id) => id === 'plane:1', { + expanded: true, + }); + registerPickOwner('test-route', (id) => id.startsWith('route:'), { + passive: (id) => !id.startsWith('route:step:'), + }); + t.after(() => { + unregisterPickOwner('test-fires'); + unregisterPickOwner('test-planes'); + unregisterPickOwner('test-route'); + }); + const fire = { set: 'fires:1', id: 'fire:1' }; + const plane = { set: 'planes:1', id: 'plane:1' }; + const exact = (hit) => ({ topHit: { ...hit }, hit }); + // A coarse tap: nothing exact, the contact found nearby. + const near = (hit) => ({ topHit: null, hit }); + assert.equal( + cardKeepsClick(near(fire), true), + true, + 'fires act only on exact hits', + ); + assert.equal(cardKeepsClick(near(plane), true), false, 'aircraft act nearby'); + assert.equal( + cardKeepsClick(near(fire), false), + false, + 'open map: Context names it', + ); + assert.equal( + cardKeepsClick(exact(fire), true), + false, + "an exact fire is the fire's", + ); + const line = { set: 'route:1', id: 'route:line' }; + const step = { set: 'route:1', id: 'route:step:2' }; + // Every card layer acts over a passive route, so the card keeps the click. + assert.equal( + cardKeepsClick(exact(line), true), + true, + 'a route acts for nobody', + ); + assert.equal( + cardKeepsClick(exact(step), true), + false, + "a step is directions' own", + ); + assert.equal(cardKeepsClick({ topHit: null, hit: null }, true), false); +}); diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index fec21a0549..561fc503cc 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -28,6 +28,7 @@ export function createLifecycle({ registerPickOwner, unregisterPickOwner, isOwnedByOtherLayer, + isActedOnByOtherLayer, isCardBackground, } = services.picking; const { onFocusTargetAppear } = services.focus; @@ -429,7 +430,26 @@ export function createLifecycle({ typeof pickedId === 'string' && !isOwnedByOtherLayer?.('cctv', pickedId) && Boolean(isCardBackground?.(hit)); - if (pickedId !== null && !cardBackground) return; + // A passive owner's pick (a flight trail, a directions route) acts + // for nobody, so a live top CCTV card over it keeps the click. + const passiveUnderCard = + cardId && + typeof pickedId === 'string' && + Boolean(isActedOnByOtherLayer) && + isOwnedByOtherLayer?.('cctv', pickedId) && + !isActedOnByOtherLayer('cctv', pickedId); + if (pickedId !== null && !cardBackground && !passiveUnderCard) return; + // A coarse tap's touch contact (not the exact pick) that its layer + // acts on (an aircraft, a vessel, a radio station) is that layer's + // click, even under a card of ours. + const contactId = resolvePickId(event.hit ?? null); + if ( + cardId && + contactId && + contactId !== pickedId && + isActedOnByOtherLayer?.('cctv', contactId, { expanded: true }) + ) + return; if (cardHit && cardHit.sourceId !== CCTV_OVERLAY_SOURCE_ID) return; if (cardId) { activateCctvCameraFromWorldClick( diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index c1ffdb4da8..ea43a55990 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -84,7 +84,9 @@ test('world clicks respect the painted top card and registered card backgrounds' viewer.scene = { canvas: {}, pick: () => (picked ? { id: picked } : undefined), + drillPick: () => drilled.map((id) => ({ id })), }; + let drilled = []; const input = fakeInput(viewer); const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }; const foreignCard = { @@ -141,6 +143,8 @@ test('world clicks respect the painted top card and registered card backgrounds' lifecycle.detachViewListeners(); input.destroy(); picking.unregisterPickOwner('area-control'); + picking.unregisterPickOwner('test-trails'); + picking.unregisterPickOwner('test-planes'); picking.unregisterCardBackground('area-fixture'); }); await lifecycle.methods.init(viewer); @@ -190,6 +194,37 @@ test('world clicks respect the painted top card and registered card backgrounds' { ...drone, id: 'unregistered-local-entity' }, ]) click(hit, [ownCard], []); + // A passive owner's pick (a trail, a route) acts for nobody: the live top + // card keeps the click, and with no card the pick is not empty map. + const trail = { set: 'trails:1', id: 'gev-trail:fl-1:head', surface: false }; + picking.registerPickOwner('test-trails', (id) => id === trail.id, { + passive: true, + }); + click(trail, [ownCard], ['cam-1']); + click(trail, [], []); + click(trail, [foreignCard, ownCard], []); + picking.unregisterPickOwner('test-trails'); + // A coarse tap whose touch contact is an aircraft (a layer that acts on + // nearby contacts) is the aircraft's, even under a live CCTV card. + const previousMatch = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + picking.registerPickOwner('test-planes', (id) => id === 'plane:1', { + expanded: true, + }); + drilled = ['plane:1']; + click(null, [ownCard], []); + // With no card, the bare tap near the aircraft still deselects. + click(null, [], ['clear']); + // A contact whose layer acts only on exact hits leaves the card its tap. + picking.registerPickOwner('test-exact', (id) => id === 'exact:1'); + drilled = ['exact:1']; + click(null, [ownCard], ['cam-1']); + picking.unregisterPickOwner('test-exact'); + drilled = []; + click(null, [ownCard], ['cam-1']); + picking.unregisterPickOwner('test-planes'); + if (previousMatch) globalThis.matchMedia = previousMatch; + else delete globalThis.matchMedia; picking.registerPickOwner('area-control', (id) => id === drone.id); click(drone, [ownCard], []); picking.unregisterPickOwner('area-control'); diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 898ea6c9a5..3d3984376b 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -352,7 +352,11 @@ export function createEarthquakesLayer({ const pickId = picking.resolvePickId(hit); const actedOn = picking.isActedOnByOtherLayer ?? picking.isOwnedByOtherLayer; - if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId)) return; + // Exact-only handlers cannot act on a nearby touch hit. Compare ids, + // since the dispatcher may expose distinct objects for the same pick. + const expanded = + 'topHit' in click && picking.resolvePickId(click.topHit) !== pickId; + if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId, { expanded })) return; const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID, }); diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs index 528ff6fbe3..6a2b3bf808 100644 --- a/src/layers/earthquakes/selection.test.mjs +++ b/src/layers/earthquakes/selection.test.mjs @@ -4,6 +4,7 @@ import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import * as picking from '../../data/pickRegistry.js'; // Registers the shared `gev-trail:` owner as passive, as the app does. import '../../data/trailRenderer.js'; +import { createSelection as createFireSelection } from '../firms/selection.js'; import { fakeInput } from '../../input/testDoubles.mjs'; import { createDroneAirspaceLayer } from '../droneAirspace/index.js'; import { @@ -36,7 +37,10 @@ const quake = (id, extra = {}) => ({ }); /** A layer whose globe clicks, card hits and context store the test drives. */ -function harness(rows, { context = null, ripples = null } = {}) { +function harness( + rows, + { context = null, ripples = null, input: inputFactory = null } = {}, +) { let snapshot = rows; const handlers = []; const opened = []; @@ -50,41 +54,44 @@ function harness(rows, { context = null, ripples = null } = {}) { let foreignTop = null; const viewer = {}; const { draw } = bindFakeDraw(viewer); + const overlayHost = { + setEntries(sourceId, entries) { + if (sourceId === EARTHQUAKE_CARD_SOURCE_ID) cards.push(entries); + if (sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) labels.push(entries); + }, + setVisible: (sourceId, show) => visible.set(sourceId, show), + clearSource() {}, + // As the real host does, only an interactive entry painted now is hit. + hitTest(_x, _y, { sourceId } = {}) { + // Unfiltered, as the host answers: another layer's entry on top + // first, else this layer's own. + if (!sourceId) + return ( + foreignTop ?? + this.hitTest(_x, _y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID }) ?? + this.hitTest(_x, _y, { sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID }) + ); + const hit = overlayHits.get(sourceId); + const painted = + sourceId === EARTHQUAKE_CARD_SOURCE_ID ? cards.at(-1) : labels.at(-1); + const entry = painted?.find((e) => e.id === hit?.entryId); + return hit && entry?.interactive === true ? hit : null; + }, + }; const layer = createEarthquakesLayer({ source: { getSnapshot: async () => snapshot }, - overlayHost: { - setEntries(sourceId, entries) { - if (sourceId === EARTHQUAKE_CARD_SOURCE_ID) cards.push(entries); - if (sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) labels.push(entries); - }, - setVisible: (sourceId, show) => visible.set(sourceId, show), - clearSource() {}, - // As the real host does, only an interactive entry painted now is hit. - hitTest(_x, _y, { sourceId } = {}) { - // Unfiltered, as the host answers: another layer's entry on top - // first, else this layer's own. - if (!sourceId) - return ( - foreignTop ?? - this.hitTest(_x, _y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID }) ?? - this.hitTest(_x, _y, { sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID }) - ); - const hit = overlayHits.get(sourceId); - const painted = - sourceId === EARTHQUAKE_CARD_SOURCE_ID ? cards.at(-1) : labels.at(-1); - const entry = painted?.find((e) => e.id === hit?.entryId); - return hit && entry?.interactive === true ? hit : null; - }, - }, - input: () => ({ - onClick(callback) { - const handler = { callback, destroyed: false }; - handlers.push(handler); - return () => { - handler.destroyed = true; - }; - }, - }), + overlayHost, + input: + inputFactory ?? + (() => ({ + onClick(callback) { + const handler = { callback, destroyed: false }; + handlers.push(handler); + return () => { + handler.destroyed = true; + }; + }, + })), picking, context, ripples, @@ -108,6 +115,8 @@ function harness(rows, { context = null, ripples = null } = {}) { visible, focused, handlers, + overlayHost, + overlayHits, discs, setRows(next) { snapshot = next; @@ -657,7 +666,9 @@ test('a touch-expanded sibling hit takes precedence over a quake label', async ( h.layer.enable(h.viewer); await h.layer.update(h.viewer); h.clickDisc('ak1'); - picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); + picking.registerPickOwner('test-plane', (id) => id === 'plane-9', { + expanded: true, + }); h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', null, { set: 'flights:1', id: 'plane-9', @@ -931,3 +942,78 @@ test('quake card and label act over a flight trail and a directions route', asyn h.layer.destroy(); } }); + +test('coarse FIRMS near-misses leave quake overlays actionable; exact fire hits act once', async (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + let sceneHit = null; + const fireHit = { set: 'firms:test', id: 'fire:test' }; + let input; + const h = harness([quake('ak1')], { + input(viewer) { + viewer.scene = { + pick: () => (sceneHit ? { id: sceneHit } : null), + drillPick: () => [{ id: fireHit }], + }; + input ??= fakeInput(viewer); + return input.input; + }, + }); + const fire = { lat: 60, lon: -153, frp: 5, acqMs: 1, sensor: 'test' }; + const fireFocus = []; + const state = { + _viewer: h.viewer, + _icons: { id: fireHit.set }, + _pickIndexById: new Map([[fireHit.id, fire]]), + _fireByCardId: new Map(), + _contextIds: new Set(), + }; + const selection = createFireSelection({ + layerState: state, + services: { + picking, + context: {}, + focus: { requestWorldFocus: (x) => fireFocus.push(x) }, + }, + components: { + cards: { rebuildAmbientLabels() {} }, + model: { firePosition: () => ({ x: 1, y: 2, z: 3 }) }, + }, + config: { id: 'firms', name: 'FIRMS', overlayHost: h.overlayHost }, + feed: {}, + }); + try { + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + selection.installClickHandler(); + picking.registerPickOwner('firms', (id) => state._pickIndexById.has(id)); + h.overlayHits.set(EARTHQUAKE_OVERLAY_SOURCE_ID, { + sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID, + entryId: 'ak1', + }); + input.click(); + assert.equal(h.focused.length, 1, 'label acts on the exact miss'); + assert.equal(fireFocus.length, 0, 'nearby fire does not act'); + h.overlayHits.clear(); + h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, { + sourceId: EARTHQUAKE_CARD_SOURCE_ID, + entryId: 'earthquake-card:ak1', + }); + input.click(); + assert.equal(h.opened.length, 1, 'selected card opens once'); + assert.equal(fireFocus.length, 0); + sceneHit = fireHit; + input.click(); + assert.equal(fireFocus.length, 1, 'exact fire hit acts'); + assert.equal(h.opened.length, 1, 'card yields to the exact fire'); + } finally { + selection.removeClickHandler(); + picking.unregisterPickOwner('firms'); + h.layer.destroy(); + input?.destroy(); + } +}); diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index edbae6734b..d6bcdd9cc3 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -13,7 +13,8 @@ export function createSelection({ config, feed, }) { - const { resolvePickId, isOwnedByOtherLayer } = services.picking; + const { resolvePickId, isOwnedByOtherLayer, isActedOnByOtherLayer } = + services.picking; const { requestWorldFocus } = services.focus; const { selectEntityContext, @@ -42,14 +43,34 @@ export function createSelection({ } // A pick that belongs to a sibling layer (e.g. an aircraft) is not // "empty space" — leave the selection alone and let that layer handle it. + // A passive owner's pick (a flight trail, a directions route) acts for + // nobody, so a card of ours painted over it still takes the click. + let passivePick = false; if (picked) { const pickedId = resolvePickId(picked); - if (pickedId && isOwnedByOtherLayer(id, pickedId)) return; + if (pickedId && isOwnedByOtherLayer(id, pickedId)) { + passivePick = + Boolean(isActedOnByOtherLayer) && + !isActedOnByOtherLayer(id, pickedId); + if (!passivePick) return; + } } const cardHit = overlayHost.hitTest?.( event.screenPosition?.x, event.screenPosition?.y, ); + if (passivePick && cardHit?.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return; + // A coarse tap's touch contact (not the exact pick) that its layer acts + // on (an aircraft, a vessel, a radio station) is that layer's click, + // even under a card of ours. + const contactId = resolvePickId(event.hit ?? null); + if ( + cardHit && + contactId && + contactId !== resolvePickId(picked ?? null) && + isActedOnByOtherLayer?.(id, contactId, { expanded: true }) + ) + return; if (cardHit) { if (cardHit.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return; const carded = layerState._fireByCardId.get(cardHit.entryId); diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js index 790aad1495..f85260f735 100644 --- a/src/layers/flights/lifecycle.js +++ b/src/layers/flights/lifecycle.js @@ -134,6 +134,14 @@ export function createLifecycle({ registerPickOwner( 'flights', (pickedId) => flightState._icons?.has(pickedId) === true, + { + expanded: true, + // A click on the aircraft already tracked is ignored: for that one + // plane the layer acts on nothing, so a card over it keeps the tap. + passive: (pickedId) => + Boolean(flightState._trackedIcao) && + pickedId === flightState._trackedIcao, + }, ); const frame = findFrame(viewer); if (!flightState._preRenderRemove && frame) { diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js index 0389ef3f02..7c96171206 100644 --- a/src/layers/military/lifecycle.js +++ b/src/layers/military/lifecycle.js @@ -115,6 +115,14 @@ export function createLifecycle({ registerPickOwner( 'military', (pickedId) => flightState._icons?.has(pickedId) === true, + { + expanded: true, + // A click on the aircraft already tracked is ignored: for that one + // plane the layer acts on nothing, so a card over it keeps the tap. + passive: (pickedId) => + Boolean(flightState._trackedIcao) && + pickedId === flightState._trackedIcao, + }, ); // The flights layer suppresses its military duplicates while we render them setMilitaryLayerActive(true); diff --git a/src/layers/news/layer.test.mjs b/src/layers/news/layer.test.mjs index 0070b6b773..7ad0d9a8a1 100644 --- a/src/layers/news/layer.test.mjs +++ b/src/layers/news/layer.test.mjs @@ -5,11 +5,7 @@ import { fromDegrees } from '../../geo/ellipsoid.js'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; import { NEWS_KEY_PROVIDERS, createNewsLayer } from './index.js'; -import { - findPickOwner, - registerPickOwner, - unregisterPickOwner, -} from '../../data/pickRegistry.js'; +import { findPickOwner } from '../../data/pickRegistry.js'; // Registers the shared `gev-trail:` no-op owner, as the app does. import '../../data/trailRenderer.js'; import { getSelectedEntityContext } from '../../data/contextStore.js'; diff --git a/src/layers/radio/interaction.js b/src/layers/radio/interaction.js index cc129d491a..9e1b59f134 100644 --- a/src/layers/radio/interaction.js +++ b/src/layers/radio/interaction.js @@ -48,11 +48,26 @@ export function createInteraction({ RADIO_PICK_WINDOW_PX, )) { const stationId = stationFromPick(picked); - if (stationId) return stationId; + if (!stationId) continue; + // Found only through our wider window, not as the tap's touch contact: + // another layer's card or label painted here is that layer's click, + // since its handler never sees this window. + if (stationFromPick(event.hit) !== stationId && foreignCardAt(event)) + return null; + return stationId; } return null; } + /** Whether another layer's world-overlay card or label is under a click. */ + function foreignCardAt(event) { + const top = services.overlays?.hitTestWorldOverlay?.( + event.screenPosition?.x, + event.screenPosition?.y, + ); + return Boolean(top) && top.sourceId !== RADIO_OVERLAY_SOURCE_ID; + } + function radioPresentationAllowed() { if (!layerState._managerLifecyclePresentation) return layerState._enabled; return ( @@ -80,7 +95,9 @@ export function createInteraction({ function installInteraction() { if (!layerState._viewer || layerState._clickSubscription) return; - registerPickOwner('radio', (id) => id.startsWith(RADIO_PREFIX)); + registerPickOwner('radio', (id) => id.startsWith(RADIO_PREFIX), { + expanded: true, + }); const viewer = layerState._viewer; layerState._clickSubscription = inputFor(viewer).onClick((event) => { if (!radioPresentationAllowed()) return; diff --git a/src/layers/radio/interaction.test.mjs b/src/layers/radio/interaction.test.mjs index c88310bee9..40d2e48a37 100644 --- a/src/layers/radio/interaction.test.mjs +++ b/src/layers/radio/interaction.test.mjs @@ -62,3 +62,42 @@ test('a direct hit needs no drill, and another layer’s contact keeps its click }); assert.equal(pickedRadioStationAt(other), null); }); + +// A station found only through radio's wider window, not as the tap's own +// pick or its touch contact, sits under another layer's card or label: that +// layer acts and never sees this window, so radio leaves the click. +test('a window-only station yields to a card painted over it', () => { + let top = null; + const radio = createInteraction({ + state: { _stationById: new Map([['kexp', {}]]) }, + services: { + picking: { + resolvePickId: (picked) => picked?.id ?? null, + isOwnedByOtherLayer: () => false, + registerPickOwner() {}, + unregisterPickOwner() {}, + }, + overlays: { + setOverlaySourceVisible() {}, + hitTestWorldOverlay: () => top, + }, + }, + parts: { rendering: { radioStationIdFromPick } }, + }); + const station = hit('radio:kexp'); + const near = (contact = null) => ({ + ...clickEvent({ windowHits: [station] }), + hit: contact, + screenPosition: { x: 5, y: 5 }, + }); + assert.equal(radio.pickedRadioStationAt(near()), 'kexp', 'open map'); + top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }; + assert.equal(radio.pickedRadioStationAt(near()), null, 'under a quake card'); + assert.equal( + radio.pickedRadioStationAt(near(station)), + 'kexp', + 'the touch contact: the card yielded to the station', + ); + top = { sourceId: 'radio', entryId: 'radio:kexp' }; + assert.equal(radio.pickedRadioStationAt(near()), 'kexp', 'our own card'); +}); diff --git a/src/layers/streetLevel/selection.js b/src/layers/streetLevel/selection.js index 9e01729b62..1d7a673c23 100644 --- a/src/layers/streetLevel/selection.js +++ b/src/layers/streetLevel/selection.js @@ -24,7 +24,23 @@ export function createSelection({ state, parts }) { function onClick(event) { if (!state.viewer || !state.enabled) return; const hit = event.windowHit(CLICK_PICK_WINDOW_PX, CLICK_PICK_WINDOW_PX); - const route = parts.router.resolve(pickIdOf(hit)); + const windowId = pickIdOf(hit); + // A coarse tap's touch contact (event.hit) reaches farther than this + // window; a card or label over it yields to our item there, so it is ours. + const contact = event.hit; + const contactId = + contact && !contact.surface + ? pickIdOf({ drawHit: contact.set ? contact : null, id: event.id }) + : null; + let route = parts.router.resolve(windowId); + // Found only through our window, not as the contact (which is the exact + // hit whenever there is one): another layer's card or label painted here + // is that layer's click, since its handler never sees this window. + if (route && windowId !== contactId) { + const at = event.screenPosition; + if (state.services.overlayHit?.(at?.x, at?.y)) return; + } + if (!route && contactId) route = parts.router.resolve(contactId); // Not ours: the ground handler decides whether it is the map itself. if (!route) { parts.openAtGround?.({ surface: hit.surface, ground: groundOf(event) }); @@ -71,7 +87,12 @@ export function createSelection({ state, parts }) { if (state.clickSubscription) return; state.clickSubscription = inputFor(viewer).onClick(onClick); document.addEventListener('keydown', onKeyDown); - picking?.registerPickOwner?.(STREET_LEVEL_LAYER_ID, parts.router.ownsPick); + picking?.registerPickOwner?.(STREET_LEVEL_LAYER_ID, parts.router.ownsPick, { + expanded: true, + // The core's position marker is ours but selects nothing: a card over + // it keeps the tap. + passive: (id) => !parts.router.resolve(id)?.instance, + }); } function uninstall() { diff --git a/src/layers/streetLevel/selection.test.mjs b/src/layers/streetLevel/selection.test.mjs index 07f55b9e19..e1bc976f69 100644 --- a/src/layers/streetLevel/selection.test.mjs +++ b/src/layers/streetLevel/selection.test.mjs @@ -4,6 +4,7 @@ import * as Cesium from 'cesium'; import { createSelection } from './selection.js'; import { createPickRouter } from './pickRouter.js'; import { fakeInput } from '../../input/testDoubles.mjs'; +import * as pickRegistry from '../../data/pickRegistry.js'; /** The selection installed on a stand-in viewer, with what its clicks reach. */ function harness({ @@ -289,3 +290,137 @@ test('a click on a provider line hands it the ground under the click, measured o h.restore(); } }); + +// An image found only through Street Level's own window (not the exact pick) +// under another layer's card or label is that card's click: its layer never +// sees this window. +test('an item found only in our window yields to a card painted over it', () => { + let top = null; + const h = harness({ + services: { overlayHit: () => top }, + sceneExtras: { + pick: (_position, width = 3) => + width >= 9 ? { id: 'mly:img:near' } : null, + }, + }); + try { + h.click(); + assert.deepEqual(h.opened, ['near'], 'open map: the window finds it'); + top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }; + h.click(); + assert.deepEqual(h.opened, ['near'], 'under a card: the card keeps it'); + assert.equal(h.groundClicks.length, 0); + } finally { + h.restore(); + } +}); + +// A coarse tap's touch contact reaches farther than this window. A quake card +// or label over that contact yields to it, so Street Level takes it here. +test('a coarse touch contact beyond our window is ours to open', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const h = harness({ + services: { + picking: pickRegistry, + overlayHit: () => ({ sourceId: 'earthquake-card', entryId: 'q' }), + }, + sceneExtras: { + pick: () => null, + drillPick: () => [{ id: 'mly:img:contact' }], + }, + }); + try { + h.click(); + assert.deepEqual(h.opened, ['contact']); + assert.equal(h.groundClicks.length, 0); + } finally { + h.restore(); + } +}); + +// The exact hit or the touch contact is ours under a card too: a quake card +// or label yields to a Street Level owner's pick, so yielding back would +// leave the click dead. Line parts compare by the sequence they pick as. +test('an exact or contact hit on our line part acts under a card', (t) => { + const part = { + set: 'street-level:mapillary-coverage:1', + id: 'mly:seq:abc#2', + meta: { pick: 'mly:seq:abc' }, + }; + const card = () => ({ sourceId: 'earthquake-card', entryId: 'q' }); + const exact = harness({ services: { overlayHit: card } }); + try { + exact.scene.under = part; + exact.click(); + assert.deepEqual(exact.sequences.selects, ['abc'], 'mouse, exact part'); + } finally { + exact.restore(); + } + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const contact = harness({ + services: { picking: pickRegistry, overlayHit: card }, + sceneExtras: { + pick: (_position, width = 3) => (width >= 9 ? { id: part } : null), + drillPick: () => [{ id: part }], + }, + }); + try { + contact.click(); + assert.deepEqual(contact.sequences.selects, ['abc'], 'coarse contact'); + } finally { + contact.restore(); + } +}); + +// Our window catching another layer's item says nothing about our own touch +// contact beyond it: that contact is still ours under a card. +test('a contact of ours acts even when our window finds another item', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const h = harness({ + services: { + picking: pickRegistry, + overlayHit: () => ({ sourceId: 'earthquake-card', entryId: 'q' }), + }, + sceneExtras: { + pick: (_position, width = 3) => + width >= 9 ? { id: { set: 'flights:1', id: 'flight:9' } } : null, + drillPick: () => [{ id: 'mly:img:contact' }], + }, + }); + try { + h.click(); + assert.deepEqual(h.opened, ['contact']); + } finally { + h.restore(); + } +}); + +// The core's position marker is ours but selects nothing, so it is a passive +// pick: a card painted over it keeps the tap. Our images and lines act. +test('the position marker is a passive pick; our items act', () => { + const h = harness({ services: { picking: pickRegistry } }); + try { + const acted = (id) => + pickRegistry.isActedOnByOtherLayer('test-card', id, { expanded: true }); + assert.equal(pickRegistry.findPickOwner('sl:pos'), 'street-level'); + assert.equal(acted('sl:pos'), false, 'the marker acts for nobody'); + assert.equal(acted('mly:img:abc'), true, 'an image opens'); + } finally { + h.restore(); + } +}); diff --git a/src/layers/vessels/lifecycle.js b/src/layers/vessels/lifecycle.js index c9c7d3e344..5ebebd0970 100644 --- a/src/layers/vessels/lifecycle.js +++ b/src/layers/vessels/lifecycle.js @@ -192,8 +192,10 @@ export function createLifecycle({ }); } // Pick-ownership (H2): a vessel icon's pick id is its row id, the record's id. - registerPickOwner('ais-live-vessels', (pickedId) => - state.records.byId.has(pickedId), + registerPickOwner( + 'ais-live-vessels', + (pickedId) => state.records.byId.has(pickedId), + { expanded: true }, ); // Vessels are asked for by view, so ask again when the view moves away. removeViewListener(); diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index f236aebf7e..7a4821dc45 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -10,7 +10,8 @@ export function createSelection({ options, }) { const { state } = vesselState; - const { isOwnedByOtherLayer } = services.picking; + const { isOwnedByOtherLayer, isActedOnByOtherLayer, resolvePickId } = + services.picking; const { requestWorldFocus } = services.worldFocus; const { selectEntityContext, @@ -47,19 +48,46 @@ export function createSelection({ // `gev-trail:*` pick is also a no-op. Every other non-vessel pick — sibling // unowned scene picks dismiss the current vessel inspection. if (ownRecordPick && (!pickedId || !record)) return; - if (pickedId && !record && String(pickedId).startsWith('gev-trail:')) - return; + /** Whether this layer's own card is painted under the click. */ + const ownCardUnder = () => + vesselState._vesselOverlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + )?.sourceId === VESSEL_OVERLAY_SOURCE_ID; + // A passive owner's pick (a trail, a directions route) acts for nobody: + // a card of ours painted over it keeps the click; otherwise a no-op. + const passivePick = + Boolean(pickedId) && + !record && + (String(pickedId).startsWith('gev-trail:') || + (Boolean(isActedOnByOtherLayer) && + isOwnedByOtherLayer('ais-live-vessels', pickedId) && + !isActedOnByOtherLayer('ais-live-vessels', pickedId))); + if (passivePick && !ownCardUnder()) return; // A sibling layer already owns this click. Preserve the current vessel // selection and do not compete with its camera command. const siblingOwned = - pickedId && isOwnedByOtherLayer('ais-live-vessels', pickedId); + !passivePick && + pickedId && + isOwnedByOtherLayer('ais-live-vessels', pickedId); // Cyclone geometry is ambient context behind painted cards. Its handler // yields to the same foreground AIS hit. Keep moving-contact precedence // unchanged: those handlers may issue their own camera command. const cycloneBackground = siblingOwned && !isOwnedByOtherLayer('weather-cyclones', pickedId); - if (siblingOwned && !cycloneBackground) return; + if (siblingOwned && !cycloneBackground) { + // A coarse tap's nearby contact (not the exact pick) whose layer acts + // only on exact hits (a fire, a camera) does not take a tap on this + // layer's own card: that card keeps it. + const nearMissOfExactOnly = + isActedOnByOtherLayer && + resolvePickId?.(event.topHit ?? null) !== pickedId && + !isActedOnByOtherLayer('ais-live-vessels', pickedId, { + expanded: true, + }); + if (!nearMissOfExactOnly || !ownCardUnder()) return; + } // Cards are painted on a pointer-events:none canvas, so the scene pick is // usually terrain behind the card. Resolve against the host's current diff --git a/src/ui/entityContextBridge.js b/src/ui/entityContextBridge.js index eea7e72c29..cb1906f233 100644 --- a/src/ui/entityContextBridge.js +++ b/src/ui/entityContextBridge.js @@ -1,4 +1,4 @@ -import { resolvePickedContext } from '../data/pickedContext.js'; +import { cardKeepsClick, resolvePickedContext } from '../data/pickedContext.js'; import { followedOf, onFollowChanged } from '../data/followed.js'; import { fromDegreesInto } from '../geo/ellipsoid.js'; import { inputFor } from '../input/dispatcher.js'; @@ -315,6 +315,12 @@ export function installEntityContext({ dataManager: getDataManager(), }); if (identity) { + // A card or label painted over an item its layer does not act on here + // (a quake card beside a fire, or over a route) is the card's click. + const underCard = Boolean( + overlayHit?.(event.screenPosition?.x, event.screenPosition?.y), + ); + if (cardKeepsClick(event, underCard)) return; // These layers start following on their own click; following again // from here would fight them (the flights layer reads a second track // of the same plane as a click on empty map and lets go). diff --git a/src/ui/entityContextBridge.test.mjs b/src/ui/entityContextBridge.test.mjs new file mode 100644 index 0000000000..541350bd5a --- /dev/null +++ b/src/ui/entityContextBridge.test.mjs @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createPinia } from 'pinia'; +import { installEntityContext } from './entityContextBridge.js'; +import { useEntityCardStore } from './stores/entityCard.js'; +import { fakeInput } from '../input/testDoubles.mjs'; +import { + registerPickOwner, + unregisterPickOwner, +} from '../data/pickRegistry.js'; + +// A coarse tap that misses everything exactly finds a fire within the shared +// touch window. On open map Context names it; under a quake card or label the +// card takes the tap, since the fire layer acts only on exact hits; an exact +// hit on the fire is the fire's, under a card or not. +test('Context leaves a near-missed exact-only item to a card painted over it', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const fire = { set: 'test-fires:1', id: 'fire:1' }; + registerPickOwner('test-fires', (id) => id === fire.id); + t.after(() => unregisterPickOwner('test-fires')); + let exact = false; + const viewer = { + scene: { + pick: () => (exact ? { id: fire } : null), + drillPick: () => [{ id: fire }], + }, + }; + const input = fakeInput(viewer); + let cardOnTop = false; + const pinia = createPinia(); + const disconnect = installEntityContext({ + viewer, + getDataManager: () => ({ + isEnabled: () => true, + layers: new Map(), + getAll: () => [], + }), + pinia, + overlayHit: () => + cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null, + }); + t.after(() => { + disconnect(); + input.destroy(); + }); + const store = useEntityCardStore(pinia); + const named = []; + store.select = (identity) => named.push(identity.id); + const tap = () => { + named.length = 0; + input.click(); + return [...named]; + }; + assert.deepEqual(tap(), ['fire:1'], 'open map: Context names the fire'); + cardOnTop = true; + assert.deepEqual(tap(), [], 'under a card: the card keeps the tap'); + exact = true; + assert.deepEqual(tap(), ['fire:1'], 'an exact hit is the fire’s'); +}); + +// Every card layer acts over a passive owner's pick (a directions route), so +// Context leaves an exact route hit under a card to that card, and names it on +// open map as before. +test('Context leaves an exact passive route under a card to the card', (t) => { + const route = { set: 'test-route:1', id: 'route:line' }; + registerPickOwner('test-route', (id) => id.startsWith('route:'), { + passive: true, + }); + t.after(() => unregisterPickOwner('test-route')); + const viewer = { scene: { pick: () => ({ id: route }) } }; + const input = fakeInput(viewer); + let cardOnTop = false; + const pinia = createPinia(); + const disconnect = installEntityContext({ + viewer, + getDataManager: () => ({ + isEnabled: () => true, + layers: new Map(), + getAll: () => [], + }), + pinia, + overlayHit: () => + cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null, + }); + t.after(() => { + disconnect(); + input.destroy(); + }); + const named = []; + useEntityCardStore(pinia).select = (identity) => named.push(identity.id); + input.click(); + assert.deepEqual(named, ['route:line'], 'open map: Context names the route'); + cardOnTop = true; + input.click(); + assert.deepEqual(named, ['route:line'], 'under a card: the card keeps it'); +}); From 54fd3d3bed8a1ae950f2c38d67e587179bcf19da Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Tue, 17 Nov 2026 15:51:14 +0530 Subject: [PATCH 012/138] fix(picking): settle which layers act on a click when it resolves The flights and military layers treat the aircraft they already track as a passive pick, but they start tracking during the click itself. A card handler running later in the same click then saw the plane as passive and acted too: a quake card opened its source while the plane started tracking, and fire, CCTV and vessel cards could do the same. The pick registry now records the acting owners of a click's exact hit and touch contact when the dispatcher first resolves them, and the quake, FIRMS, CCTV, vessel and Context checks read that record for the rest of the click. Calls without a click keep the live lookup. --- docs/CURRENT-STATE.md | 10 ++- src/data/aisLiveVessels.test.mjs | 45 ++++++++++++- src/data/firmsInteraction.test.mjs | 32 ++++++++++ src/data/pickRegistry.js | 55 +++++++++++----- src/data/pickedContext.js | 2 +- src/data/pickedContext.test.mjs | 22 ++++++- src/input/dispatcher.js | 9 ++- src/layers/cctv/lifecycle.js | 7 ++- src/layers/cctv/lifecycle.test.mjs | 16 +++++ src/layers/earthquakes/index.js | 3 +- src/layers/earthquakes/selection.test.mjs | 77 +++++++++++++++++------ src/layers/firms/selection.js | 4 +- src/layers/vessels/selection.js | 5 +- 13 files changed, 239 insertions(+), 48 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f492bedce2..064fa13e44 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2067,9 +2067,13 @@ another layer's card or label painted over it, so a quake card or label beside one acts alone, with a mouse or a coarse pointer. Fire and CCTV cards in turn yield to a touch contact whose layer acts on it. The aircraft a layer already tracks and Street Level's position marker are passive picks, since a click on -either does nothing. Fire, CCTV and vessel cards, like the quake's, act over a -passive owner's pick (a flight trail, the directions route); with no card -there, that pick still leaves a selection alone. Context +either does nothing. The pick registry records which owners act on a click's +exact hit and touch contact when the click first reads them +(`rememberClickPickActions`), and every layer asks that record for the rest of +the click, so an aircraft that starts tracking during the click does not leave +it to a later card handler as well. Fire, CCTV and vessel cards, like the +quake's, act over a passive owner's pick (a flight trail, the directions +route); with no card there, that pick still leaves a selection alone. Context (`src/ui/entityContextBridge.js`) names what a click identifies, except under a world-overlay card or label when the item's owner does not act on that hit (`cardKeepsClick` in `src/data/pickedContext.js`): a passive route, or a fire diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs index 25747f257c..fc2c09a3f9 100644 --- a/src/data/aisLiveVessels.test.mjs +++ b/src/data/aisLiveVessels.test.mjs @@ -1012,7 +1012,12 @@ function makeCesiumEvent() { }; } -function installWireHarness(picked, stateOverrides = {}, sceneExtras = {}) { +function installWireHarness( + picked, + stateOverrides = {}, + sceneExtras = {}, + firstClick = null, +) { const hadWindow = Object.hasOwn(globalThis, 'window'); const hadDocument = Object.hasOwn(globalThis, 'document'); const priorWindow = globalThis.window; @@ -1041,6 +1046,8 @@ function installWireHarness(picked, stateOverrides = {}, sceneExtras = {}) { scene: { pick: () => picked, ...sceneExtras }, }; const input = fakeInput(viewer); + // A subscriber that runs before the layer's own (an aircraft layer). + if (firstClick) input.input.onClick(firstClick); // The camera port other layers follow through, with no pose to read; its // followChanged event counts who listens. const followChanged = makeCesiumEvent(); @@ -1993,6 +2000,42 @@ test('vessel interaction wire: a sibling-owned pick wins without selection mutat } }); +// The aircraft layer runs first and starts tracking the plane under the +// vessel's card, making it passive. The card reads the owners that acted +// when the click resolved, so it still yields: one action. +test('vessel interaction wire: a card yields to an aircraft that starts tracking in the same click', (t) => { + let tracked = null; + registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9', { + expanded: true, + passive: (pickedId) => pickedId === tracked, + }); + t.after(() => unregisterPickOwner('test-planes')); + const harness = installWireHarness( + { id: 'plane:9' }, + { selectedRecord: null }, + {}, + (event) => { + if (event.hit?.id === 'plane:9') tracked = 'plane:9'; + }, + ); + const requests = []; + harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) => + requests.push(event.detail), + ); + _setVesselOverlayHostForTest( + hostWithCardHit(`vessel:${harness.record.mmsi}`), + ); + try { + harness.handler.click({ position: { x: 10, y: 20 } }); + assert.equal(tracked, 'plane:9', 'the aircraft starts tracking'); + assert.equal(requests.length, 0, 'the vessel card yields'); + assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi ?? null, null); + } finally { + _setVesselOverlayHostForTest(null); + harness.cleanup(); + } +}); + // A trail acts for nobody: the vessel's card painted over it still selects, // and a bare trail pick stays a no-op that keeps the selection. test('vessel interaction wire: a card over a trail selects; a bare trail is a no-op', () => { diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index 0bdf158f98..026be0a877 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -64,6 +64,7 @@ function harness({ withGlobe = false, feed = null, drilled = null, + firstClick = null, } = {}) { const hadWindow = Object.hasOwn(globalThis, 'window'); const priorWindow = globalThis.window; @@ -137,6 +138,8 @@ function harness({ if (!withGlobe) layer.attachShellServices({ imageryHost: () => ({ kind: 'none' }) }); const input = fakeInput(viewer); + // A subscriber that runs before the layer's own (an aircraft layer). + if (firstClick) input.input.onClick(firstClick); // The LOD rebuild (and with it the context-registration sweep) is inert // without a data source, so tests that drive a real refresh need one. if (withDataSource) layer.init(viewer); @@ -576,6 +579,35 @@ test('a fire card keeps a tap whose contact does not act; bare taps still clear' } }); +// The aircraft layer runs first and starts tracking the plane it was clicked +// on, which makes that plane passive. The fire card painted over it reads +// the owners that acted when the click resolved, so it still yields. +test('a fire card yields to an aircraft that starts tracking in the same click', (t) => { + const fire = makeFire(); + let tracked = null; + registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9', { + expanded: true, + passive: (pickedId) => pickedId === tracked, + }); + t.after(() => unregisterPickOwner('test-planes')); + const h = harness({ + fires: [fire], + picked: { id: 'plane:9' }, + cardHit: `fire:${fireDetectionKey(fire)}`, + firstClick: (event) => { + if (event.hit?.id === 'plane:9') tracked = 'plane:9'; + }, + }); + try { + h.click(); + assert.equal(tracked, 'plane:9', 'the aircraft starts tracking'); + assert.equal(h.requests.length, 0, 'the fire card yields'); + assert.equal(h.layer.getSelectedInfo(), null); + } finally { + h.cleanup(); + } +}); + test('a stale card id resolves to nothing instead of an arbitrary fire', () => { const h = harness({ picked: { primitive: {}, content: {}, featureId: 0 }, diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js index b16264f71f..9b4ef36047 100644 --- a/src/data/pickRegistry.js +++ b/src/data/pickRegistry.js @@ -35,6 +35,8 @@ const _owners = new Map(); const _passive = new Map(); /** Owners whose click handlers also select nearby contacts. */ const _expanded = new Set(); +/** @type {WeakMap>} */ +const clickActions = new WeakMap(); /** * Layers whose shapes are background to any card painted over them: their * click handlers stand aside under a card, so the card's layer may act there. @@ -130,33 +132,58 @@ export function isOwnedByOtherLayer(layerId, pickedId) { return false; } +/** @param {string} pickedId @returns {Generator<[string, boolean]>} */ +function* actingPickOwners(pickedId) { + for (const [ownerId, predicate] of _owners) { + try { + if (!predicate(pickedId)) continue; + const passive = _passive.get(ownerId); + if (passive === true) continue; + if (typeof passive === 'function' && passive(pickedId)) continue; + yield [ownerId, _expanded.has(ownerId)]; + } catch { + // a broken predicate must never break click handling + } + } +} + +/** + * Hold the acting owners as soon as a click resolves a hit. A handler can + * start tracking the hit and make it passive before later handlers run. + * @param {object} click The shared dispatcher event. + * @param {import('../render/contract/query').Hit|null} hit The resolved hit. + */ +export function rememberClickPickActions(click, hit) { + const pickedId = resolvePickId(hit); + if (!pickedId) return; + let actions = clickActions.get(click); + if (!actions) clickActions.set(click, (actions = new Map())); + if (!actions.has(pickedId)) { + actions.set(pickedId, [...actingPickOwners(pickedId)]); + } +} + /** * True when some OTHER registered layer owns the picked id and acts on a * click on it: {@link isOwnedByOtherLayer} without passive owners. A card * painted over a passive pick (a flight trail) is still the card's click. * @param {string} layerId - The asking layer's id (excluded from the scan). * @param {string} pickedId - Picked primitive/entity id. - * @param {{expanded?: boolean}} [options] A nearby rather than exact hit: - * only owners whose handlers select nearby contacts take precedence. + * @param {{expanded?: boolean, click?: object}} [options] For a nearby hit, + * only expanded owners take precedence. Pass the shared click to use the + * acting owners from when it first resolved this hit. * @returns {boolean} */ export function isActedOnByOtherLayer( layerId, pickedId, - { expanded = false } = {}, + { expanded = false, click } = {}, ) { if (!pickedId) return false; - for (const [ownerId, predicate] of _owners) { - if (ownerId === layerId || (expanded && !_expanded.has(ownerId))) continue; - try { - if (!predicate(pickedId)) continue; - const passive = _passive.get(ownerId); - if (passive === true) continue; - if (typeof passive === 'function' && passive(pickedId)) continue; - return true; - } catch { - // a broken predicate must never break click handling - } + const owners = + clickActions.get(click)?.get(pickedId) ?? actingPickOwners(pickedId); + for (const [ownerId, selectsNearby] of owners) { + if (ownerId !== layerId && (!expanded || selectsNearby)) return true; } return false; } diff --git a/src/data/pickedContext.js b/src/data/pickedContext.js index ed23d093ff..803075244a 100644 --- a/src/data/pickedContext.js +++ b/src/data/pickedContext.js @@ -147,5 +147,5 @@ export function cardKeepsClick(click, underCard) { const pickId = resolvePickId(click.hit); if (!pickId) return false; const expanded = pickId !== resolvePickId(click.topHit ?? null); - return !isActedOnByOtherLayer('', pickId, { expanded }); + return !isActedOnByOtherLayer('', pickId, { expanded, click }); } diff --git a/src/data/pickedContext.test.mjs b/src/data/pickedContext.test.mjs index 70ed704b4d..6d147bfeaa 100644 --- a/src/data/pickedContext.test.mjs +++ b/src/data/pickedContext.test.mjs @@ -11,7 +11,7 @@ globalThis.CustomEvent ||= class CustomEvent { globalThis.dispatchEvent ||= () => true; const { registerEntityContext } = await import('./contextStore.js'); -const { registerPickOwner, unregisterPickOwner, findPickOwner } = await import('./pickRegistry.js'); +const { registerPickOwner, unregisterPickOwner, findPickOwner, rememberClickPickActions } = await import('./pickRegistry.js'); const { resolvePickedContext, pickedKindForLayer, cardKeepsClick } = await import('./pickedContext.js'); function manager({ enabled = new Set(['flights', 'local-datacenters']), modules = {} } = {}) { @@ -147,3 +147,23 @@ test('a card keeps a click from items whose layer does not act on that hit', (t) ); assert.equal(cardKeepsClick({ topHit: null, hit: null }, true), false); }); + +// An aircraft layer can start tracking the plane it was clicked on before +// Context runs, making that plane passive. Context reads the owners that +// acted when the click resolved, so the card over it does not keep the click. +test('a card keeps a click by the owners that acted when it resolved', (t) => { + let tracked = null; + registerPickOwner('test-planes', (id) => id === 'plane:9', { + expanded: true, + passive: (id) => id === tracked, + }); + t.after(() => unregisterPickOwner('test-planes')); + const plane = { set: 'planes:1', id: 'plane:9' }; + const click = { topHit: plane, hit: plane }; + rememberClickPickActions(click, plane); + tracked = 'plane:9'; + assert.equal(cardKeepsClick(click, true), false, 'the aircraft acted'); + // A click that resolves now sees the tracked plane as passive. + const later = { topHit: { ...plane }, hit: { ...plane } }; + assert.equal(cardKeepsClick(later, true), true); +}); diff --git a/src/input/dispatcher.js b/src/input/dispatcher.js index 7d4ea04606..6387a7a1c2 100644 --- a/src/input/dispatcher.js +++ b/src/input/dispatcher.js @@ -51,6 +51,7 @@ import { import { findPickOwner, pickContact, + rememberClickPickActions, resolvePickId, } from '../data/pickRegistry.js'; import { isPickedWorldPosition } from '../data/scenePick.js'; @@ -456,7 +457,9 @@ function createClickEvent(viewer, queryOf, at, gesture) { // The adapter's own pick of this click is the renderer's pass, held // now: read later, it would be another, of a scene drawn since. void native()?.native.pick; - return topHitOf(hit, () => native()?.foreign() ?? null); + const top = topHitOf(hit, () => native()?.foreign() ?? null); + rememberClickPickActions(this, top); + return top; }); }, get drawHit() { @@ -467,7 +470,7 @@ function createClickEvent(viewer, queryOf, at, gesture) { return once('hit', () => { const q = query(); if (!q) return this.topHit; - return pickContact(q, position, { + const hit = pickContact(q, position, { picked: this.topHit, // Everything drawn there, as the adapter sees it, so a contact // search stops at what is drawn over a contact outside the draw @@ -480,6 +483,8 @@ function createClickEvent(viewer, queryOf, at, gesture) { : this.drill(limit, width, height); }, }); + rememberClickPickActions(this, hit); + return hit; }); }, get id() { diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 561fc503cc..2e3da9c172 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -437,7 +437,7 @@ export function createLifecycle({ typeof pickedId === 'string' && Boolean(isActedOnByOtherLayer) && isOwnedByOtherLayer?.('cctv', pickedId) && - !isActedOnByOtherLayer('cctv', pickedId); + !isActedOnByOtherLayer('cctv', pickedId, { click: event }); if (pickedId !== null && !cardBackground && !passiveUnderCard) return; // A coarse tap's touch contact (not the exact pick) that its layer // acts on (an aircraft, a vessel, a radio station) is that layer's @@ -447,7 +447,10 @@ export function createLifecycle({ cardId && contactId && contactId !== pickedId && - isActedOnByOtherLayer?.('cctv', contactId, { expanded: true }) + isActedOnByOtherLayer?.('cctv', contactId, { + expanded: true, + click: event, + }) ) return; if (cardHit && cardHit.sourceId !== CCTV_OVERLAY_SOURCE_ID) return; diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index ea43a55990..cf1c3f98bd 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -88,6 +88,12 @@ test('world clicks respect the painted top card and registered card backgrounds' }; let drilled = []; const input = fakeInput(viewer); + // An aircraft layer that runs before ours and starts tracking the plane + // it was clicked on, which makes that plane passive mid-click. + let tracked = null; + input.input.onClick((event) => { + if (event.hit?.id === 'plane:9') tracked = 'plane:9'; + }); const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }; const foreignCard = { sourceId: 'earthquake-card', @@ -145,6 +151,7 @@ test('world clicks respect the painted top card and registered card backgrounds' picking.unregisterPickOwner('area-control'); picking.unregisterPickOwner('test-trails'); picking.unregisterPickOwner('test-planes'); + picking.unregisterPickOwner('test-tracking'); picking.unregisterCardBackground('area-fixture'); }); await lifecycle.methods.init(viewer); @@ -225,6 +232,15 @@ test('world clicks respect the painted top card and registered card backgrounds' picking.unregisterPickOwner('test-planes'); if (previousMatch) globalThis.matchMedia = previousMatch; else delete globalThis.matchMedia; + // The live card reads the owners that acted when the click resolved, so it + // yields to the aircraft even though tracking made it passive meanwhile. + picking.registerPickOwner('test-tracking', (id) => id === 'plane:9', { + expanded: true, + passive: (id) => id === tracked, + }); + click({ set: 'flights:1', id: 'plane:9', surface: false }, [ownCard], []); + assert.equal(tracked, 'plane:9', 'the aircraft started tracking'); + picking.unregisterPickOwner('test-tracking'); picking.registerPickOwner('area-control', (id) => id === drone.id); click(drone, [ownCard], []); picking.unregisterPickOwner('area-control'); diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 3d3984376b..93e715e03e 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -356,7 +356,8 @@ export function createEarthquakesLayer({ // since the dispatcher may expose distinct objects for the same pick. const expanded = 'topHit' in click && picking.resolvePickId(click.topHit) !== pickId; - if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId, { expanded })) return; + if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId, { expanded, click })) + return; const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID, }); diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs index 6a2b3bf808..65f82c8745 100644 --- a/src/layers/earthquakes/selection.test.mjs +++ b/src/layers/earthquakes/selection.test.mjs @@ -701,33 +701,70 @@ test("another layer's card over a quake disc takes the click, and the disc yield } }); -test("another layer's object under the quake card takes the click", async () => { - const h = harness([quake('ak1')]); - picking.registerPickOwner('test-plane', (id) => id === 'plane-9'); - try { +for (const coarse of [false, true]) { + test(`a quake card yields while an aircraft starts tracking (${coarse ? 'coarse' : 'exact'} hit)`, async (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: coarse }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const plane = { set: 'flights:1', id: 'plane-9' }; + let sceneHit = null; + let nearby = null; + let tracked = null; + let tracks = 0; + let input; + const h = harness([quake('ak1')], { + input(viewer) { + viewer.scene = { + pick: () => (sceneHit ? { id: sceneHit } : null), + drillPick: () => (nearby ? [{ id: nearby }] : []), + }; + input = fakeInput(viewer); + // The aircraft layer runs first and changes its passive predicate + // synchronously after reading the dispatched hit. + input.input.onClick((event) => { + const id = event.hit?.id; + if (id !== plane.id || tracked === id) return; + tracked = id; + tracks++; + }); + return input.input; + }, + }); + picking.registerPickOwner('test-plane', (id) => id === plane.id, { + expanded: true, + passive: (id) => id === tracked, + }); + t.after(() => { + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + input?.destroy(); + }); h.layer.enable(h.viewer); await h.layer.update(h.viewer); - h.clickDisc('ak1'); + sceneHit = { set: h.discs().spec.id, id: 'earthquake:ak1' }; + input.click(); const card = h.lastCard()[0]; - // The card is painted over a plane: the flight layer acts on the click, - // so the card neither opens its link nor changes. - overlayHitCard(h, card.id, { set: 'flights:1', id: 'plane-9' }); - assert.deepEqual(h.opened, []); + h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, { + sourceId: EARTHQUAKE_CARD_SOURCE_ID, + entryId: card.id, + }); + sceneHit = coarse ? null : plane; + nearby = coarse ? plane : null; + + input.click(); + assert.equal(tracks, 1, 'the aircraft starts tracking'); + assert.deepEqual(h.opened, [], 'the quake card yields for the whole click'); assert.equal(h.lastCard()[0].id, card.id, 'the card stays'); - // Over open ground the card opens the USGS page. - h.clickCard(card.id); + + input.click(); + assert.equal(tracks, 1, 'already tracking the aircraft'); assert.deepEqual(h.opened, [ 'https://earthquake.usgs.gov/earthquakes/eventpage/ak1', ]); - } finally { - picking.unregisterPickOwner('test-plane'); - h.layer.destroy(); - } -}); - -/** Click this layer's card with `hit` (another layer's object) under it. */ -function overlayHitCard(h, entryId, hit) { - h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, entryId, hit); + }); } for (const kind of ['card', 'label']) { diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index d6bcdd9cc3..6788cf64f4 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -51,7 +51,7 @@ export function createSelection({ if (pickedId && isOwnedByOtherLayer(id, pickedId)) { passivePick = Boolean(isActedOnByOtherLayer) && - !isActedOnByOtherLayer(id, pickedId); + !isActedOnByOtherLayer(id, pickedId, { click: event }); if (!passivePick) return; } } @@ -68,7 +68,7 @@ export function createSelection({ cardHit && contactId && contactId !== resolvePickId(picked ?? null) && - isActedOnByOtherLayer?.(id, contactId, { expanded: true }) + isActedOnByOtherLayer?.(id, contactId, { expanded: true, click: event }) ) return; if (cardHit) { diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index 7a4821dc45..1aba2248b5 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -62,7 +62,9 @@ export function createSelection({ (String(pickedId).startsWith('gev-trail:') || (Boolean(isActedOnByOtherLayer) && isOwnedByOtherLayer('ais-live-vessels', pickedId) && - !isActedOnByOtherLayer('ais-live-vessels', pickedId))); + !isActedOnByOtherLayer('ais-live-vessels', pickedId, { + click: event, + }))); if (passivePick && !ownCardUnder()) return; // A sibling layer already owns this click. Preserve the current vessel @@ -85,6 +87,7 @@ export function createSelection({ resolvePickId?.(event.topHit ?? null) !== pickedId && !isActedOnByOtherLayer('ais-live-vessels', pickedId, { expanded: true, + click: event, }); if (!nearMissOfExactOnly || !ownCardUnder()) return; } From 99bd0443cd0d19c6026cfc969373b4516ed4f68d Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Tue, 17 Nov 2026 17:18:27 +0530 Subject: [PATCH 013/138] fix(touch): keep radio and Street Level contacts under a card Under another layer's card, radio and Street Level yielded whenever their own pick window found an item that was not the tap's touch contact. If the contact was a different station or Street Level item of theirs, the card yielded to that contact too, and the tap did nothing. Under a card they now act on their own touch contact, and still yield when the contact is not theirs. On bare map the window keeps its precedence. --- docs/CURRENT-STATE.md | 4 ++- src/layers/radio/interaction.js | 8 +++--- src/layers/radio/interaction.test.mjs | 32 +++++++++++++++++++++++ src/layers/streetLevel/selection.js | 7 ++++- src/layers/streetLevel/selection.test.mjs | 30 +++++++++++++++++++++ 5 files changed, 76 insertions(+), 5 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 064fa13e44..712b3af4c0 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2064,7 +2064,9 @@ vessels act on that contact, and so do radio and Street Level, which also pick through their own windows (17 and 9 px). A station or Street Level item found only through that window, not as the exact hit or the touch contact, yields to another layer's card or label painted over it, so a quake card or label beside -one acts alone, with a mouse or a coarse pointer. Fire and CCTV cards in turn +one acts alone, with a mouse or a coarse pointer; under such a card, their own +touch contact stays theirs even when the window names another item. Fire and +CCTV cards in turn yield to a touch contact whose layer acts on it. The aircraft a layer already tracks and Street Level's position marker are passive picks, since a click on either does nothing. The pick registry records which owners act on a click's diff --git a/src/layers/radio/interaction.js b/src/layers/radio/interaction.js index 9e1b59f134..154652aed3 100644 --- a/src/layers/radio/interaction.js +++ b/src/layers/radio/interaction.js @@ -51,9 +51,11 @@ export function createInteraction({ if (!stationId) continue; // Found only through our wider window, not as the tap's touch contact: // another layer's card or label painted here is that layer's click, - // since its handler never sees this window. - if (stationFromPick(event.hit) !== stationId && foreignCardAt(event)) - return null; + // since its handler never sees this window. A station of ours that is + // the contact is still ours: that card yields to it. + const contactStationId = stationFromPick(event.hit); + if (contactStationId !== stationId && foreignCardAt(event)) + return contactStationId; return stationId; } return null; diff --git a/src/layers/radio/interaction.test.mjs b/src/layers/radio/interaction.test.mjs index 40d2e48a37..e11dd61bdf 100644 --- a/src/layers/radio/interaction.test.mjs +++ b/src/layers/radio/interaction.test.mjs @@ -101,3 +101,35 @@ test('a window-only station yields to a card painted over it', () => { top = { sourceId: 'radio', entryId: 'radio:kexp' }; assert.equal(radio.pickedRadioStationAt(near()), 'kexp', 'our own card'); }); + +// Under another layer's card, radio's window can name a different station +// from the tap's touch contact. The card yields to that contact, a station of +// ours, so radio acts on it instead of leaving the click dead. +test('under a card, the touch contact station is ours even when the window names another', () => { + const radio = createInteraction({ + state: { _stationById: new Map([['kexp', {}], ['kuow', {}]]) }, + services: { + picking: { + resolvePickId: (picked) => picked?.id ?? null, + isOwnedByOtherLayer: () => false, + registerPickOwner() {}, + unregisterPickOwner() {}, + }, + overlays: { + setOverlaySourceVisible() {}, + hitTestWorldOverlay: () => ({ + sourceId: 'earthquake-card', + entryId: 'earthquake-card:ak1', + }), + }, + }, + parts: { rendering: { radioStationIdFromPick } }, + }); + const tap = (contact) => ({ + ...clickEvent({ windowHits: [hit('radio:kexp')] }), + hit: contact, + screenPosition: { x: 5, y: 5 }, + }); + assert.equal(radio.pickedRadioStationAt(tap(hit('radio:kuow'))), 'kuow'); + assert.equal(radio.pickedRadioStationAt(tap(null)), null, 'no contact'); +}); diff --git a/src/layers/streetLevel/selection.js b/src/layers/streetLevel/selection.js index 1d7a673c23..9a7cfea8f5 100644 --- a/src/layers/streetLevel/selection.js +++ b/src/layers/streetLevel/selection.js @@ -36,9 +36,14 @@ export function createSelection({ state, parts }) { // Found only through our window, not as the contact (which is the exact // hit whenever there is one): another layer's card or label painted here // is that layer's click, since its handler never sees this window. + // An item of ours that is the contact is still ours: that card yields + // to it. if (route && windowId !== contactId) { const at = event.screenPosition; - if (state.services.overlayHit?.(at?.x, at?.y)) return; + if (state.services.overlayHit?.(at?.x, at?.y)) { + route = contactId ? parts.router.resolve(contactId) : null; + if (!route) return; + } } if (!route && contactId) route = parts.router.resolve(contactId); // Not ours: the ground handler decides whether it is the map itself. diff --git a/src/layers/streetLevel/selection.test.mjs b/src/layers/streetLevel/selection.test.mjs index e1bc976f69..db5304b8a0 100644 --- a/src/layers/streetLevel/selection.test.mjs +++ b/src/layers/streetLevel/selection.test.mjs @@ -424,3 +424,33 @@ test('the position marker is a passive pick; our items act', () => { h.restore(); } }); + +// Under another layer's card, our window can name a different item from the +// tap's touch contact. The card yields to that contact, an item of ours, so +// Street Level opens it instead of leaving the click dead. +test('under a card, the touch contact item is ours even when the window names another', (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const h = harness({ + services: { + picking: pickRegistry, + overlayHit: () => ({ sourceId: 'earthquake-card', entryId: 'q' }), + }, + sceneExtras: { + pick: (_position, width = 3) => + width >= 9 ? { id: 'mly:img:window' } : null, + drillPick: () => [{ id: 'mly:img:contact' }], + }, + }); + try { + h.click(); + assert.deepEqual(h.opened, ['contact']); + assert.equal(h.groundClicks.length, 0); + } finally { + h.restore(); + } +}); From fde5f95b45b90d16510fa9d24462f1442246ca09 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Tue, 17 Nov 2026 18:34:00 +0530 Subject: [PATCH 014/138] docs(changelog): add earthquake selection entry --- changelog.d/1781-earthquake-click-details.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 changelog.d/1781-earthquake-click-details.md diff --git a/changelog.d/1781-earthquake-click-details.md b/changelog.d/1781-earthquake-click-details.md new file mode 100644 index 0000000000..8dc909f6d0 --- /dev/null +++ b/changelog.d/1781-earthquake-click-details.md @@ -0,0 +1,7 @@ +- Make earthquake discs and magnitude labels selectable, with magnitude, USGS + class, depth, location, time and source details. Labels also fly to the quake; + the selected disc shows a fading gradient and bounded contour animation. + Prevent dead or duplicate taps across the affected overlay cards, nearby + contacts and passive trails/routes, including radio and Street Level pick + windows, and keep the Context panel from taking a card's click + (Manjunath, @manjunath22466, #1781). From 731228081771f32fdf9cd686615a36a72de552c8 Mon Sep 17 00:00:00 2001 From: manjunath22466 Date: Wed, 18 Nov 2026 19:19:41 +0530 Subject: [PATCH 015/138] fix(earthquakes): address review follow-ups on click arbitration A drifting touch tap or a cockpit-mode tap on a fire, quake or vessel card beside an aircraft did nothing: the cards deferred to the aircraft, whose click handler ignores such taps. Pick owners can now declare the clicks they ignore (registerPickOwner(..., { declinesClick })); flights and military decline a drag or a cockpit tap and CCTV declines any click that is not clean, so a card over them keeps that tap. Also from review: - the selected quake's contour rings sit on the ground the disc is draped on, re-read through the heights service while they paint; - a label's fly-to frames the whole disc for large quakes; - a quake that ages out of the feed clears its selection as evicted; - id-less quakes are named by their content, not their row; - the Bhote Koshi trigger-record callout opens its source on a click, as its keyboard action does, and yields like the other cards; - the card's place line is cut to 48 characters, its link hint shows only with an opener, and its accessible name carries depth, place and time; a link-less card's click and keyboard action fly to the quake; - camera trace comparison scales its tolerance with the value and wraps heading and roll. --- docs/CURRENT-STATE.md | 32 +++-- src/app/layers/earthquakeRipples.js | 48 +++++++- src/app/layers/earthquakeRipples.test.mjs | 32 +++++ src/app/layers/earthquakes.js | 4 + src/data/bhoteKoshiLocator.js | 53 +++++++++ src/data/bhoteKoshiLocator.test.mjs | 86 +++++++++++++ src/data/pickOwnerExpanded.test.mjs | 21 +++- src/data/pickRegistry.js | 29 ++++- src/i18n/locales/ar.json | 2 + src/i18n/locales/de.json | 2 + src/i18n/locales/es.json | 2 + src/i18n/locales/fr.json | 2 + src/i18n/locales/he.json | 2 + src/i18n/locales/it.json | 2 + src/i18n/locales/ja.json | 2 + src/i18n/locales/pt.json | 2 + src/i18n/locales/ru.json | 2 + src/i18n/locales/sv.json | 2 + src/i18n/locales/uk.json | 2 + src/i18n/locales/zh-CN.json | 2 + src/i18n/locales/zh-Hant.json | 2 + src/layers/cctv/lifecycle.js | 34 ++++-- src/layers/cctv/lifecycle.test.mjs | 39 +++++- src/layers/earthquakes/index.js | 51 ++++++-- src/layers/earthquakes/model.js | 64 ++++++++-- src/layers/earthquakes/records.js | 13 +- src/layers/earthquakes/records.test.mjs | 31 ++++- src/layers/earthquakes/selection.test.mjs | 139 +++++++++++++++++++++- src/layers/flights/lifecycle.js | 6 + src/layers/military/lifecycle.js | 6 + src/render/cesium/cameraGoldens.test.mjs | 25 +++- src/worldFocus.js | 16 ++- src/worldFocus.test.mjs | 23 ++++ 33 files changed, 702 insertions(+), 76 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 712b3af4c0..57f59afdaa 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -2047,14 +2047,20 @@ Clicking a quake's disc selects it; clicking its magnitude label (what a far view can hit) also flies the camera there through the world-focus request (`earthquake` framing in `src/worldFocus.js`). The selected quake shows a card (`describeEarthquake`): magnitude and USGS class (`M5.5 · Moderate`), a -six-step class meter with the depth band, place, UTC time and source; with a -USGS event id the card opens that event's page. The selection is also the +six-step class meter with the depth band, place (cut to 48 characters; the +card's accessible name carries all of it), UTC time and source; with a USGS +event id the card opens that event's page, and without one a click or its +keyboard action flies to the quake. The selection is also the shared context selection, so "what's selected" answers with it. Its disc is painted with a gradient fading to the outer circle and wavy contour lines -(shaped by the quake's id, never crossing) under the labels. The package takes -clicks, picking, context, focus, the opener, the painter and the translator by -injection (`src/app/layers/earthquakes.js`); without input and picking it draws -and takes no clicks, and its labels stay non-interactive. +(shaped by the quake's id, never crossing) under the labels, drawn at the +ground height the disc is draped on (read again, at most twice a second, while +they paint, as the ground loads under a label's fly-to). A label's +fly-to frames the whole disc, scaling its range from the disc's radius above +the M6 framing. The package takes clicks, picking, context, focus, the ground +height, the opener, the painter and the translator by injection +(`src/app/layers/earthquakes.js`); without input and picking it draws and takes +no clicks, and its labels stay non-interactive. On a coarse pointer, a nearby FIRMS or CCTV icon that requires an exact hit does not swallow a quake card or label tap, or a tap on a vessel's own card. Owners that pick nearby contacts register as `expanded` pick owners: flights, @@ -2069,13 +2075,19 @@ touch contact stays theirs even when the window names another item. Fire and CCTV cards in turn yield to a touch contact whose layer acts on it. The aircraft a layer already tracks and Street Level's position marker are passive picks, since a click on -either does nothing. The pick registry records which owners act on a click's -exact hit and touch contact when the click first reads them -(`rememberClickPickActions`), and every layer asks that record for the rest of +either does nothing, and the aircraft layers decline a tap that drifts past +the click travel or comes in cockpit mode (`declinesClick`), as CCTV declines +any click that is not clean, so a card over them keeps that tap. The pick +registry records which owners act on a click's exact hit and touch contact +when the click first reads them (`rememberClickPickActions`), and every layer +asks that record for the rest of the click, so an aircraft that starts tracking during the click does not leave it to a later card handler as well. Fire, CCTV and vessel cards, like the quake's, act over a passive owner's pick (a flight trail, the directions -route); with no card there, that pick still leaves a selection alone. Context +route); with no card there, that pick still leaves a selection alone. The +Bhote Koshi trigger-record callout (`src/data/bhoteKoshiLocator.js`) opens its +source on a click, as its keyboard action does, and yields in the same way: to +a drag, and to a layer that acts on its exact pick or touch contact. Context (`src/ui/entityContextBridge.js`) names what a click identifies, except under a world-overlay card or label when the item's owner does not act on that hit (`cardKeepsClick` in `src/data/pickedContext.js`): a passive route, or a fire diff --git a/src/app/layers/earthquakeRipples.js b/src/app/layers/earthquakeRipples.js index c761eee0fe..015a101189 100644 --- a/src/app/layers/earthquakeRipples.js +++ b/src/app/layers/earthquakeRipples.js @@ -74,6 +74,15 @@ const reducedMotion = () => { } }; +/** How often the rings re-read the ground height under the quake. */ +const HEIGHT_READ_INTERVAL_MS = 500; +/** + * A ground height the rings accept, in metres: the Dead Sea shore to above + * Everest. Anything else is a bad sample (a hit on something drawn above + * the ground, or a broken tile), and the rings stay where they are. + */ +const groundHeightOk = (h) => Number.isFinite(h) && h >= -500 && h <= 9000; + /** * The selected earthquake's contour lines, painted on the world overlay: * wavy closed lines, shaped by the quake's id (earthquakeContourShape), run @@ -220,9 +229,32 @@ export function createEarthquakeRipples({ ); } + /** + * Re-read the ground height under the quake, at most twice a second while + * painting: the ground loads and refines as the camera comes in, and the + * rings move onto it once it differs by more than a metre. + */ + function settleHeight() { + if (!target.heightAt) return; + const at = now(); + if (at - target.heightReadAt < HEIGHT_READ_INTERVAL_MS) return; + target.heightReadAt = at; + let height = null; + try { + height = target.heightAt(); + } catch { + height = null; + } + if (!groundHeightOk(height) || Math.abs(height - target.heightM) <= 1) + return; + target.heightM = height; + target.center = fromDegrees(target.lon, target.lat, height); + } + function paint(frame) { if (!target) return; const { ctx } = frame; + settleHeight(); const center = target.center; onScreen = false; if (frame.occluder?.isPointVisible?.(center) === false) return; @@ -309,7 +341,7 @@ export function createEarthquakeRipples({ /** * Run the contour lines around one quake, replacing any other. - * @param {{id: string, lon: number, lat: number, radiusM: number, color: string}} next + * @param {{id: string, lon: number, lat: number, heightM?: number, heightAt?: () => number|null, radiusM: number, color: string}} next * @param {{restart?: boolean}} [options] `restart: false` updates the * same quake in place (a feed refresh) without running it again. */ @@ -336,7 +368,19 @@ export function createEarthquakeRipples({ } target = { id: next.id, - center: fromDegrees(next.lon, next.lat), + // On the ground the disc is draped on: the height known now, then + // re-read while painting (see `settleHeight`), since a label's fly-to + // starts from far away, before that ground has loaded. + lon: next.lon, + lat: next.lat, + heightM: groundHeightOk(next.heightM) ? next.heightM : 0, + heightAt: typeof next.heightAt === 'function' ? next.heightAt : null, + heightReadAt: -Infinity, + center: fromDegrees( + next.lon, + next.lat, + groundHeightOk(next.heightM) ? next.heightM : 0, + ), radiusM: next.radiusM, color: next.color || 'rgb(255,165,0)', shape: earthquakeContourShape(next.id), diff --git a/src/app/layers/earthquakeRipples.test.mjs b/src/app/layers/earthquakeRipples.test.mjs index e97b9f00a8..1a7e047276 100644 --- a/src/app/layers/earthquakeRipples.test.mjs +++ b/src/app/layers/earthquakeRipples.test.mjs @@ -418,3 +418,35 @@ test('a refresh of the same quake does not run a settled selection again', () => assert.equal(h.frames.size, 1); h.ripples.dispose(); }); + +// The rings sit on the ground the disc is draped on. A label's fly-to starts +// far away, before that ground loads, so the painter reads the height again +// while it paints and moves the rings onto it. +test('the rings move onto the ground height once it loads', () => { + const h = harness(); + let ground = null; + h.ripples.show({ ...target, heightM: 0, heightAt: () => ground }); + h.advance(600); + const [lane] = h.lanes; + lane.painter(h.frame()); + const atSea = h.fills.at(-1).transform; + h.fills.length = 0; + ground = 4000; + h.advance(600); + lane.painter(h.frame()); + const onGround = h.fills.at(-1).transform; + assert.notDeepEqual(onGround, atSea, 'the centre moved up onto the ground'); + // A change of a metre or less, or an impossible height, leaves them put. + for (const next of [4000.5, 25000, -2000]) { + ground = next; + h.advance(600); + lane.painter(h.frame()); + assert.deepEqual(h.fills.at(-1).transform, onGround, String(next)); + } + // Reads are bounded: a second paint within the interval does not ask again. + let reads = 0; + h.ripples.show({ ...target, id: 'ak2', heightAt: () => (reads++, 4000) }); + lane.painter(h.frame()); + lane.painter(h.frame()); + assert.equal(reads, 1); +}); diff --git a/src/app/layers/earthquakes.js b/src/app/layers/earthquakes.js index dc56448d35..1862f4736e 100644 --- a/src/app/layers/earthquakes.js +++ b/src/app/layers/earthquakes.js @@ -7,6 +7,7 @@ import * as context from '../../data/contextStore.js'; import { isPointerFree } from '../../data/inputOwnership.js'; import { requestWorldFocus } from '../../worldFocus.js'; import { createEarthquakeRipples } from './earthquakeRipples.js'; +import { heightsOf } from '../../queries/heights.js'; import { formatDate, formatNumber, t } from '../../i18n/index.js'; const EVENT_TIME = Object.freeze({ @@ -40,6 +41,9 @@ export function createApplicationEarthquakes(options) { openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'), focus: { requestWorldFocus }, ripples: createEarthquakeRipples(), + // The loaded ground (terrain or tiles) the clamped disc is draped on. + groundHeight: (viewer, lon, lat) => + viewer ? heightsOf(viewer).now({ lon, lat }) : null, text: earthquakeCardText, ...options, }); diff --git a/src/data/bhoteKoshiLocator.js b/src/data/bhoteKoshiLocator.js index 81c3e3a196..20598df4b7 100644 --- a/src/data/bhoteKoshiLocator.js +++ b/src/data/bhoteKoshiLocator.js @@ -1,7 +1,11 @@ import { clearOverlaySource, + hitTestWorldOverlay, setOverlayEntries, } from '../overlays/worldOverlay.js'; +import { inputFor } from '../input/dispatcher.js'; +import { isActedOnByOtherLayer, resolvePickId } from './pickRegistry.js'; +import { isTrackingSelectionGesture } from './trackingClickGesture.js'; import { governorRequestRender } from '../renderGovernor.js'; import { drawOf, findCamera } from '../render/rendererOf.js'; import { hexColor } from '../render/color.js'; @@ -279,8 +283,12 @@ export function createBhoteKoshiLocatorLayer({ cancelFrame = (handle) => cancelAnimationFrame(handle), scheduleDelay = (callback, delayMs) => setTimeout(callback, delayMs), cancelDelay = (handle) => clearTimeout(handle), + input = inputFor, + hitTest = hitTestWorldOverlay, } = {}) { let _viewer = null; + // The globe click that opens an actionable callout of ours on top. + let _removeClick = null; const _serial = ++layerSerial; // Whether the layer draws: from enable until it is let go. let _drawing = false; @@ -1107,6 +1115,7 @@ export function createBhoteKoshiLocatorLayer({ renderPresentation(); registerDynamicCredit(viewer, BHOTE_KOSHI_LOCATOR_CREDIT); showOsmCredit(viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID); + installCalloutClick(viewer); requestRender('bhote-koshi-locator-callout'); try { @@ -1141,8 +1150,52 @@ export function createBhoteKoshiLocatorLayer({ } } + /** + * An actionable callout of ours (the trigger record's) is a card painted + * over the globe: a click on it opens its source, as its keyboard action + * does. Like the other cards, it leaves a drag alone and yields to a layer + * that acts on what is under it (an aircraft, a vessel): its exact pick, or + * a coarse tap's touch contact whose layer acts on nearby contacts. + */ + function installCalloutClick(viewer) { + if (_removeClick) return; + let clicks = null; + try { + clicks = input?.(viewer) ?? null; + } catch { + clicks = null; + } + _removeClick = + clicks?.onClick?.((event) => { + if (!_enabled || !isTrackingSelectionGesture(event.gesture)) return; + const top = hitTest?.(event.screenPosition?.x, event.screenPosition?.y); + if (top?.sourceId !== BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID) return; + const exactId = resolvePickId(event.topHit ?? null); + if ( + exactId && + isActedOnByOtherLayer(BHOTE_KOSHI_LOCATOR_LAYER_ID, exactId, { + click: event, + }) + ) + return; + const contactId = resolvePickId(event.hit ?? null); + if ( + contactId && + contactId !== exactId && + isActedOnByOtherLayer(BHOTE_KOSHI_LOCATOR_LAYER_ID, contactId, { + expanded: true, + click: event, + }) + ) + return; + if (typeof top.entry?.activate === 'function') top.entry.activate(); + }) ?? null; + } + async function disable() { hideOsmCredit(_viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID); + _removeClick?.(); + _removeClick = null; _enabled = false; _boundaryReady = false; _boundaryResolved = false; diff --git a/src/data/bhoteKoshiLocator.test.mjs b/src/data/bhoteKoshiLocator.test.mjs index a24afefee6..5c421ec6cb 100644 --- a/src/data/bhoteKoshiLocator.test.mjs +++ b/src/data/bhoteKoshiLocator.test.mjs @@ -11,6 +11,7 @@ import { import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js'; import * as Cesium from 'cesium'; import { setLocale } from '../i18n/index.js'; +import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js'; import { SceneDirector } from '../scenes/director.js'; import { createPlaybackClock } from '../director/clock.js'; import { createDefaultScenePacks } from '../scenes/packs/defaults.js'; @@ -1049,3 +1050,88 @@ test('Bhote Koshi locator layers draw sets of their own, and halos only as they assert.equal(await second.disable(), true); assert.equal(viewer._test.live().length, 0); }); + +// The trigger record's callout is an actionable card: the layers under it +// stand aside for it, so a click on it opens its source, as its keyboard +// action does; anything else on top is left alone. +test('a click on the locator callout runs its action', async () => { + const viewer = viewerFixture(); + let onClick = null; + let top = null; + const activated = []; + const layer = createBhoteKoshiLocatorLayer({ + overlayHost: overlayHostFixture(), + requestRender() {}, + ...nonRunningAnimation(), + input: () => ({ + onClick(callback) { + onClick = callback; + return () => { + onClick = null; + }; + }, + }), + hitTest: () => top, + }); + await layer.init(viewer); + await layer.enable(viewer); + const click = (extra = {}) => + onClick?.({ + screenPosition: { x: 5, y: 5 }, + gesture: { travelPx: 0, durationMs: 80 }, + topHit: null, + hit: null, + ...extra, + }); + top = { + sourceId: BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID, + entryId: 'bhote-koshi-trigger-record-callout', + entry: { activate: () => activated.push('trigger') }, + }; + click(); + assert.deepEqual(activated, ['trigger']); + top = { + sourceId: 'earthquake-card', + entry: { activate: () => activated.push('other') }, + }; + click(); + assert.deepEqual(activated, ['trigger'], 'another layer on top is its own'); + // A drag that ends on it is not a click on it. + top = { + sourceId: BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID, + entry: { activate: () => activated.push('trigger') }, + }; + click({ gesture: { travelPx: 30, durationMs: 80 } }); + assert.deepEqual(activated, ['trigger'], 'a drag does not open it'); + // An aircraft under it is that layer's click, exact or a touch contact. + registerPickOwner('test-planes', (id) => id === 'plane:1', { + expanded: true, + }); + try { + const plane = { set: 'planes:1', id: 'plane:1' }; + click({ topHit: plane, hit: plane }); + click({ topHit: null, hit: plane }); + assert.deepEqual(activated, ['trigger'], 'the aircraft takes it'); + } finally { + unregisterPickOwner('test-planes'); + } + // A layer that acts only on exact hits does not take a touch contact, and + // one that ignores this click (a long press on a camera) takes nothing: the + // callout keeps both. + registerPickOwner('test-cameras', (id) => id === 'cam:1', { + declinesClick: (event) => (event?.gesture?.durationMs ?? 0) > 400, + }); + try { + const cam = { set: 'cams:1', id: 'cam:1' }; + click({ topHit: null, hit: cam }); + assert.equal(activated.length, 2, 'a near miss of an exact-only camera'); + click({ topHit: cam, hit: cam, gesture: { travelPx: 0, durationMs: 900 } }); + assert.equal(activated.length, 3, 'a long press the camera ignores'); + click({ topHit: cam, hit: cam }); + assert.equal(activated.length, 3, 'a clean click on the camera is its own'); + } finally { + unregisterPickOwner('test-cameras'); + } + await layer.disable(); + assert.equal(onClick, null, 'disable removes the click handler'); +}); diff --git a/src/data/pickOwnerExpanded.test.mjs b/src/data/pickOwnerExpanded.test.mjs index 83ab4afa79..ea013e7ef6 100644 --- a/src/data/pickOwnerExpanded.test.mjs +++ b/src/data/pickOwnerExpanded.test.mjs @@ -51,10 +51,12 @@ function recordingPicking() { }; } -function withDocument(t) { +function withDocument(t, { cockpit = () => false } = {}) { const previous = globalThis.document; globalThis.document = { - body: { classList: { contains: () => false } }, + body: { + classList: { contains: (name) => name === 'cockpit-mode' && cockpit() }, + }, addEventListener() {}, removeEventListener() {}, }; @@ -73,7 +75,8 @@ for (const [name, layerId, create] of [ ['military', 'military', createMilitaryLifecycle], ]) { test(`${name} registers its aircraft as acting on nearby touch hits`, (t) => { - withDocument(t); + let cockpit = false; + withDocument(t, { cockpit: () => cockpit }); const { registered, services } = recordingPicking(); const flightState = stub({ _icons: { show: false, has: (id) => id === `${name}-1` }, @@ -92,6 +95,18 @@ for (const [name, layerId, create] of [ lifecycle.enable({}); assert.equal(registered.get(layerId)?.expanded, true); assert.equal(actsOnNearbyHit(`${name}-1`), true); + // The handler ignores a dragged tap and any tap in cockpit mode, so the + // aircraft acts on neither click. + const nearby = (gesture) => + picking.isActedOnByOtherLayer('earthquakes', `${name}-1`, { + expanded: true, + click: { gesture }, + }); + assert.equal(nearby({ travelPx: 0, durationMs: 80 }), true, 'a tap'); + assert.equal(nearby({ travelPx: 12, durationMs: 80 }), false, 'a drag'); + cockpit = true; + assert.equal(nearby({ travelPx: 0, durationMs: 80 }), false, 'cockpit'); + cockpit = false; // A click on the aircraft already tracked is ignored, so it is passive. flightState._trackedIcao = `${name}-1`; assert.equal(actsOnNearbyHit(`${name}-1`), false); diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js index 9b4ef36047..815aac0536 100644 --- a/src/data/pickRegistry.js +++ b/src/data/pickRegistry.js @@ -35,6 +35,12 @@ const _owners = new Map(); const _passive = new Map(); /** Owners whose click handlers also select nearby contacts. */ const _expanded = new Set(); +/** + * Owners whose click handlers act on none of their picks for some clicks + * (aircraft layers ignore a dragged tap, or any tap in cockpit mode). + * @type {Map boolean>} + */ +const _declines = new Map(); /** @type {WeakMap>} */ const clickActions = new WeakMap(); /** @@ -64,20 +70,25 @@ export function resolvePickId(hit) { * @param {string} layerId - Owning layer id (e.g. 'flights'). * @param {(pickedId: string) => boolean} predicate - Returns true when the * picked primitive/entity id belongs to this layer. - * @param {{passive?: boolean | ((pickedId: string) => boolean), expanded?: boolean}} [options] + * @param {{passive?: boolean | ((pickedId: string) => boolean), expanded?: boolean, declinesClick?: (click: object) => boolean}} [options] * `passive`: the layer never acts on a click on these picks (all of them, * or those the predicate names). See {@link isActedOnByOtherLayer}. * `expanded`: preserve precedence for handlers that select nearby contacts, * through the shared contact hit or their own pick window. + * `declinesClick`: true for a click the layer's handler ignores whatever it + * picked (a dragged tap); for that click its picks act for nobody. * @returns {void} */ export function registerPickOwner( layerId, predicate, - { passive, expanded = false } = {}, + { passive, expanded = false, declinesClick } = {}, ) { if (!layerId || typeof predicate !== 'function') return; _owners.set(layerId, predicate); + if (typeof declinesClick === 'function') + _declines.set(layerId, declinesClick); + else _declines.delete(layerId); if (expanded) _expanded.add(layerId); else _expanded.delete(layerId); if (passive === true || typeof passive === 'function') @@ -93,6 +104,7 @@ export function registerPickOwner( export function unregisterPickOwner(layerId) { _owners.delete(layerId); _expanded.delete(layerId); + _declines.delete(layerId); _passive.delete(layerId); } @@ -132,11 +144,16 @@ export function isOwnedByOtherLayer(layerId, pickedId) { return false; } -/** @param {string} pickedId @returns {Generator<[string, boolean]>} */ -function* actingPickOwners(pickedId) { +/** + * @param {string} pickedId + * @param {object} [click] The click being arbitrated, if any. + * @returns {Generator<[string, boolean]>} + */ +function* actingPickOwners(pickedId, click) { for (const [ownerId, predicate] of _owners) { try { if (!predicate(pickedId)) continue; + if (click && _declines.get(ownerId)?.(click)) continue; const passive = _passive.get(ownerId); if (passive === true) continue; if (typeof passive === 'function' && passive(pickedId)) continue; @@ -159,7 +176,7 @@ export function rememberClickPickActions(click, hit) { let actions = clickActions.get(click); if (!actions) clickActions.set(click, (actions = new Map())); if (!actions.has(pickedId)) { - actions.set(pickedId, [...actingPickOwners(pickedId)]); + actions.set(pickedId, [...actingPickOwners(pickedId, click)]); } } @@ -181,7 +198,7 @@ export function isActedOnByOtherLayer( ) { if (!pickedId) return false; const owners = - clickActions.get(click)?.get(pickedId) ?? actingPickOwners(pickedId); + clickActions.get(click)?.get(pickedId) ?? actingPickOwners(pickedId, click); for (const [ownerId, selectsNearby] of owners) { if (ownerId !== layerId && (!expanded || selectsNearby)) return true; } diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 1b23b2b88a..a663ecb5c1 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -3645,6 +3645,8 @@ "Source: {value}": "المصدر: {value}", "Click the card to open EMODnet ↗": "انقر على البطاقة لفتح EMODnet ↗", "Click the card to open the source ↗": "انقر على البطاقة لفتح المصدر ↗", + "Open the source for {title}, {details}": "فتح مصدر «{title}»، {details}", + "Focus earthquake {title}, {details}": "التركيز على الزلزال {title}، {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata غير متاح؛ يُعرض EMODnet فقط", "EMODnet unavailable; showing Wikidata only": "EMODnet غير متاح؛ يُعرض Wikidata فقط", "Shipwrecks unavailable": "بيانات حطام السفن غير متاحة", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 4b132bdc95..0a95dbeb73 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -3325,6 +3325,8 @@ "Source: {value}": "Quelle: {value}", "Click the card to open EMODnet ↗": "Eintrag anklicken, um EMODnet zu öffnen ↗", "Click the card to open the source ↗": "Eintrag anklicken, um die Quelle zu öffnen ↗", + "Open the source for {title}, {details}": "Quelle für {title} öffnen, {details}", + "Focus earthquake {title}, {details}": "Erdbeben {title} fokussieren, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata nicht verfügbar; nur EMODnet wird angezeigt", "EMODnet unavailable; showing Wikidata only": "EMODnet nicht verfügbar; nur Wikidata wird angezeigt", "Shipwrecks unavailable": "Schiffswracks nicht verfügbar", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 17d5fa7f42..f47660ae32 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -3405,6 +3405,8 @@ "Source: {value}": "Fuente: {value}", "Click the card to open EMODnet ↗": "Haz clic en la tarjeta para abrir EMODnet ↗", "Click the card to open the source ↗": "Haz clic en la tarjeta para abrir la fuente ↗", + "Open the source for {title}, {details}": "Abrir la fuente de {title}, {details}", + "Focus earthquake {title}, {details}": "Enfocar el terremoto {title}, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata no disponible; solo se muestra EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet no disponible; solo se muestra Wikidata", "Shipwrecks unavailable": "Naufragios no disponibles", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 821ea7d78d..d233a74773 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -3405,6 +3405,8 @@ "Source: {value}": "Source : {value}", "Click the card to open EMODnet ↗": "Cliquez sur la fiche pour ouvrir EMODnet ↗", "Click the card to open the source ↗": "Cliquez sur la fiche pour ouvrir la source ↗", + "Open the source for {title}, {details}": "Ouvrir la source de {title}, {details}", + "Focus earthquake {title}, {details}": "Centrer sur le séisme {title}, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata indisponible ; seul EMODnet est affiché", "EMODnet unavailable; showing Wikidata only": "EMODnet indisponible ; seul Wikidata est affiché", "Shipwrecks unavailable": "Épaves indisponibles", diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index d8f6d5e082..e2d65f7942 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -3531,6 +3531,8 @@ "Click the card to open EMODnet ↗": "לחץ על הכרטיס כדי לפתוח את EMODnet ↗", "Click the card to open the article ↗": "לחץ על הכרטיס כדי לפתוח את הערך ↗", "Click the card to open the source ↗": "לחץ על הכרטיס כדי לפתוח את המקור ↗", + "Open the source for {title}, {details}": "פתיחת המקור של {title}, {details}", + "Focus earthquake {title}, {details}": "התמקדות ברעידת האדמה {title}, {details}", "All years": "כל השנים", "Period": "תקופה", "From": "מ-", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 99a74ffc61..c166ddf76a 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -3405,6 +3405,8 @@ "Source: {value}": "Fonte: {value}", "Click the card to open EMODnet ↗": "Fai clic sulla scheda per aprire EMODnet ↗", "Click the card to open the source ↗": "Fai clic sulla scheda per aprire la fonte ↗", + "Open the source for {title}, {details}": "Apri la fonte di {title}, {details}", + "Focus earthquake {title}, {details}": "Inquadra il terremoto {title}, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata non disponibile; solo EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet non disponibile; solo Wikidata", "Shipwrecks unavailable": "Relitti non disponibili", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index f52bf611a8..d9859b0e0e 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -3245,6 +3245,8 @@ "Source: {value}": "出典:{value}", "Click the card to open EMODnet ↗": "カードをクリックしてEMODnetを開く ↗", "Click the card to open the source ↗": "カードをクリックして出典を開く ↗", + "Open the source for {title}, {details}": "{title}のソースを開く({details})", + "Focus earthquake {title}, {details}": "地震{title}にフォーカス({details})", "Wikidata unavailable; showing EMODnet only": "Wikidataを利用できません。EMODnetのみ表示しています", "EMODnet unavailable; showing Wikidata only": "EMODnetを利用できません。Wikidataのみ表示しています", "Shipwrecks unavailable": "難破船データを利用できません", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 1381de0147..ec56549bb7 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -3405,6 +3405,8 @@ "Source: {value}": "Fonte: {value}", "Click the card to open EMODnet ↗": "Clique no cartão para abrir o EMODnet ↗", "Click the card to open the source ↗": "Clique no cartão para abrir a fonte ↗", + "Open the source for {title}, {details}": "Abrir a fonte de {title}, {details}", + "Focus earthquake {title}, {details}": "Focar terremoto {title}, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata indisponível; mostrando só o EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet indisponível; mostrando só o Wikidata", "Shipwrecks unavailable": "Naufrágios indisponíveis", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index eb90cce216..3b68b43589 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -3485,6 +3485,8 @@ "Source: {value}": "Источник: {value}", "Click the card to open EMODnet ↗": "Нажмите на карточку, чтобы открыть EMODnet ↗", "Click the card to open the source ↗": "Нажмите на карточку, чтобы открыть источник ↗", + "Open the source for {title}, {details}": "Открыть источник: {title}, {details}", + "Focus earthquake {title}, {details}": "Фокус на землетрясении {title}, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показан только EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet недоступен; показана только Wikidata", "Shipwrecks unavailable": "Данные о кораблекрушениях недоступны", diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 84eebf04f7..dd789b4f67 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -3244,6 +3244,8 @@ "Click the card to open EMODnet ↗": "Klicka på kortet för att öppna EMODnet ↗", "Click the card to open the article ↗": "Klicka på kortet för att öppna artikeln ↗", "Click the card to open the source ↗": "Klicka på kortet för att öppna källan ↗", + "Open the source for {title}, {details}": "Öppna källan för {title}, {details}", + "Focus earthquake {title}, {details}": "Fokusera på jordbävningen {title}, {details}", "All years": "Alla år", "Period": "Period", "From": "Från", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index e632648d41..e4d6fc35ce 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -3485,6 +3485,8 @@ "Source: {value}": "Джерело: {value}", "Click the card to open EMODnet ↗": "Клацніть картку, щоб відкрити EMODnet ↗", "Click the card to open the source ↗": "Клацніть картку, щоб відкрити джерело ↗", + "Open the source for {title}, {details}": "Відкрити джерело: {title}, {details}", + "Focus earthquake {title}, {details}": "Фокус на землетрусі {title}, {details}", "Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показано лише EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet недоступний; показано лише Wikidata", "Shipwrecks unavailable": "Дані про затонулі судна недоступні", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index d11d6b5545..892ca0215d 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -3245,6 +3245,8 @@ "Source: {value}": "来源:{value}", "Click the card to open EMODnet ↗": "点击卡片打开 EMODnet ↗", "Click the card to open the source ↗": "点击卡片打开来源 ↗", + "Open the source for {title}, {details}": "打开 {title} 的来源,{details}", + "Focus earthquake {title}, {details}": "聚焦地震 {title},{details}", "Wikidata unavailable; showing EMODnet only": "Wikidata 不可用;仅显示 EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet 不可用;仅显示 Wikidata", "Shipwrecks unavailable": "沉船数据不可用", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 34409cc9d8..f0ff358b85 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -3245,6 +3245,8 @@ "Source: {value}": "來源:{value}", "Click the card to open EMODnet ↗": "點擊卡片打開 EMODnet ↗", "Click the card to open the source ↗": "點擊卡片打開來源 ↗", + "Open the source for {title}, {details}": "打開 {title} 的來源,{details}", + "Focus earthquake {title}, {details}": "聚焦地震 {title},{details}", "Wikidata unavailable; showing EMODnet only": "Wikidata 不可用;僅顯示 EMODnet", "EMODnet unavailable; showing Wikidata only": "EMODnet 不可用;僅顯示 Wikidata", "Shipwrecks unavailable": "沉船數據不可用", diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 2e3da9c172..cd704d2617 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -5,6 +5,7 @@ import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js'; import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js'; import { inputFor } from '../../input/dispatcher.js'; +import { isTrackingClickGesture } from '../../data/trackingClickGesture.js'; import { GROUND_PRIOR_INIT_WAIT_MS, CALIBRATION_RANGE_FLOOR_M, @@ -509,19 +510,26 @@ export function createLifecycle({ layerState._lastUpdate = Date.now(); // Pick-ownership (H2): camera icons use the camera id directly; // coverage polyline entities use `cctv--` entity ids. - registerPickOwner('cctv', (pickedId) => { - if (layerState._recordById.has(pickedId)) return true; - if ( - typeof pickedId === 'string' && - pickedId.startsWith(GIZMO_ID_PREFIX) - ) - return true; - const coverage = - /^cctv-(.+)-(?:ray-tl|ray-tr|ray-br|ray-bl|cap|plane|plane-label)$/.exec( - pickedId, - ); - return Boolean(coverage && layerState._recordById.has(coverage[1])); - }); + registerPickOwner( + 'cctv', + (pickedId) => { + if (layerState._recordById.has(pickedId)) return true; + if ( + typeof pickedId === 'string' && + pickedId.startsWith(GIZMO_ID_PREFIX) + ) + return true; + const coverage = + /^cctv-(.+)-(?:ray-tl|ray-tr|ray-br|ray-bl|cap|plane|plane-label)$/.exec( + pickedId, + ); + return Boolean(coverage && layerState._recordById.has(coverage[1])); + }, + // The world click handler takes only clean clicks (see + // `bindCctvWorldClickGesture`), so a card over a camera keeps any + // other tap. + { declinesClick: (click) => !isTrackingClickGesture(click?.gesture) }, + ); if (!layerState._activeCameraId && layerState._records.length) { layerState._activeCameraId = parts.navigation.openingCameraId(); layerState._autoHopSuspended = false; diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index cf1c3f98bd..2ff86b0fff 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -136,8 +136,8 @@ test('world clicks respect the painted top card and registered card backgrounds' }; const services = { sprites: {}, - focus: {}, - render: {}, + focus: { onFocusTargetAppear: () => noop }, + render: { releaseContinuousRender: noop }, picking, activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) }, }; @@ -152,6 +152,7 @@ test('world clicks respect the painted top card and registered card backgrounds' picking.unregisterPickOwner('test-trails'); picking.unregisterPickOwner('test-planes'); picking.unregisterPickOwner('test-tracking'); + picking.unregisterPickOwner('test-exact'); picking.unregisterCardBackground('area-fixture'); }); await lifecycle.methods.init(viewer); @@ -214,6 +215,13 @@ test('world clicks respect the painted top card and registered card backgrounds' // A coarse tap whose touch contact is an aircraft (a layer that acts on // nearby contacts) is the aircraft's, even under a live CCTV card. const previousMatch = globalThis.matchMedia; + const restoreMatch = () => { + if (previousMatch) globalThis.matchMedia = previousMatch; + else delete globalThis.matchMedia; + }; + // Restored below for the fine-pointer clicks that follow; here too, so a + // failing assertion cannot leave the coarse pointer for later tests. + t.after(restoreMatch); globalThis.matchMedia = () => ({ matches: true }); picking.registerPickOwner('test-planes', (id) => id === 'plane:1', { expanded: true, @@ -230,8 +238,7 @@ test('world clicks respect the painted top card and registered card backgrounds' drilled = []; click(null, [ownCard], ['cam-1']); picking.unregisterPickOwner('test-planes'); - if (previousMatch) globalThis.matchMedia = previousMatch; - else delete globalThis.matchMedia; + restoreMatch(); // The live card reads the owners that acted when the click resolved, so it // yields to the aircraft even though tracking made it passive meanwhile. picking.registerPickOwner('test-tracking', (id) => id === 'plane:9', { @@ -253,4 +260,28 @@ test('world clicks respect the painted top card and registered card backgrounds' [foreignCard, ownCard], ['cam-1'], ); + // CCTV takes only clean clicks, so for a long press or a drag its cameras + // act for nobody: a card painted over one keeps that tap. + // Enable's own work is beside the point here: only its registration. + Object.assign(parts.cards, { + refreshAmbientCards: noop, + startCardFrameLoop: noop, + }); + parts.frames = { refreshProjectionImage: noop }; + Object.assign(parts.geometryQueue, { startGeometryLoadQueue: noop }); + parts.navigation = { openingCameraId: () => 'cam-1' }; + Object.assign(parts.projection, { + ensureProjectionRuntime: noop, + startProjectionLoop: noop, + }); + state._cctvOverlayHost.setVisible ??= noop; + lifecycle.methods.enable(); + t.after(() => picking.unregisterPickOwner('cctv')); + const acted = (gesture) => + picking.isActedOnByOtherLayer('earthquakes', 'cam-1', { + click: { gesture }, + }); + assert.equal(acted({ travelPx: 0, durationMs: 80 }), true, 'a clean click'); + assert.equal(acted({ travelPx: 0, durationMs: 900 }), false, 'a long press'); + assert.equal(acted({ travelPx: 20, durationMs: 80 }), false, 'a drag'); }); diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 93e715e03e..1389662a74 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -35,6 +35,8 @@ export const EARTHQUAKES_LAYER_ID = 'earthquakes'; export const EARTHQUAKE_CARD_SOURCE_ID = 'earthquake-card'; /** A disc's item id is this prefix and the event's stable id. */ const PICK_PREFIX = 'earthquake:'; +/** Fly-to range per metre of disc radius: 220 km frames an M6 (64 km). */ +const EARTHQUAKE_FOCUS_RANGE_PER_RADIUS = 3.5; /** The selected quake's flat fill, faint under the painted gradient. */ const SELECTED_DISC_ALPHA = 0.04; const CARD_HOST_OPTIONS = Object.freeze({ @@ -73,8 +75,12 @@ let instances = 0; * @param {{requestWorldFocus: (detail: object) => boolean}} [options.focus] * The camera transfer a clicked magnitude label asks for. * @param {{show: (target: {id: string, lon: number, lat: number, - * radiusM: number, color: string}) => void, hide: () => void}} [options.ripples] + * heightM?: number, heightAt?: () => number|null, radiusM: number, + * color: string}) => void, hide: () => void}} [options.ripples] * The selected quake's animated contour rings. + * @param {(viewer: object, lon: number, lat: number) => number|null} [options.groundHeight] + * The loaded ground height under a point, so the rings sit on the disc + * that is draped there; null (or no service) draws them at sea level. * @param {object} [options.text] Card formatters (see describeEarthquake). */ export function createEarthquakesLayer({ @@ -87,6 +93,7 @@ export function createEarthquakesLayer({ openExternal = null, focus = null, ripples = null, + groundHeight = null, text = undefined, } = {}) { if (typeof source?.getSnapshot !== 'function') @@ -189,12 +196,14 @@ export function createEarthquakesLayer({ function publishCard({ user = false } = {}) { const event = _selectedId ? _eventById.get(_selectedId) : null; if (!_enabled || !event) { - clearSelection(); + // A refresh that no longer carries the selected quake evicts it, as + // other feeds report; anything else is a deliberate clear. + clearSelection({ evicted: _enabled && Boolean(_selectedId) && !user }); return; } const { title, details, link, accessibilityLabel } = describeEarthquake( event, - text, + { ...text, canOpen: Boolean(openExternal) }, ); _selectedLink = link && openExternal ? link : null; const card = { @@ -222,6 +231,12 @@ export function createEarthquakesLayer({ openExternal(target); return true; }; + } else if (focus?.requestWorldFocus) { + // No source to open: the card's keyboard action flies to its quake, + // as a fire card's focuses its fire, so it stays in the action list. + const stableId = event.stableId; + card.accessibilityLabel = accessibilityLabel; + card.activate = () => selectAndFocus(stableId); } _selectedCardId = card.id; overlayHost.setEntries( @@ -232,11 +247,22 @@ export function createEarthquakesLayer({ overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, true); publishContext(event, user); fadeDisc(event.stableId); + let heightM = null; + try { + heightM = groundHeight?.(_viewer, event.lon, event.lat) ?? null; + } catch { + heightM = null; + } ripples?.show?.( { id: event.stableId, lon: event.lon, lat: event.lat, + heightM: Number.isFinite(heightM) ? heightM : 0, + // Read again as the ground loads: a label's fly-to starts far away. + heightAt: groundHeight + ? () => groundHeight(_viewer, event.lon, event.lat) + : null, radiusM: earthquakeDiscRadiusM(event.mag), color: depthAccent(event.depthKm || 0), }, @@ -284,10 +310,12 @@ export function createEarthquakesLayer({ } } - function clearContext() { + function clearContext({ evicted = false } = {}) { if (!context || !_contextId) return; try { - context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID); + context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID, { + evicted, + }); context.getContextStore().entities.delete(_contextId); } catch { // store unavailable: nothing to clean @@ -295,12 +323,12 @@ export function createEarthquakesLayer({ _contextId = null; } - function clearSelection() { + function clearSelection({ evicted = false } = {}) { const had = _selectedId || _selectedCardId; _selectedId = null; _selectedCardId = null; _selectedLink = null; - clearContext(); + clearContext({ evicted }); ripples?.hide?.(); fadeDisc(null); if (had) @@ -362,7 +390,11 @@ export function createEarthquakesLayer({ sourceId: EARTHQUAKE_CARD_SOURCE_ID, }); if (cardHit && cardHit.entryId === _selectedCardId) { + // The card's action, as its keyboard action: open the source, or + // with none, fly to the quake. if (_selectedLink) openExternal(_selectedLink); + else if (focus?.requestWorldFocus && _selectedId) + selectAndFocus(_selectedId); return; } // A magnitude label is what a far view (the whole globe) can click: @@ -399,6 +431,11 @@ export function createEarthquakesLayer({ id: `${PICK_PREFIX}${stableId}`, label: earthquakeMagnitudeTitle(event.mag), position: fromDegrees(event.lon, event.lat), + // The whole disc in view: the framing's range fits an M6 disc, so a + // larger one scales it (the framing stays the floor). + radiusM: earthquakeDiscRadiusM(event.mag), + rangeM: + earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS, }); return true; } diff --git a/src/layers/earthquakes/model.js b/src/layers/earthquakes/model.js index 228758c011..4e0abaf107 100644 --- a/src/layers/earthquakes/model.js +++ b/src/layers/earthquakes/model.js @@ -23,6 +23,12 @@ export const EARTHQUAKE_MARK_MAGNITUDE = 6; /** The longest place a timeline mark's label carries, ellipsis and all. */ const MARK_PLACE_LENGTH = 40; +/** + * The longest place line the detail card shows, ellipsis and all, so a long + * place or translation keeps the card inside a phone's width. The card's + * accessible name carries the whole place. + */ +const CARD_PLACE_LENGTH = 48; /** A magnitude as the map's labels show it: `M6.4`. */ export const earthquakeMagnitudeTitle = (magnitude) => @@ -163,43 +169,77 @@ const oneDecimal = (value) => String(Math.round(value * 10) / 10); * @param {(text: string, values?: object) => string} [text.t] Translator. * @param {(time: number) => string} [text.formatTime] An event time. * @param {(value: number) => string} [text.formatDepth] A depth in km. + * @param {boolean} [text.canOpen] Whether a link can be opened here (an + * opener is injected); without one the card offers no link to click. * @returns {{title: string, details: string[], link: string|null, - * accessibilityLabel: string}} + * accessibilityLabel: string}} `accessibilityLabel` names the card's + * action, with its details: opening the source, or focusing the quake. */ export function describeEarthquake( event, - { t = english, formatTime = utcMinute, formatDepth = oneDecimal } = {}, + { + t = english, + formatTime = utcMinute, + formatDepth = oneDecimal, + canOpen = true, + } = {}, ) { const details = []; + // What the card says, spoken: depth, the whole place, and the time. + const spoken = []; // Severity at a glance, right under the title: the class meter, then // where in the crust it broke. const glance = [earthquakeSeverityMeter(event?.mag)]; if (Number.isFinite(event?.depthKm)) { - glance.push( - `${earthquakeDepthBandName(event.depthKm, t)} · ${t('{km} km deep', { - km: formatDepth(event.depthKm), - })}`, - ); + const depth = `${earthquakeDepthBandName(event.depthKm, t)} · ${t( + '{km} km deep', + { km: formatDepth(event.depthKm) }, + )}`; + glance.push(depth); + spoken.push(depth); } details.push(glance.join(' ')); const place = typeof event?.place === 'string' ? event.place.replace(/\s+/g, ' ').trim() : ''; - if (place) details.push(place); - if (Number.isFinite(event?.time)) details.push(formatTime(event.time)); - details.push(t('Source: {value}', { value: 'USGS' })); + if (place) { + // Cut by characters, not UTF-16 units, so a pair is never split. + const chars = Array.from(place); + details.push( + chars.length > CARD_PLACE_LENGTH + ? `${chars + .slice(0, CARD_PLACE_LENGTH - 1) + .join('') + .trimEnd()}…` + : place, + ); + spoken.push(place); + } + if (Number.isFinite(event?.time)) { + const time = formatTime(event.time); + details.push(time); + spoken.push(time); + } + const source = t('Source: {value}', { value: 'USGS' }); + details.push(source); + // The source closes the spoken details, so they are never empty. + spoken.push(source); const link = earthquakeEventLink(event?.usgsId); - if (link) details.push(t('Click the card to open the source ↗')); + const opens = Boolean(link) && canOpen; + if (opens) details.push(t('Click the card to open the source ↗')); const title = `${earthquakeMagnitudeTitle(event?.mag)} · ${earthquakeSeverityName( event?.mag, t, )}`; + const summary = { title, details: spoken.join(', ') }; return { title, details, link, - accessibilityLabel: t('Open the source for {title}', { title }), + accessibilityLabel: opens + ? t('Open the source for {title}, {details}', summary) + : t('Focus earthquake {title}, {details}', summary), }; } diff --git a/src/layers/earthquakes/records.js b/src/layers/earthquakes/records.js index 397b4bb1c8..caaf8bc879 100644 --- a/src/layers/earthquakes/records.js +++ b/src/layers/earthquakes/records.js @@ -28,10 +28,15 @@ export function normalizeEarthquakeSnapshot(geojson) { return null; // A missing magnitude cannot establish that this event meets M2.5+. if (mag == null || mag < 2.5) continue; - const stableId = - feature.id == null || feature.id === '' - ? `event-${index + 1}` - : String(feature.id); + // An id-less event is named by what it is (time, position, depth and + // magnitude), not by its row, so a refresh that inserts a row keeps the + // selection on the same quake; a revision to any of those names a new + // one. Two id-less events that match exactly fall back to the row. + const idless = feature.id == null || feature.id === ''; + let stableId = idless + ? `event-${[properties.time ?? 'na', lon, lat, depthKm ?? 'na', mag].join(':')}` + : String(feature.id); + if (idless && ids.has(stableId)) stableId = `${stableId}:${index + 1}`; if (ids.has(stableId)) return null; ids.add(stableId); rows.push({ diff --git a/src/layers/earthquakes/records.test.mjs b/src/layers/earthquakes/records.test.mjs index cd7b6a8741..bc3447db2b 100644 --- a/src/layers/earthquakes/records.test.mjs +++ b/src/layers/earthquakes/records.test.mjs @@ -37,7 +37,7 @@ test('normalizeEarthquakeSnapshot parses valid GeoJSON earthquake features', () }); }); -test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is missing or blank', () => { +test('normalizeEarthquakeSnapshot names id-less events by their content, not their row', () => { const geojson = { features: [ { @@ -55,10 +55,35 @@ test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is mi const rows = normalizeEarthquakeSnapshot(geojson); assert.equal(rows.length, 2); - assert.equal(rows[0].stableId, 'event-1'); + assert.equal(rows[0].stableId, 'event-1711930000000:139.6917:35.6895:25:3.5'); assert.equal(rows[0].usgsId, null); - assert.equal(rows[1].stableId, 'event-2'); + assert.equal( + rows[1].stableId, + 'event-1711931000000:-70.6693:-33.4489:45.2:5.1', + ); assert.equal(rows[1].usgsId, ''); + // A row inserted ahead of them keeps each id-less quake's id, so a selected + // one stays selected across the refresh. + const inserted = normalizeEarthquakeSnapshot({ + features: [ + { + id: 'us7000new', + geometry: { type: 'Point', coordinates: [10, 20, 5] }, + properties: { mag: 4, place: 'New', time: 1711932000000 }, + }, + ...geojson.features, + ], + }); + assert.deepEqual( + inserted.map((row) => row.stableId).slice(1), + rows.map((row) => row.stableId), + ); + // Two id-less events that match exactly stay apart. + const twins = normalizeEarthquakeSnapshot({ + features: [geojson.features[0], geojson.features[0]], + }); + assert.equal(twins.length, 2); + assert.notEqual(twins[0].stableId, twins[1].stableId); }); test('normalizeEarthquakeSnapshot filters events below M2.5 without dropping the feed', () => { diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs index 65f82c8745..496908b19a 100644 --- a/src/layers/earthquakes/selection.test.mjs +++ b/src/layers/earthquakes/selection.test.mjs @@ -39,7 +39,12 @@ const quake = (id, extra = {}) => ({ /** A layer whose globe clicks, card hits and context store the test drives. */ function harness( rows, - { context = null, ripples = null, input: inputFactory = null } = {}, + { + context = null, + ripples = null, + groundHeight = null, + input: inputFactory = null, + } = {}, ) { let snapshot = rows; const handlers = []; @@ -95,6 +100,7 @@ function harness( picking, context, ripples, + groundHeight, pointer: { isPointerFree: () => true }, openExternal: (url) => opened.push(url), focus: { @@ -179,7 +185,10 @@ test('clicking a quake disc shows its detail card; empty map clears it', async ( 'Click the card to open the source ↗', ]); assert.equal(card.interactive, true); - assert.equal(card.accessibilityLabel, 'Open the source for M4.1 · Light'); + assert.equal( + card.accessibilityLabel, + 'Open the source for M4.1 · Light, Intermediate · 112.4 km deep, 42 km W of Fixture, Alaska, 2026-11-13 15:37 UTC, Source: USGS', + ); assert.equal(h.visible.get(EARTHQUAKE_CARD_SOURCE_ID), true); h.click(null); @@ -209,11 +218,17 @@ test('a quake with no USGS id gets a card with no link', async () => { h.clickDisc('event-1'); const [card] = h.lastCard(); assert.equal(card.interactive, true, 'hit-testable, so a click keeps it'); - assert.equal(card.activate, undefined); - assert.equal(card.accessibilityLabel, undefined, 'no action to offer'); assert.ok(!card.details.some((line) => line.includes('Click the card'))); + // No source to open: a click on the card flies to the quake instead. h.clickCard(card.id); assert.deepEqual(h.opened, []); + assert.equal(h.focused.length, 1); + // Its keyboard action does the same, so it still has a place in the + // action list. + assert.match(card.accessibilityLabel, /^Focus earthquake M2\.5 · Minor, /); + assert.equal(card.activate(), true); + assert.equal(h.focused.length, 2); + assert.deepEqual(h.opened, []); assert.equal(h.lastCard()[0].id, card.id, 'the card stays'); h.layer.destroy(); }); @@ -360,6 +375,24 @@ test('describeEarthquake translates through the given formatters', () => { assert.equal(bare.title, 'M3.0 · Minor'); assert.deepEqual(bare.details, ['■□□□□□', 'Source: USGS']); assert.equal(bare.link, null); + assert.equal( + bare.accessibilityLabel, + 'Focus earthquake M3.0 · Minor, Source: USGS', + ); + // A place cut short never splits a character made of a surrogate pair. + const emoji = describeEarthquake(quake('ak9', { place: '🌋'.repeat(60) })); + assert.equal(Array.from(emoji.details[1]).length, 48); + assert.ok(!/[\uD800-\uDBFF]…$/.test(emoji.details[1])); + // A long place is cut short on the card; the accessible name keeps it all. + const long = 'A very long place name '.repeat(4).trim(); + const wide = describeEarthquake(quake('ak9', { place: long })); + assert.equal(Array.from(wide.details[1]).length, 48); + assert.ok(wide.details[1].endsWith('…')); + assert.ok(wide.accessibilityLabel.includes(long)); + // With no opener to follow a link, the card does not offer one. + const closed = describeEarthquake(quake('ak9'), { canOpen: false }); + assert.ok(!closed.details.some((line) => line.includes('Click the card'))); + assert.match(closed.accessibilityLabel, /^Focus earthquake /); }); test('severity follows the USGS magnitude classes; depth bands the disc colours', () => { @@ -418,6 +451,9 @@ test('clicking a magnitude label selects the quake and flies to it', async () => assert.ok( Math.hypot(detail.position.x, detail.position.y, detail.position.z) > 6e6, ); + // The whole disc in view: radius and range scale with the magnitude. + assert.equal(detail.radiusM, 32000); + assert.equal(detail.rangeM, 32000 * 3.5); // The keyboard path does the same. assert.equal( @@ -470,21 +506,34 @@ test('the selected quake runs contour rings to its disc edge; clearing stops the hide: () => calls.push(['hide']), dispose: () => calls.push(['dispose']), }; + // The ground the disc is draped on: the rings are drawn at its height. + const heights = []; const h = harness( [quake('ak1', { mag: 5, depthKm: 10 }), quake('ak2', { mag: 3 })], - { ripples }, + { + ripples, + groundHeight: (viewer, lon, lat) => { + heights.push([lon, lat]); + return lon === -153.3 ? 1840 : null; + }, + }, ); h.layer.enable(h.viewer); await h.layer.update(h.viewer); h.clickDisc('ak1'); const shown = calls.findLast(([kind]) => kind === 'show')[1]; - assert.deepEqual(shown, { + const { heightAt, ...rest } = shown; + assert.deepEqual(rest, { id: 'ak1', lon: -153.3, lat: 60, + heightM: 1840, radiusM: 32000, color: 'rgb(255,0,0)', }); + assert.deepEqual(heights.at(-1), [-153.3, 60]); + // The painter can read the ground again as it loads (a label's fly-to). + assert.equal(heightAt(), 1840); assert.equal( h.discs().items.get('earthquake:ak1').geometry.semiMajor, shown.radiusM, @@ -1054,3 +1103,81 @@ test('coarse FIRMS near-misses leave quake overlays actionable; exact fire hits input?.destroy(); } }); + +// A tap that drifts more than the tracking click travel is ignored by the +// aircraft layers, so a quake card painted beside an aircraft keeps it. +test('a quake card keeps a dragged tap beside an aircraft that declines it', async (t) => { + const previous = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true }); + t.after(() => { + if (previous) globalThis.matchMedia = previous; + else delete globalThis.matchMedia; + }); + const plane = { set: 'flights:1', id: 'plane-9' }; + let sceneHit = null; + let nearby = null; + let input; + const h = harness([quake('ak1')], { + input(viewer) { + viewer.scene = { + pick: () => (sceneHit ? { id: sceneHit } : null), + drillPick: () => (nearby ? [{ id: nearby }] : []), + }; + input = fakeInput(viewer); + return input.input; + }, + }); + picking.registerPickOwner('test-plane', (id) => id === plane.id, { + expanded: true, + declinesClick: (click) => (click?.gesture?.travelPx ?? 0) > 6, + }); + t.after(() => { + picking.unregisterPickOwner('test-plane'); + h.layer.destroy(); + input?.destroy(); + }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + sceneHit = { set: h.discs().spec.id, id: 'earthquake:ak1' }; + input.click(); + const card = h.lastCard()[0]; + h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, { + sourceId: EARTHQUAKE_CARD_SOURCE_ID, + entryId: card.id, + }); + sceneHit = null; + nearby = plane; + // A still tap: the aircraft acts on its contact, so the card yields. + input.tap({ x: 10, y: 10 }); + assert.deepEqual(h.opened, []); + // A tap that drifts 10 px: the aircraft ignores it, so the card opens. + input.down({ x: 10, y: 10 }); + input.move({ x: 20, y: 10 }, { x: 10, y: 10 }); + input.up({ x: 20, y: 10 }); + input.click({ x: 20, y: 10 }); + assert.equal(h.opened.length, 1, 'the card keeps the dragged tap'); +}); + +// A refresh that no longer carries the selected quake evicts it, as other +// feeds report; a click on empty map is a deliberate clear. +test('a quake that ages out of the feed is cleared as evicted', async () => { + const clears = []; + const context = { + registerEntityContext: (record) => ({ ...record, id: record.id }), + selectEntityContext() {}, + clearSelectedEntityContextForLayer: (layerId, options) => + clears.push([layerId, options?.evicted === true]), + getContextStore: () => ({ entities: new Map() }), + }; + const h = harness([quake('ak1'), quake('ak2')], { context }); + h.layer.enable(h.viewer); + await h.layer.update(h.viewer); + h.clickDisc('ak1'); + h.setRows([quake('ak2')]); + await h.layer.update(h.viewer); + assert.deepEqual(clears.at(-1), ['earthquakes', true], 'aged out: evicted'); + h.clickDisc('ak2'); + h.click(null); + assert.deepEqual(clears.at(-1), ['earthquakes', false], 'empty map'); + h.layer.destroy(); +}); diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js index f85260f735..fa25261e83 100644 --- a/src/layers/flights/lifecycle.js +++ b/src/layers/flights/lifecycle.js @@ -1,3 +1,4 @@ +import { isTrackingSelectionGesture } from '../../data/trackingClickGesture.js'; import { findCamera, findFrame } from '../../render/rendererOf.js'; import { loadFleetModelSet } from '../../data/fleetModels.js'; import { forgetPlacedAircraft } from './placed.js'; @@ -141,6 +142,11 @@ export function createLifecycle({ passive: (pickedId) => Boolean(flightState._trackedIcao) && pickedId === flightState._trackedIcao, + // The click handler ignores a dragged tap and any tap in cockpit + // mode, so a card over the aircraft keeps that tap. + declinesClick: (click) => + !isTrackingSelectionGesture(click?.gesture) || + Boolean(document.body?.classList.contains('cockpit-mode')), }, ); const frame = findFrame(viewer); diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js index 7c96171206..c7e667d4ff 100644 --- a/src/layers/military/lifecycle.js +++ b/src/layers/military/lifecycle.js @@ -1,3 +1,4 @@ +import { isTrackingSelectionGesture } from '../../data/trackingClickGesture.js'; import { findCamera, findFrame } from '../../render/rendererOf.js'; import { loadFleetModelSet } from '../../data/fleetModels.js'; import { forgetPlacedAircraft } from '../flights/placed.js'; @@ -122,6 +123,11 @@ export function createLifecycle({ passive: (pickedId) => Boolean(flightState._trackedIcao) && pickedId === flightState._trackedIcao, + // The click handler ignores a dragged tap and any tap in cockpit + // mode, so a card over the aircraft keeps that tap. + declinesClick: (click) => + !isTrackingSelectionGesture(click?.gesture) || + Boolean(document.body?.classList.contains('cockpit-mode')), }, ); // The flights layer suppresses its military duplicates while we render them diff --git a/src/render/cesium/cameraGoldens.test.mjs b/src/render/cesium/cameraGoldens.test.mjs index 91ca593516..d6983579cb 100644 --- a/src/render/cesium/cameraGoldens.test.mjs +++ b/src/render/cesium/cameraGoldens.test.mjs @@ -2,7 +2,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { recordCameraGoldens } from './cameraGoldens.js'; -import { near } from '../conformance/expect.js'; +import { near, nearAngle } from '../conformance/expect.js'; // The recorder is deterministic, but platforms can differ in the last bits // of trigonometric arithmetic. Keep structure and discrete values exact. @@ -18,7 +18,16 @@ function compareTrace(actual, expected, path = []) { path.at(-2) === 'position' || key === 'height' || (path.at(-2) === 'view' && Number(key) >= 12 && Number(key) <= 14); - near(actual, expected, metres ? 1e-8 : 1e-14, label); + // A few ulps of the value itself, so large untagged values (pick points, + // ray origins, the far plane) are not held below one ulp. + const tolerance = Math.max( + metres ? 1e-8 : 1e-14, + Math.abs(expected) * 4 * Number.EPSILON, + ); + // Heading and roll wrap at 2π: a value just under it is one just over 0. + if (key === 'heading' || key === 'roll') + nearAngle(actual, expected, tolerance, label); + else near(actual, expected, tolerance, label); return; } if (expected !== null && typeof expected === 'object') { @@ -71,3 +80,15 @@ test('trace comparison tolerates only numeric roundoff, preserving structure and const { label, ...missing } = expected; assert.throws(() => compareTrace(missing, expected)); }); + +test('trace comparison scales with the value and wraps heading and roll', () => { + // One ulp of a ground pick point (about 5e-10 at 3e6 m) is roundoff. + const far = 3_000_000.123; + compareTrace({ pick: far + 2 * Number.EPSILON * far }, { pick: far }); + assert.throws(() => compareTrace({ pick: far + 1e-6 }, { pick: far })); + // A heading just under 2π is one just over 0. + compareTrace({ heading: 2 * Math.PI - 1e-16 }, { heading: 1e-16 }); + compareTrace({ roll: 1e-16 }, { roll: 2 * Math.PI - 1e-16 }); + assert.throws(() => compareTrace({ heading: 0.1 }, { heading: 0 })); + assert.throws(() => compareTrace({ heading: NaN }, { heading: 0 })); +}); diff --git a/src/worldFocus.js b/src/worldFocus.js index cf9e2fb90f..f2c3d1ce91 100644 --- a/src/worldFocus.js +++ b/src/worldFocus.js @@ -18,8 +18,9 @@ export const WORLD_FOCUS_FRAMING = Object.freeze({ // A stopped train's one fly-to, and the frame a moving train is followed // in (src/layers/rail/follow.js): the train and the track either side. train: Object.freeze({ radiusM: 200, rangeM: 2500, pitchDeg: -35 }), - // A clicked quake's magnitude label: its disc (2^M km across, so about - // 11 km at M2.5 and 128 km at M6) and the ground around it. + // A clicked quake's magnitude label: its disc (2^M km in radius, so about + // 6 km at M2.5 and 64 km at M6) and the ground around it. A larger quake + // passes its own radius and range (never less than these). earthquake: Object.freeze({ radiusM: 20000, rangeM: 220000, pitchDeg: -45 }), 'sighting-area': Object.freeze({ radiusM: 11000, @@ -115,13 +116,20 @@ export function flyToWorldTarget(viewer, target = {}) { target.durationSec > 0 ? target.durationSec : WORLD_CLICK_FOCUS_DURATION_SEC; + // A target may ask for more room than its kind's framing (a large quake's + // disc), never less. + const atLeast = (value, floor) => + Number.isFinite(value) && value > floor ? value : floor; camera.flyToBounds( - { center: target.position, radius: framing.radiusM }, + { + center: target.position, + radius: atLeast(target.radiusM, framing.radiusM), + }, { offset: { heading, pitch: toRadians(framing.pitchDeg), - range: framing.rangeM, + range: atLeast(target.rangeM, framing.rangeM), }, durationS: duration, easing: 'cubicInOut', diff --git a/src/worldFocus.test.mjs b/src/worldFocus.test.mjs index 8512a969d4..de4981fd20 100644 --- a/src/worldFocus.test.mjs +++ b/src/worldFocus.test.mjs @@ -206,6 +206,29 @@ test('fires frame wider than vessels — a fire is read by its surroundings', () ); }); +// A large quake's disc does not fit the earthquake framing, so the target +// asks for more room; it never gets less than the framing. +test('a target can widen its framing, never narrow it', () => { + const fly = (extra) => { + const camera = stubCamera(); + flyToWorldTarget(bindFakeCesiumCamera({ camera }), { + kind: 'earthquake', + id: 'earthquake:us1', + position: POSITION, + ...extra, + }); + return camera.calls.flights[0]; + }; + const m72 = fly({ radiusM: 147000, rangeM: 514000 }); + assert.equal(m72.sphere.radius, 147000); + assert.equal(m72.options.offset.range, 514000); + const m3 = fly({ radiusM: 8000, rangeM: 28000 }); + assert.equal(m3.sphere.radius, WORLD_FOCUS_FRAMING.earthquake.radiusM); + assert.equal(m3.options.offset.range, WORLD_FOCUS_FRAMING.earthquake.rangeM); + const bad = fly({ radiusM: NaN, rangeM: -1 }); + assert.equal(bad.options.offset.range, WORLD_FOCUS_FRAMING.earthquake.rangeM); +}); + test('every framing is a real oblique standoff, not a nadir or an inside-out sphere', () => { const kinds = Object.keys(WORLD_FOCUS_FRAMING); assert.deepEqual(kinds.sort(), [ From 89ebfa85d1f1f82fc91fef1f938b468369d9f422 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 19:00:04 +0400 Subject: [PATCH 016/138] Changelog: describe only the F change for 1598 --- changelog.d/1598-f-collapses-data-layers.md | 4 ++++ changelog.d/1598-shortcuts-modifier-keys.md | 5 ----- 2 files changed, 4 insertions(+), 5 deletions(-) create mode 100644 changelog.d/1598-f-collapses-data-layers.md delete mode 100644 changelog.d/1598-shortcuts-modifier-keys.md diff --git a/changelog.d/1598-f-collapses-data-layers.md b/changelog.d/1598-f-collapses-data-layers.md new file mode 100644 index 0000000000..e0f4df4973 --- /dev/null +++ b/changelog.d/1598-f-collapses-data-layers.md @@ -0,0 +1,4 @@ +- `F` now collapses and reopens the Data Layers panel the way the panel's own + button does, and its rail entry stays. Before, `F` hid the panel together + with its rail entry, so only another `F` brought it back (asturksever, + #1598). diff --git a/changelog.d/1598-shortcuts-modifier-keys.md b/changelog.d/1598-shortcuts-modifier-keys.md deleted file mode 100644 index 80c30dde51..0000000000 --- a/changelog.d/1598-shortcuts-modifier-keys.md +++ /dev/null @@ -1,5 +0,0 @@ -- Keep single-key app shortcuts off Cmd, Ctrl and Alt combinations, so Cmd+F, - Cmd+C and Cmd+R reach the browser instead of hiding the layer panel or - switching layers on. `F` now collapses the layer panel the way its button - does, instead of hiding the panel and the button that brings it back - (asturksever, #1598). From 3a24768a2dd85175d24ca24604472c4bda05b351 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 19:02:17 +0400 Subject: [PATCH 017/138] Test that F collapses Data Layers through PanelChrome and keeps its rail entry --- src/ui/panelChromeButtons.test.mjs | 45 ++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/ui/panelChromeButtons.test.mjs b/src/ui/panelChromeButtons.test.mjs index 75678f8e62..75d9e72493 100644 --- a/src/ui/panelChromeButtons.test.mjs +++ b/src/ui/panelChromeButtons.test.mjs @@ -14,6 +14,8 @@ import PanelCollapseButton from './rail/PanelCollapseButton.vue'; import RailPanel from './rail/RailPanel.vue'; import UiPanel from './kit/UiPanel.vue'; import { usePanelChromeStore } from './stores/panelChrome.js'; +import { useDisplayStore } from './stores/display.js'; +import { DisplayBindings } from './displayBindings.js'; import CommandDockView from './views/CommandDockView.vue'; function mount(t, component) { @@ -462,3 +464,46 @@ test('the accordion closes peers through the real store, and opens them again', assert.equal(panels[0].className, ''); chrome.destroy(); }); + +test('F collapses Data Layers like its button and keeps its rail entry', (t) => { + document.body.innerHTML = ` +
`; + const panel = document.getElementById('data-panel'); + const store = usePanelChromeStore(createPinia()); + const chrome = panelChrome(store); + followPanelState(store, 'data-panel', panel); + chrome._disclosurePanelIds = new Set(['data-panel']); + const bindings = new DisplayBindings({ + viewer: null, + services: { isScopeMaskEnabled: () => false, cycleDetectionMode() {} }, + elements: { _locationSearch: document.createElement('input') }, + operations: { + _setScope() {}, + _togglePanel: (panelId) => chrome._togglePanel(panelId), + }, + readState: () => ({}), + claimDetection() {}, + displayStore: useDisplayStore(createPinia()), + }); + bindings._initUI(); + t.after(() => { + bindings.destroy(); + chrome.destroy(); + }); + const press = (init = {}) => + document.body.dispatchEvent( + new KeyboardEvent('keydown', { key: 'f', bubbles: true, ...init }), + ); + + press(); + assert.equal(store.panels['data-panel']?.collapsed, true); + assert.ok(panel.classList.contains('collapsed')); + // `active` is what keeps Data Layers in the rail. + assert.ok(panel.classList.contains('active')); + press({ metaKey: true }); + assert.equal(store.panels['data-panel'].collapsed, true, 'Cmd+F is not ours'); + press(); + assert.equal(store.panels['data-panel'].collapsed, false); + assert.ok(!panel.classList.contains('collapsed')); + assert.ok(panel.classList.contains('active')); +}); From a3f4af91f8cf84845035c1b9daf1fb5dd18e95ab Mon Sep 17 00:00:00 2001 From: Manjunath Paparaju Date: Wed, 18 Nov 2026 13:00:41 -0800 Subject: [PATCH 018/138] Add the Omnibar: one field above the footer for places, layers and commands On desktop the dock becomes one search bar (Omnibar.vue) that shows the rows the line-reading pipeline makes: places with nearby suggestions, coordinates, map items, layers, commands, plans such as "go to Austin and show flights", guided walks through the real controls, and Ask GEV for questions. Enter runs only what the line asks for outright. The map credits move below the bar onto the Power Up row, the voice waveform shows in the bar while voice is on, and the dock's Location and Visual trays are hidden in this layout. The phone layout is unchanged. Long place names are kept out of automatic Ask GEV. Co-authored-by: Sameh Khamis --- docs/CURRENT-STATE.md | 284 ++++ src/creditAttribution.test.mjs | 259 +++- src/i18n/locales/ar.json | 31 +- src/i18n/locales/de.json | 23 +- src/i18n/locales/es.json | 25 +- src/i18n/locales/fr.json | 25 +- src/i18n/locales/he.json | 25 +- src/i18n/locales/it.json | 25 +- src/i18n/locales/ja.json | 21 +- src/i18n/locales/pt.json | 25 +- src/i18n/locales/ru.json | 27 +- src/i18n/locales/sv.json | 23 +- src/i18n/locales/uk.json | 27 +- src/i18n/locales/zh-CN.json | 21 +- src/i18n/locales/zh-Hant.json | 21 +- src/ui/applicationShell.js | 14 + src/ui/commandDock.test.mjs | 1596 +++++++++++++++++++++++ src/ui/entityContextBridge.js | 12 +- src/ui/leftPanelRail.js | 32 +- src/ui/locationControls.js | 38 +- src/ui/locationControls.test.mjs | 1 + src/ui/locationSearch.js | 2 + src/ui/omnibarIntent.js | 11 +- src/ui/omnibarIntent.test.mjs | 1 + src/ui/omnibarRows.test.mjs | 9 +- src/ui/panelRails.test.mjs | 32 + src/ui/stores/entityCard.js | 6 + src/ui/stores/globeActions.js | 3 + src/ui/stores/omnibar.js | 9 +- src/ui/styles/guide.css | 413 ++++++ src/ui/styles/omnibar-dock.css | 360 +++++ src/ui/views/CommandDockView.vue | 4 +- src/ui/views/SceneChromeView.vue | 2 + src/ui/views/panels/Omnibar.vue | 1341 +++++++++++++++++++ src/ui/views/panels/VoiceVisualizer.vue | 66 +- style.css | 2 + 36 files changed, 4741 insertions(+), 75 deletions(-) create mode 100644 src/ui/styles/guide.css create mode 100644 src/ui/styles/omnibar-dock.css create mode 100644 src/ui/views/panels/Omnibar.vue diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7292252ac1..9c3a7804a9 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7814,6 +7814,290 @@ and unreachable upstream (502/504) separately from road geometry. - `partial` is a feed state of its own, ranked between `fallback` and `nominal`, so one partial layer, or partial plus nominal, reads partial, not off or nominal (HUD, voice view state, `analyst_query`, `brief`, the agent world packet). Its narration note says coverage is incomplete rather than not live. - A summary asked for before the camera starts moving never paints over the next view: `moveStart` marks the summary dirty and bumps its revision, as `moveEnd` does, aborts the request in flight and stops a reply still typing; neither a reply nor a fallback line (on an error, the 5 s timeout, the abort, or a failed context build) paints once the revision has moved. A dropped request forgets its signature and a timeout counts as a failure, so the next 15 s tick asks again even over the same place. An interrupted typewriter reply also forgets its signature; fully displayed answers remain reusable. +### Omnibar + +The desktop Omnibar sits above the footer with the existing mic and chat +buttons on either side. Suggestions open upward; the phone field stays at +the top and opens downward. While voice is on, the desktop field shows +three audio traces in place of the search text and icon. The thinking dots +sit on the field's top edge. World Time appears immediately above the dock +and hides while suggestions, chat, or voice settings are visible. `/` +focuses search from outside a text field, as do Cmd+K on macOS and Ctrl+K +elsewhere (Ctrl+K on macOS is left alone); none of them takes focus from an +open modal dialog or from inside a dialog such as the guide. While voice is +on, the suggestions give way to the waveform but an error stays shown. The map credits stay on the +Power Up row in the ordinary desktop layout, and the two lower tactical HUD +readouts start at the same height. + +Pending owner decision: in the desktop Omnibar layout +(`src/ui/styles/omnibar-dock.css`) the legacy Location and Visual trays of +the command dock are hidden (`#command-dock > :is(#location-bar, +#control-panel)`), as is the tactical and minimal HUD's mode readout +(`.hud-readout:has(> #hud-mode)`). Search moves to the Omnibar and presets to +the Visual rail; the phone shell and exclusive modes keep their layouts. + +The field offers places, latitude/longitude and grid coordinates, named map +entities, and layer controls. The strip can show cities and landmarks, +nearby small places from the bundled Wikidata packs, selected items and +drawing shapes. The cities of a state or country are those inside its +extent and in its country (by the ISO code Photon returns); with only one of +the two known, that one decides. Selecting a +guided result highlights the existing app controls. "Show me how", "how do +I …" and "how to …" find a walk by the words people use: a layer's name +("how to turn on flights"), or a feature's (`FEATURE_TOPICS` in +`src/ui/omnibarRows.js`): the style or look ("change the map style"), the +map underneath ("change the map", "switch to OpenStreetMap"), the HUD, +north or the compass, tilt, the globe or a reset ("get back to the globe"), +sharing, clearing all layers, and drawing and measuring ("how to measure +distance": open Utilities, press Draw, pick Line for a distance or Area for +its size). A leading `>` opens the +command menu; use it for exact layer commands such as `> show flights`. + +The rows come from one pure pipeline, `createOmnibar` in +`src/ui/omnibarRows.js`: the line is normalised once (`normalizeLine` in +`src/ui/omnibarIntent.js`, through `readLine` in `src/ui/omnibarRows.js`: +full-width forms folded, curly apostrophes made straight, a closing full +stop or "!" dropped (an initial's kept, as in "Washington D.C."), and a +"please" before or after a request dropped, never one in a name ("Please +Touch Museum", "Pretty Please")), read once (`parseOmnibar`), turned into +rows, and ordered by the Enter rule; the same reader decides what may go +to Photon and what is a count request. A whole line searched as a place is +searched as typed ("Paris, Texas.", "Yahoo!"). The +component (`Omnibar.vue`) supplies the layers, Photon's answers, the map's +items and the selection, and runs the chosen row; the strip of chips under +the field (landmarks, cities of a region, villages, recent places, draw +shapes) is built in the component from the same normalised line. What Enter does with no +row chosen follows one rule, in `src/ui/omnibarEnter.js` (`enterDefault`), +pinned by an input-to-outcome table in `src/ui/omnibarRows.test.mjs` and +by the mounted table in `src/ui/commandDock.test.mjs`. Only the first row can be the default; an +empty field and a bare `>` have none; the pointer never chooses a row +(hovering then pressing Enter runs the default, a click runs the row), and +the arrow keys choose any row. Enter performs an action (a plan, a layer +switch, a command, Ask GEV) only when the line asks for it outright: + +- the action's own clause starts with a verb from the one list + (`ACTION_VERB` in `src/ui/omnibarIntent.js`, read in any letter case by + `hasActionVerb`): show, hide, turn, switch, toggle, enable, disable, add, + remove, display (with something after it), play, start, open, close, + enter, listen, tune, mute, unmute, follow, track, draw, measure, share, + copy, reset, silence, pause, "nearest plane" and the like, or a clause + ending in "on" or "off" ("radio off"). A style, map, camera move, HUD or + layer followed by "on" or "off" reads as that switch ("noir off" and + "turn off noir" go back to the normal style, "orbit off" stops the camera, + "osm off" runs nothing), never as a place called "off"; words that also start names count + only alone or before what they act on ("clear the map", "zoom in", + "tilt", "orbit", "stop the radio", "kill the radio", "face north"). Verbs + are read per clause, so a verb inside a place's name asks for nothing + ("radio near Clear Lake", "radio in Show Low", "radio near Stop, + Arkansas" search the place). A layer is asked for only by a switch (show, + display, add, enable, turn or switch on, hide, remove, disable, turn or + switch off) right before its word: "Show Low radio" and "Kill Devil Hills + radio" name places, and a verb with a name left beside its keywords asks + for nothing else in its clause ("Show Low noir", "Start Point noir", + "Track Hill noir"). A clause joined to a "go to" + clause by "and" or "then" counts as asked ("go to Paris, Texas and + noir"); +- or it is a command's exact label, alone or after `>` ("North up", "Noir", + "> Clear all layers"). A command row runs on nothing else: a bare switch + verb ("hide", "turn off", "disable") only lists what it could switch; +- or a data layer's whole shown name or synonym alone, which names that + layer as a command's label does ("flights", "earthquakes", "Satellite"); +- or, for Ask GEV, it is a real question: it ends with "?" (full-width + "?" and Arabic "؟" too), has a word of two letters or more, and has a + question's form (below), or two words in a + non-Latin script; or five Han, Kana or Hangul characters ("what?", "??", + "N Y?", "New York?", "Truth or Consequences?" and "東京都?" are not: + Ask GEV is offered first and Enter runs nothing; small talk such as "what's up" or "how's it going" is never one); or, without "?", it + starts with + what/where/when/who/why/how/which followed by is, are, was, do, does, + did, can, could, should, would, will, 's, many, much, far, long or to, + then has a word about something ("what is here", "how far is paris"; not + "what is", "how to", "who is it"), and is not written as a name (three + words or more, each capitalised: "Where Is My Mind"). A line starting + with an auxiliary and a pronoun or determiner (is it, can you, do it…) + asks only with "?": without it, Ask GEV is offered first and Enter runs + nothing ("can you show me", "is it raining in tokyo"), and with a capital + after its first two words it is a name and searches the place ("Can You + Imagine", "Do it Best Hardware"). "Can Tho City" and "Is Kinabalu Park" + are places. A line + with a comma and no "?" is a place ("Why, Arizona"), never a question. + Any other line, small talk and question words included ("why", "help", + "what cheer", "List"), still offers the place row first, with Ask GEV + after it. + +A whole layer name with a place after near, in, around, over, across or +above ("flights near Tokyo", "earthquakes above m5 in japan") asks outright +too; after "of" or "at" the line may be a name and the whole line is +offered as a place first ("Planes of Fame Air Museum", "Boats at Sea"). Keywords without a +verb ask for nothing, however many clauses they fill ("New York City +noir", "Fire and Rain", "noir and cctv near austin, north up"): with a +place after near or in that place is searched, and otherwise the whole +line is offered as a place first ("Storm Lake and Spencer", "Thermal and +Indio"), the plan after it. Draw opens on Enter only for "draw" itself or a +draw verb with something to draw ("draw a line"; not "Draw Bridge"), and a +guided walk found by forgiving a typo, or on a line written as a title +("How To Train Your Dragon"), is offered, never run. A switch verb before +a capitalised name that names no layer is a place ("Remove Island", +"Toggle Inn"). A +layer row runs only when the line names that layer before any other, by a +whole word of its shown or English name (never its id, and not a word of +kind such as local, global, live, world, new, open, data, map, view or +level) or a synonym, with a plural "s" allowed from four letters +("flights" yes; "a", "display", "Local", "Global", "new" no). "show +flights" with Live Flights already on offers Live Flights, which then +switches nothing; Military Flights, which also has the word, is only +offered after it. Words about a layer after a switch are no place ("show radio +stations", "show flights here"); without the switch the line may be a name +("Train Station"). A line of more than six words left over as a +place (ten with a number in it), or of more than eight words that asks for +nothing outright, is a sentence (pasted text, a remark): it is never sent to +Photon, Ask GEV is offered, and so is a row that searches the whole line as a +place when picked ("San Miguel de las Piedras Primera Sección"); Enter runs +neither. A word that is +both a bundled place's name and, alone, a command, style or layer word +(`PLACE_WORDS` in `src/ui/omnibarEnter.js`: Bike, Hurricane, Normal, Rain, +Ski, Street, Thermal) searches the place first and offers the switch +second. The list comes from sweeping every bundled name (139,502), alone +and with " radio" and " noir" after it, through the mounted Omnibar; after +it, none defaults to anything but a place. A test samples about 2,000 of +them. Some actions need more: sound (the Radio layer and command), +clearing the map, closing panels and the cockpit need a verb or their exact +label ("turn on radio", "close all panels", "enter cockpit"; not "radio near +tokyo" or "Radio, Tokyo"), and the microphone, sharing the view, resetting +it and the globe view need their exact label ("Talk to GEV", "Share this +view", "Reset view", "Globe view"; not "mic", "share", "home" or "start +over"). +Otherwise the place row is the default and moves first ("Thermal, +California", "radio near tokyo" searches Tokyo), and any plan or command is +offered after it; a line with neither ("hi", "NY", "?") runs nothing. "hide everything near tokyo" clears the layers and flies to +Tokyo. Following needs a callsign or ICAO address (letters and a digit), a +nine-digit MMSI or the name of something loaded on the map, so "Track +Hill" and "Track 29" are places; "nearest plane" counts alone or before a +place ("Nearest Plane Crash Site" is a name), and "goto" only with a place +after it ("Goto" is a town). A row chosen with the arrow keys is kept by its key while rows +arrive above it, and the default comes back if it goes away. After a row +runs with Enter, the field empties and keeps focus for the next line on +desktop; a tapped or clicked row lets go of it, and on the phone shell any +row does (so the keyboard does not stay over the map), and so do Ask GEV, the mic, the cockpit, following, a guided +walk, and any row while drawing is on (the draw tool reads Enter, Backspace +and Esc). Escape closes the list, and on an empty, closed field lets go of +it, so the app's own keys work again. While voice +is on, the list is closed (not expanded) and Enter runs nothing. Text that +may be private is never looked up or searched while typed or on Enter: only +things already loaded on the map may match it, locally, and when only a +long run of digits makes it look private and it has words (an address can: +"Москва, ул. Тверская, д. 13, 125009") one row searches it as a place only +when picked (see below). + +After "go to" (or "fly to" and the like) the rest of the clause, and a +following part after a comma that has no verb, is the place, read before +any keyword in it: "go to Thermal, California" only searches there. A +request ending that clause is peeled off and offered as a plan after the +place: "in", "with" or "at" and a style, map or layer ("go to tokyo in +noir", "go to London with flights"), a switch and a layer ("go to tokyo show +flights"), or a comma part that is exactly a style, map, camera move or +layer ("go to Tokyo, north up"). A line with one keyword and no verb beside +the rest of a name ("Tilt Cove", "tokyo traffic", "Hurricane, Utah") offers +the whole line as a place first and the plan second. Further places joined +with "and" are offered as their own rows. Things loaded on the map that +match the line are offered too: a callsign, tail number or transponder +code puts them first, and otherwise the place row keeps the top, so +"Hamburg" goes to the city before the ship HAMBURG. An unrecognized explicit command +stays in search. Questions can be sent through Ask GEV, which uses the +existing typed chat. + +Han, Hangul and Kana names are looked up from two characters (東京), others +from three. + +Plans run step by step, and a layer step reads the layer's state when it +runs, not when the line was read. A step the app refuses (an action +answering `ok: false`, a layer switch answering `false`, a globe action no +connected owner answers, a panel to open with no rail button) stops the +plan and shows the same error under the field as a single action, with +the action's own short spoken reason (`say`) when it gives one and the +interface is in English (the runner speaks English, so other languages +get the translated message alone); a flight cancelled by a newer +one stops the plan quietly. A running plan is superseded, and none of its +later steps run, when the field's text changes, another row or chip is +chosen, Escape is pressed, the field is reset after a finished choice, or the +Omnibar unmounts. Focus leaving the field (a click on the map, the mic, the +search shortcut) does not cancel it. The guide's placement check pauses +while the tab is hidden. +A place search on its own runs through Location and shares its cancellation +and errors, keeping the separate Location draft intact. + +While typing, a short line (six words or fewer, no `?`, not a command, +coordinates, a hex code, a callsign such as UAL2110 or N123AB, and nothing +that may be private) is sent to +Photon for place suggestions: at most one request every 500 ms per tab, +and none for a minute after a refusal. Photon is the keyless geocoder the +place search already uses; a submitted search is not part of this spacing. +A line that may be one name ("Satellite Beach") is looked up whole. While +its suggestions show, or a recent-place chip that came from them, the +OpenStreetMap credit shows too; recent chips from the bundled packs credit +Wikidata. Private text, by `mayBePrivate` in +`src/search/placeSuggestions.js`, is never sent to Photon, offered as a +place, searched or sent to GEV; only things already loaded on the map may +match it, locally. The line is read after NFKC, so full-width letters, +digits and "@" count, and digits of any script count as digits. It is +any line with: an "@" with something right on both sides, ending a word, +starting a lowercase handle ("@jdoe"), or spaced before a domain ("john @ +gmail.com") (an email address or a handle, also while it is typed; spaced, as in "Nanjampeta @ +Chandambylu", it is part of a name); seven digits or more with nothing but spaces, +punctuation, symbols or format characters between them (a phone, card, +SSN or account number or its start: "+1 415 555", "4111 1111", "123 45 +6789", "123456789", "4111.1111.1111.1111", "123–45–6789"; a street address's house number +and its postcode are read apart: five digits, or between the street and +the city "00-950", "111 21", "125009", "1100-053", or four digits after a +comma ("Straße 120, 1070 Wien"); and so are a US ZIP+4 after a word, +a Brazilian CEP, a Japanese postcode after "〒" or before the address, and +digits on either side of "#", so "Hauptstrasse 12 10115 Berlin", "DC +20500-0003", "〒100-0001 東京都千代田区" and "Calle 100 # 19-61" are places, +while a seven-digit postcode alone such as "Tel Aviv 6100000" still reads +as private); a phone number written with dots; two letters, two +digits and ten more letters or digits (an IBAN's shape); "password", +"passcode", "passwd", "ssn", "pw", "pwd" or "bearer" followed by anything, +"token", "secret", "api key", "key" or "pass" followed by ":" or "=", a +door, access, gate, alarm, entry or security code followed by a digit, "api +key", "access token" or "secret key" followed by a word of six characters +or more, the word for "password" in the interface's languages +(contraseña, Passwort, mot de passe, пароль…) followed by anything, or "pin" +(also "pin code", "pin number", "pin is") followed by a digit; a word +starting `sk_`, `sk-`, `rk_`, `pk_live`, `ghp_` or a Slack token's `xoxb-` and the like (any case) or +`AIza`, `eyJ` or `AKIA`; or a word that may be a password or key, with letters and digits mixed +within one run (a number beside a word, as in "Yanino-1", "2-chōme" or +"Route-66", is a name): eight characters or more, six or more with four +letters and a digit ("hunter22", "Area51"), or six or more with letters, +digits and a symbol ("Tr0ub4dor&3"). The password words match whole words +only ("Sachsenhausen" is a place). Over the bundled names (139,502), five +read as private: two with stray digits ("Maliga0N", "Jerónim67") and three +with number lists or codes. When the text may be private the field says +so ("Looks private, so nothing is searched or sent"), and a line whose +only private sign is an address-sized run of digits (no group over six +digits, nine at most in all, counted as they fold, and no word such as +card, code, key, phone or account beside them, in English and some other +European languages; compounds such as "Kreditkartennummer" and words in +other scripts are not read), with words beside it, gets a row +to search it as a place on purpose ("Search … as a place anyway"), which +runs the ordinary place search and its online services only when picked; a +bare number, an email or handle, a password, key, code or IBAN gets none. +A nine-digit number or a short phone number written with no such word +still gets the row: only picking it sends anything. One-time and verification codes, +OTP, 2FA, MFA, CVV and CVC values, "card ending" digits, passphrases, +recovery or seed phrases, "my secret is …" and an email spelled out ("john +at example dot com") are private too. Text that parses as coordinates or a +grid reference is not private. A place's name is six words at most, or ten +when it has a number in it (an address: "1600 Pennsylvania Ave NW +Washington DC 20500"). The places you go to from the Omnibar (the last 20: +name, position and where the name came from) are kept in this browser's +`localStorage` under `gev:omnibar:recent-places` for the strip; nothing +clears them but the browser's own site data. Setting `PHOTON_URL` +empty turns the suggestions off along with it. Small places come from the +bundled Wikidata packs and are never looked up online; a small place with +the name of a city within 3 km in the same country is that city, and only +the city is listed. At most 64 detail tiles are kept in memory, the least +recently used dropped first. + ### Place-search providers Coordinate input requires exactly two nonempty components; extra comma or semicolon separators decline to geocoding rather than silently choosing a location. diff --git a/src/creditAttribution.test.mjs b/src/creditAttribution.test.mjs index b695666103..879f58d64e 100644 --- a/src/creditAttribution.test.mjs +++ b/src/creditAttribution.test.mjs @@ -6,6 +6,12 @@ import test from 'node:test'; import { fileURLToPath } from 'node:url'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +// The Omnibar's desktop footer (src/ui/styles/omnibar-dock.css) is part of +// the cascade below like every other stylesheet; its rules carry the +// Omnibar scope, so they are modelled as a layout of their own. +const omnibarCss = readStylesheet( + path.join(ROOT, 'src/ui/styles/omnibar-dock.css'), +); const css = readStylesheet(path.join(ROOT, 'style.css')); /* @@ -125,11 +131,56 @@ function specificity(selector) { return [ids, classes, types]; } -/** Flatten style.css into rules carrying their raw media stack. */ +/** Collapse whitespace and the padding inside brackets of a selector. */ +const tidySelector = (part) => + part + .replace(/\s+/g, ' ') + .trim() + .replace(/\(\s+/g, '(') + .replace(/\s+\)/g, ')'); + +/** + * A nested selector resolved against its parent rule's selectors, as CSS + * nesting does: `&` stands for the parent, and a selector without one is a + * descendant of it. + */ +function nestSelectors(parents, head) { + const own = splitTopLevel(head, ',').map(tidySelector).filter(Boolean); + if (!parents) return own; + return parents.flatMap((parent) => + own.map((part) => + part.includes('&') ? part.replaceAll('&', parent) : `${parent} ${part}`, + ), + ); +} + +/** + * Flatten style.css into rules carrying their raw media stack. Nested style + * rules (CSS nesting) and media queries nested in a rule are resolved to + * full selectors, so a nested rule is modelled like any other. + */ function flattenRules(source) { const src = source.replace(/\/\*[\s\S]*?\*\//g, ''); const rules = []; - const mediaStack = []; + // Open blocks, innermost last: media queries and style rules. + const stack = []; + const mediaStack = () => + stack.filter((frame) => frame.media).map((frame) => frame.media); + const parentRule = () => + [...stack].reverse().find((frame) => frame.rule)?.rule || null; + const declare = (text) => { + const rule = parentRule(); + const trimmed = text.trim(); + if (!rule || !trimmed) return; + const colon = trimmed.indexOf(':'); + if (colon < 0) return; + const value = trimmed.slice(colon + 1).trim(); + rule.decls.push({ + prop: trimmed.slice(0, colon).trim().toLowerCase(), + value: value.replace(/\s*!important$/i, '').trim(), + important: /!important\s*$/i.test(value), + }); + }; let index = 0; let prelude = ''; while (index < src.length) { @@ -137,14 +188,13 @@ function flattenRules(source) { if (char === '{') { const head = prelude.replace(/\s+/g, ' ').trim(); prelude = ''; + index += 1; if (head.startsWith('@media')) { - mediaStack.push(head.slice('@media'.length).trim()); - index += 1; + stack.push({ media: head.slice('@media'.length).trim() }); continue; } if (head.startsWith('@')) { let level = 1; - index += 1; while (index < src.length && level > 0) { if (src[index] === '{') level += 1; else if (src[index] === '}') level -= 1; @@ -152,43 +202,34 @@ function flattenRules(source) { } continue; } - const close = src.indexOf('}', index); - assert.ok(close > index, `unterminated rule block for "${head}"`); - const decls = []; - for (const raw of src.slice(index + 1, close).split(';')) { - const text = raw.trim(); - if (!text) continue; - const colon = text.indexOf(':'); - if (colon < 0) continue; - const value = text.slice(colon + 1).trim(); - decls.push({ - prop: text.slice(0, colon).trim().toLowerCase(), - value: value.replace(/\s*!important$/i, '').trim(), - important: /!important\s*$/i.test(value), - }); - } - rules.push({ + const rule = { order: rules.length, - media: [...mediaStack], - parts: splitTopLevel(head, ',') - .map((part) => - part.trim().replace(/\(\s+/g, '(').replace(/\s+\)/g, ')'), - ) - .filter(Boolean), - decls, - }); - index = close + 1; + media: mediaStack(), + parts: nestSelectors(parentRule()?.parts, head), + decls: [], + }; + rules.push(rule); + stack.push({ rule }); + continue; + } + if (char === ';') { + declare(prelude); + prelude = ''; + index += 1; continue; } if (char === '}') { - mediaStack.pop(); + // The last declaration of a block may omit its semicolon. + declare(prelude); prelude = ''; + stack.pop(); index += 1; continue; } prelude += char; index += 1; } + assert.equal(stack.length, 0, 'unbalanced braces in style.css'); return rules; } @@ -227,6 +268,29 @@ const RECOGNIZED = new Set([ ]); const DOCKED_RAIL = 'body.context-docked #right-context-rail'; + +// The desktop Omnibar layout: the scope its stylesheet nests every rule in. +// It applies on the desktop shell (above the 720px phone breakpoint) while +// the Omnibar and the voice control share the dock; outside it the legacy +// layout below governs. +const OMNIBAR_SCOPE = + 'body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(.ui-clean-view):not(.recording-mode):where(:has(#gev-omnibar):has(#command-dock > #gev-voice-control))'; +const OMNIBAR = Object.freeze({ + dock: `${OMNIBAR_SCOPE} #command-dock`, + credit: `${OMNIBAR_SCOPE} :is(#cesium-credits, #gev-credits)`, + minimalCredit: `${OMNIBAR_SCOPE}:has(#intel-hud[data-variant='minimal'].active) :is(#cesium-credits, #gev-credits)`, + minimalRail: `${OMNIBAR_SCOPE}:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) #right-context-rail`, + trays: `${OMNIBAR_SCOPE} #command-dock > :is(#location-bar, #control-panel)`, +}); +// What each Omnibar-scope rule may set on a modelled box; the Omnibar +// clearance test resolves every one of them through the full cascade. +const OMNIBAR_RECOGNIZED = new Map([ + [OMNIBAR.dock, new Set(['top', 'bottom', 'height', 'min-height'])], + [OMNIBAR.credit, new Set(['bottom'])], + [OMNIBAR.minimalCredit, new Set(['bottom'])], + [OMNIBAR.minimalRail, new Set(['max-height'])], +]); +const OMNIBAR_MIN_WIDTH = 721; const ELEMENT_KEYS = [ '#cesium-credits', '#command-dock', @@ -300,8 +364,11 @@ function ownBoxEntries() { // So is Stories, with GEV's chrome stepped aside; storiesCredit.test.mjs // pins its attribution placement. if ( - /^body\.stories-mode:not\(#gs-a\):not\(#gs-b\) #(cesium|gev)-credits$/.test(part) - ) continue; + /^body\.stories-mode:not\(#gs-a\):not\(#gs-b\) #(cesium|gev)-credits$/.test( + part, + ) + ) + continue; entries.push({ rule, part }); } } @@ -521,6 +588,22 @@ test('the model refuses every cascade construct it cannot resolve', () => { // Expanded Context covers the right edge top to bottom; the credit row // stops short of it instead (the docked-Context test below). if (part === DOCKED_RAIL) continue; + if (part.startsWith(OMNIBAR_SCOPE)) { + const allowed = OMNIBAR_RECOGNIZED.get(part); + for (const decl of guarded) { + if (!allowed?.has(decl.prop)) + complaints.push( + `unrecognized Omnibar rule positions a modelled element: "${part}" (${decl.prop})`, + ); + if (decl.important) + complaints.push(`!important on ${decl.prop} of "${part}"`); + } + if (rule.media.length) + complaints.push( + `media query on Omnibar rule "${part}": ${rule.media.join(' && ')}`, + ); + continue; + } if (!RECOGNIZED.has(part)) { complaints.push( `unrecognized selector positions a modelled element: "${part}" (${guarded.map((d) => d.prop).join(', ')})`, @@ -771,6 +854,116 @@ test('right rail measurement cannot persist into a painted attribution layout', // ── Clearance ─────────────────────────────────────────────────────────────── +/** A custom property's value as the Omnibar scope declares it. */ +function omnibarVar(name) { + const decls = RULES.filter((rule) => rule.parts.includes(OMNIBAR_SCOPE)) + .flatMap((rule) => rule.decls) + .filter((decl) => decl.prop === name); + assert.equal(decls.length, 1, `${name} is declared once in the Omnibar scope`); + return decls[0].value; +} + +/** A length in the Omnibar layout, with its scope's own custom properties. */ +function omnibarPx(value, viewportHeight, where) { + const substituted = value.replace( + /var\((--omnibar-[\w-]+)\)/g, + (_, name) => omnibarVar(name), + ); + return toPx(substituted, viewportHeight, where); +} + +test('Omnibar reserves a non-overlapping desktop footer at native credit sizing', () => { + // The Omnibar layout resolves through the same cascade as the legacy one: + // every legacy rule that could still match competes with the scope's. + const trayOpen = [ + '#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', + ); + for (const width of WIDTHS.filter((w) => w >= OMNIBAR_MIN_WIDTH)) { + for (const height of HEIGHTS) { + for (const minimal of [false, true]) { + const dock = resolve( + ['#command-dock', ...trayOpen, OMNIBAR.dock], + 'bottom', + width, + 'Omnibar dock', + ); + assert.equal(dock.part, OMNIBAR.dock, `the Omnibar owns the dock at ${width}px`); + // Its top and height too: a legacy top or height winning here would + // move or stretch the dock the clearance below is measured from. + for (const [prop, value] of [ + ['top', 'auto'], + ['height', '56px'], + ]) { + const own = resolve( + ['#command-dock', ...trayOpen, OMNIBAR.dock], + prop, + width, + `Omnibar dock ${prop}`, + ); + assert.equal(own.part, OMNIBAR.dock, `the Omnibar owns the dock ${prop} at ${width}px`); + assert.equal(own.decl.value, value, `Omnibar dock ${prop} at ${width}px`); + } + const credit = resolve( + [ + ...CREDIT_SELECTORS, + OMNIBAR.credit, + ...(minimal ? [MINIMAL_HUD_CREDIT, OMNIBAR.minimalCredit] : []), + ], + 'bottom', + width, + 'Omnibar credit', + ); + assert.ok( + credit.part.startsWith(OMNIBAR_SCOPE), + `the Omnibar owns the credit row at ${width}px`, + ); + const dockBottom = omnibarPx(dock.decl.value, height, 'Omnibar dock bottom'); + const creditTop = + omnibarPx(credit.decl.value, height, 'Omnibar credit bottom') + + CREDIT_HEIGHT_PX; + assert.ok( + dockBottom - creditTop >= MIN_CLEARANCE_PX, + `at ${width}x${height}${minimal ? ' (minimal HUD)' : ''} the Omnibar dock (${dockBottom}px) must clear the credit line (${creditTop}px)`, + ); + } + } + } + // No legacy tray opens over the credit: both are hidden in this layout, + // and no rule elsewhere forces them back. + const trays = RULES.find((rule) => rule.parts.includes(OMNIBAR.trays)); + assert.ok(trays, 'the Omnibar layout hides the legacy trays'); + assert.equal(trays.decls.find((decl) => decl.prop === 'display')?.value, 'none'); + for (const rule of RULES) { + for (const part of rule.parts) { + if (!/#(location-bar|control-panel)$/.test(lastCompound(part))) continue; + assert.ok( + !rule.decls.some((decl) => decl.prop === 'display' && decl.important), + `"${part}" forces a hidden tray back with !important`, + ); + } + } + // The minimal-HUD rail cap only shortens the rail, which is anchored at + // its top, so it can only add room above the credit. + const rail = RULES.find((rule) => rule.parts.includes(OMNIBAR.minimalRail)); + const cap = rail.decls.find((decl) => decl.prop === '--omnibar-minimal-rail-height'); + assert.match(cap?.value || '', /^min\(\s*var\(--right-stack-max-height, 70vh\),/); + assert.equal( + rail.decls.find((decl) => decl.prop === 'max-height')?.value, + 'var(--omnibar-minimal-rail-height)', + ); + assert.doesNotMatch( + omnibarCss, + /\.cesium-widget-credits|\.cesium-credit-logoContainer|\.cesium-credit-textContainer/, + 'the footer uses the original credit text and logo sizing', + ); +}); + test('every open dock tray clears the required credit at every modelled viewport', () => { // Below 900px the tray widens to nearly the viewport and lands on the // bottom-left corner where the credit lives. The clearance is NOT one fixed diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index a14abe67f5..1aa9457d77 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -4675,5 +4675,34 @@ "other": "عرض {what} في {place} ({count} عنصر)" }, "Go there": "انتقل إلى هناك", - "Open draw options": "فتح خيارات الرسم" + "Open draw options": "فتح خيارات الرسم", + "{what} in {place}: {count} items": { + "zero": "{what} في {place}: ‏{count} عنصر", + "one": "{what} في {place}: ‏{count} عنصر", + "two": "{what} في {place}: ‏{count} عنصران", + "few": "{what} في {place}: ‏{count} عناصر", + "many": "{what} في {place}: ‏{count} عنصرًا", + "other": "{what} في {place}: ‏{count} عنصر" + }, + "{count} items in view": { + "zero": "{count} عنصر في العرض", + "one": "{count} عنصر في العرض", + "two": "{count} عنصران في العرض", + "few": "{count} عناصر في العرض", + "many": "{count} عنصرًا في العرض", + "other": "{count} عنصر في العرض" + }, + "Selected · near {name}": "محدّد · قرب {name}", + "Near {name}": "بالقرب من {name}", + "Stop drawing": "إيقاف الرسم", + "{place} · landmarks": "{place} · معالم", + "In {place}": "داخل {place}", + "Near {place}": "بالقرب من {place}", + "Unable to complete this action: {reason}": "تعذر إكمال هذا الإجراء: ‏{reason}", + "Unable to complete this action. Please try again.": "تعذر إكمال هذا الإجراء. يرجى المحاولة مرة أخرى.", + "{layer} M{mag}+": "{layer} بقوة M{mag} فأكثر", + "Search places, layers and things on the map, or ask GEV": "ابحث عن أماكن وطبقات وعناصر على الخريطة، أو اسأل GEV", + "Search places, layers, flights… or ask GEV · > for commands": "ابحث عن أماكن وطبقات ورحلات جوية… أو اسأل GEV · > للأوامر", + "No matching command": "لا يوجد أمر مطابق", + "Looks private, so nothing is searched or sent": "يبدو خاصًا، لذا لا يُبحث عنه ولا يُرسل" } diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index 786bfa741e..fc654eabb1 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -4259,5 +4259,26 @@ "other": "{what} in der Region {place} anzeigen ({count} Elemente)" }, "Go there": "Dorthin wechseln", - "Open draw options": "Zeichenoptionen öffnen" + "Open draw options": "Zeichenoptionen öffnen", + "{what} in {place}: {count} items": { + "one": "{what} in der Region {place}: {count} Element", + "other": "{what} in der Region {place}: {count} Elemente" + }, + "{count} items in view": { + "one": "{count} Element im Blick", + "other": "{count} Elemente im Blick" + }, + "Selected · near {name}": "Auswahl · nahe {name}", + "Near {name}": "Nahe {name}", + "Stop drawing": "Zeichnen beenden", + "{place} · landmarks": "{place} · Sehenswürdigkeiten", + "In {place}": "In der Region {place}", + "Near {place}": "Nahe {place}", + "Unable to complete this action: {reason}": "Diese Aktion konnte nicht abgeschlossen werden: {reason}", + "Unable to complete this action. Please try again.": "Diese Aktion konnte nicht abgeschlossen werden. Bitte versuche es erneut.", + "{layer} M{mag}+": "{layer} ab Magnitude {mag}", + "Search places, layers and things on the map, or ask GEV": "Suche Orte, Ebenen und Kartenelemente oder frage GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Orte, Ebenen, Flüge suchen… oder GEV fragen · > für Befehle", + "No matching command": "Kein passender Befehl", + "Looks private, so nothing is searched or sent": "Sieht privat aus, daher wird nichts gesucht oder gesendet" } diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 38c484b85f..1c4543818d 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -4363,5 +4363,28 @@ "other": "Mostrar {what} en {place} ({count} elementos)" }, "Go there": "Ir allí", - "Open draw options": "Abrir opciones de dibujo" + "Open draw options": "Abrir opciones de dibujo", + "{what} in {place}: {count} items": { + "one": "{what} en {place}: {count} elemento", + "many": "{what} en {place}: {count} de elementos", + "other": "{what} en {place}: {count} elementos" + }, + "{count} items in view": { + "one": "{count} elemento a la vista", + "many": "{count} de elementos a la vista", + "other": "{count} elementos a la vista" + }, + "Selected · near {name}": "Selección · cerca de {name}", + "Near {name}": "Cerca de {name}", + "Stop drawing": "Dejar de dibujar", + "{place} · landmarks": "{place} · lugares de interés", + "In {place}": "En {place}", + "Near {place}": "Cerca de {place}", + "Unable to complete this action: {reason}": "No se pudo completar esta acción: {reason}", + "Unable to complete this action. Please try again.": "No se pudo completar esta acción. Inténtalo de nuevo.", + "{layer} M{mag}+": "{layer} de M{mag} o más", + "Search places, layers and things on the map, or ask GEV": "Busca lugares, capas y elementos del mapa, o pregunta a GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Busca lugares, capas, vuelos… o pregunta a GEV · > para comandos", + "No matching command": "Ningún comando coincide", + "Looks private, so nothing is searched or sent": "Parece privado, así que no se busca ni se envía nada" } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 95725609fb..725b762065 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -4363,5 +4363,28 @@ "other": "Afficher {what} dans la zone de {place} ({count} éléments)" }, "Go there": "Y aller", - "Open draw options": "Ouvrir les options de dessin" + "Open draw options": "Ouvrir les options de dessin", + "{what} in {place}: {count} items": { + "one": "{what} dans la zone de {place} : {count} élément", + "many": "{what} dans la zone de {place} : {count} d’éléments", + "other": "{what} dans la zone de {place} : {count} éléments" + }, + "{count} items in view": { + "one": "{count} élément visible", + "many": "{count} d’éléments visibles", + "other": "{count} éléments visibles" + }, + "Selected · near {name}": "Sélection · près de {name}", + "Near {name}": "Près de {name}", + "Stop drawing": "Arrêter le dessin", + "{place} · landmarks": "{place} · points d’intérêt", + "In {place}": "Dans la zone de {place}", + "Near {place}": "Près de {place}", + "Unable to complete this action: {reason}": "Impossible de terminer cette action : {reason}", + "Unable to complete this action. Please try again.": "Impossible de terminer cette action. Veuillez réessayer.", + "{layer} M{mag}+": "{layer} de magnitude {mag} ou plus", + "Search places, layers and things on the map, or ask GEV": "Recherchez des lieux, des couches et des éléments sur la carte, ou interrogez GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Recherchez des lieux, des couches, des vols… ou interrogez GEV · > pour les commandes", + "No matching command": "Aucune commande correspondante", + "Looks private, so nothing is searched or sent": "Semble privé, donc rien n’est recherché ni envoyé" } diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index bda1806ab2..07d2cb56e7 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -4363,5 +4363,28 @@ "other": "הצגת {what} ב{place} ({count} פריטים)" }, "Go there": "מעבר למקום", - "Open draw options": "פתיחת אפשרויות הציור" + "Open draw options": "פתיחת אפשרויות הציור", + "{what} in {place}: {count} items": { + "one": "{what} ב{place}: ‏{count} פריט", + "two": "{what} ב{place}: ‏{count} פריטים", + "other": "{what} ב{place}: ‏{count} פריטים" + }, + "{count} items in view": { + "one": "{count} פריט בתצוגה", + "two": "{count} פריטים בתצוגה", + "other": "{count} פריטים בתצוגה" + }, + "Selected · near {name}": "נבחר · ליד {name}", + "Near {name}": "ליד {name}", + "Stop drawing": "הפסקת הציור", + "{place} · landmarks": "{place} · אתרים בולטים", + "In {place}": "בתוך {place}", + "Near {place}": "בסביבת {place}", + "Unable to complete this action: {reason}": "לא ניתן להשלים את הפעולה: ‏{reason}", + "Unable to complete this action. Please try again.": "לא ניתן להשלים את הפעולה. נסו שוב.", + "{layer} M{mag}+": "{layer} בעוצמה M{mag} ומעלה", + "Search places, layers and things on the map, or ask GEV": "חפשו מקומות, שכבות ופריטים במפה, או שאלו את GEV", + "Search places, layers, flights… or ask GEV · > for commands": "חיפוש מקומות, שכבות וטיסות… או שאלה ל‑GEV · > לפקודות", + "No matching command": "אין פקודה תואמת", + "Looks private, so nothing is searched or sent": "נראה פרטי, ולכן שום דבר לא מחופש או נשלח" } diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 45b64e9c08..ba9c86cdb2 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -4363,5 +4363,28 @@ "other": "Mostra {what} a {place} ({count} elementi)" }, "Go there": "Vai lì", - "Open draw options": "Apri le opzioni di disegno" + "Open draw options": "Apri le opzioni di disegno", + "{what} in {place}: {count} items": { + "one": "{what} a {place}: {count} elemento", + "many": "{what} a {place}: {count} di elementi", + "other": "{what} a {place}: {count} elementi" + }, + "{count} items in view": { + "one": "{count} elemento in vista", + "many": "{count} di elementi in vista", + "other": "{count} elementi in vista" + }, + "Selected · near {name}": "Selezione · vicino a {name}", + "Near {name}": "Vicino a {name}", + "Stop drawing": "Interrompi il disegno", + "{place} · landmarks": "{place} · punti di interesse", + "In {place}": "A {place}", + "Near {place}": "Vicino a {place}", + "Unable to complete this action: {reason}": "Impossibile completare questa azione: {reason}", + "Unable to complete this action. Please try again.": "Impossibile completare questa azione. Riprova.", + "{layer} M{mag}+": "{layer} di magnitudo {mag} o superiore", + "Search places, layers and things on the map, or ask GEV": "Cerca luoghi, livelli ed elementi sulla mappa oppure chiedi a GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Cerca luoghi, livelli, voli… oppure chiedi a GEV · > per i comandi", + "No matching command": "Nessun comando corrispondente", + "Looks private, so nothing is searched or sent": "Sembra privato, quindi non viene cercato né inviato nulla" } diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 0fe1a3c597..cda461467b 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -4155,5 +4155,24 @@ "other": "{place}の{what}を表示({count}件)" }, "Go there": "その場所に移動", - "Open draw options": "描画オプションを開く" + "Open draw options": "描画オプションを開く", + "{what} in {place}: {count} items": { + "other": "{place}の{what}:{count}件" + }, + "{count} items in view": { + "other": "{count}件表示中" + }, + "Selected · near {name}": "選択中 · {name}の周辺", + "Near {name}": "{name}の周辺", + "Stop drawing": "描画を終了", + "{place} · landmarks": "{place} · 名所", + "In {place}": "{place}の範囲内", + "Near {place}": "{place}の周辺", + "Unable to complete this action: {reason}": "この操作を完了できませんでした:{reason}", + "Unable to complete this action. Please try again.": "この操作を完了できませんでした。もう一度お試しください。", + "{layer} M{mag}+": "{layer}(M{mag}以上)", + "Search places, layers and things on the map, or ask GEV": "場所、レイヤー、マップ上の対象を検索するか、GEVに質問", + "Search places, layers, flights… or ask GEV · > for commands": "場所、レイヤー、航空便を検索… またはGEVに質問 · > でコマンド", + "No matching command": "一致するコマンドがありません", + "Looks private, so nothing is searched or sent": "個人情報の可能性があるため、検索も送信もしません" } diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index 5e75f06d6c..7505611ece 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -4363,5 +4363,28 @@ "other": "Mostrar {what} em {place} ({count} itens)" }, "Go there": "Ir até lá", - "Open draw options": "Abrir opções de desenho" + "Open draw options": "Abrir opções de desenho", + "{what} in {place}: {count} items": { + "one": "{what} em {place}: {count} item", + "many": "{what} em {place}: {count} de itens", + "other": "{what} em {place}: {count} itens" + }, + "{count} items in view": { + "one": "{count} item à vista", + "many": "{count} de itens à vista", + "other": "{count} itens à vista" + }, + "Selected · near {name}": "Seleção · perto de {name}", + "Near {name}": "Perto de {name}", + "Stop drawing": "Parar de desenhar", + "{place} · landmarks": "{place} · pontos de interesse", + "In {place}": "Em {place}", + "Near {place}": "Perto de {place}", + "Unable to complete this action: {reason}": "Não foi possível concluir esta ação: {reason}", + "Unable to complete this action. Please try again.": "Não foi possível concluir esta ação. Tente novamente.", + "{layer} M{mag}+": "{layer} de magnitude {mag} ou mais", + "Search places, layers and things on the map, or ask GEV": "Busque lugares, camadas e elementos no mapa ou pergunte ao GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Busque lugares, camadas, voos… ou pergunte ao GEV · > para comandos", + "No matching command": "Nenhum comando correspondente", + "Looks private, so nothing is searched or sent": "Parece privado, por isso nada é pesquisado nem enviado" } diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index 3f3f224cfd..03b46c3591 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -4467,5 +4467,30 @@ "other": "Показать {what} · {place} ({count} объекта)" }, "Go there": "Перейти туда", - "Open draw options": "Открыть параметры рисования" + "Open draw options": "Открыть параметры рисования", + "{what} in {place}: {count} items": { + "one": "{what} · {place}: {count} объект", + "few": "{what} · {place}: {count} объекта", + "many": "{what} · {place}: {count} объектов", + "other": "{what} · {place}: {count} объекта" + }, + "{count} items in view": { + "one": "{count} объект в поле зрения", + "few": "{count} объекта в поле зрения", + "many": "{count} объектов в поле зрения", + "other": "{count} объекта в поле зрения" + }, + "Selected · near {name}": "Выбрано · рядом с {name}", + "Near {name}": "Рядом с {name}", + "Stop drawing": "Завершить рисование", + "{place} · landmarks": "{place} · достопримечательности", + "In {place}": "Места в {place}", + "Near {place}": "Рядом с {place}", + "Unable to complete this action: {reason}": "Не удалось выполнить действие: {reason}", + "Unable to complete this action. Please try again.": "Не удалось выполнить действие. Попробуйте ещё раз.", + "{layer} M{mag}+": "{layer} с магнитудой от {mag}", + "Search places, layers and things on the map, or ask GEV": "Ищите места, слои и объекты на карте или спросите GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Ищите места, слои, рейсы… или спросите GEV · > для команд", + "No matching command": "Подходящая команда не найдена", + "Looks private, so nothing is searched or sent": "Похоже на личные данные, поэтому ничего не ищется и не отправляется" } diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 14c8ed02ee..fd2cb35a42 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -4259,5 +4259,26 @@ "other": "Visa {what} i {place} ({count} objekt)" }, "Go there": "Gå dit", - "Open draw options": "Öppna ritalternativ" + "Open draw options": "Öppna ritalternativ", + "{what} in {place}: {count} items": { + "one": "{what} i {place}: {count} objekt", + "other": "{what} i {place}: {count} objekt" + }, + "{count} items in view": { + "one": "{count} objekt i vyn", + "other": "{count} objekt i vyn" + }, + "Selected · near {name}": "Valt objekt · nära {name}", + "Near {name}": "Nära {name}", + "Stop drawing": "Sluta rita", + "{place} · landmarks": "{place} · sevärdheter", + "In {place}": "I {place}", + "Near {place}": "Nära {place}", + "Unable to complete this action: {reason}": "Det gick inte att slutföra åtgärden: {reason}", + "Unable to complete this action. Please try again.": "Det gick inte att slutföra åtgärden. Försök igen.", + "{layer} M{mag}+": "{layer} med magnitud {mag} eller högre", + "Search places, layers and things on the map, or ask GEV": "Sök efter platser, lager och objekt på kartan eller fråga GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Sök efter platser, lager, flyg… eller fråga GEV · > för kommandon", + "No matching command": "Inget matchande kommando", + "Looks private, so nothing is searched or sent": "Ser privat ut, så inget söks eller skickas" } diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index d778b54801..ff34b3aaeb 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -4467,5 +4467,30 @@ "other": "Показати {what} · {place} ({count} об’єкта)" }, "Go there": "Перейти туди", - "Open draw options": "Відкрити параметри малювання" + "Open draw options": "Відкрити параметри малювання", + "{what} in {place}: {count} items": { + "one": "{what} · {place}: {count} об’єкт", + "few": "{what} · {place}: {count} об’єкти", + "many": "{what} · {place}: {count} об’єктів", + "other": "{what} · {place}: {count} об’єкта" + }, + "{count} items in view": { + "one": "{count} об’єкт у полі зору", + "few": "{count} об’єкти у полі зору", + "many": "{count} об’єктів у полі зору", + "other": "{count} об’єкта у полі зору" + }, + "Selected · near {name}": "Вибране · поблизу {name}", + "Near {name}": "Поблизу {name}", + "Stop drawing": "Припинити малювання", + "{place} · landmarks": "{place} · визначні місця", + "In {place}": "Місця в {place}", + "Near {place}": "Поблизу {place}", + "Unable to complete this action: {reason}": "Не вдалося виконати цю дію: {reason}", + "Unable to complete this action. Please try again.": "Не вдалося виконати цю дію. Спробуйте ще раз.", + "{layer} M{mag}+": "{layer} з магнітудою від {mag}", + "Search places, layers and things on the map, or ask GEV": "Шукайте місця, шари й об’єкти на карті або запитайте GEV", + "Search places, layers, flights… or ask GEV · > for commands": "Шукайте місця, шари, рейси… або запитайте GEV · > для команд", + "No matching command": "Відповідної команди не знайдено", + "Looks private, so nothing is searched or sent": "Схоже на особисті дані, тому нічого не шукається й не надсилається" } diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index c2d1f49e94..f4333ece82 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -4155,5 +4155,24 @@ "other": "显示{place}的{what}({count} 个)" }, "Go there": "前往该地点", - "Open draw options": "打开绘制选项" + "Open draw options": "打开绘制选项", + "{what} in {place}: {count} items": { + "other": "{place}的{what}:{count} 个" + }, + "{count} items in view": { + "other": "视野内 {count} 个" + }, + "Selected · near {name}": "已选中 · {name}附近", + "Near {name}": "{name}附近", + "Stop drawing": "停止绘制", + "{place} · landmarks": "{place} · 地标", + "In {place}": "{place}境内", + "Near {place}": "{place}附近", + "Unable to complete this action: {reason}": "无法完成此操作:{reason}", + "Unable to complete this action. Please try again.": "无法完成此操作。请重试。", + "{layer} M{mag}+": "{layer}(震级 M{mag} 及以上)", + "Search places, layers and things on the map, or ask GEV": "搜索地点、图层和地图上的对象,或向 GEV 提问", + "Search places, layers, flights… or ask GEV · > for commands": "搜索地点、图层、航班… 或问 GEV · > 输入命令", + "No matching command": "没有匹配的命令", + "Looks private, so nothing is searched or sent": "疑似隐私信息,因此不会搜索或发送" } diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index 640f5bb730..210a831dc9 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -4155,5 +4155,24 @@ "other": "顯示{place}的{what}({count} 個)" }, "Go there": "前往該地點", - "Open draw options": "打開繪製選項" + "Open draw options": "打開繪製選項", + "{what} in {place}: {count} items": { + "other": "{place}的{what}:{count} 個" + }, + "{count} items in view": { + "other": "視野內 {count} 個" + }, + "Selected · near {name}": "已選中 · {name}附近", + "Near {name}": "{name}附近", + "Stop drawing": "停止繪製", + "{place} · landmarks": "{place} · 地標", + "In {place}": "{place}境內", + "Near {place}": "{place}附近", + "Unable to complete this action: {reason}": "無法完成此操作:{reason}", + "Unable to complete this action. Please try again.": "無法完成此操作。請重試。", + "{layer} M{mag}+": "{layer}(震級 M{mag} 及以上)", + "Search places, layers and things on the map, or ask GEV": "搜索地點、圖層和地圖上的對象,或向 GEV 提問", + "Search places, layers, flights… or ask GEV · > for commands": "搜索地點、圖層、航班… 或問 GEV · > 輸入命令", + "No matching command": "沒有匹配的命令", + "Looks private, so nothing is searched or sent": "疑似隱私信息,因此不會搜索或發送" } diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index ed10b008f6..6b636f9b51 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -78,6 +78,12 @@ import { useCockpitStore } from './stores/cockpit.js'; import { useGlobeActionsStore } from './stores/globeActions.js'; import { useRecordingStore } from './stores/recording.js'; import { onPlacePacksLoadingChange } from '../data/placeBelow.js'; +import { + hideOsmCredit, + registerDynamicCredit, + showOsmCredit, + WIKIDATA_PLACES_CREDIT, +} from '../data/dataCredits.js'; import { withPlacePacks } from './placePacksLoading.js'; import { preloadOwnerFlags } from './ownerFlag.js'; @@ -182,6 +188,14 @@ export class StyleManager extends ShellFacade { layers: () => this._dataManager?.getAll?.() || [], setLayer: (id, enabled) => this._dataManager?.setEnabled(id, enabled, { origin: 'user' }), + // The Omnibar shows names from the bundled Wikidata packs. + creditPlaces: () => + registerDynamicCredit(this.viewer, WIKIDATA_PLACES_CREDIT), + // Photon's suggestions are OpenStreetMap data: credited while shown. + creditSuggestions: (shown) => + shown + ? showOsmCredit(this.viewer, 'omnibar') + : hideOsmCredit(this.viewer, 'omnibar'), }); // Scrolling at a screen edge steps through that side's rail panels. this._removeRailEdgeScroll = installRailEdgeScroll(); diff --git a/src/ui/commandDock.test.mjs b/src/ui/commandDock.test.mjs index 733c34425e..5f6d1bf2ab 100644 --- a/src/ui/commandDock.test.mjs +++ b/src/ui/commandDock.test.mjs @@ -8,7 +8,13 @@ import { createApp, h, nextTick } from 'vue'; import { setLocale } from '../i18n/index.js'; import { useDisplayStore } from './stores/display.js'; import { useLocationStore } from './stores/location.js'; +import { useOmnibarStore } from './stores/omnibar.js'; +import { useVoiceStore } from './stores/voice.js'; +import { useGlobeActionsStore } from './stores/globeActions.js'; import { LocationControls } from './locationControls.js'; +import { LocationSearch } from './locationSearch.js'; +import { LocationNavigation } from './locationNavigation.js'; +import { NavigationController } from './navigationController.js'; import { MOBILE_TABS, initMobileShell } from './mobileShell.js'; import CommandDockView from './views/CommandDockView.vue'; import SceneChromeView from './views/SceneChromeView.vue'; @@ -486,3 +492,1593 @@ test('the search toggle opens the field, and a lookup marks it', async (t) => { assert.equal(field.classList.contains('searching'), false); assert.equal(field.classList.contains('expanded'), false); }); + +function omnibarFixture(t, onSearch = () => {}) { + const mounted = fixture(t); + const { $, pinia } = mounted; + const location = useLocationStore(pinia); + const controls = new LocationControls({ + elements: { search: $('#location-search') }, + cities: {}, + getExpandedCity: () => null, + onCity() {}, + onPoi() {}, + onReset() {}, + onSearch: (query) => { + controls.setSearching(true); + return onSearch(query); + }, + onSearchEdit: () => controls.setSearchError(null), + publish: (view) => location.publish(view), + requestFrame() {}, + cancelFrame() {}, + }); + t.after(() => controls.destroy()); + location.connect(controls); + const mutations = []; + // Switching a layer changes its state, as the app's layers do. + const fixtureLayers = [ + { id: 'flights', name: 'Flights', enabled: false }, + { + id: 'scene-layer', + name: 'Scene Layer', + enabled: false, + showInTogglePanel: false, + }, + ]; + useOmnibarStore(pinia).connect({ + layers: () => fixtureLayers, + setLayer: (id, enabled) => { + mutations.push([id, enabled]); + const layer = fixtureLayers.find((each) => each.id === id); + if (layer) layer.enabled = enabled; + }, + }); + const voiceEvents = []; + useVoiceStore(pinia).connect({ emit: (...args) => voiceEvents.push(args) }); + const globeEvents = []; + useGlobeActionsStore(pinia).connect({ + northUp: () => globeEvents.push('northUp'), + }); + const input = $('#gev-omnibar-input'); + async function type(text) { + input.focus(); + input.value = text; + input.dispatchEvent(new Event('input', { bubbles: true })); + await nextTick(); + } + async function key(key, options = {}) { + input.dispatchEvent( + new KeyboardEvent('keydown', { key, bubbles: true, ...options }), + ); + await nextTick(); + } + function option(kind) { + return [ + ...document.querySelectorAll('#gev-omnibar-list [role="option"]'), + ].find((row) => + row.classList.contains(`omnibar-item--${kind.toLowerCase()}`), + ); + } + return { + ...mounted, + controls, + mutations, + voiceEvents, + globeEvents, + input, + type, + key, + option, + }; +} + +test('omnibar preserves ambiguous and disambiguated place queries, including IME input', async (t) => { + const searched = []; + const { type, key, mutations } = omnibarFixture(t, (query) => + searched.push(query), + ); + await type('Little Rock'); + await key('Enter', { isComposing: true }); + assert.deepEqual(searched, []); + await key('Enter'); + await type('Paris, Texas'); + await key('Enter'); + assert.deepEqual(searched, ['Little Rock', 'Paris, Texas']); + assert.deepEqual(mutations, []); +}); + +test('omnibar executes explicit commands and click selections, while guides and unknown commands do not mutate', async (t) => { + const { + $, + type, + key, + option, + mutations, + voiceEvents, + globeEvents, + pinia, + input, + } = omnibarFixture(t); + await type('> show flights'); + await key('Enter'); + await type('> hide flights'); + await key('Enter'); + assert.deepEqual(mutations, [ + ['flights', true], + ['flights', false], + ]); + await type('scene layer'); + assert.equal(option('Layer'), undefined); + assert.equal(option('Guide'), undefined); + await type('> show scene-layer'); + await key('Enter'); + assert.equal(mutations.length, 2); + await type('> not a command'); + await key('Enter'); + assert.deepEqual(voiceEvents, []); + await type('flights'); + const layer = option('Layer'); + layer.dispatchEvent(new Event('pointerdown', { bubbles: true })); + assert.equal( + mutations.length, + 2, + 'starting a touch scroll does not select a layer', + ); + layer.click(); + await nextTick(); + assert.deepEqual(mutations[2], ['flights', true]); + await type('how to see flights'); + option('Guide').click(); + await nextTick(); + assert.ok($('.gev-guide [role="dialog"]')); + $('.gev-guide-close').click(); + assert.deepEqual(globeEvents, []); + assert.equal(mutations.length, 3); + await type('> north up'); + for (const mode of ['scene-playback-mode', 'cockpit-mode']) { + document.body.classList.add(mode); + try { + const escape = new KeyboardEvent('keydown', { + key: 'Escape', + bubbles: true, + cancelable: true, + }); + input.dispatchEvent(escape); + assert.equal(escape.defaultPrevented, false); + await key('Enter'); + assert.deepEqual(globeEvents, []); + } finally { + document.body.classList.remove(mode); + } + } + await key('Enter'); + assert.deepEqual(globeEvents, ['northUp']); + let accepted = false; + useOmnibarStore(pinia).connect({ + layers: () => [{ id: 'flights', name: 'Flights', enabled: false }], + setLayer: () => accepted, + }); + await type('> show flights'); + await key('Enter'); + assert.ok($('#gev-omnibar [role="alert"]').textContent.trim()); + assert.equal(input.getAttribute('aria-expanded'), 'true'); + accepted = true; + await key('Enter'); + assert.equal($('#gev-omnibar [role="alert"]').textContent.trim(), ''); + assert.equal(input.getAttribute('aria-expanded'), 'false'); +}); + +test('omnibar uses the existing microphone and typed chat controls', async (t) => { + const { $, type, option, voiceEvents } = omnibarFixture(t); + await nextTick(); + $('#gev-omnibar button').click(); + await type('What is here?'); + option('Ask').click(); + await nextTick(); + assert.deepEqual(voiceEvents, [ + ['button'], + ['chat-restore'], + ['chat-prompt', 'What is here?'], + ['chat-submit'], + ]); +}); + +test('a replacement omnibar search keeps newer input and leaves the dock draft alone', async (t) => { + const pending = []; + const { $, type, key, input, option, mutations } = omnibarFixture( + t, + (query) => new Promise((resolve) => pending.push({ query, resolve })), + ); + $('#location-search').value = 'unfinished dock query'; + await type('Paris'); + await key('Enter'); + await type('Paris, Texas'); + await key('Enter'); + assert.deepEqual( + pending.map(({ query }) => query), + ['Paris', 'Paris, Texas'], + ); + pending[0].resolve(); + await nextTick(); + assert.equal(document.activeElement, input); + assert.equal(input.value, 'Paris, Texas'); + await type('flights'); + option('Layer').click(); + await nextTick(); + assert.deepEqual( + mutations, + [['flights', true]], + 'a pending place lookup does not block an explicit layer selection', + ); + pending[1].resolve(); + await nextTick(); + assert.equal($('#location-search').value, 'unfinished dock query'); +}); + +test('a superseded compound command does not run steps after its flight', async (t) => { + const { type, key, pinia, mutations, globeEvents } = omnibarFixture(t); + let finishFlight; + const calls = []; + useOmnibarStore(pinia).connectRunner((name) => { + calls.push(name); + return new Promise((resolve) => { + finishFlight = resolve; + }); + }); + + await type('go to Austin and show flights'); + await key('Enter'); + assert.deepEqual(calls, ['fly_to_location']); + await type('> north up'); + await key('Enter'); + assert.deepEqual(globeEvents, ['northUp']); + finishFlight({ ok: true }); + await nextTick(); + assert.deepEqual(mutations, []); +}); + +test('a cancelled flight stops the remaining steps in an omnibar command', async (t) => { + const { type, key, pinia, mutations } = omnibarFixture(t); + useOmnibarStore(pinia).connectRunner(async (name) => { + assert.equal(name, 'fly_to_location'); + return { ok: false, cancelled: true }; + }); + await type('go to Austin and show flights'); + await key('Enter'); + assert.deepEqual(mutations, []); +}); + +test('failed omnibar searches keep focus and clear their error on edit without changing the dock', async (t) => { + const { $, controls, input, type, key } = omnibarFixture(t, () => { + controls.setSearchError('No match'); + controls.settleSearch({ keepQuery: true }); + }); + $('#location-search').value = 'unfinished dock query'; + await type('missing place'); + const results = $('.omnibar-results'); + results.scrollTop = 20; + assert.equal(results.scrollTop, 20); + await key('Enter'); + assert.equal(document.activeElement, input); + assert.equal(results.scrollTop, 0); + assert.equal($('#location-search').value, 'unfinished dock query'); + assert.ok($('#gev-omnibar [role="alert"]')); + await type('corrected place'); + assert.equal($('#gev-omnibar [role="alert"]').textContent.trim(), ''); + await key('Escape'); + assert.equal(document.activeElement, input); + assert.equal(input.getAttribute('aria-expanded'), 'false'); +}); + +for (const firstOrigin of ['omnibar', 'dock']) { + test(`a pending ${firstOrigin} search yields to the other field without settling its draft`, async (t) => { + const requests = []; + let lookup; + const { $, controls, input, type, key } = omnibarFixture(t, (query) => + lookup.run(query), + ); + controls.onSearch = (query) => lookup.run(query); + const navigation = new NavigationController({ + viewer: {}, + tracking: { + flightsLayer: {}, + militaryFlightsLayer: {}, + satellitesLayer: {}, + }, + clearLocation() {}, + cancelShareSelection() {}, + getDataManager: () => null, + settleSearch: (options) => controls.settleSearch(options), + }); + const owner = { + _disposed: false, + get _activeLocationSearchGeneration() { + return navigation._activeLocationSearchGeneration; + }, + set _activeLocationSearchGeneration(value) { + navigation._activeLocationSearchGeneration = value; + }, + _locationControls: controls, + _setLocationSearchError: + LocationNavigation.prototype._setLocationSearchError, + _settleLocationSearchUi: + navigation._settleLocationSearchUi.bind(navigation), + }; + lookup = new LocationSearch({ + input: $('#location-search'), + begin: () => navigation._stampNavigation(), + isCurrent: (generation) => + generation === navigation._navigationGeneration, + setSearching: (value) => controls.setSearching(value), + search: (query, options) => + new Promise((resolve, reject) => + requests.push({ query, options, resolve, reject }), + ), + }); + lookup.subscribe(({ state, change }) => + LocationNavigation.prototype._handleLocationSearchState.call( + owner, + state, + change, + ), + ); + t.after(() => lookup.destroy()); + const dock = $('#location-search'); + async function submit(origin, text) { + if (origin === 'omnibar') { + await type(text); + await key('Enter'); + } else { + dock.value = text; + dock.focus(); + dock.dispatchEvent( + new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }), + ); + await nextTick(); + } + } + const lastOrigin = firstOrigin === 'omnibar' ? 'dock' : 'omnibar'; + await submit(firstOrigin, 'Old place'); + if (firstOrigin === 'omnibar') { + await submit('dock', ' '); + assert.equal(requests.length, 1); + assert.equal(controls.searchOrigin, 'omnibar'); + assert.equal(requests[0].options.signal.aborted, false); + } + await submit(lastOrigin, 'New place'); + assert.deepEqual( + requests.map(({ query }) => query), + ['Old place', 'New place'], + ); + assert.equal(requests[0].options.signal.aborted, true); + const latestInput = lastOrigin === 'dock' ? dock : input; + assert.equal(latestInput.value, 'New place'); + assert.equal(document.activeElement, latestInput); + requests[0].reject(new Error('obsolete provider failure')); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(controls.searching, true); + assert.equal(controls.searchError, null); + assert.equal(latestInput.value, 'New place'); + assert.equal(document.activeElement, latestInput); + requests[1].resolve(null); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.equal(controls.searching, false); + assert.equal(controls.searchOrigin, lastOrigin); + assert.equal(latestInput.value, 'New place'); + assert.equal(document.activeElement, latestInput); + const omnibarError = $('#gev-omnibar [role="alert"]').textContent.trim(); + const dockError = $('#location-search-error').textContent.trim(); + assert.equal(Boolean(omnibarError), lastOrigin === 'omnibar'); + assert.equal(Boolean(dockError), lastOrigin === 'dock'); + }); +} + +/** The suggestion rows as `kind: label`, top first. */ +function omnibarRows() { + return [...document.querySelectorAll('#gev-omnibar-list .omnibar-item')].map( + (row) => + `${[...row.classList].find((name) => name.startsWith('omnibar-item--')).slice(14)}: ${row.querySelector('.omnibar-item-label').textContent.trim()}`, + ); +} + +test('a command leads only on its exact name, and never the mic or cockpit', async (t) => { + const { type, input } = omnibarFixture(t); + const first = () => omnibarRows()[0]; + const activeRow = () => + document.getElementById(input.getAttribute('aria-activedescendant')); + for (const text of ['Voi', 'mic', 'Fly', 'Pilot']) { + await type(text); + assert.match(first(), /^place: /, `${text}: ${omnibarRows().join(' | ')}`); + assert.ok( + !activeRow().classList.contains('omnibar-item--mic'), + `${text} must not default to the microphone`, + ); + assert.doesNotMatch(activeRow().textContent, /cockpit/i, text); + } + // Still offered, after the first row. + await type('mic'); + assert.ok(omnibarRows().includes('mic: Talk to GEV')); + await type('Fly'); + assert.ok(omnibarRows().includes('plan: Enter cockpit')); + // A search word alone only finds its command, after the first row. + await type('Globe'); + assert.equal(first(), 'place: Go to Globe'); + assert.ok(omnibarRows().includes('plan: Globe view')); + // "Home" reads as Reset view, a whole-view change, so it is no default. + await type('Home'); + assert.equal(first(), 'plan: Reset view'); + assert.equal(input.getAttribute('aria-activedescendant'), null); + // A general word is no command name: Enter on it clears nothing. + await type('everything'); + assert.notEqual(first(), 'plan: Clear all layers'); +}); + +test('an empty field has no default row, so a bare Enter asks nothing', async (t) => { + const { type, key, input, voiceEvents, option } = omnibarFixture(t); + await type(''); + assert.ok(option('view-ask'), 'the empty field still offers What’s here?'); + assert.equal(input.getAttribute('aria-activedescendant'), null); + await key('Enter'); + assert.deepEqual(voiceEvents, []); + await key('ArrowDown'); + assert.equal( + input.getAttribute('aria-activedescendant'), + 'gev-omnibar-item-0', + ); +}); + +test('short place names that start like questions keep a place row first', async (t) => { + const { type } = omnibarFixture(t); + for (const text of ['Can Tho', 'Tell City']) { + await type(text); + const rows = omnibarRows(); + assert.equal(rows[0], `place: Go to ${text}`, rows.join(' | ')); + assert.ok( + rows.indexOf(`place: Go to ${text}`) < + rows.findIndex((row) => row.startsWith('ask:')), + ); + } + await type('Can Tho?'); + assert.match(omnibarRows()[0], /^ask: /); +}); + +test('near-miss lines in the field: clears, turning off, and a place named like a verb', async (t) => { + const searched = []; + const { type, key } = omnibarFixture(t, (query) => searched.push(query)); + await type('hide everything'); + assert.equal(omnibarRows()[0], 'plan: Clear all layers'); + await type('remove everything'); + assert.equal(omnibarRows()[0], 'plan: Clear all layers'); + await type('How do I turn off flights'); + // Flights is off already: its row offers nothing to switch. + assert.ok( + [ + ...document.querySelectorAll( + '#gev-omnibar-list .omnibar-item--layer small', + ), + ].some((hint) => hint.textContent === 'Layer'), + omnibarRows().join(' | '), + ); + await type('Show Low, AZ'); + assert.equal(omnibarRows()[0], 'place: Go to Show Low, AZ'); + await key('Enter'); + assert.deepEqual(searched, ['Show Low, AZ']); +}); + +test('Escape while a plan waits on its flight leaves the layers alone', async (t) => { + const { type, key, pinia, mutations, input } = omnibarFixture(t); + let finishFlight; + useOmnibarStore(pinia).connectRunner( + () => + new Promise((resolve) => { + finishFlight = resolve; + }), + ); + await type('go to Austin and show flights'); + await key('Enter'); + assert.equal(input.getAttribute('aria-busy'), 'true'); + await key('Escape'); + assert.equal(input.getAttribute('aria-busy'), 'false'); + finishFlight({ ok: true }); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(mutations, []); +}); + +test('a plan step that fails stops the plan and shows the error', async (t) => { + const { $, type, key, pinia, mutations } = omnibarFixture(t); + const calls = []; + useOmnibarStore(pinia).connectRunner(async (name) => { + calls.push(name); + return name === 'fly_to_location' + ? { ok: false, error: 'no route' } + : { ok: true }; + }); + await type('go to Austin and show flights'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(calls, ['fly_to_location']); + assert.deepEqual(mutations, []); + assert.ok($('#gev-omnibar [role="alert"]').textContent.trim()); + + // A layer the shell refuses is an error too. + useOmnibarStore(pinia).connect({ + layers: () => [{ id: 'flights', name: 'Flights', enabled: false }], + setLayer: () => false, + }); + useOmnibarStore(pinia).connectRunner(async () => ({ ok: true })); + await type('show flights near tokyo'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.ok($('#gev-omnibar [role="alert"]').textContent.trim()); +}); + +test('radio off in a plan flies there first and turns the radio off', async (t) => { + const { type, key, pinia } = omnibarFixture(t); + const calls = []; + useOmnibarStore(pinia).connectRunner(async (name, args) => { + calls.push([name, args]); + return { ok: true }; + }); + await type('tokyo and turn off the radio'); + assert.equal(omnibarRows()[0], 'plan: Tokyo · Radio off'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(calls, [ + ['fly_to_location', { query: 'tokyo', waitForArrival: true }], + ['control_radio', { action: 'disable' }], + ]); +}); + +test('the field states what it controls and the mic its state', async (t) => { + const { $, type, input } = omnibarFixture(t); + input.blur(); + await nextTick(); + assert.equal(input.getAttribute('aria-controls'), null); + await type('flights'); + assert.equal(input.getAttribute('aria-controls'), 'gev-omnibar-list'); + assert.ok($('#gev-omnibar-list')); + const mic = $('.omnibar-mic'); + // Off until a voice session is in voice mode. + assert.equal(mic.getAttribute('aria-pressed'), 'false'); +}); + +test('the guide is a non-modal dialog that takes focus and only Escape', async (t) => { + const { $, type, option } = omnibarFixture(t); + await type('how to see flights'); + option('Guide').click(); + await nextTick(); + await nextTick(); + const dialog = $('.gev-guide [role="dialog"]'); + assert.equal(dialog.getAttribute('aria-modal'), 'false'); + // Steps are announced from a status line, not the whole dialog. + assert.equal(dialog.getAttribute('aria-live'), null); + assert.equal($('.gev-guide-status').getAttribute('role'), 'status'); + assert.equal(document.activeElement, dialog); + const other = new KeyboardEvent('keydown', { + key: 'a', + bubbles: true, + cancelable: true, + }); + document.dispatchEvent(other); + assert.equal(other.defaultPrevented, false); + assert.ok($('.gev-guide'), 'another key leaves the guide open'); + const escape = new KeyboardEvent('keydown', { + key: 'Escape', + bubbles: true, + cancelable: true, + }); + document.dispatchEvent(escape); + assert.equal(escape.defaultPrevented, true); + assert.equal($('.gev-guide'), null); +}); + +test('a bare ">" picks nothing, and whole-map commands need their name', async (t) => { + const { type, key, pinia, input, mutations } = omnibarFixture(t); + const acted = []; + useGlobeActionsStore(pinia).connect({ + clear: () => acted.push('clear'), + reset: () => acted.push('reset'), + northUp: () => acted.push('northUp'), + }); + for (const text of ['>', '> ', '> cl', '> clear']) { + await type(text); + assert.ok(omnibarRows().length, text); + assert.equal(input.getAttribute('aria-activedescendant'), null, text); + await key('Enter'); + } + assert.deepEqual(acted, []); + assert.deepEqual(mutations, []); + // Its exact name makes it the default. + await type('> Clear all layers'); + assert.equal( + input.getAttribute('aria-activedescendant'), + 'gev-omnibar-item-0', + ); + await key('Enter'); + assert.deepEqual(acted, ['clear']); + // A harmless command still leads on its name. + await type('> North up'); + await key('Enter'); + assert.deepEqual(acted, ['clear', 'northUp']); +}); + +test('place names holding a command word go to the place on Enter', async (t) => { + const searched = []; + const { type, key, input, pinia } = omnibarFixture(t, (query) => + searched.push(query), + ); + useOmnibarStore(pinia).connect({ + layers: () => [ + { id: 'flights', name: 'Flights', enabled: false }, + { id: 'rocket-launches', name: 'Rocket launches', enabled: false }, + { id: 'earthquakes', name: 'Earthquakes', enabled: false }, + { id: 'radio', name: 'Radio', enabled: false }, + ], + setLayer: () => {}, + }); + const activeRow = () => + document.getElementById(input.getAttribute('aria-activedescendant')); + for (const text of [ + 'Cockpit Country, Jamaica', + 'Radio City Music Hall', + 'Radio Free Europe', + 'Thermal, California', + 'Tilt Cove', + 'Hud Valley', + 'Rock and Roll Hall of Fame', + 'cockpit', + 'cockpit view', + ]) { + await type(text); + assert.match( + omnibarRows()[0], + /^place: Go to /, + `${text}: ${omnibarRows().join(' | ')}`, + ); + assert.ok(activeRow().classList.contains('omnibar-item--place'), text); + await key('Enter'); + assert.equal(searched.at(-1), text); + } + // The plan is still offered, second. + await type('Thermal, California'); + assert.equal(omnibarRows()[1], 'plan: California · Style: Thermal'); + // A word alone is no action default. + for (const text of ['music', 'link', 'heat', 'green', 'rotate', 'missions']) { + await type(text); + assert.ok( + !/^(plan|mic): /.test( + activeRow()?.classList.contains('omnibar-item--place') + ? '' + : omnibarRows()[0], + ), + `${text}: ${omnibarRows().join(' | ')}`, + ); + assert.ok(activeRow()?.classList.contains('omnibar-item--place'), text); + } + // "earth" offers the globe view before the earthquakes layer. + await type('earth'); + const rows = omnibarRows(); + const globe = rows.indexOf('plan: Globe view'); + assert.ok(globe > 0, rows.join(' | ')); + const quakes = rows.findIndex((row) => row.startsWith('layer: Earthquakes')); + assert.ok(quakes === -1 || globe < quakes, rows.join(' | ')); +}); + +test('several places and a magnitude floor in one line', async (t) => { + const { type, pinia } = omnibarFixture(t); + useOmnibarStore(pinia).connect({ + layers: () => [ + { id: 'flights', name: 'Flights', enabled: false }, + { id: 'earthquakes', name: 'Earthquakes', enabled: false }, + ], + setLayer: () => {}, + }); + await type('flights near New York and Paris'); + const rows = omnibarRows(); + assert.match(rows[0], /^plan: New York · /); + assert.ok(rows.includes('place: Go to Paris'), rows.join(' | ')); + await type('show me earthquakes above m5 in japan'); + assert.ok( + omnibarRows().includes('place: Go to Japan'), + omnibarRows().join(' | '), + ); +}); + +test('a refusal shows the action’s own short reason', async (t) => { + const { $, type, key, pinia } = omnibarFixture(t); + useOmnibarStore(pinia).connectRunner(async () => ({ + ok: false, + error: 'internal: no such entity', + say: 'I could not find that flight.', + })); + await type('follow ual123'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + const alert = $('#gev-omnibar [role="alert"]').textContent; + assert.match(alert, /I could not find that flight\./); + assert.doesNotMatch(alert, /internal/); +}); + +test('a plan whose flight does not land stops before its layers', async (t) => { + const { type, key, pinia, mutations } = omnibarFixture(t); + // A location search that was superseded answers neither true nor found. + useLocationStore(pinia).controls.search = async () => ({ cancelled: true }); + await type('go to Austin and show flights'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(mutations, []); +}); + +test('pressing the mic stops a plan still waiting on its flight', async (t) => { + const { type, key, pinia, mutations, voiceEvents, $ } = omnibarFixture(t); + let land; + useOmnibarStore(pinia).connectRunner((name) => + name === 'fly_to_location' + ? new Promise((resolve) => { + land = () => resolve({ ok: true }); + }) + : { ok: true }, + ); + await type('go to Austin and show flights'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + $('#gev-omnibar .omnibar-mic').click(); + assert.deepEqual(voiceEvents.at(-1), ['button']); + land(); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(mutations, []); +}); + +test('"how to measure distance" walks to Draw in Utilities', async (t) => { + const { type, key, $ } = omnibarFixture(t); + const rail = document.body.appendChild(document.createElement('div')); + rail.className = 'ui-rail--left'; + const utilities = rail.appendChild(document.createElement('button')); + utilities.className = 'ui-rail__item'; + utilities.dataset.railItem = 'utilities-panel'; + utilities.setAttribute('aria-pressed', 'true'); + const draw = document.body.appendChild(document.createElement('button')); + draw.id = 'draw-toggle'; + t.after(() => { + rail.remove(); + draw.remove(); + $('.gev-guide-close')?.click(); + }); + await type('how to measure distance'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + assert.match( + $('.gev-guide [role="dialog"]').textContent, + /Press Draw to start drawing on the map/, + ); +}); + +test('the field keeps focus after a command, a plan or a layer runs', async (t) => { + const { type, key, input } = recordingOmnibar(t, ['cctv']); + input.focus(); + for (const text of ['> North up', 'North up', 'show flights', 'noir']) { + await type(text); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + assert.equal(document.activeElement, input, text); + assert.equal(input.value, '', text); + } +}); + +test('a tapped or clicked row lets go of the field', async (t) => { + const { type, input } = recordingOmnibar(t); + input.focus(); + await type('North up'); + document.querySelector('#gev-omnibar-list .omnibar-item').click(); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + assert.notEqual(document.activeElement, input); +}); + +test('while drawing, Enter leaves the keys to the draw tool', async (t) => { + const { type, key, input, pinia } = recordingOmnibar(t); + useDisplayStore(pinia).publishDraw({ active: true, shape: 'line' }); + input.focus(); + await type('North up'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + assert.notEqual(document.activeElement, input); +}); + +test("on the phone, the keyboard's Go key lets go of the field too", async (t) => { + const { type, key, input } = recordingOmnibar(t); + document.body.classList.add('mobile-shell'); + t.after(() => document.body.classList.remove('mobile-shell')); + input.focus(); + await type('North up'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + assert.notEqual(document.activeElement, input); +}); + +test('Escape closes the list, then lets go of the empty field', async (t) => { + const { key, input } = recordingOmnibar(t); + input.focus(); + await key('Escape'); + assert.equal(document.activeElement, input); + await key('Escape'); + assert.notEqual(document.activeElement, input); +}); + +test('asking GEV hands the keyboard to the chat', async (t) => { + const { type, key, input } = recordingOmnibar(t); + input.focus(); + await type('how far is paris'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.notEqual(document.activeElement, input); +}); + +test('text withheld as private says so', async (t) => { + const { type } = recordingOmnibar(t); + const note = () => + [...document.querySelectorAll('#gev-omnibar [role="status"]')].find( + (element) => /Looks private/.test(element.textContent), + ); + await type('4111 1111 1111 1111'); + assert.notEqual(note().style.display, 'none'); + await type('Tokyo'); + assert.equal(note().style.display, 'none'); +}); + +test('a panel with no rail button fails rather than passing for done', async (t) => { + const { enter, $ } = recordingOmnibar(t); + await enter('Open Utilities'); + assert.match( + $('#gev-omnibar [role="alert"]').textContent, + /Unable to complete this action/, + ); +}); + +test('outside English a refusal shows the translated message alone', async (t) => { + t.after(() => setLocale('en')); + setLocale('de'); + const { type, key, pinia, $ } = omnibarFixture(t); + useOmnibarStore(pinia).connectRunner(async () => ({ + ok: false, + say: 'I could not find that flight.', + })); + await type('follow ual123'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + const alert = $('#gev-omnibar [role="alert"]').textContent; + assert.ok(alert.trim()); + assert.doesNotMatch(alert, /could not find/); +}); + +test('a recent place that came from Photon shows the OpenStreetMap credit', async (t) => { + const store = globalThis.localStorage; + store.setItem( + 'gev:omnibar:recent-places', + JSON.stringify([ + { + name: 'Shibuya Crossing', + latitude: 35.6595, + longitude: 139.7005, + source: 'photon', + }, + ]), + ); + t.after(() => store.removeItem('gev:omnibar:recent-places')); + stubPhoton(t); + const { type, credits } = recordingOmnibar(t); + await type('Tokyo'); + assert.ok( + [...document.querySelectorAll('.omnibar-strip__chip')].some((chip) => + chip.textContent.includes('Shibuya Crossing'), + ), + ); + assert.equal(credits.at(-1), true); +}); + +/** The fixture with a recording runner and globe actions, as the shell has. */ +function recordingOmnibar( + t, + layers = [], + { acts: actNames = ['clear', 'reset', 'share', 'northUp', 'tilt'] } = {}, +) { + const searched = []; + const fixture = omnibarFixture(t, (query) => searched.push(query)); + const calls = []; + const acted = []; + const switched = []; + const credits = []; + // One list, so a test can change a layer's live state. + const layerList = [ + { id: 'flights', name: 'Flights', enabled: false }, + ...layers.map((id) => ({ + id, + name: id.replace(/-/g, ' '), + enabled: false, + })), + ]; + useOmnibarStore(fixture.pinia).connect({ + layers: () => layerList, + setLayer: (...args) => switched.push(args), + creditSuggestions: (shown) => credits.push(shown), + }); + useOmnibarStore(fixture.pinia).connectRunner(async (name, args) => { + calls.push([name, args]); + return { ok: true }; + }); + const acts = {}; + for (const act of actNames) acts[act] = () => acted.push(act); + useGlobeActionsStore(fixture.pinia).connect(acts); + async function enter(text) { + await fixture.type(text); + await fixture.key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + } + return { + ...fixture, + searched, + calls, + acted, + switched, + credits, + layerList, + enter, + }; +} + +test('the radio and sharing are never Enter defaults unless named in full', async (t) => { + const { enter, calls, acted, input, type, switched } = recordingOmnibar(t, [ + 'radio', + ]); + for (const text of [ + 'radio', + 'Radio', + '> radio', + 'share', + 'Share', + 'copy map', + ]) { + await enter(text); + assert.deepEqual(calls, [], text); + assert.deepEqual(acted, [], text); + } + await type('radio'); + // Not asked outright: the place row leads, the Radio layer follows. + assert.deepEqual(omnibarRows().slice(0, 2), [ + 'place: Go to Radio', + 'layer: Radio', + ]); + assert.equal( + input.getAttribute('aria-activedescendant'), + 'gev-omnibar-item-0', + ); + // The Radio layer plays sound too: a verb turns it on, its name alone not. + assert.deepEqual(switched, []); + await enter('turn on radio'); + assert.deepEqual(switched, [['radio', true]]); + await enter('Share this view'); + assert.deepEqual(acted, ['share']); + // Its full name runs the command where no Radio layer answers it first. + await enter('Enable Radio'); + assert.deepEqual(switched.at(-1), ['radio', true]); + assert.deepEqual(calls, []); +}); + +test('the radio command runs on its full name', async (t) => { + const { enter, calls } = recordingOmnibar(t); + await enter('radio'); + assert.deepEqual(calls, []); + await enter('Enable Radio'); + assert.deepEqual(calls, [['control_radio', { action: 'enable' }]]); +}); + +test('"go to" takes the rest of its clause as the place, keywords and all', async (t) => { + const { enter, calls, acted, switched, searched } = recordingOmnibar(t); + for (const [text, place] of [ + ['go to cockpit country', 'cockpit country'], + ['go to Thermal, California', 'Thermal, California'], + ['fly to Tilt Cove', 'Tilt Cove'], + ['go to Night Vision Way', 'Night Vision Way'], + ['go to Whole Earth Provision', 'Whole Earth Provision'], + ]) { + await enter(text); + // A place alone goes through the place search, with nothing else run. + assert.equal(searched.at(-1), place, text); + assert.deepEqual(calls, [], text); + } + assert.deepEqual(acted, []); + assert.deepEqual(switched, []); + calls.length = 0; + await enter('go to Austin and show flights'); + assert.deepEqual( + calls.map(([name]) => name), + ['fly_to_location'], + ); + assert.deepEqual(switched, [['flights', true]]); +}); + +test('a radio verb must apply to the radio', async (t) => { + const { enter, calls } = recordingOmnibar(t); + await enter('play radio in Kill Devil Hills'); + assert.deepEqual(calls, [ + ['control_radio', { action: 'enable', locationQuery: 'kill devil hills' }], + ]); +}); + +test('Ask GEV is no default for a word or two, and CJK names are places from two characters', async (t) => { + const { enter, voiceEvents, searched, input, type } = recordingOmnibar(t); + // Two letters are too few for a place or a question; "help" may be a + // place, so it searches rather than asking. + for (const text of ['NY', 'Uk', 'hi']) { + await type(text); + assert.equal(input.getAttribute('aria-activedescendant'), null, text); + await enter(text); + } + await enter('help'); + assert.deepEqual(voiceEvents, []); + assert.deepEqual(searched.splice(0), ['help']); + for (const text of ['東京', '北京', '서울']) { + await type(text); + assert.equal(omnibarRows()[0], `place: Go to ${text}`, text); + await enter(text); + } + assert.deepEqual(searched, ['東京', '北京', '서울']); + await enter('what is here?'); + assert.deepEqual(voiceEvents.at(-1), ['chat-submit']); +}); + +test('the place service is asked about whole names, never about callsigns', async (t) => { + const asked = []; + const realFetch = globalThis.fetch; + globalThis.fetch = async (url) => { + asked.push(new URL(String(url)).searchParams.get('q')); + return Response.json({ features: [] }); + }; + t.after(() => { + globalThis.fetch = realFetch; + }); + const { type } = recordingOmnibar(t, ['traffic']); + const settle = () => new Promise((resolve) => setTimeout(resolve, 800)); + for (const text of ['UAL2110', 'N123AB', 'BAW15K']) { + await type(text); + await settle(); + } + assert.deepEqual(asked, []); + for (const text of ['Tokyo traffic', 'Home, Washington', '東京']) { + await type(text); + await settle(); + } + assert.deepEqual(asked, ['Tokyo traffic', 'Home, Washington', '東京']); +}); + +test('the search shortcut leaves an open dialog its focus', async (t) => { + const { input } = recordingOmnibar(t); + const dialog = document.body.appendChild(document.createElement('div')); + dialog.setAttribute('role', 'dialog'); + dialog.setAttribute('aria-modal', 'true'); + const button = dialog.appendChild(document.createElement('button')); + button.focus(); + document.dispatchEvent( + new KeyboardEvent('keydown', { key: '/', bubbles: true, cancelable: true }), + ); + assert.notEqual(document.activeElement, input); + dialog.remove(); + button.blur(); + document.dispatchEvent( + new KeyboardEvent('keydown', { key: '/', bubbles: true, cancelable: true }), + ); + assert.equal(document.activeElement, input); +}); + +// ── Enter-safety table ───────────────────────────────────────────────── +// Every line below is typed into the mounted Omnibar and Enter pressed with +// no row chosen; the table says exactly what runs. See src/ui/omnibarEnter.js +// and the Omnibar section of docs/CURRENT-STATE.md for the rule. +// `search(q)` is the place search, `fly(q)` a plan's flight, `nothing` +// means Enter ran nothing at all. +const ENTER_TABLE = [ + // A switch after its subject, a closing full stop, "please", + // names that look like questions, words about a layer. + ['noir off', 'style(normal)'], + ['turn off noir', 'style(normal)'], + ['Show flights.', 'layer(flights,on)'], + ['please show flights', 'layer(flights,on)'], + ['North up.', 'globe(northUp)'], + ['Do it Best Hardware', 'search(Do it Best Hardware)'], + ['Can You Imagine', 'search(Can You Imagine)'], + ['Show radio stations', 'layer(radio,on)'], + ['I went to the store yesterday and it was really great', 'nothing'], + ['123 45 6789', 'nothing'], + ['hunter22', 'nothing'], + // A layer is asked for only by a switch right before its word. + ['Kill Devil Hills radio', 'search(Kill Devil Hills radio)'], + ['Show Low radio', 'search(Show Low radio)'], + ['show low radio', 'search(show low radio)'], + ['Show Low noir', 'search(Show Low noir)'], + ['See radio', 'search(See radio)'], + ['PIN code 1234', 'nothing'], + ['my bank pin is 1234', 'nothing'], + ['123-45-6789', 'nothing'], + ['pw hunter2', 'nothing'], + ['Bearer abcdef', 'nothing'], + // Verbs in any letter case. + ['Turn on the radio', 'layer(radio,on)'], + ['Turn On Radio', 'layer(radio,on)'], + ['Draw', 'open(utilities)'], + // A bundled place's name that is also a command or layer word. + ['Thermal', 'search(Thermal)'], + ['Normal', 'search(Normal)'], + ['Hurricane', 'search(Hurricane)'], + ['Ski', 'search(Ski)'], + ['Street', 'search(Street)'], + ['Bike', 'search(Bike)'], + ['Rain', 'search(Rain)'], + // A question's form alone asks nothing. + ['Is there', 'search(Is there)'], + ['Can I', 'search(Can I)'], + ['Do it', 'search(Do it)'], + ['what is', 'search(what is)'], + ['how to', 'search(how to)'], + ['Who is it', 'search(Who is it)'], + ['N Y?', 'nothing'], + ['how far is paris', 'ask(how far is paris)'], + ['東京はどこ?', 'ask(東京はどこ?)'], + ['وين القاهرة؟', 'ask(وين القاهرة؟)'], + ['what cheer', 'search(what cheer)'], + ['List', 'search(List)'], + ['Describe', 'search(Describe)'], + // Verbs are read per clause, never inside a place's name. + ['radio near Clear Lake', 'search(clear lake)'], + ['radio in Show Low', 'search(show low)'], + ['Clear Lake radio', 'search(Clear Lake radio)'], + ['radio near Race Track', 'search(race track)'], + ['radio near Zoom Hill', 'search(zoom hill)'], + ['radio near Stop, Arkansas', 'search(stop, arkansas)'], + ['radio near Mute', 'search(mute)'], + ['turn radio on', 'radio(enable)'], + ['start radio', 'radio(enable)'], + ['toggle radio', 'layer(radio,on)'], + ['Track Hill', 'search(Track Hill)'], + // A question mark alone is no question; names that start like one are places. + ['?', 'nothing'], + ['??', 'nothing'], + ['what?', 'nothing'], + ['Why?', 'nothing'], + ['who?', 'nothing'], + ['Can Tho City', 'search(Can Tho City)'], + ['Can Gio District', 'search(Can Gio District)'], + ['Is Kinabalu Park', 'search(Is Kinabalu Park)'], + // A bare switch verb only lists what it could switch. + ['hide', 'nothing'], + ['remove', 'nothing'], + ['disable', 'nothing'], + ['turn off', 'nothing'], + ['switch off', 'nothing'], + ['clear everything', 'globe(clear)'], + ['hide everything near tokyo', 'fly(tokyo) + globe(clear)'], + ['hide everything in tokyo', 'fly(tokyo) + globe(clear)'], + // Private text gets no rows and no search. + ['4111 1111 1111 1111', 'nothing'], + ['+1 (415) 555-0100', 'nothing'], + ['SSN 123-45-6789', 'nothing'], + ['GB29 NWBK 6016 1331 9268 19', 'nothing'], + ['sk_live_51Habcdef', 'nothing'], + ['pk_live_abc', 'nothing'], + ['password hunter2', 'nothing'], + ['me@example.com', 'nothing'], + ['>', 'nothing'], + ['> ', 'nothing'], + ['a', 'nothing'], + ['ny', 'nothing'], + ['Uk', 'nothing'], + ['hi', 'nothing'], + ['help', 'search(help)'], + ['Is', 'nothing'], + ['why', 'search(why)'], + ['how', 'search(how)'], + ['what', 'search(what)'], + ['who', 'search(who)'], + ['where', 'search(where)'], + ['explain', 'search(explain)'], + ['summarize', 'search(summarize)'], + ['Why, Arizona', 'search(Why, Arizona)'], + ['What Cheer', 'search(What Cheer)'], + ['What Cheer, Iowa', 'search(What Cheer, Iowa)'], + ['Tell City', 'search(Tell City)'], + ['Tell City, Indiana', 'search(Tell City, Indiana)'], + ['Can Tho', 'search(Can Tho)'], + ['Can Tho, Vietnam', 'search(Can Tho, Vietnam)'], + ['what is here', 'ask(what is here)'], + ['how far is tokyo', 'ask(how far is tokyo)'], + // An auxiliary's question without "?" offers GEV but runs nothing. + ['is it raining in tokyo', 'nothing'], + ['is it raining in tokyo?', 'ask(is it raining in tokyo?)'], + ['where is tokyo?', 'ask(where is tokyo?)'], + ['radio', 'search(radio)'], + ['> radio', 'nothing'], + ['radio near tokyo', 'search(tokyo)'], + ['Radio, Tokyo', 'search(Radio, Tokyo)'], + ['radio in Kill Devil Hills', 'search(kill devil hills)'], + ['play radio in Tokyo', 'radio(enable@tokyo)'], + ['turn on radio', 'layer(radio,on)'], + ['radio on', 'radio(enable)'], + ['Enable Radio', 'layer(radio,on)'], + ['Radio City Music Hall', 'search(Radio City Music Hall)'], + ['share', 'nothing'], + ['copy map', 'nothing'], + ['Share this view', 'globe(share)'], + ['home', 'nothing'], + ['start over', 'nothing'], + ['Reset view', 'globe(reset)'], + ['globe', 'search(globe)'], + ['Globe view', 'zoom_to_globe'], + ['clear', 'search(clear)'], + ['clear map', 'globe(clear)'], + ['hide everything', 'globe(clear)'], + ['Clear all layers', 'globe(clear)'], + ['> Clear all layers', 'globe(clear)'], + ['> cl', 'nothing'], + ['close all panels', 'close(left) + close(right)'], + ['Close left panel', 'close(left)'], + ['cockpit', 'search(cockpit)'], + ['Cockpit Country', 'search(Cockpit Country)'], + ['enter cockpit', 'control_cockpit'], + ['mic', 'search(mic)'], + ['Talk to GEV', 'mic'], + ['display', 'nothing'], + ['turn on', 'nothing'], + ['flights', 'layer(flights,on)'], + ['show flights', 'layer(flights,on)'], + ['earthquakes', 'layer(earthquakes,on)'], + ['Hurricane, Utah', 'search(Hurricane, Utah)'], + ['Thermal, California', 'search(Thermal, California)'], + ['Tilt Cove', 'search(Tilt Cove)'], + ['Satellite Beach', 'search(Satellite Beach)'], + ['tokyo traffic', 'search(tokyo traffic)'], + ['go to tokyo in noir', 'search(tokyo)'], + ['go to tokyo, noir', 'search(tokyo)'], + ['go to Tokyo, north up', 'search(tokyo)'], + ['take me to Austin in thermal', 'search(austin)'], + ['go to London with flights', 'search(london)'], + ['go to tokyo show flights', 'search(tokyo)'], + ['go to Thermal, California', 'search(Thermal, California)'], + ['fly to Tilt Cove', 'search(Tilt Cove)'], + ['go to Night Vision Way', 'search(Night Vision Way)'], + ['go to cockpit country', 'search(cockpit country)'], + ['go to Whole Earth Provision', 'search(Whole Earth Provision)'], + ['go to Austin and show flights', 'fly(austin) + layer(flights,on)'], + [ + 'go to Austin and show flights in noir', + 'fly(austin) + style(noir) + layer(flights,on)', + ], + ['show flights near Tokyo', 'fly(tokyo) + layer(flights,on)'], + ['flights near tokyo', 'fly(tokyo) + layer(flights,on)'], + ['earthquakes above m5 in japan', 'fly(japan) + layer(earthquakes,on)'], + ['go to Paris, Texas and noir', 'fly(paris, texas) + style(noir)'], + ['go to tokyo and follow UAL123', 'fly(tokyo) + follow(ual123)'], + // Keywords without a verb ask for nothing, however many clauses: the + // place after "near" is searched and the plan offered. + ['noir and cctv near austin, north up', 'search(austin)'], + [ + 'show noir and show cctv near austin, face north', + 'fly(austin) + style(noir) + layer(cctv,on) + globe(northUp)', + ], + ['noir', 'style(noir)'], + ['North up', 'globe(northUp)'], + ['> North up', 'globe(northUp)'], + ['zoom in', 'adjust_camera_zoom'], + ['orbit', 'move_camera'], + ['follow UAL123', 'follow(ual123)'], + ['nearest plane to heathrow', 'select_nearest_aircraft'], + ['東京', 'search(東京)'], + ['Show Low, AZ', 'search(Show Low, AZ)'], + ['Paris, Texas', 'search(Paris, Texas)'], +]; + +async function enterOutcome(t, text, { hover = false } = {}) { + const realFetch = globalThis.fetch; + globalThis.fetch = async () => Response.json({ features: [] }); + t.after(() => { + globalThis.fetch = realFetch; + }); + const m = recordingOmnibar(t, [ + 'earthquakes', + 'cctv', + 'radio', + 'traffic', + 'weather-cyclones', + 'ski-pistes', + 'bikeshare', + 'weather-radar', + ]); + // Open side panels whose rail buttons record a close. + const closed = []; + const opened = []; + for (const side of ['left', 'right']) { + const rail = document.body.appendChild(document.createElement('div')); + rail.className = `ui-rail--${side}`; + const button = rail.appendChild(document.createElement('button')); + button.className = 'ui-rail__item'; + button.setAttribute('aria-pressed', 'true'); + button.dataset.railItem = `${side}-panel`; + button.addEventListener('click', () => closed.push(side)); + } + // Utilities, closed, for "open draw options". + const utilities = document + .querySelector('.ui-rail--left') + .appendChild(document.createElement('button')); + utilities.className = 'ui-rail__item'; + utilities.setAttribute('aria-pressed', 'false'); + utilities.dataset.railItem = 'utilities-panel'; + utilities.addEventListener('click', () => opened.push('utilities')); + await m.type(text); + if (hover) { + const rows = [ + ...document.querySelectorAll('#gev-omnibar-list .omnibar-item'), + ]; + rows.at(-1)?.dispatchEvent(new MouseEvent('mousemove', { bubbles: true })); + await nextTick(); + } + await m.key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + const events = [ + ...m.searched.map((q) => `search(${q})`), + ...m.calls.map(([name, args]) => + name === 'fly_to_location' + ? `fly(${args.query})` + : name === 'set_visual_style' + ? `style(${args.style})` + : name === 'control_radio' + ? `radio(${args.action}${args.locationQuery ? `@${args.locationQuery}` : ''})` + : name === 'track_entity' + ? `follow(${args.query})` + : name, + ), + ...m.switched.map(([id, on]) => `layer(${id},${on ? 'on' : 'off'})`), + ...m.acted.map((act) => `globe(${act})`), + ...m.voiceEvents + .filter(([kind]) => kind === 'chat-prompt') + .map(([, q]) => `ask(${q})`), + ...m.voiceEvents.filter(([kind]) => kind === 'button').map(() => 'mic'), + ...closed.map((side) => `close(${side})`), + ...opened.map((panel) => `open(${panel})`), + ]; + return events.join(' + ') || 'nothing'; +} + +for (const [text, expected] of ENTER_TABLE) + test(`Enter on ${JSON.stringify(text)} runs ${expected}`, async (t) => { + assert.equal(await enterOutcome(t, text), expected); + }); + +// The pointer last on the Ask GEV row, or on a guarded plan, changes +// nothing: Enter still runs the default (or nothing). +for (const [text, expected] of [ + ['radio near tokyo', 'search(tokyo)'], + ['Share', 'nothing'], + ['hi', 'nothing'], +]) + test(`hovering a row of ${JSON.stringify(text)} never makes it what Enter runs`, async (t) => { + assert.equal(await enterOutcome(t, text, { hover: true }), expected); + }); + +/** Route Photon requests to a stub; return the queries it was sent. */ +function stubPhoton(t, features = () => []) { + const asked = []; + const realFetch = globalThis.fetch; + globalThis.fetch = async (url) => { + const q = new URL(String(url)).searchParams.get('q'); + asked.push(q); + return Response.json({ features: features(q) }); + }; + t.after(() => { + globalThis.fetch = realFetch; + }); + return asked; +} +const settle = (ms = 800) => new Promise((resolve) => setTimeout(resolve, ms)); + +for (const text of [ + '4111 1111 1111 1111', + '4111-1111-1111-1111', + '+1 (415) 555-0100', + '415.555.0100 x12', + 'SSN 123-45-6789', + 'GB29 NWBK 6016 1331 9268 19', + 'DE89370400440532013000', + 'sk_live_51Habcdef', + 'rk_live_51Habcdef', + 'pk_live_abc', + 'password hunter2', + 'my passcode is 4433', + 'pin 1234', + 'me@example.com', + 'PIN code 1234', + 'my bank pin is 1234', + '123-45-6789', + 'pw hunter2', + 'Bearer abcdef', +]) + test(`private text ${JSON.stringify(text)} is never looked up or searched`, async (t) => { + const asked = stubPhoton(t); + const { type, key, searched, calls } = recordingOmnibar(t); + await type(text); + await settle(); + // At most a row to search it as a place on purpose, which Enter skips. + assert.ok(omnibarRows().every((row) => row.includes('as a place anyway'))); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(asked, []); + assert.deepEqual(searched, []); + assert.deepEqual(calls, []); + }); + +test('a row chosen with the keys stays chosen when rows arrive above it', async (t) => { + stubPhoton(t, (q) => [ + { + geometry: { type: 'Point', coordinates: [2.35, 48.86] }, + properties: { + name: 'Paris', + country: 'France', + countrycode: 'fr', + osm_value: 'city', + }, + }, + { + geometry: { type: 'Point', coordinates: [-95.55, 33.66] }, + properties: { + name: `${q} Texas`, + country: 'United States', + countrycode: 'us', + osm_value: 'city', + }, + }, + ]); + const { type, key, voiceEvents, searched } = recordingOmnibar(t); + await type('Paris'); + // Choose Ask GEV, the second row, before the suggestions come in. + assert.deepEqual(omnibarRows(), [ + 'place: Go to Paris', + 'ask: Ask GEV: “Paris”', + ]); + await key('ArrowDown'); + await settle(); + assert.ok(omnibarRows().length > 2, omnibarRows().join(' | ')); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(searched, []); + assert.deepEqual( + voiceEvents.find(([kind]) => kind === 'chat-prompt'), + ['chat-prompt', 'Paris'], + ); +}); + +test('a plan switches a layer by its state when it runs, not when it was read', async (t) => { + const { type, key, switched, calls, layerList } = recordingOmnibar(t); + await type('go to Austin and show flights'); + // Flights came on elsewhere after the line was read. + layerList[0].enabled = true; + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual( + calls.map(([name]) => name), + ['fly_to_location'], + ); + assert.deepEqual(switched, []); +}); + +test('a globe action nobody answers fails the plan', async (t) => { + const { $, type, key, acted } = recordingOmnibar(t, [], { acts: ['clear'] }); + await type('go to Austin and tilt'); + await key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + assert.deepEqual(acted, []); + assert.ok($('#gev-omnibar [role="alert"]').textContent.trim()); +}); + +test('the OpenStreetMap credit shows while Photon suggestions do', async (t) => { + stubPhoton(t, () => [ + { + geometry: { type: 'Point', coordinates: [139.69, 35.69] }, + properties: { + name: 'Tokyo', + country: 'Japan', + countrycode: 'jp', + osm_value: 'city', + }, + }, + ]); + const { type, key, credits } = recordingOmnibar(t); + await type('Tokyo'); + await settle(); + assert.deepEqual(credits, [true]); + await key('Escape'); + await nextTick(); + assert.deepEqual(credits, [true, false]); +}); + +test('ids name no layer: "Local" and "Global" search a place', async (t) => { + stubPhoton(t); + const searched = []; + const fixture = omnibarFixture(t, (query) => searched.push(query)); + const switched = []; + useOmnibarStore(fixture.pinia).connect({ + layers: () => [ + { id: 'local-firms', name: 'Active fires', enabled: false }, + { id: 'global-context', name: 'World context', enabled: false }, + // A shown name holding a word of kind names it only in full. + { id: 'local-adsb', name: 'Local ADS-B', enabled: false }, + ], + setLayer: (...args) => switched.push(args), + }); + for (const text of ['Local', 'Global']) { + await fixture.type(text); + await fixture.key('Enter'); + await new Promise((resolve) => setTimeout(resolve, 0)); + } + assert.deepEqual(switched, []); + assert.deepEqual(searched, ['Local', 'Global']); +}); + +// A deterministic sample of about 2,000 bundled place names, alone and with +// " radio" and " noir" after them: none may default to an action. Sweeping +// every name the same way takes minutes, so the suite samples them. +test('bundled place names never default to an action', async (t) => { + stubPhoton(t); + const { readFile, readdir } = await import('node:fs/promises'); + const names = new Set(); + const cities = JSON.parse( + await readFile( + new URL( + '../data/local_data/wikidata_cities/cities.json', + import.meta.url, + ), + 'utf8', + ), + ); + for (const row of cities.rows) names.add(row[0]); + const dir = new URL('../data/local_data/wikidata_places/', import.meta.url); + for (const file of (await readdir(dir)).sort()) + if (/^-?\d+_-?\d+\.json$/.test(file)) + for (const row of JSON.parse(await readFile(new URL(file, dir), 'utf8')) + .rows) + names.add(row[0]); + const all = [...names].sort(); + const step = Math.floor(all.length / 2000); + const sample = all.filter((_, index) => index % step === 0); + // The words of PLACE_WORDS are in the sample too. + sample.push( + 'Thermal', + 'Normal', + 'Hurricane', + 'Ski', + 'Street', + 'Bike', + 'Rain', + ); + const { type, input } = recordingOmnibar(t, [ + 'radio', + 'traffic', + 'earthquakes', + 'weather-cyclones', + 'news', + ]); + const wrong = []; + for (const name of sample) + for (const text of [name, `${name} radio`, `${name} noir`]) { + await type(text); + const id = input.getAttribute('aria-activedescendant'); + const row = id && document.getElementById(id); + if (row && !row.classList.contains('omnibar-item--place')) + wrong.push(`${text} => ${row.textContent.trim()}`); + } + assert.ok(sample.length > 1900, `${sample.length} names`); + assert.deepEqual(wrong, []); +}); diff --git a/src/ui/entityContextBridge.js b/src/ui/entityContextBridge.js index eea7e72c29..927532f496 100644 --- a/src/ui/entityContextBridge.js +++ b/src/ui/entityContextBridge.js @@ -62,7 +62,7 @@ export function installEntityContext({ const voice = useVoiceStore(pinia); const cockpitStore = useCockpitStore(pinia); const chrome = usePanelChromeStore(pinia); - /** Whether Context is open; a closed panel reads nothing. */ + /** Whether Context is open. (readView also reads while the Omnibar is focused.) */ const isOpen = () => chrome.panels['global-context-panel']?.collapsed === false; const doc = globalThis.document; @@ -223,7 +223,8 @@ export function installEntityContext({ // the height. Read when the camera settles, not every frame. const readView = () => { const port = camera(); - if (!port || !isOpen()) return; + if (!port || (!isOpen() && doc?.activeElement?.id !== 'gev-omnibar-input')) + return; const pose = port.pose(); if (![pose.lat, pose.lon, pose.height].every(Number.isFinite)) return; const middle = pickWorld?.(viewer, 0.5, 0.5); @@ -272,6 +273,12 @@ export function installEntityContext({ listen(); readView(); }, 0); + // The Omnibar's nearby suggestions also need a fresh center even with + // Context closed. Its focus event requests one camera read. + const onSearchFocus = (event) => { + if (event.target?.id === 'gev-omnibar-input') readView(); + }; + doc?.addEventListener('focusin', onSearchFocus); // Opening the panel describes the view as it is now. let wasOpen = isOpen(); const offChrome = chrome.$subscribe(() => { @@ -356,6 +363,7 @@ export function installEntityContext({ clearTimeout(trailing); offFollow(); offChrome(); + doc?.removeEventListener('focusin', onSearchFocus); clearTimeout(followCheck); globalThis.removeEventListener?.('gev:entity-selected', onSelected); store.connect(null); diff --git a/src/ui/leftPanelRail.js b/src/ui/leftPanelRail.js index c5c65378b3..44eef21fd5 100644 --- a/src/ui/leftPanelRail.js +++ b/src/ui/leftPanelRail.js @@ -115,8 +115,15 @@ export function layoutLeftPanelRail({ if (hiddenByAncestor) continue; const rect = obstacle.getBoundingClientRect(); if (rect.width <= 0 || rect.height <= 0) continue; - const overlapsHorizontally = - rect.right > stackRect.left && rect.left < stackRect.right; + // The centered controls can enter the stack's transparent outer gutter. + // Only constrain the lane if they reach an expanded panel itself, whose + // actual bounds also include the edge-rail offset. + const lanes = ['world-timeline', 'gev-voice-control'].includes(obstacle.id) + ? laidOutPanels.map((panel) => panel.getBoundingClientRect()) + : [stackRect]; + const overlapsHorizontally = lanes.some( + (lane) => rect.right > lane.left && rect.left < lane.right, + ); if (!overlapsHorizontally) continue; if (rect.top < baseTop && rect.bottom <= viewportHeight * 0.5) { @@ -220,11 +227,20 @@ export function layoutLeftPanelRail({ const tailLayoutBottom = tailLayoutTop + tailRequiredHeight; const tailAvailableHeight = Math.max(0, obstacleSafeBottom - obstacleSafeTop); const tailTolerance = wasTail ? stabilityBand : -stabilityBand; + // Data Layers has a scrollable list and a fixed footer. Give it the full + // desktop lane while short control panels keep their natural height. + const fillDataLayers = + exclusive && + expandedPanels.length === 1 && + expandedPanels[0].id === 'data-panel' && + Boolean(documentRef?.getElementById?.('gev-omnibar')); const shouldTail = + !fillDataLayers && expandedPanels.length > 0 && tailLayoutTop >= obstacleSafeTop - tailTolerance && tailLayoutBottom <= obstacleSafeBottom + tailTolerance; - const shouldFocus = exceedsCenteredCorridor && !shouldTail; + const shouldFocus = + fillDataLayers || (exceedsCenteredCorridor && !shouldTail); // Focus mode owns the lane, so let every expanded panel share the full // obstacle-safe corridor. Tail/normal layouts keep the balanced // viewport centering used for compact accordion stacks. @@ -250,10 +266,12 @@ export function layoutLeftPanelRail({ rowGap * Math.max(0, expandedPanels.length - 1), ) : naturalExpandedHeight; - const allocatedExpandedHeights = allocatePanelStackHeights({ - naturalHeights: naturalExpandedHeights, - availableHeight: expandedAvailableHeight, - }); + const allocatedExpandedHeights = fillDataLayers + ? [expandedAvailableHeight] + : allocatePanelStackHeights({ + naturalHeights: naturalExpandedHeights, + availableHeight: expandedAvailableHeight, + }); const autoCollapseIndices = hud.visible ? panelStackAutoCollapseIndices({ naturalHeights: naturalExpandedHeights, diff --git a/src/ui/locationControls.js b/src/ui/locationControls.js index 388fb51e14..80d189e5e1 100644 --- a/src/ui/locationControls.js +++ b/src/ui/locationControls.js @@ -46,6 +46,7 @@ export class LocationControls { onCity, onPoi, onSearch, + onSearchEdit, onReset, publish, doc, @@ -74,6 +75,7 @@ export class LocationControls { poi: t('Landmark: --'), }; this.searchError = null; + this.searchOrigin = 'dock'; // The search field: whether it is open, and whether a lookup runs. this.searchExpanded = Boolean(searchExpanded); this.searching = false; @@ -96,12 +98,16 @@ export class LocationControls { onPoi(cityId, index); }); this.bind(elements.search, 'keydown', (event) => { - if (event.key === 'Enter') void onSearch(elements.search.value); + if (event.key === 'Enter') + void this.search(elements.search.value, { origin: 'dock' }); }); // Typing corrects a failed query; closing the field (which empties it) drops its error. - this.bind(elements.search, 'input', () => onSearchEdit?.()); + this.bind(elements.search, 'input', () => { + if (this.searchOrigin === 'dock') onSearchEdit?.(); + }); this.bind(elements.search, 'blur', () => { - if (!elements.search.value) onSearchEdit?.(); + if (this.searchOrigin === 'dock' && !elements.search.value) + onSearchEdit?.(); }); this.present(); } @@ -138,9 +144,29 @@ export class LocationControls { searchError: this.searchError, searchExpanded: this.searchExpanded, searching: this.searching, + searchOrigin: this.searchOrigin, orbit: this.orbit && { ...this.orbit }, }; } + /** Search through the same lifecycle as the location field. */ + search(query, { origin = 'omnibar' } = {}) { + if (this.destroyed || !String(query || '').trim()) return false; + this._requestedSearchOrigin = origin; + // Beginning navigation synchronously settles the previous lookup. That + // handoff must not clear or blur the draft just submitted by either field. + this._startingSearch = true; + try { + return this.onSearch(query); + } finally { + this._startingSearch = false; + this._requestedSearchOrigin = null; + } + } + /** Editing an external query clears its prior lookup error. */ + editSearch() { + if (!this.destroyed && this.searchOrigin === 'omnibar') + this.onSearchEdit?.(); + } /** A city pill was clicked. */ chooseCity(id) { if (!this.destroyed) this.onCity(id); @@ -233,6 +259,8 @@ export class LocationControls { /** Mark the search field while a lookup runs. */ setSearching(active) { if (this.destroyed) return; + if (active && this._requestedSearchOrigin) + this.searchOrigin = this._requestedSearchOrigin; this.searching = Boolean(active); this.present(); } @@ -243,6 +271,10 @@ export class LocationControls { settleSearch({ keepQuery = false } = {}) { if (this.destroyed) return; this.searching = false; + if (this._startingSearch || this.searchOrigin === 'omnibar') { + this.present(); + return; + } if (!keepQuery) { this.closeSearch(); return; diff --git a/src/ui/locationControls.test.mjs b/src/ui/locationControls.test.mjs index 2863564c8f..555536b65a 100644 --- a/src/ui/locationControls.test.mjs +++ b/src/ui/locationControls.test.mjs @@ -108,6 +108,7 @@ test('the tray presents its cities, empty status and no landmarks at first', () searchError: null, searchExpanded: false, searching: false, + searchOrigin: 'dock', orbit: null, }); f.controls.highlightCity('b'); diff --git a/src/ui/locationSearch.js b/src/ui/locationSearch.js index aeed9320ef..689a3a3795 100644 --- a/src/ui/locationSearch.js +++ b/src/ui/locationSearch.js @@ -101,6 +101,8 @@ export class LocationSearch { destination: { ...destination }, }; this.channel.publish(change('found')); + // Found and still the current search: a plan may go on. + return current() && !controller.signal.aborted; } else { this.onMissing?.(); if (!current() || controller.signal.aborted) return; diff --git a/src/ui/omnibarIntent.js b/src/ui/omnibarIntent.js index aefaa07df0..03ea30938a 100644 --- a/src/ui/omnibarIntent.js +++ b/src/ui/omnibarIntent.js @@ -185,8 +185,8 @@ const AUX_FORM = /** * Whether a line is a real question, which Ask GEV may answer on Enter (a * billed call): - * - one ending with "?" that has two words and two letters or more (or - * three Han, Kana or Hangul characters); + * - one ending with "?" that has a question form or two non-Latin words + * with a word of two letters or more, or five Han, Kana or Hangul characters; * - without "?", only a question word's form ("what is here", "how far is * paris") with a word about something after it, and not written as a * name ("Where Is My Mind"). @@ -209,13 +209,12 @@ export function isRealQuestion(text) { const words = line.replace(/\?+$/, '').split(/\s+/).filter(Boolean); if (line.endsWith('?')) // A name with "?" ("New York?", "Truth or Consequences?", "東京都?") is - // offered to GEV, not sent: a question's form, or four words or more - // (five Han, Kana or Hangul characters, written without spaces; two - // words in other non-Latin scripts). + // offered to GEV, not sent: a question's form, or five Han, Kana or + // Hangul characters written without spaces, or two words in other + // non-Latin scripts. return ( ((WH_FORM.test(line) || AUX_FORM.test(line) || - words.length >= 4 || // Question words in other scripts are not read: two words do. (words.length >= 2 && !/\p{Script=Latin}/u.test(line))) && words.some((word) => (word.match(/\p{L}/gu) || []).length >= 2)) || diff --git a/src/ui/omnibarIntent.test.mjs b/src/ui/omnibarIntent.test.mjs index 08a6df10e7..5ceb9e578f 100644 --- a/src/ui/omnibarIntent.test.mjs +++ b/src/ui/omnibarIntent.test.mjs @@ -252,6 +252,7 @@ test('ar and he mark every Omnibar string alike with a right-to-left mark', asyn // U+200F, so the punctuation stays with the right-to-left text before it. const sources = await Promise.all( [ + './views/panels/Omnibar.vue', './views/panels/VoiceVisualizer.vue', './omnibarIntent.js', './omnibarRows.js', diff --git a/src/ui/omnibarRows.test.mjs b/src/ui/omnibarRows.test.mjs index 3d6533275c..a62cdde11c 100644 --- a/src/ui/omnibarRows.test.mjs +++ b/src/ui/omnibarRows.test.mjs @@ -148,16 +148,15 @@ const OUTCOMES = [ ['remove island', 'nothing'], ['show noir and show cctv', 'style(noir) + layer(cctv,on)'], // a name with "?" is offered to GEV, - // never sent; a question's form or four words are. + // never sent; a question's form is. ['New York?', 'nothing'], ['Truth or Consequences?', 'nothing'], + ['Ho Chi Minh City?', 'nothing'], + ['Santa Cruz de la Sierra?', 'nothing'], ['東京都?', 'nothing'], ['東京はどこ?', 'ask(東京はどこ?)'], ['is it far?', 'ask(is it far?)'], - [ - 'how about the weather in paris today?', - 'ask(how about the weather in paris today?)', - ], + ['how about the weather in paris today?', 'nothing'], ['123–45–6789', 'nothing'], ['what is 4111–1111–1111–1111?', 'nothing'], // a switch with its place after "in" asks; diff --git a/src/ui/panelRails.test.mjs b/src/ui/panelRails.test.mjs index ce1c824466..cf5a534451 100644 --- a/src/ui/panelRails.test.mjs +++ b/src/ui/panelRails.test.mjs @@ -232,6 +232,38 @@ test('left corridor respects a lower obstacle but ignores an obstacle hidden by assert.equal(Number(f.stack.dataset.safeBottomPct), 65.47); }); +test('a centered timeline only shortens the corridor when it reaches the visible panel', () => { + const f = fixture('left'); + f.stack.rect.width = 360; + f.stack.rect.right = f.stack.rect.left + 360; + f.expand(f.first, 850); + const timeline = element('world-timeline', { top: 650, left: 320 }); + f.options.obstacles = [timeline]; + f.run(); + const clear = Number(f.stack.dataset.safeBottomPct); + timeline.rect.left = 280; + f.run(); + assert(clear > 85); + assert(Number(f.stack.dataset.safeBottomPct) < 73); +}); + +test('Data Layers extends to the HUD even if its list is currently short', () => { + const f = fixture('left'); + f.first.id = 'data-panel'; + f.options.documentRef.getElementById = (id) => + id === 'gev-omnibar' ? {} : null; + f.expand(f.first, 250); + f.options.obstacles = [element('hud', { top: 760, height: 45 })]; + f.run(); + assert.equal(f.stack.dataset.layoutMode, 'focus'); + assert(Number(f.stack.dataset.safeBottomPct) > 80); + assert( + parseFloat( + f.first.style.getPropertyValue('--left-panel-allocated-height'), + ) > 500, + ); +}); + for (const side of ['left', 'right']) { test(`${side} mobile layout releases desktop height/position styles and labels`, () => { const f = fixture(side, { mobile: true }); diff --git a/src/ui/stores/entityCard.js b/src/ui/stores/entityCard.js index 611065ac2d..a0186fea2c 100644 --- a/src/ui/stores/entityCard.js +++ b/src/ui/stores/entityCard.js @@ -6,6 +6,7 @@ import { describeEntity, layerBreakdown, nearbyByKind, + nearbyEntities, layerMatches, searchEntities, viewSummary, @@ -204,6 +205,10 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { return nearbyByKind(shell.value?.dataManager?.(), { lat, lon }, options); } + function nearbySelected() { + return nearbyEntities(dataManager(), card.value); + } + /** Whether a card's layer is known to the layer manager and switched off. */ function layerOff(layerId) { const dm = dataManager(); @@ -333,6 +338,7 @@ export const useEntityCardStore = defineStore('gev-entity-card', () => { following, search, nearbyGroups, + nearbySelected, alertsAt, liveLayers, breakdown, diff --git a/src/ui/stores/globeActions.js b/src/ui/stores/globeActions.js index 58247604ff..74243e1452 100644 --- a/src/ui/stores/globeActions.js +++ b/src/ui/stores/globeActions.js @@ -79,6 +79,8 @@ export const useGlobeActionsStore = defineStore('gev-globe-actions', () => { } const { act, owns } = owners; + /** Whether a connected owner answers this action at all. */ + const answers = (name) => Boolean(owners.ownerOf(name)); return { clearBusy, @@ -91,5 +93,6 @@ export const useGlobeActionsStore = defineStore('gev-globe-actions', () => { detach, act, owns, + answers, }; }); diff --git a/src/ui/stores/omnibar.js b/src/ui/stores/omnibar.js index 68c2e4e259..a4210b75fa 100644 --- a/src/ui/stores/omnibar.js +++ b/src/ui/stores/omnibar.js @@ -5,11 +5,14 @@ import { markRaw, shallowRef } from 'vue'; * The top-bar omnibar's link to the shell. The shell connects the actions * the omnibar offers: `layers()` lists the data layers as `{id, name, * enabled}`, and `setLayer(id, enabled)` turns one on or off as a user click - * would. Place search runs through the location controls and Ask GEV through - * the voice controls, so neither is repeated here. + * would. `creditPlaces()`, optional, credits the bundled Wikidata place + * packs once a name from them is shown, and `creditSuggestions(shown)`, + * optional, shows the OpenStreetMap credit while Photon's suggestions are. Place search runs through the + * location controls and Ask GEV through the voice controls, so neither is + * repeated here. */ export const useOmnibarStore = defineStore('gev-omnibar', () => { - /** `{layers(), setLayer(id, enabled)}`, or null while disconnected. */ + /** `{layers(), setLayer(id, enabled), creditPlaces?()}`, or null while disconnected. */ const controls = shallowRef(null); /** @param {?object} next The shell's omnibar actions, or null. */ diff --git a/src/ui/styles/guide.css b/src/ui/styles/guide.css new file mode 100644 index 0000000000..d19da7a3a4 --- /dev/null +++ b/src/ui/styles/guide.css @@ -0,0 +1,413 @@ +/* ── "Show me how" guide ─────────────────────────────────────────────── + A spotlight dims everything but the control to press and frames it with + tactical corner brackets; a second frame marks a part of it (a layer's + switch). A glass callout beside it, with an arrow to the target, says + what to do and how far along the walk is. Clicks pass through to the + app: the guide only points. */ +.gev-guide { + --gev-guide-accent: #ff9f43; + --gev-guide-accent-soft: rgba(255, 159, 67, 0.5); + position: fixed; + z-index: 400; + inset: 0; + pointer-events: none; +} + +/* ── Spotlight ── */ +.gev-guide-ring { + position: fixed; + border: 1px solid rgba(255, 159, 67, 0.28); + border-radius: 8px; + box-shadow: 0 0 0 200vmax rgba(3, 8, 14, 0.55); + opacity: 0; + transition: + left 280ms cubic-bezier(0.2, 0.8, 0.2, 1), + top 280ms cubic-bezier(0.2, 0.8, 0.2, 1), + width 280ms cubic-bezier(0.2, 0.8, 0.2, 1), + height 280ms cubic-bezier(0.2, 0.8, 0.2, 1), + opacity 160ms ease; +} + +/* Corner brackets, drawn as eight short gradient strokes. */ +.gev-guide-ring::before { + position: absolute; + inset: -3px; + background: + linear-gradient(var(--gev-guide-accent) 0 0) top left / 12px 2px, + linear-gradient(var(--gev-guide-accent) 0 0) top left / 2px 12px, + linear-gradient(var(--gev-guide-accent) 0 0) top right / 12px 2px, + linear-gradient(var(--gev-guide-accent) 0 0) top right / 2px 12px, + linear-gradient(var(--gev-guide-accent) 0 0) bottom left / 12px 2px, + linear-gradient(var(--gev-guide-accent) 0 0) bottom left / 2px 12px, + linear-gradient(var(--gev-guide-accent) 0 0) bottom right / 12px 2px, + linear-gradient(var(--gev-guide-accent) 0 0) bottom right / 2px 12px; + background-repeat: no-repeat; + content: ''; + filter: drop-shadow(0 0 4px rgba(255, 159, 67, 0.6)); +} + +/* A soft ping that grows out of the frame: "press here". */ +.gev-guide-ring > i { + position: absolute; + inset: 0; + border: 1px solid var(--gev-guide-accent-soft); + border-radius: inherit; + animation: gev-guide-ping 1.8s cubic-bezier(0.2, 0.7, 0.3, 1) infinite; +} + +/* A second frame inside the spotlight does not dim the screen again. */ +.gev-guide-ring--sub { + border-color: rgba(255, 159, 67, 0.4); + border-radius: 6px; + box-shadow: none; +} + +.gev-guide-ring--sub::before { + inset: -2px; + background-size: + 8px 2px, + 2px 8px, + 8px 2px, + 2px 8px, + 8px 2px, + 2px 8px, + 8px 2px, + 2px 8px; +} + +/* ── Callout ── */ +.gev-guide-callout { + position: fixed; + width: 280px; + padding: 0.7rem 0.8rem 0.65rem; + color: rgba(232, 238, 242, 0.95); + background: rgba(40, 44, 52, 0.9); + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 12px; + box-shadow: + 0 16px 40px rgba(0, 0, 0, 0.55), + inset 0 1px 0 rgba(255, 255, 255, 0.06); + backdrop-filter: blur(22px) saturate(1.3); + -webkit-backdrop-filter: blur(22px) saturate(1.3); + opacity: 0; + transform: translateY(4px); + transition: + left 280ms cubic-bezier(0.2, 0.8, 0.2, 1), + top 280ms cubic-bezier(0.2, 0.8, 0.2, 1), + opacity 180ms ease, + transform 180ms ease; + pointer-events: auto; +} + +.gev-guide.visible .gev-guide-callout { + opacity: 1; + transform: none; +} + +/* A leader line from the callout to the target's frame, ending in a dot. */ +.gev-guide-callout::before, +.gev-guide-callout::after { + position: absolute; + top: var(--gev-guide-arrow-y, 50%); + content: ''; + transition: top 280ms cubic-bezier(0.2, 0.8, 0.2, 1); +} + +.gev-guide-callout::before { + width: 18px; + height: 1px; + background: var(--gev-guide-accent); + box-shadow: 0 0 6px rgba(255, 159, 67, 0.7); +} + +.gev-guide-callout::after { + width: 5px; + height: 5px; + margin-top: -2px; + background: var(--gev-guide-accent); + border-radius: 50%; + box-shadow: 0 0 6px rgba(255, 159, 67, 0.9); +} + +.gev-guide-callout[data-side='right']::before { + right: 100%; +} + +.gev-guide-callout[data-side='right']::after { + right: calc(100% + 15px); +} + +.gev-guide-callout[data-side='left']::before { + left: 100%; +} + +.gev-guide-callout[data-side='left']::after { + left: calc(100% + 15px); +} + +.gev-guide-callout[data-side='none']::before, +.gev-guide-callout[data-side='none']::after { + display: none; +} + +/* The edge the line leaves from picks up the accent. */ +.gev-guide-callout[data-side='right'] { + border-left-color: rgba(255, 159, 67, 0.55); +} + +.gev-guide-callout[data-side='left'] { + border-right-color: rgba(255, 159, 67, 0.55); +} + +/* Header: what this walk is about, how far along, and a close. */ +.gev-guide-head { + display: flex; + align-items: center; + gap: 0.5rem; +} + +.gev-guide-title, +.gev-guide-count { + margin: 0; + font-family: var(--font-mono); + font-size: 0.56rem; + letter-spacing: 0.12rem; + text-transform: uppercase; +} + +.gev-guide-title { + flex: 1; + min-width: 0; + overflow: hidden; + color: var(--gev-guide-accent); + text-overflow: ellipsis; + white-space: nowrap; +} + +.gev-guide-count { + color: rgba(214, 220, 226, 0.55); + font-variant-numeric: tabular-nums; + letter-spacing: 0.06rem; +} + +.gev-guide-close { + display: grid; + place-items: center; + width: 20px; + height: 20px; + margin: -2px -4px 0 0; + padding: 0; + color: rgba(214, 220, 226, 0.55); + font-size: 0.95rem; + line-height: 1; + background: none; + border: 0; + border-radius: 5px; + cursor: pointer; +} + +.gev-guide-close:hover, +.gev-guide-close:focus-visible { + color: #fff; + background: rgba(255, 255, 255, 0.08); +} + +/* Progress: one segment per step. */ +.gev-guide-progress { + display: flex; + gap: 3px; + margin: 0.45rem 0 0.6rem; + padding: 0; + list-style: none; +} + +.gev-guide-progress li { + flex: 1; + height: 2px; + background: rgba(214, 220, 226, 0.16); + border-radius: 2px; + transition: background 220ms ease; +} + +.gev-guide-progress li.done { + background: rgba(255, 159, 67, 0.55); +} + +.gev-guide-progress li.current { + background: var(--gev-guide-accent); + box-shadow: 0 0 6px rgba(255, 159, 67, 0.6); +} + +.gev-guide-callout.swap .gev-guide-body { + animation: gev-guide-swap 260ms ease both; +} + +.gev-guide-text { + margin: 0; + font-size: 0.84rem; + line-height: 1.45; +} + +/* "Press the highlighted control", with a live dot. */ +.gev-guide-hint { + display: flex; + align-items: center; + gap: 0.45rem; + margin: 0.4rem 0 0; + color: rgba(214, 220, 226, 0.6); + font-size: 0.68rem; +} + +.gev-guide-hint[hidden] { + display: none; +} + +.gev-guide-hint-dot { + width: 6px; + height: 6px; + flex: none; + background: var(--gev-guide-accent); + border-radius: 50%; + animation: gev-guide-blink 1.4s ease-in-out infinite; +} + +/* Footer: the Esc hint on the left, the buttons on the right. */ +.gev-guide-actions { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.4rem; + margin-top: 0.7rem; + padding-top: 0.55rem; + border-top: 1px solid rgba(255, 255, 255, 0.07); +} + +.gev-guide-actions > span { + display: flex; + gap: 0.4rem; +} + +.gev-guide-keys { + display: flex; + align-items: center; + gap: 0.35rem; + margin: 0; + color: rgba(214, 220, 226, 0.45); + font-size: 0.62rem; +} + +.gev-guide-keys[hidden] { + display: none; +} + +/* With the Esc hint gone, the offer's buttons sit on the right. */ +.gev-guide-actions > span:only-of-type { + margin-left: auto; +} + +.gev-guide-keys kbd { + padding: 0.05rem 0.3rem; + font-family: var(--font-mono); + font-size: 0.54rem; + border: 1px solid rgba(214, 220, 226, 0.22); + border-radius: 4px; +} + +.gev-guide-actions button { + padding: 0.28rem 0.6rem; + color: #1a1206; + font-family: var(--font-mono); + font-size: 0.58rem; + font-weight: 600; + letter-spacing: 0.1rem; + text-transform: uppercase; + white-space: nowrap; + background: var(--gev-guide-accent); + border: 1px solid var(--gev-guide-accent); + border-radius: 6px; + cursor: pointer; + transition: + background 140ms ease, + color 140ms ease, + border-color 140ms ease; +} + +.gev-guide-actions button[hidden] { + display: none; +} + +.gev-guide-actions button:hover, +.gev-guide-actions button:focus-visible { + background: #ffb36b; + border-color: #ffb36b; +} + +/* Secondary buttons: skip a step that waits, or decline the offer. */ +.gev-guide-actions button.quiet, +.gev-guide-actions .gev-guide-skip { + color: rgba(214, 220, 226, 0.75); + font-weight: 400; + background: none; + border-color: rgba(214, 220, 226, 0.2); +} + +.gev-guide-actions button.quiet:hover, +.gev-guide-actions button.quiet:focus-visible, +.gev-guide-actions .gev-guide-skip:hover, +.gev-guide-actions .gev-guide-skip:focus-visible { + color: #fff; + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 159, 67, 0.6); +} + +@keyframes gev-guide-ping { + 0% { + opacity: 0.9; + transform: scale(1); + } + + 100% { + opacity: 0; + transform: scale(1.12); + } +} + +@keyframes gev-guide-blink { + 50% { + opacity: 0.3; + } +} + +@keyframes gev-guide-swap { + from { + opacity: 0; + transform: translateY(3px); + } +} + +@media (prefers-reduced-motion: reduce) { + .gev-guide-ring, + .gev-guide-callout, + .gev-guide-callout::before { + transition: none; + } + + .gev-guide-ring > i, + .gev-guide-hint-dot, + .gev-guide-callout.swap .gev-guide-body { + animation: none; + } +} + +/* The guide's live status: read by screen readers, not shown. */ +.gev-guide-status { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + border: 0; +} diff --git a/src/ui/styles/omnibar-dock.css b/src/ui/styles/omnibar-dock.css new file mode 100644 index 0000000000..362a48920b --- /dev/null +++ b/src/ui/styles/omnibar-dock.css @@ -0,0 +1,360 @@ +/* Shared desktop command surface. Mobile and exclusive owners keep their layout. */ +body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not( + .ui-clean-view + ):not(.recording-mode):where( + :has(#gev-omnibar):has(#command-dock > #gev-voice-control) + ) { + --omnibar-dock-width: clamp(400px, 32vw, 460px); + --omnibar-dock-bottom: 74px; + --omnibar-coordinates-bottom: 4.25rem; + --world-timeline-lift: 0px; + + #intel-hud:is([data-variant='tactical'], [data-variant='minimal']) + :is(.hud-top-left, .hud-top-right) { + top: clamp(92px, 10vh, 112px); + } + + #intel-hud:is([data-variant='tactical'], [data-variant='minimal']) + .hud-top-left + .hud-readout:has(> #hud-mode) { + display: none; + } + #top-center-actions { + top: clamp(86px, 9.55vh, 108px); + } + #left-panel-stack.layout-focus { + bottom: var(--left-stack-safe-bottom, 4vh); + } + + #world-timeline { + bottom: calc(var(--omnibar-dock-bottom) + 66px); + 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); + z-index: 149; + width: var(--omnibar-dock-width); + max-width: none; + height: 56px; + min-height: 0; + overflow: visible; + align-items: center; + padding: 0; + } + #command-dock > #gev-voice-control { + box-sizing: border-box; + flex: none; + width: 100%; + min-width: 0; + max-width: none; + height: 56px; + margin: 0; + padding: 0 8px; + gap: 0; + align-items: center; + justify-content: space-between; + border: 1px solid rgba(120, 220, 255, 0.16); + border-radius: 18px; + background: linear-gradient( + 180deg, + rgba(16, 28, 36, 0.9), + rgba(6, 14, 20, 0.94) + ); + box-shadow: + inset 0 1px 0 rgba(200, 245, 255, 0.07), + 0 12px 32px rgba(0, 0, 0, 0.45); + backdrop-filter: none; + } + &:has(#gev-omnibar:focus-within) #command-dock > #gev-voice-control { + border-color: rgba(54, 220, 255, 0.5); + box-shadow: + 0 12px 32px rgba(0, 0, 0, 0.45), + 0 0 0 3px rgba(54, 220, 255, 0.1); + } + #command-dock > #gev-voice-control::before, + #command-dock > #gev-voice-control::after { + content: ''; + position: absolute; + top: 16px; + bottom: 16px; + width: 1px; + height: auto; + transform: none; + background: rgba(120, 220, 255, 0.12); + pointer-events: none; + } + #command-dock > #gev-voice-control::before { + inset-inline-start: 54px; + inset-inline-end: auto; + } + #command-dock > #gev-voice-control::after { + inset-inline-start: auto; + inset-inline-end: 54px; + } + #gev-voice-control > :is(#gev-voice-button, #gev-chat-button):focus-visible { + outline: 2px solid #7bd3ef; + outline-offset: 2px; + } + #gev-voice-control > :is(#gev-voice-button, #gev-chat-button) { + display: grid; + place-items: center; + flex: none; + width: 40px; + height: 40px; + min-width: 0; + margin: 0; + padding: 0; + border: 1px solid rgba(120, 220, 255, 0.18); + border-radius: 50%; + background: rgba(5, 17, 24, 0.48); + box-shadow: + inset 0 2px 4px rgba(0, 0, 0, 0.58), + inset 0 -1px 0 rgba(169, 226, 245, 0.12), + 0 1px 0 rgba(169, 226, 245, 0.1); + transform: none; + } + #gev-voice-control + > :is(#gev-voice-button, #gev-chat-button):is( + :hover, + [aria-pressed='true'], + [aria-expanded='true'] + ) { + background: rgba(54, 220, 255, 0.14); + border-color: rgba(54, 220, 255, 0.6); + } + #command-dock #gev-voice-control .gev-mic-orbit, + #command-dock #gev-chat-button > svg { + box-sizing: border-box; + width: 19px; + height: 19px; + padding: 0; + background: none; + border: 0; + box-shadow: none; + } + #gev-voice-button .gev-mic-orbit img { + width: 19px; + height: 19px; + filter: saturate(0.35) brightness(1.25); + } + #gev-voice-button .gev-mic-orbit::before, + #gev-voice-button .gev-mic-orbit::after { + display: none; + } + #gev-voice-control :is(.gev-mic-label, .gev-chat-label) { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } + /* Status remains readable while live; idle meter is decorative. */ + #command-dock + #gev-voice-control:not([data-assistant-mode='voice']) + > .gev-voice-visualizer, + #command-dock + #gev-voice-control:not([data-chat-busy='true']) + > .gev-chat-thinking { + display: none; + } + #command-dock #gev-voice-control[data-chat-busy='true'] > .gev-chat-thinking { + position: absolute; + top: 10px; + left: 50%; + height: 0; + transform: translateX(-50%); + pointer-events: none; + z-index: 151; + } + #gev-voice-control > .gev-voice-readout { + position: absolute; + inset-inline: 0; + top: auto; + bottom: calc(100% + 8px); + pointer-events: none; + } + #gev-voice-control[data-assistant-mode='idle'] > .gev-voice-readout { + visibility: hidden; + } + + #gev-omnibar { + top: auto; + bottom: calc(var(--omnibar-dock-bottom) + 11px); + left: 50%; + width: calc(var(--omnibar-dock-width) - 120px); + transform: translateX(-50%); + } + #gev-omnibar .omnibar-field { + height: 34px; + padding-inline: 9px 6px; + border: 1px solid rgba(151, 213, 231, 0.27); + border-radius: 9px; + background: rgba(172, 219, 239, 0.07); + box-shadow: none; + backdrop-filter: none; + } + #gev-omnibar-input { + font-size: 0.86rem; + text-overflow: ellipsis; + } + #gev-omnibar-input::placeholder { + color: #b6cbd4; + } + #gev-omnibar .omnibar-field:focus-within { + border-color: rgba(95, 230, 255, 0.66); + background: rgba(109, 206, 232, 0.1); + } + #gev-omnibar .omnibar-search-icon { + color: #a9cfda; + } + #gev-omnibar :is(.omnibar-mic, .omnibar-edge) { + display: none; + } + #gev-omnibar .omnibar-results { + position: absolute; + inset-inline: -60px; + top: auto; + bottom: calc(100% + 11px); + max-height: min( + 360px, + max(0px, calc(100dvh - var(--omnibar-dock-bottom) - 144px)) + ); + overflow: auto; + border-radius: 18px 18px 0 0; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(50, 54, 62, 0.86); + backdrop-filter: blur(26px) saturate(1.2); + -webkit-backdrop-filter: blur(26px) saturate(1.2); + box-shadow: 0 14px 32px rgba(0, 0, 0, 0.45); + } + &:has(#gev-omnibar.has-results):not( + :has(#gev-voice-control[data-assistant-mode='voice']) + ) + #command-dock + > #gev-voice-control { + border-start-start-radius: 0; + border-start-end-radius: 0; + } + #command-dock + #gev-voice-control[data-assistant-mode='voice'] + > .gev-voice-visualizer { + position: absolute; + display: block; + inset: auto 64px 10px; + width: auto; + height: 28px; + opacity: 1; + transform: none; + pointer-events: none; + } + #gev-voice-control > .gev-voice-visualizer > span { + display: none; + } + #gev-voice-control > .gev-voice-visualizer > .gev-voice-wave { + display: block; + width: 100%; + height: 100%; + overflow: visible; + mask-image: linear-gradient( + 90deg, + transparent, + #000 16%, + #000 84%, + transparent + ); + } + .gev-voice-wave path { + fill: none; + stroke-linecap: round; + stroke-linejoin: round; + } + .gev-voice-wave__main { + stroke: #5fe6ff; + stroke-width: 2; + filter: drop-shadow(0 0 4px rgba(54, 220, 255, 0.55)); + } + .gev-voice-wave__echo { + stroke: #36dcff; + stroke-width: 1.2; + opacity: 0.35; + } + .gev-voice-wave__soft { + stroke: #9ff1ff; + stroke-width: 1; + opacity: 0.6; + } + &:has(#gev-voice-control[data-assistant-mode='voice']) #gev-omnibar { + .omnibar-field { + background: transparent; + } + :is(input, .omnibar-kbd, .omnibar-search-icon) { + visibility: hidden; + } + /* Suggestions give way to the waveform; an error stays in view. */ + .omnibar-results:not(.has-feedback), + .omnibar-results .omnibar-list { + display: none; + } + } + @media (prefers-reduced-motion: no-preference) { + #command-dock #gev-voice-control[data-assistant-mode='voice'] { + animation: omnibar-listening 2.4s ease-in-out infinite; + } + } + + /* Desktop uses Omnibar for search and the Visual rail for presets. */ + #command-dock > :is(#location-bar, #control-panel) { + display: none; + } + + /* Align the plain credits with Power Up. */ + :is(#cesium-credits, #gev-credits), + &:has(#intel-hud[data-variant='minimal'].active) + :is(#cesium-credits, #gev-credits) { + bottom: 1rem; + } + #intel-hud[data-variant='tactical'] .hud-bottom-right { + bottom: calc(4.2rem - 26px); + } + #intel-hud:is([data-variant='tactical'], [data-variant='minimal']) + .hud-bottom-left { + bottom: var(--omnibar-coordinates-bottom); + } + &:not(.context-docked):has(#intel-hud[data-variant='minimal'].active) + #right-context-rail { + --omnibar-minimal-rail-height: min( + var(--right-stack-max-height, 70vh), + calc( + 100dvh - var(--right-stack-safe-top, 26vh) - + var(--omnibar-coordinates-bottom) - 3.1rem - 1.2vh + ) + ); + max-height: var(--omnibar-minimal-rail-height); + > [data-panel-id]:not(.collapsed) { + max-height: var(--omnibar-minimal-rail-height); + } + } +} + +@keyframes omnibar-listening { + 0%, + 100% { + border-color: rgba(54, 220, 255, 0.35); + } + 50% { + border-color: rgba(54, 220, 255, 0.75); + } +} diff --git a/src/ui/views/CommandDockView.vue b/src/ui/views/CommandDockView.vue index ed2db21964..e3f827fd34 100644 --- a/src/ui/views/CommandDockView.vue +++ b/src/ui/views/CommandDockView.vue @@ -153,10 +153,10 @@ function selectMapSource(chip) { - + - + diff --git a/src/ui/views/SceneChromeView.vue b/src/ui/views/SceneChromeView.vue index b742ec0269..106850fec4 100644 --- a/src/ui/views/SceneChromeView.vue +++ b/src/ui/views/SceneChromeView.vue @@ -19,6 +19,7 @@ import AwarenessDirection from './panels/AwarenessDirection.vue'; import UiButton from '../kit/UiButton.vue'; import GlobeActions from './panels/GlobeActions.vue'; import { useGlobeActionsStore } from '../stores/globeActions.js'; +import Omnibar from './panels/Omnibar.vue'; import RenderFailure from './panels/RenderFailure.vue'; import WorldTimeline from './panels/WorldTimeline.vue'; @@ -90,6 +91,7 @@ const vToastText = { +
{{ loading ? loading.detail : '' }} diff --git a/src/ui/views/panels/Omnibar.vue b/src/ui/views/panels/Omnibar.vue new file mode 100644 index 0000000000..1b4479a6c9 --- /dev/null +++ b/src/ui/views/panels/Omnibar.vue @@ -0,0 +1,1341 @@ + + + + + diff --git a/src/ui/views/panels/VoiceVisualizer.vue b/src/ui/views/panels/VoiceVisualizer.vue index b29a7e7dac..8067698e1b 100644 --- a/src/ui/views/panels/VoiceVisualizer.vue +++ b/src/ui/views/panels/VoiceVisualizer.vue @@ -1,11 +1,12 @@ + + diff --git a/style.css b/style.css index b8136340c4..1a79c9aeba 100644 --- a/style.css +++ b/style.css @@ -61,4 +61,6 @@ @import './src/ui/styles/ai-chat.css'; @import './src/ui/styles/scope-off-shadows.css'; @import './src/ui/styles/stories-entry.css'; +@import './src/ui/styles/omnibar-dock.css'; +@import './src/ui/styles/guide.css'; @import './src/ui/styles/cyber.css'; From 24731951a0c6438173fa768c25faedd1018d65d5 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 18 Nov 2026 13:00:41 -0800 Subject: [PATCH 019/138] Fly a looked-up place by its coordinates alone, and adopt the bar's files A place row sent its name with its coordinates, and a name that matches a city preset wins over them: "Paris, Texas" flew to Paris, France. Only the coordinates go now. The bar's styles and dock tests join the format scope and the bar its package. Co-authored-by: Manjunath Paparaju --- scripts/format-scope.json | 5 ++++- scripts/package-boundaries.json | 21 +++++++++++++++++++-- src/ui/views/panels/Omnibar.vue | 13 +++++++++---- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/scripts/format-scope.json b/scripts/format-scope.json index ae4431aa6e..0e353a030a 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1588,5 +1588,8 @@ "scripts/wikidataPlaceTiles.mjs", "src/tooling/wikidataPlaceTiles.test.mjs", "src/ui/omnibarIntent.test.mjs", - "src/ui/omnibarRows.test.mjs" + "src/ui/omnibarRows.test.mjs", + "src/ui/styles/omnibar-dock.css", + "src/ui/styles/guide.css", + "src/ui/commandDock.test.mjs" ] diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a09757f481..9c3c766101 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -289,7 +289,23 @@ "src/render/modelParts.js", "src/ui/views/panels/AircraftModelHero.vue", "src/data/retryableLoad.js", - "src/data/local_data/wikidata_places/files.js" + "src/data/local_data/wikidata_places/files.js", + "src/ui/views/panels/Omnibar.vue", + "src/exclusiveSurfaces.js", + "src/geoDistance.js", + "src/ui/omnibarGuide.js", + "src/cityPois.js", + "src/search/photonSetting.js", + "src/sources/requestDeadline.js", + "src/ui/omnibarEnter.js", + "src/ui/omnibarIntent.js", + "src/data/placeNames.js", + "src/search/plusCode.js", + "src/keylessGeocoder.js", + "src/ui/omnibarRows.js", + "src/search/gridReference.js", + "src/search/coordinateParser.js", + "src/search/placeSuggestions.js" ], "external": ["vue", "pinia", "vue-i18n"] }, @@ -1657,7 +1673,8 @@ "src/ui/entityContextBridge.js", "src/data/trackingClickGesture.js", "src/ui/stores/sceneSharing.js", - "src/maps/attribution.js" + "src/maps/attribution.js", + "src/data/dataCredits.js" ], "external": [ "cesium", diff --git a/src/ui/views/panels/Omnibar.vue b/src/ui/views/panels/Omnibar.vue index 1b4479a6c9..fa4f6f3afd 100644 --- a/src/ui/views/panels/Omnibar.vue +++ b/src/ui/views/panels/Omnibar.vue @@ -372,9 +372,13 @@ const strip = computed(() => { return all.length ? { title, chips: all } : null; }); -/** Fly to a place by its coordinates, as a looked-up place row does. */ -async function goTo({ name, latitude, longitude }) { - if (runner.value) return settled(await runner.value('fly_to_location', { latitude, longitude, query: name })); +/** + * Fly to a place by its coordinates, as a looked-up place row does. Only the + * coordinates go: with its name, "Paris, Texas" would fly to the city + * preset Paris. + */ +async function goTo({ latitude, longitude }) { + if (runner.value) return settled(await runner.value('fly_to_location', { latitude, longitude })); const location = locationStore.controls; if (!location || location.destroyed) throw new Error(); await location.search(`${latitude}, ${longitude}`); @@ -820,7 +824,8 @@ async function choose(item, { viaKey = false } = {}) { else if (item.kind === 'count-show' || item.kind === 'place') { const { coords, place } = item; if (coords && runner.value) { - if (!settled(await runner.value('fly_to_location', { ...coords, query: place }))) return; + // The coordinates alone: a name would win over them (see goTo). + if (!settled(await runner.value('fly_to_location', { ...coords }))) return; } else { const location = locationStore.controls; if (!location || location.destroyed) throw new Error(); From d7f10e4d2af41c4dc8972790cdaee890ae1295dd Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 18 Nov 2026 13:11:44 -0800 Subject: [PATCH 020/138] Fix the search bar's stale errors, hidden-field shortcuts and repeated Enter From review: - An error goes when a chip is chosen, and a search's error shows only under the line it was for: a lookup that fails after the line was edited says nothing under the new text. - With voice on the field is hidden: "/" and Cmd/Ctrl+K no longer focus it, and nothing is looked up for it. - Without the action runner a refused or cancelled search keeps the line, as the plan path does (only true is success). - Text an input method is still composing is read when it is committed. - A held or repeated Enter does not restart the same line over its flight. - A city chip for the city whose landmarks are open flies there instead of folding the landmarks. - "villages around here" is looked up again for the current view. - Data Layers takes the full lane only where the desktop dock is laid out, by the condition omnibar-dock.css uses. - On short phones the HUD readout moves under the field it shared a row with. - CURRENT-STATE says the phone gains a field and which places are kept. Co-authored-by: Manjunath Paparaju --- docs/CURRENT-STATE.md | 7 +++--- src/ui/leftPanelRail.js | 23 ++++++++++++++++- src/ui/panelRails.test.mjs | 7 +++++- src/ui/views/panels/Omnibar.vue | 44 ++++++++++++++++++++++++++++----- 4 files changed, 70 insertions(+), 11 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 9c3a7804a9..8ef379cc99 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7817,8 +7817,8 @@ and unreachable upstream (502/504) separately from road geometry. ### Omnibar The desktop Omnibar sits above the footer with the existing mic and chat -buttons on either side. Suggestions open upward; the phone field stays at -the top and opens downward. While voice is on, the desktop field shows +buttons on either side. Suggestions open upward. On phones the Omnibar is +a field near the top, beside the Search sheet, and opens downward. While voice is on, the desktop field shows three audio traces in place of the search text and icon. The thinking dots sit on the field's top edge. World Time appears immediately above the dock and hides while suggestions, chat, or voice settings are visible. `/` @@ -8088,7 +8088,8 @@ recovery or seed phrases, "my secret is …" and an email spelled out ("john at example dot com") are private too. Text that parses as coordinates or a grid reference is not private. A place's name is six words at most, or ten when it has a number in it (an address: "1600 Pennsylvania Ave NW -Washington DC 20500"). The places you go to from the Omnibar (the last 20: +Washington DC 20500"). The places picked from the Omnibar's rows and chips that carry a position +(a typed name searched as a place, or a plan's place, is not kept; the last 20: name, position and where the name came from) are kept in this browser's `localStorage` under `gev:omnibar:recent-places` for the strip; nothing clears them but the browser's own site data. Setting `PHOTON_URL` diff --git a/src/ui/leftPanelRail.js b/src/ui/leftPanelRail.js index 44eef21fd5..d714c18f86 100644 --- a/src/ui/leftPanelRail.js +++ b/src/ui/leftPanelRail.js @@ -7,6 +7,27 @@ import { import { measurePanelNaturalHeight } from './panelMeasurement.js'; import { settleSideAccordion } from './panelAccordion.js'; +/** + * Whether the desktop Omnibar dock is laid out, by the condition + * omnibar-dock.css lays it out by: the bar and the voice control in the + * dock, outside the phone layout, the cockpit, playback, clean view and + * recording. + */ +const DOCK_OFF = [ + 'mobile-shell', + 'cockpit-mode', + 'scene-playback-mode', + 'ui-clean-view', + 'recording-mode', +]; +function desktopOmnibarDock(documentRef) { + if (!documentRef?.getElementById?.('gev-omnibar')) return false; + const body = documentRef.body; + if (DOCK_OFF.some((name) => body?.classList?.contains?.(name))) return false; + const voice = documentRef.getElementById('gev-voice-control'); + return Boolean(voice) && voice.parentElement?.id === 'command-dock'; +} + /** * Measure and place the left panel rail for one synchronous layout pass. * The caller owns scheduling, obstacle selection, disclosure preferences and @@ -233,7 +254,7 @@ export function layoutLeftPanelRail({ exclusive && expandedPanels.length === 1 && expandedPanels[0].id === 'data-panel' && - Boolean(documentRef?.getElementById?.('gev-omnibar')); + desktopOmnibarDock(documentRef); const shouldTail = !fillDataLayers && expandedPanels.length > 0 && diff --git a/src/ui/panelRails.test.mjs b/src/ui/panelRails.test.mjs index cf5a534451..7a2db6433b 100644 --- a/src/ui/panelRails.test.mjs +++ b/src/ui/panelRails.test.mjs @@ -250,8 +250,13 @@ test('a centered timeline only shortens the corridor when it reaches the visible test('Data Layers extends to the HUD even if its list is currently short', () => { const f = fixture('left'); f.first.id = 'data-panel'; + const dock = { id: 'command-dock' }; f.options.documentRef.getElementById = (id) => - id === 'gev-omnibar' ? {} : null; + id === 'gev-omnibar' + ? {} + : id === 'gev-voice-control' + ? { parentElement: dock } + : null; f.expand(f.first, 250); f.options.obstacles = [element('hud', { top: 760, height: 45 })]; f.run(); diff --git a/src/ui/views/panels/Omnibar.vue b/src/ui/views/panels/Omnibar.vue index fa4f6f3afd..20a4327b92 100644 --- a/src/ui/views/panels/Omnibar.vue +++ b/src/ui/views/panels/Omnibar.vue @@ -53,7 +53,12 @@ const error = ref(''); const busy = ref(false); let generation = 0; let stopGuide; -const searchError = computed(() => locationView.value?.searchOrigin === 'omnibar' ? locationView.value.searchError : ''); +// A search's error shows under the line it was for: one that fails after +// the line was edited says nothing under the new text. +const searchedFor = ref(null); +const searchError = computed(() => + locationView.value?.searchOrigin === 'omnibar' && searchedFor.value === query.value ? locationView.value.searchError : '', +); const feedback = computed(() => error.value || searchError.value); const voiceOn = computed(() => voice.view?.root?.assistantMode === 'voice'); // Voice taking over supersedes whatever the field was still running: a plan @@ -133,7 +138,8 @@ watch(query, (value) => { // Only text that may name a place goes to the place service, and only the // part that names it: never private text, a question, a sentence, a // command, a switch, coordinates or an aircraft code (see placeQuery). - const asked = suggester.enabled ? reader.value.placeQuery(text) : null; + // Nothing is looked up for a field hidden under voice. + const asked = suggester.enabled && !voiceOn.value ? reader.value.placeQuery(text) : null; if (!asked) { places.value = []; placesFor.value = ''; @@ -381,6 +387,7 @@ async function goTo({ latitude, longitude }) { if (runner.value) return settled(await runner.value('fly_to_location', { latitude, longitude })); const location = locationStore.controls; if (!location || location.destroyed) throw new Error(); + searchedFor.value = query.value; await location.search(`${latitude}, ${longitude}`); return true; } @@ -389,6 +396,9 @@ function chooseChip(chip, { viaKey = false } = {}) { if (screenIsOwned()) return; generation++; busy.value = false; + // A chip is a new request: the last one's error goes. + error.value = ''; + locationStore.controls?.editSearch(); if (chip.kind === 'entity') { entityCard.select(chip.identity, { fly: true }); reset({ blur: !keepsFocus(viaKey) }); @@ -406,7 +416,10 @@ function chooseChip(chip, { viaKey = false } = {}) { reset(); return; } - if (chip.kind === 'city') locationStore.controls?.chooseCity(chip.cityId); + // The city whose landmarks are open would only fold them: it is flown to. + if (chip.kind === 'city' && locationView.value?.poiCity === chip.cityId && runner.value) + void runner.value('fly_to_location', { locationId: chip.cityId }); + else if (chip.kind === 'city') locationStore.controls?.chooseCity(chip.cityId); else if (chip.kind === 'landmark') { if (locationView.value?.poiCity === chip.cityId) locationStore.controls?.choosePoi(chip.index); else { @@ -563,7 +576,10 @@ watch( () => (focused.value ? villagesAsked.value : ''), (asked) => { clearTimeout(villagesTimer); - if (!asked || villages.value?.asked === asked) return; + // "around here" and "near it" move with the view and the selection, so + // they are looked up again; a named place is the same place. + const relative = HERE.test(asked) || /^(me|it|this|that)$/i.test(asked); + if (!asked || (villages.value?.asked === asked && !relative)) return; villagesTimer = setTimeout(() => void findVillages(asked), 250); }, ); @@ -628,6 +644,9 @@ const showFeedback = computed(() => feedback.value && (focused.value || !assista const showResults = computed(() => open.value || showFeedback.value || noCommand.value || privateNote.value); function onInput(event) { + // Text an input method is still composing is read when it is committed + // (compositionend), not sent to the place service half-written. + if (event.isComposing) return; query.value = event.target.value; generation++; busy.value = false; @@ -739,6 +758,7 @@ async function runPlan(steps, current) { // the plan go on; a cancelled, missing or failed one stops it. const location = locationStore.controls; if (!location || location.destroyed) throw new Error(); + searchedFor.value = query.value; const flight = await location.search(step.place); if (flight !== true) return; } @@ -829,8 +849,11 @@ async function choose(item, { viaKey = false } = {}) { } else { const location = locationStore.controls; if (!location || location.destroyed) throw new Error(); + searchedFor.value = query.value; const result = await location.search(coords ? `${coords.latitude}, ${coords.longitude}` : place); - if (result === false || locationView.value?.searchOrigin !== 'omnibar' || searchError.value) return; + // Only a search that found the place counts: a refused or cancelled + // one (undefined) keeps the line, as the plan path does. + if (result !== true || locationView.value?.searchOrigin !== 'omnibar' || searchError.value) return; } // A typed spot is the user's own; a looked-up place keeps its source. if (coords && item.kind === 'place') rememberPlace({ name: place, ...coords, source: item.source || 'typed' }); @@ -932,6 +955,9 @@ function onKeydown(event) { } else if (event.key === 'Enter') { if (!open.value) return; event.preventDefault(); + // A held or repeated Enter does not start the same line again over its + // flight; an edited line (which clears busy) runs. + if (event.repeat || busy.value) return; if (inStrip.value && chips[chipIndex.value]) chooseChip(chips[chipIndex.value], { viaKey: true }); else choose(items.value[active.value], { viaKey: true }); } else if (event.key === 'Escape' && !showResults.value && !query.value.trim()) { @@ -952,7 +978,8 @@ function onKeydown(event) { // focuses the field. Ctrl+K on a Mac is left to the text field it is in. const isMac = /Mac|iPhone|iPad/.test(globalThis.navigator?.platform || ''); function onGlobalKeydown(event) { - if (event.defaultPrevented || event.isComposing || screenIsOwned() || !input.value?.getClientRects().length) return; + // With voice on the field is hidden: the shortcut does not focus it. + if (event.defaultPrevented || event.isComposing || voiceOn.value || screenIsOwned() || !input.value?.getClientRects().length) return; // An open modal dialog, or focus inside any dialog (the guide), keeps its // keys: the shortcut does not pull focus out of it. const doc = globalThis.document; @@ -1026,6 +1053,7 @@ watch( :placeholder="t('Search places, layers, flights… or ask GEV · > for commands')" :value="query" @input="onInput" + @compositionend="onInput" @keydown="onKeydown" @focus="focused = true; dismissed = false; navigated = false; inStrip = false; layerRevision++" @blur="focused = false" @@ -1338,6 +1366,10 @@ small { --omnibar-message-padding: 1px; --omnibar-item-padding: 2px; } + /* The field takes the HUD readout's row (48-82px): the readout sits under it. */ + :global(body.mobile-shell:has(#world-timeline):has(#gev-omnibar) #intel-hud .hud-bottom-left) { + top: calc(var(--mobile-top-inset, 0px) + 88px); + } } :global(body.ui-clean-view #gev-omnibar), :global(body.recording-mode #gev-omnibar), From 3d3382f78697ab4bf5fbf89df84bd250a440ca19 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 18 Nov 2026 15:00:28 -0800 Subject: [PATCH 021/138] Add the changelog entry for the Omnibar Co-authored-by: Manjunath Paparaju --- changelog.d/1824-omnibar.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 changelog.d/1824-omnibar.md diff --git a/changelog.d/1824-omnibar.md b/changelog.d/1824-omnibar.md new file mode 100644 index 0000000000..0ca86d39dd --- /dev/null +++ b/changelog.d/1824-omnibar.md @@ -0,0 +1,12 @@ +- Add the Omnibar: one field for places, coordinates, map items, layers + and commands, with a strip of nearby places, guided walks through the + real controls (found by everyday wording such as "how do I change the + map style"), plans such as "go to Austin and show flights", and Ask GEV + for questions. On desktop the dock rises to a bar above the bottom with + the map credits below it on the Power Up row, World Time hides while + suggestions or chat are open, and the dock's Location and Visual trays + and the HUD's mode readout give way to the Omnibar and the Visual panel. + Phones get the field too, with the HUD readout under it on short + screens. The last 20 places you went to from the Omnibar are kept in + this browser (`localStorage` `gev:omnibar:recent-places`) + (manjunath22466, samehkhamis, #1824). From 9df858e9fe4400484f918cfa643592c70cf6e958 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Wed, 18 Nov 2026 15:33:06 -0800 Subject: [PATCH 022/138] Start the right panels below the Stories card while it is up With the Omnibar's lifted dock the right column rises level with the left one, under the NEW GEV Stories card, whose buttons then took clicks meant for the panel's controls (Street Level's FIT and FILL). The card is now an obstacle for the right column, and its arrival or departure lays the column out again. Co-authored-by: Manjunath Paparaju --- src/ui/panelLayoutController.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/ui/panelLayoutController.js b/src/ui/panelLayoutController.js index abcd4dff06..7b21b72d09 100644 --- a/src/ui/panelLayoutController.js +++ b/src/ui/panelLayoutController.js @@ -57,6 +57,9 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [ '#intel-hud .hud-right-edge', '#cockpit-context', '#cockpit-signal-stream', + // The "NEW: GEV Stories" card under the Stories button: panels start below + // it while it is up, so its buttons never sit over a panel's controls. + '#hPop', '#cesium-credits .cesium-credit-logoContainer', '#cesium-credits .cesium-credit-textContainer', '#gev-credits', @@ -64,6 +67,14 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [ '#gev-voice-control', '#world-timeline', ].join(', '); +/** True when a mutation adds or removes the Stories card (`#hPop`). */ +function movesStoriesCard(record) { + for (const list of [record.addedNodes, record.removedNodes]) + for (const node of list) + if (node.id === 'hPop' || node.querySelector?.('#hPop')) return true; + return false; +} + export class PanelLayoutController { constructor({ readHud, @@ -92,6 +103,7 @@ export class PanelLayoutController { this._rightStackPreferredPanelId = null; this._rightStackReconsiderAutoCollapse = false; this._rightStackResizeObserver = null; + this._storiesCardObserver = null; this._cockpitLayoutFrame = null; this._cockpitLayoutTimer = null; this._leftPanelStack = document.getElementById('left-panel-stack'); @@ -246,6 +258,18 @@ export class PanelLayoutController { attributes: true, attributeFilter: ['class', 'hidden', 'data-variant'], }); + // The Stories card comes and goes inside the Stories view; only its + // arrival or departure moves the rail, not the view's other changes. + const storiesHost = document.getElementById('gev-stories-host'); + if (storiesHost) { + this._storiesCardObserver = new MutationObserver((records) => { + if (records.some(movesStoriesCard)) this._scheduleRightPanelLayout(); + }); + this._storiesCardObserver.observe(storiesHost, { + subtree: true, + childList: true, + }); + } const hud = document.getElementById('intel-hud'); if (hud) { this._rightStackMutationObserver.observe(hud, { @@ -464,6 +488,7 @@ export class PanelLayoutController { '_leftStackMutationObserver', '_rightStackResizeObserver', '_rightStackMutationObserver', + '_storiesCardObserver', ]) { this[field]?.disconnect(); this[field] = null; From d68adcea2172ca484f70ebc99f6118b02731a9e4 Mon Sep 17 00:00:00 2001 From: Manjunath Paparaju Date: Wed, 18 Nov 2026 18:47:20 +0530 Subject: [PATCH 023/138] Remove the Cyber HUD layout and keep its sonar as a visual style Display > HUD > Sonar now turns the sonar sweep on over Tactical or Minimal. It is off by default, ON reveals its five sliders, and it keeps its guards: an OFF control, the sweep only while the HUD is visible and outside Cockpit, no animation under reduced motion, and repaint timers re-armed only after a drawn frame that still shows contacts. The Cyber layout, its shell skin and its Cockpit lanes are removed. Share links, scenes, saved views and set_hud that name Cyber open Tactical with Sonar on; links and scene shots record Tactical with Sonar under the same code, and a restored state that names another layout turns Sonar off. set_cyber_sonar keeps its name and works under any layout. A newer Sonar toggle or voice setting wins over a share-link restore that lands later. From 1200px wide the command dock and World Timeline sit 74px above the bottom edge, as in the Omnibar layout, leaving the bottom row to the map attribution (left) and the Power Up corner row (right). The attribution moves to the bottom right when the page runs right to left, where the corner row sits at the bottom left, and a long credit line wraps upward before reaching the corner row. The Tactical bottom-right readout sits 8px above Power Up and the coordinates start level with it. The World Timeline is narrowed to sit between the corners. Toasts keep clear of the raised dock and the chat and voice panel height budgets subtract its rise. Below 1200px the layout is unchanged. The left rail treats the centered World Timeline and voice control as obstacles only where they reach a laid-out panel. On top of the Omnibar: sonar.css replaces cyber.css after the Omnibar imports, the Omnibar's HUD guide step now says Layout picks Tactical or Minimal, and the Omnibar's Tactical bottom-right readout keeps the same 8px above Power Up. Co-authored-by: Sameh Khamis --- changelog.d/0-sonar-visual-style.md | 10 + docs/CODE-BOUNDARIES.md | 3 +- docs/CURRENT-STATE.md | 139 +- docs/SHARE-LINK-FORMAT.md | 2 +- docs/VUE-MIGRATION.md | 5 +- docs/panel-surfaces.md | 20 +- docs/translations/es.md | 1 - docs/translations/fr.md | 1 - docs/translations/it.md | 2 +- docs/translations/ja.md | 2 +- docs/translations/pt.md | 1 - docs/translations/zh-CN.md | 2 +- scripts/format-scope.json | 3 +- scripts/package-boundaries.json | 5 - scripts/qa-cockpit-utility.mjs | 92 - scripts/qa-form-fields.mjs | 10 - scripts/qa-scope-hud.mjs | 2 +- scripts/qa-segmented-controls.mjs | 29 - scripts/qa-status-badges.mjs | 2 +- server/providers/openai/instructions.js | 4 +- server/providers/openai/toolDescriptions.js | 2 +- src/cockpitMarkup.test.mjs | 6 +- src/cockpitUtilityLayout.js | 45 +- src/cockpitUtilityLayout.test.mjs | 72 +- src/contextTabKeyboard.test.mjs | 2 +- src/cyberSonar.js | 14 +- src/cyberSonar.test.mjs | 22 +- src/cyberSonarScene.test.mjs | 43 +- src/data/detectionAwarenessEcho.test.mjs | 2 +- src/data/detectionHost.test.mjs | 8 +- src/firstRunExperience.test.mjs | 6 +- src/hud.js | 14 +- src/hudLayoutPolicy.js | 9 +- src/hudLayouts.js | 49 +- src/i18n/locales/ar.json | 9 +- src/i18n/locales/de.json | 9 +- src/i18n/locales/es.json | 9 +- src/i18n/locales/fr.json | 9 +- src/i18n/locales/he.json | 9 +- src/i18n/locales/it.json | 9 +- src/i18n/locales/ja.json | 9 +- src/i18n/locales/pt.json | 9 +- src/i18n/locales/ru.json | 9 +- src/i18n/locales/sv.json | 9 +- src/i18n/locales/uk.json | 9 +- src/i18n/locales/zh-CN.json | 9 +- src/i18n/locales/zh-Hant.json | 9 +- src/i18n/same-as-english.json | 4 - src/layers/awareness/policy.js | 2 +- src/layers/awareness/rangeRing.js | 12 +- src/layers/awareness/rangeRing.test.mjs | 6 +- src/overlays/worldOverlay.js | 2 +- src/panelStackLayout.test.mjs | 2 +- src/radioMarkup.test.mjs | 12 +- src/render/cesium/iconSetPrimitive.js | 2 +- src/share/viewCodec.js | 3 + src/share/viewCodec.test.mjs | 16 +- src/sharelink.celestial.test.mjs | 1 + src/streetLevelMarkup.test.mjs | 14 - src/ui/applicationShell.js | 13 +- src/ui/cockpitDisplayPortal.js | 15 +- src/ui/cockpitLayout.js | 138 +- src/ui/cockpitUtilityControls.test.mjs | 30 +- src/ui/cssContentCaption.test.mjs | 5 +- src/ui/cyberSonarControls.js | 14 +- src/ui/cyberSonarControls.test.mjs | 29 +- src/ui/cyberTheme.test.mjs | 950 ------ src/ui/displayBindings.js | 16 +- src/ui/displayPanel.test.mjs | 26 +- src/ui/displayPanelActions.test.mjs | 2 +- src/ui/displayPanelScroll.js | 6 - src/ui/hudSonarStyle.test.mjs | 666 +++++ src/ui/omnibarGuide.js | 4 +- src/ui/panelChrome.js | 3 +- src/ui/panelRails.test.mjs | 32 +- src/ui/providerSettings.test.mjs | 8 +- src/ui/radioControls.js | 5 +- src/ui/railPanelChrome.test.mjs | 35 +- src/ui/rightPanelRail.js | 3 +- src/ui/rtlLayout.test.mjs | 17 - src/ui/sidePanelDisclosure.test.mjs | 6 +- src/ui/styles/ai-chat.css | 34 +- src/ui/styles/cockpit-panels.css | 104 +- src/ui/styles/cockpitBridge.css | 49 +- src/ui/styles/cockpitOrbital.css | 6 +- src/ui/styles/command-dock-trays.css | 90 +- src/ui/styles/command-dock.css | 13 +- src/ui/styles/controls.css | 48 +- src/ui/styles/cyber.css | 2916 ------------------- src/ui/styles/layers.css | 8 +- src/ui/styles/library.css | 27 +- src/ui/styles/news.css | 5 - src/ui/styles/omnibar-dock.css | 4 +- src/ui/styles/overlays.css | 22 +- src/ui/styles/panel-surfaces.css | 17 - src/ui/styles/rail-split.css | 40 +- src/ui/styles/rtl.css | 6 - src/ui/styles/scenes.css | 2 +- src/ui/styles/sonar.css | 89 + src/ui/styles/visual-panel.css | 92 +- src/ui/styles/voice-card.css | 7 +- src/ui/styles/voice-cost.css | 11 +- src/ui/styles/world-timeline.css | 10 +- src/ui/views/CockpitView.vue | 48 +- src/ui/views/ProviderSettingsView.vue | 29 +- src/ui/views/panels/DisplayPanel.vue | 21 +- src/ui/views/panels/MissionDetail.vue | 2 +- src/ui/visualSettings.js | 113 +- src/voice/actionSchemas.test.mjs | 8 +- src/voice/gevActions.js | 2 +- src/voice/speech.js | 2 +- style.css | 2 +- 112 files changed, 1433 insertions(+), 5239 deletions(-) create mode 100644 changelog.d/0-sonar-visual-style.md delete mode 100644 src/ui/cyberTheme.test.mjs delete mode 100644 src/ui/displayPanelScroll.js create mode 100644 src/ui/hudSonarStyle.test.mjs delete mode 100644 src/ui/styles/cyber.css create mode 100644 src/ui/styles/sonar.css diff --git a/changelog.d/0-sonar-visual-style.md b/changelog.d/0-sonar-visual-style.md new file mode 100644 index 0000000000..d22f7b2afb --- /dev/null +++ b/changelog.d/0-sonar-visual-style.md @@ -0,0 +1,10 @@ +- Remove the Cyber HUD layout and keep its sonar as a visual style. Display > + HUD > Sonar turns it on over Tactical or Minimal; it is off by default and + ON reveals its five sliders. Share links, scenes and saved views that name + Cyber open in Tactical with Sonar on, links and scene shots carry Tactical + with Sonar the same way, and the `set_cyber_sonar` voice action works under + any layout. A newer Sonar choice takes precedence over a pending share-link + restore. From 1200px wide the command dock and World Timeline sit 74px up, + the map attribution sits on the Power Up baseline, and the coordinates start + level with the bottom-right readout instead of overlapping the attribution + and Power Up (manjunath22466, #0). diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index 2852bea0ae..f6519813eb 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -781,8 +781,7 @@ palettes use `--gev-field-background`, `--gev-field-border-color`, `--gev-field-color` and `--gev-field-disabled-opacity`. Radio retains its own compact density and arrow space. CCTV owns calibration editor width in `cctv.css`; the shared inline density does not impose a feature-specific width. -Cyber supplies a shared-field palette explicitly and keeps its legacy native -field rules separate, so Radio's palette remains an intentional exception. +Radio's palette remains an intentional exception. ### Read-only status badges diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 8ef379cc99..ec48047b6f 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -846,8 +846,7 @@ detection, style parameters, 3D aircraft, Scope and Clean UI; Effects, Celestial, Bloom and Sharpen; and Reset to default at the foot. Each control is a card (`src/ui/styles/visual-panel.css`) whose header row ends in an on/off pill worded in the current language (Clean UI, an action, has none; -the buttons carry their state as `aria-pressed`). Under the Cyber HUD the -cards keep Cyber's own red skin. The presets and chips call the +the buttons carry their state as `aria-pressed`). The presets and chips call the same Display store actions as the dock's Visual Presets tray, which stays on desktop and phone as before, along with Location; voice `Visual Presets` still opens that tray. On a phone the More sheet shows that tray right above @@ -872,8 +871,7 @@ the out-of-the-box look: the Normal style, the first-run post defaults (bloom off, sharpen on at 49%, the HUD shown, Dense detection at 75% with its fade and outside opacity, the celestial ring off), Elastic allocation, Scope on at 100% feather and 100% opacity, and 3D aircraft on in -Proximity. The HUD layout follows the Normal style, as choosing it does: the -Tactical HUD, except that the Cyber HUD stays Cyber. Inside Contacts, which +Proximity. The HUD layout stays as the viewer set it. Inside Contacts, which lends detection for the session, the reset's detection becomes what leaving Contacts puts back and what a share link carries. It leaves the map source, the pinned scope terminus, Sonar's settings, other styles' parameters, the layers and the panels alone. @@ -1013,9 +1011,9 @@ and Radio through the cockpit layout pass, whose floor matches it, so an open panel still stops short of the briefing. Contact and Live Signals are shorter, in the same glass, with the briefing's rows and weather tiles tightened; Regional News stays a briefing page. In a right-to-left language, the rail keeps its -physical side as the cockpit's other windows do. The Cyber HUD and the phone -keep their own cockpit layouts, with the Display and Radio launchers as -before, and edge mode does not apply in the cockpit. +physical side as the cockpit's other windows do. The phone keeps its own +cockpit layout, with the Display and Radio launchers as before, and edge mode +does not apply in the cockpit. ## God's Eye View in conversations — October 2, 2026 @@ -1117,73 +1115,77 @@ at 70% opacity behind telemetry, vertical metadata and scene chrome. Original HUD text color, glow and opacity are preserved. Scope OFF brightens the tagline and Active Style label with the shared secondary text color. The title plate covers the eye and title without moving the title or tagline. Scope ON retains -the original HUD presentation; Cyber retains its existing skin. +the original HUD presentation. `node scripts/qa-scope-hud.mjs` checks native input, range, layout persistence, restoration and both Scope presentations. `QA_SCREENSHOT_DIR` saves screenshots. ## HUD layouts — October 29, 2026 -Display > HUD > Layout offers Tactical, Minimal and Cyber; the `set_hud` voice -action accepts the same three. The Operator layout is retired. Share links +Display > HUD > Layout offers Tactical and Minimal; the `set_hud` voice +action accepts the same two. The Operator layout is retired. Share links keep its enum code so older links still parse, and a link, scene or saved state that names Operator restores the default Tactical layout. Operator was the only layout that showed the HUD's top banner bar, so its markup and styles are removed too. -## Cyber HUD — September 30, 2026 +## Sonar visual style — November 18, 2026 -Display > HUD > Layout includes Cyber, also available through the HUD voice -action and shared visual state. An explicit first transition into Cyber selects -FLIR with Ironbow 0.42. An explicit switch back to another HUD layout restores -the visual preset used before Cyber; restored links and scenes remain -authoritative. The skin uses shared red/slate panel treatments in map and cockpit, -with compact 200px collapsed controls and wider expanded panels. Other HUD -layouts retain their existing presentation. -Chamfered panel expand/collapse controls use an inset keyboard-focus outline and -red hover border in both map and cockpit, so clipping does not hide the highlight. - -Cyber's map-side right rail opens one panel at a time while keeping collapsed -launchers available. Display, CCTV and Context scroll their contents inside fixed -headers and decorative frames. The narrow-screen rail remains scrollable to reach -each panel. Radio retains the shared nested Context player without relocating -playback controls on theme changes. - -Voice help/error popups and Location/Visual Presets pins extend beyond their -Cyber frames without being clipped: the shapes decorate non-interactive -pseudo-elements. The lower-left telemetry card leaves room for attribution's -full logo row. New panels can use the [shared surface contract](panel-surfaces.md) -for theme tokens, rail input and a fixed header with a bounded scroll body. -The contract is intentionally future-facing and opt-in; its first production -adopter will land after this change. Existing owners still control disclosure, -persistence and placement, while small-screen rail popup clipping and other -integration limits remain documented in the contract. - -On desktop, Cyber raises the left rail so it clears the lower coordinate card. -`layoutRightPanelRail` reads that rendered top as its measured `baseTop`, which -keeps the right rail aligned. Cockpit retains its separate rail placement for -its visor layout. +The Cyber HUD layout and its shell skin are removed. Its sonar stays as an +opt-in visual style over Tactical or Minimal: Display > HUD > Sonar is OFF by +default, and ON reveals the Rings, Range, Power, Opacity and Sector sliders. +Share links, scenes and saved views that name Cyber keep its enum code and +open in Tactical with Sonar on. Links and scene shots record Tactical with +Sonar on under that same code, and a restored state that names another layout +turns Sonar off; Minimal has no such code, so its Sonar is not carried. +An explicit Sonar toggle or validated voice setting takes visual restore +authority, so a delayed share-link restore cannot undo the newer choice. +Choosing Reset Visual keeps the HUD layout and the Sonar setting. Sonar has one contact-highlighting method. Native Cesium points, billboards and labels are treated in GPU draw commands without replacing their positions, identities or pick commands. Model and canvas/DOM overlays retain their own -rendering paths. Sonar OFF stops the sweep while retaining Cyber's neutral -contact treatment. Reduced motion disables the animated sweep; cockpit and -hidden HUD states do not apply the map treatment. If the native shader is not -supported, native contacts remain available and Display reports the limitation. -No CSS scene-dimming fallback or effect selector is exposed. +rendering paths. Sonar runs only while it is on, the HUD is visible and Cockpit +is closed. Reduced motion disables the animated sweep. The sweep's repaint +timer re-arms only after a drawn frame (postRender) that still shows contacts. +If the native shader is not supported, native contacts remain available and +Display reports the limitation. No CSS scene-dimming fallback or effect +selector is exposed. The Sonar controls adjust rings, range, power, opacity and sector. Sweep opacity -affects detection painting rather than label cohort admission. Theme exit and -renderer teardown release the derived GPU resources and restore owned model -colors without replacing newer layer-owned color changes. +affects detection painting rather than label cohort admission. Turning Sonar +off and renderer teardown release the derived GPU resources and restore owned +model colors without replacing newer layer-owned color changes. -The `set_cyber_sonar` voice action adjusts the same controls without switching -themes or enabling omitted settings. State readback distinguishes configured -settings from active map/contact effects. Sonar settings are session-only and -return to their defaults on reload. Sliders accept integer values matching the +The `set_cyber_sonar` voice action keeps its name and adjusts the same +controls under any HUD layout, without switching layouts or enabling omitted +settings. State readback distinguishes configured settings from active +map/contact effects. Sonar settings are session-only and return to their +defaults (Sonar off) on reload. Sliders accept integer values matching the action's ranges. +## Bottom-corner placement — November 18, 2026 + +From 1200px the command dock and the World Timeline sit 74px above the +bottom edge, and the map attribution row sits on the bottom edge on the Power +Up baseline (bottom right when the page runs right to left, where the corner +row moves to the bottom left). A credit line too long for the space before the +corner row wraps upward instead of running under it. The Tactical bottom-right +readout (GSD / ALT / AIS) sits 8px above the Power Up row and the Tactical and +Minimal coordinates start level with it. The World Timeline is 44rem narrower +than the screen there, so it sits between the corners and they stay put while +it shows. Toasts keep 12px above the raised dock, and the chat and voice panel +height budgets subtract its rise. Below 1200px the dock reaches the bottom +corners, so it keeps to the bottom edge, the attribution row sits above it and +the coordinates clear the row's logo line. In the desktop Omnibar layout the +Omnibar's own rules (`src/ui/styles/omnibar-dock.css`) place the dock, the +World Timeline, the credits and the coordinates; its Tactical bottom-right +readout also keeps 8px above the Power Up row. The left rail treats the +centered World Timeline and voice control as obstacles only where they reach a +laid-out panel, not the stack's transparent gutter. Known limit, unchanged +from main: below 1200px with the World Timeline showing, the Tactical +bottom-right readout does not rise with the bar and can touch the dock. + Wind appears in the Weather group before Audio. The surface-weather prototype uses keyless NOAA GFS or ECMWF IFS forecasts on an approximately 1° display grid. It defaults to 10 m wind trails over the existing basemap. Speed shading is an explicit choice; earlier v2 links retain their original speed-shading meaning. @@ -2474,7 +2476,7 @@ change still in flight blocks entry until it settles. Double-clicking the selected vessel enters it, and the entry button reads BRIDGE with a ship icon both in Contacts (`#cockpit-entry`) and under the selected vessel's Intel HUD readout in the bottom-right corner (`#cockpit-entry-readout`, shown with the -HUD on, in its Tactical and Cyber layouts). Turning Live AIS Vessels off ends +HUD on, in its Tactical layout). Turning Live AIS Vessels off ends the bridge: the layer then has no subject (`getCockpitSubject` returns null). The bridge picture uses AIS alone, so no other feed being off makes it partial. Voice (`control_cockpit`) and the selection entry transaction stay aircraft-only; @@ -3210,9 +3212,8 @@ owns surrounding layout and context-specific sizing. CCTV's calibration editor width lives in `ui/styles/cctv.css`, while the shared inline field variant owns only density and spinner treatment. Radio supplies its field palette and disabled opacity through the `--gev-field-*` variables, retaining compact typography and -arrow space locally. Cyber supplies shared-field palette variables explicitly; -its legacy native-field palette rules exclude `.gev-field`. These ownership -boundaries preserve the current Tactical/Cyber appearance and native behavior. +arrow space locally. These ownership boundaries preserve the current Tactical +appearance and native behavior. ## Ordinary status badges @@ -4695,10 +4696,8 @@ isCurrent })` gates BOTH halves of the map-stack switch, which is its only > each wing shows only its icon. `CommandDockView.vue` still gives the toggles > their "Expand/Collapse …" `aria-label` and `title` (`trayWords`), so the > browser tooltip is the only visible name on hover. -> The Cyber HUD layout is excluded: it sets `--dock-side-compact` to -> 9–9.75rem, which fits its labels. The former ≤620px ellipsis clip is gone: -> the phone shell takes over at 720px, so it never applied to a visible -> dock. +> The former ≤620px ellipsis clip is gone: the phone shell takes over at +> 720px, so it never applied to a visible dock. > - **LOCATION mini-status is data-only today (2026-08-20):** the collapsed > readout now follows a free-text geocode search as well as preset pills > (`src/locationStatus.js` owns the copy for both), and every other camera @@ -4938,7 +4937,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with > corridor). Its minimal Display popover exposes Intel HUD, > Detection, Parameters, and 3D aircraft. During Cockpit, those existing > standard Display controls move into the Cockpit popover and retain their normal -> nested interaction: HUD plus Tactical/Minimal/Cyber layout, Detection plus +> nested interaction: HUD plus Tactical/Minimal layout and Sonar, Detection plus > Density/Allocation/Fade/Outside tuning, and 3D plus Proximity/All mode. The > same nodes and state return to the map Display on exit, so Cockpit does not > maintain a second control state. **Detection is owned by the CONTACTS @@ -7331,7 +7330,7 @@ silently demoting every later lookup for the session. - If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. With no tracked aircraft, an AIS vessel already selected (the vessel layer's `getSelectedInfo()`) becomes the subject, at activation and again when a deferred dependency settles, exactly as a vessel selected while `CONTACTS` is on; no nearest flight is picked and the camera is not moved. - `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width. - The Context header holds only its title and collapse control. It no longer carries a Radio shortcut or a compact Radio player: Radio is the `RADIO` section inside the panel, with its own disclosure and the single `ENABLE` power control. Cockpit keeps its own compact Radio utility. -- Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. Outside Cyber, the two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour. Cyber keeps its separately framed mode buttons, its red panel titles, and in layout-focus a framed, centred standby card over its radar art. +- Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. The two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour. - The expanded desktop header omits the redundant `ON` label; the active mode button carries state. Expanded Contact results also omit the duplicate `GLOBAL CONTEXT` / `CONTEXT ONLY` status row and begin with the selected subject and its 250 km scope. Global Context does not fabricate a selected-entity model preview: the provisional hand-authored aircraft wireframe was removed because it was not geometry extracted from the selected entity's actual asset. - Dependency ownership is reversible: disabling Global Context releases only dependencies it enabled, while user-enabled layers remain on. This also removes the Military-layer suppression handoff when Global Context owned Military, allowing an already-enabled civilian Flights layer to resume its normal mixed rendering. If OpenSky is unavailable and has no last-good cache, Flights requests a capped 250 nm adsb.lol point snapshot around the current view anchor and labels that provenance explicitly; it never relabels military-feed rows as civilian data. If both inputs fail, Flights remains `UNKNOWN`. - Space Missions is replay-isolated: Rocket Launches and Satellites are the only Data Layers permitted while the mode is active. Direct UI and voice entry capture the same pre-entry snapshot; internal dependency and restoration enables do not create a user-owned Context session. Entry waits for incompatible layers to shut down, direct incompatible enables are blocked before lifecycle work, and the entry gate remains active through the complete Rocket Launches enable. That enable includes the first mission-index load: an HTTP error, timeout, network failure or malformed payload before any index has loaded fails the enable, so Context rolls back to the pre-entry layers instead of committing an empty, isolating mode; the camera returns to its pre-entry view unless navigation took it, and a toast says the mission index could not load. A valid empty index still enters, and a refresh failure after an index loaded keeps its records and the mode. Exiting cancels the layer's own camera flights but never one navigation started. A newer same-target ON request takes ownership of the pending entry without releasing its isolation snapshot, including when it arrives while the prior request is awaiting the adoption guard. A caller abort, resource cancellation, newer OFF, or layer teardown waits for exact manager settlement and restores that snapshot without resurrecting Rocket Launches. If an abort lands after only part of a restore settles, Context completes the same exact target without the stale caller signal and then replays newer explicit layer intent. Dedicated Voice Context cancellation reports a stable cancelled result plus the current Context state; generic layer visibility additionally exposes manager phase, reason, successor, and lifecycle details. Once an exact voice visibility intent commits, a newer voice turn cannot relabel it as cancelled while Context settlement completes; pre-commit aborts remain cancellable and final lifecycle mismatches remain failures. Clear Selected Layers reserves its complete captured OFF set before sequential teardown; a newer absolute request of any origin supersedes only its layer reservation and remains authoritative. A rejected layer teardown retains the truthful enabled state, rolls already-stopped siblings back to the captured pre-entry set, and aborts replay; rapid exit/re-entry serializes the full Satellite enabled-state and parameter restore before a new snapshot is taken. Contacts remains additive and restores user-enabled layers normally. @@ -7339,7 +7338,7 @@ silently demoting every later lookup for the session. - On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification. - A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated. - Contacts rows and the Cockpit Contact counts name each cohort's provider: the source of the last snapshot, marked `FALLBACK` or `STALE` as its layer row would be. A poll in flight keeps the mark, where the layer row shows `LOADING`. A flight snapshot from the adsb.lol regional fallback reads `adsb.lol · FALLBACK`, not `OpenSky`. -- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline whose outer 1 px, half a pixel on each side, is a dark halo around a 3 px Context-blue core, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is one outlined line in an unpickable draw-port line set (`src/layers/awareness/rangeRing.js`), so a click or tap on its edge reaches the contact underneath; the halo is the line's own outline, so the translucent core and halo never darken where they meet; it moves when the subject moves. Three dim sonar pulses (3 px with a dark edge half a pixel wide on each side, same colours, at most 60% opacity), each an outlined line in the same set, grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius: one unpickable flat ellipse 2.5 km up with 270 km semi-axes, filled with a 256-pixel canvas painted with the band (two canvases in turn, each under a new key). The ellipse stands until the subject has moved 20 km from where it was built, the canvas keeping the band concentric with the subject meanwhile, and not at all while the pulses rest. Fronts and band are fixed in the world, so they step every 80 ms however many frames are drawn and look the same whether the camera moves or not; crossing the 2.5 km rim height shows or hides them at once. While the camera is below the band's 2.5 km height, where it would sweep across the sky, the pulses rest: the band and fronts are hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the band and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one step 80 ms later (the Cyber sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`) whose changes ask for the frame that draws them, so a parked view repaints at about 12.5 fps, one frame a step, and never beats the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or on a renderer without frame hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. +- The window's edge is drawn on the globe as a 250 km range ring: a 4 px polyline whose outer 1 px, half a pixel on each side, is a dark halo around a 3 px Context-blue core, 2.5 km above the ellipsoid (`AWARENESS_RANGE_RING_STYLE` in `src/layers/awareness/policy.js`). The halo keeps it legible over bright desert and snow, dark ocean and forest, and under the FLIR, NVG and CRT styles, where the earlier 1 px ellipse outline disappeared. It is one outlined line in an unpickable draw-port line set (`src/layers/awareness/rangeRing.js`), so a click or tap on its edge reaches the contact underneath; the halo is the line's own outline, so the translucent core and halo never darken where they meet; it moves when the subject moves. Three dim sonar pulses (3 px with a dark edge half a pixel wide on each side, same colours, at most 60% opacity), each an outlined line in the same set, grow slowly from the subject at constant speed, one every 3 s and each taking 9 s, and arrive at the ring at about a third of that. Behind each pulse a radial gradient in the same blue fades inward over 35% of the radius: one unpickable flat ellipse 2.5 km up with 270 km semi-axes, filled with a 256-pixel canvas painted with the band (two canvases in turn, each under a new key). The ellipse stands until the subject has moved 20 km from where it was built, the canvas keeping the band concentric with the subject meanwhile, and not at all while the pulses rest. Fronts and band are fixed in the world, so they step every 80 ms however many frames are drawn and look the same whether the camera moves or not; crossing the 2.5 km rim height shows or hides them at once. While the camera is below the band's 2.5 km height, where it would sweep across the sky, the pulses rest: the band and fronts are hidden and there is no ring flash, no echo and no frame request. Terrain or 3D tiles higher than 2.5 km (the Alps, Andes, Rockies) still cut through the band and the ring when seen from above, as the ring alone already did; the height check uses the camera's height above the ellipsoid, not above the ground. While pulses run, the ring dims to 40% and flashes to full strength as each pulse reaches it, fading over 1.8 s. As a pulse front crosses a flight, military aircraft or AIS vessel, the detection overlay draws a second bracket around that contact's own bracket, in the pulse blue on the default detection style and in the style's own line colour under NVG, FLIR and CRT, which spreads outward as it fades over 1.4 s (`AWARENESS_RANGE_ECHO`, read through `src/awarenessEcho.js`; no layer's icon is restyled, and mapped installations have no detection bracket). Pulses are born 5 km out, so the subject itself and anything nearer never echo. Pulses run for 9 s (three ring flashes) after a selection or a camera move, fading in and out over 1.2 s, then rest: the ring stays on screen at full strength, the pulses, gradient and echoes are hidden, and nothing asks for frames, so a parked Contacts view is quiet again. Only a camera move within 1.5 s of the user handling the map (pointer, wheel or touch on the Cesium canvas, which covers a drag's inertia, and a drag or touch begun there keeps counting until its last finger or button lifts, even outside the canvas, unless the window loses focus or the page is hidden first; keys typed elsewhere do not count, nor does input while Cesium's camera controls are off, as in the cockpit view, and a gesture still pending when the cockpit or another owner takes the camera is dropped) wakes them; a moving subject and the app's own camera moves (a tracked aircraft, the cockpit view, an orbit, a fly-to) do not, since they move on every refresh. While they run they never hold continuous rendering: each drawn frame arms one step 80 ms later (the sonar cadence, `CYBER_SONAR_RENDER_INTERVAL_MS`) whose changes ask for the frame that draws them, so a parked view repaints at about 12.5 fps, one frame a step, and never beats the detection lane's 80 ms gate. Under `prefers-reduced-motion`, or on a renderer without frame hooks, there are no pulses or echoes and the ring stays on screen; changing the preference mid-session rebuilds the ring. The ring follows a moving subject once it has moved 250 m. - For a selected live aircraft or vessel, the context window refreshes from the existing tracker/feed position every 750 ms, so nearest distances and cohort counts follow the subject without introducing a duplicate poll loop. - Aircraft cohort membership uses every locally loaded, selectable contact inside the 250 km window, including a plane hidden only by horizon culling or because its 3D model owns the visual. Counts and navigation therefore do not change with the current camera angle or billboard/model handoff. - Nearby examples in the context panel are focus controls: they use their owning layer's existing selection/tracking path, then frame that contact. Static-installation distances use ellipsoidal surface distance so the count matches the ground-projected context disk. @@ -7826,8 +7825,8 @@ focuses search from outside a text field, as do Cmd+K on macOS and Ctrl+K elsewhere (Ctrl+K on macOS is left alone); none of them takes focus from an open modal dialog or from inside a dialog such as the guide. While voice is on, the suggestions give way to the waveform but an error stays shown. The map credits stay on the -Power Up row in the ordinary desktop layout, and the two lower tactical HUD -readouts start at the same height. +Power Up row in the ordinary desktop layout, and the Tactical bottom-right +readout sits 8px above that row. Pending owner decision: in the desktop Omnibar layout (`src/ui/styles/omnibar-dock.css`) the legacy Location and Visual trays of @@ -8501,7 +8500,7 @@ apply to `public/` assets or built-preview serving. - Panel POSITION keys are versioned `v8` (`godsEyeView.v8.panelPos.`); collapsed-state keys remain `v6`. The one-time position reset clears stale DISPLAY placements that could overlap the Context rail. - Map Source lives in the bottom Visual Presets tray. The left accordion contains no MAP STACK panel, and the `k` panel token that addressed it is gone from the share registry, so legacy `ui=k...` state takes the ordinary unknown-token skip. - A dock popover (Visual Presets, Location) auto-dismisses on mouse-away unless pinned. Focus inside the tray defers that dismissal only when the browser reports `:focus-visible` — keyboard focus and typed-into fields hold the tray open; a mouse-clicked tile does not, because Chromium focuses a `