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.
This commit is contained in:
manjunath22466 committed 2026-11-18 19:19:41 +05:30
1 parent fde5f95b45
commit 7312280817
33 files changed
+702 -76

No files matched your search

+22 -10
View File
@@ -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
+46 -2
View File
@@ -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),
+32
View File
@@ -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);
});
+4
View File
@@ -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,
});
+53
View File
@@ -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;
+86
View File
@@ -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');
});
+18 -3
View File
@@ -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);
+23 -6
View File
@@ -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<string, (click: object) => boolean>}
*/
const _declines = new Map();
/** @type {WeakMap<object, Map<string, [string, boolean][]>>} */
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;
}
+2
View File
@@ -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": "بيانات حطام السفن غير متاحة",
+2
View File
@@ -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",
+2
View File
@@ -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",
+2
View File
@@ -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",
+2
View File
@@ -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": "מ-",
+2
View File
@@ -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",
+2
View File
@@ -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": "難破船データを利用できません",
+2
View File
@@ -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",
+2
View File
@@ -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": "Данные о кораблекрушениях недоступны",
+2
View File
@@ -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",
+2
View File
@@ -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": "Дані про затонулі судна недоступні",
+2
View File
@@ -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": "沉船数据不可用",
+2
View File
@@ -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": "沉船數據不可用",
+21 -13
View File
@@ -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-<cameraId>-<role>` 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;
+35 -4
View File
@@ -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');
});
+44 -7
View File
@@ -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;
}
+52 -12
View File
@@ -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),
};
}
+9 -4
View File
@@ -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({
+28 -3
View File
@@ -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', () => {
+133 -6
View File
@@ -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();
});
+6
View File
@@ -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);
+6
View File
@@ -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
+23 -2
View File
@@ -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 }));
});
+12 -4
View File
@@ -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',
+23
View File
@@ -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(), [