mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-19 09:42:21 +00:00
Merge pull request #1781 from manjunath22466/fix/earthquake-click-details
fix(earthquakes): make quakes clickable, with card click arbitration
This commit is contained in:
104 files changed
+5764
-436
No files matched your search
@@ -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. A
|
||||
drag ending on a quake does nothing. The card or label painted on top now
|
||||
takes a click in every layer: what is drawn under it neither acts nor loses
|
||||
its selection, and the Context panel names nothing there
|
||||
(Manjunath, @manjunath22466, #1781).
|
||||
@@ -2062,6 +2062,51 @@ 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 (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, 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.
|
||||
A press that travels past the tracking click limit is a drag, not a pick: the
|
||||
quake handler ignores it, and opening the source or clearing the selection
|
||||
also needs a short press (`src/data/trackingClickGesture.js`).
|
||||
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 near-miss taps and deselection work over a quake as before,
|
||||
and a disc yields to another layer's registered pick (an aircraft) under it.
|
||||
The card or label painted on top takes the click. The world-overlay host hands
|
||||
its hit test to the pick registry (`setClickCardHitTest`), and every click
|
||||
handler reads the topmost interactive card or label at the click through
|
||||
`clickCard(click)`, once per click, so all of them agree in any listener order
|
||||
(`src/data/pickRegistry.js`). A layer whose own card or label is on top acts
|
||||
on it, whatever is drawn under it: an aircraft, a vessel, a fire, a camera, a
|
||||
trail, a route. A layer under another layer's card or label
|
||||
(`isUnderOtherCard`) does nothing: it neither acts on its item there nor
|
||||
treats the click as empty space, so a tracked aircraft stays tracked and a
|
||||
selection stays selected. Context (`src/ui/entityContextBridge.js`) names
|
||||
nothing under a card. With no card on top, the scene rules are unchanged.
|
||||
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`). A click on the map under another layer's
|
||||
card opens no Street Level ground image. The Bhote Koshi trigger-record
|
||||
callout (`src/data/bhoteKoshiLocator.js`) opens its source on a click, as its
|
||||
keyboard action does, and ignores a drag; its evidence cards act only when
|
||||
they are the card on top.
|
||||
|
||||
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,
|
||||
@@ -8799,6 +8844,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
|
||||
|
||||
@@ -441,6 +441,12 @@
|
||||
"src/layers/earthquakes/model.js",
|
||||
"src/layers/earthquakes/source.js",
|
||||
"src/layers/earthquakes/ownership.test.mjs",
|
||||
"src/layers/earthquakes/selection.test.mjs",
|
||||
"src/layers/submarineCables/interaction.test.mjs",
|
||||
"src/ui/entityContextBridge.test.mjs",
|
||||
"src/layers/launches/clickYield.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",
|
||||
@@ -1599,5 +1605,8 @@
|
||||
"src/ui/omnibarRows.test.mjs",
|
||||
"src/ui/styles/omnibar-dock.css",
|
||||
"src/ui/styles/guide.css",
|
||||
"src/ui/commandDock.test.mjs"
|
||||
"src/ui/commandDock.test.mjs",
|
||||
"src/layers/bikeshare/selection.test.mjs",
|
||||
"src/layers/satellites/interaction.test.mjs",
|
||||
"src/layers/alpr/presentation.test.mjs"
|
||||
]
|
||||
@@ -2590,7 +2590,8 @@
|
||||
"src/layers/earthquakes/model.js",
|
||||
"src/layers/earthquakes/source.js",
|
||||
"src/layers/earthquakes/records.js",
|
||||
"src/time/worldClock.js"
|
||||
"src/time/worldClock.js",
|
||||
"src/data/trackingClickGesture.js"
|
||||
],
|
||||
"external": ["cesium"]
|
||||
},
|
||||
@@ -4189,6 +4190,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",
|
||||
@@ -5604,6 +5606,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",
|
||||
|
||||
@@ -1637,19 +1637,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);
|
||||
@@ -1695,10 +1724,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);
|
||||
@@ -1712,10 +1739,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));
|
||||
@@ -3681,6 +3709,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
|
||||
@@ -3770,6 +3801,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,
|
||||
@@ -3908,10 +3940,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');
|
||||
@@ -3924,13 +3954,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
|
||||
@@ -3980,7 +4010,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,
|
||||
@@ -4015,23 +4045,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)
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
/** 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
|
||||
* 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
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
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, 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.
|
||||
*/
|
||||
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,
|
||||
// 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),
|
||||
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();
|
||||
// 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() {
|
||||
stopFrames();
|
||||
if (!target) return;
|
||||
target = null;
|
||||
lane?.setActive(false);
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
hide();
|
||||
lane?.unregister();
|
||||
lane = null;
|
||||
}
|
||||
|
||||
return { show, hide, dispose };
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
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();
|
||||
});
|
||||
|
||||
// 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);
|
||||
});
|
||||
@@ -1,6 +1,49 @@
|
||||
import { createEarthquakesLayer } from '../../layers/earthquakes/index.js';
|
||||
import { overlayHost } from './overlayHost.js';
|
||||
/** Wire earthquake observations to the application overlay host. */
|
||||
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 { heightsOf } from '../../queries/heights.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,
|
||||
input: (viewer) => inputFor(viewer),
|
||||
picking,
|
||||
context,
|
||||
pointer: { isPointerFree },
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
|
||||
import { overlayHost } from './overlayHost.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
/** Wire cable source geometry to the application overlay host. */
|
||||
export function createApplicationCables(options) {
|
||||
return createSubmarineCableLayer({
|
||||
overlayHost,
|
||||
picking,
|
||||
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
|
||||
...options,
|
||||
});
|
||||
|
||||
@@ -403,10 +403,11 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
|
||||
'vessel click',
|
||||
);
|
||||
ordered(vesselClick, [
|
||||
'clickCard?.(event)',
|
||||
'selectAndFocusVessel(carded)',
|
||||
"isOwnedByOtherLayer('ais-live-vessels', pickedId)",
|
||||
'_vesselOverlayHost.hitTest?.(',
|
||||
'selectAndFocusVessel(record)',
|
||||
], 'vessel sibling ownership');
|
||||
], 'vessel card on top, then sibling ownership');
|
||||
const vesselFocus = body(
|
||||
vessels,
|
||||
/function selectAndFocusVessel\(record\) \{([\s\S]*?)\n \}/,
|
||||
@@ -419,8 +420,9 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
|
||||
'fire click',
|
||||
);
|
||||
ordered(fireClick, [
|
||||
'isOwnedByOtherLayer(id, pickedId)',
|
||||
'overlayHost.hitTest?.(',
|
||||
'clickCard?.(event)',
|
||||
'selectAndFocusFire(carded)',
|
||||
], 'fire sibling ownership');
|
||||
'isOwnedByOtherLayer(id, pickedId)',
|
||||
'clearFireSelection()',
|
||||
], 'fire card on top, then sibling ownership');
|
||||
});
|
||||
@@ -32,7 +32,12 @@ import aisLiveVesselsLayer from './aisLiveVessels.js';
|
||||
import { registerEntityContext, selectEntityContext } from './contextStore.js';
|
||||
import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js';
|
||||
import { ensureGeoidReady, geoidHeight } from './geoid.js';
|
||||
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
|
||||
import {
|
||||
isUnderOtherCard,
|
||||
registerPickOwner,
|
||||
setClickCardHitTest,
|
||||
unregisterPickOwner,
|
||||
} from './pickRegistry.js';
|
||||
import { applyVesselOverlayPolicy } from './vesselLabels.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import { layerFeedState } from './manager.js';
|
||||
@@ -490,7 +495,7 @@ test('first accepted position ends grace and warm data survives later open silen
|
||||
const clock = makeFakeAisRuntime(7000);
|
||||
const record = makeRecord();
|
||||
_setAisRuntimeForTest(clock.runtime);
|
||||
_setVesselOverlayHostForTest({
|
||||
useVesselHost({
|
||||
setEntries() {},
|
||||
setVisible() {},
|
||||
clearSource() {},
|
||||
@@ -540,7 +545,7 @@ test('first accepted position ends grace and warm data survives later open silen
|
||||
assert.equal(feed.error, 'awaiting usable AIS positions…');
|
||||
} finally {
|
||||
_setVesselStateForTest({ enabled: false });
|
||||
_setVesselOverlayHostForTest();
|
||||
useVesselHost();
|
||||
_setAisRuntimeForTest();
|
||||
}
|
||||
});
|
||||
@@ -1012,7 +1017,12 @@ function makeCesiumEvent() {
|
||||
};
|
||||
}
|
||||
|
||||
function installWireHarness(picked, stateOverrides = {}) {
|
||||
function installWireHarness(
|
||||
picked,
|
||||
stateOverrides = {},
|
||||
sceneExtras = {},
|
||||
firstClick = null,
|
||||
) {
|
||||
const hadWindow = Object.hasOwn(globalThis, 'window');
|
||||
const hadDocument = Object.hasOwn(globalThis, 'document');
|
||||
const priorWindow = globalThis.window;
|
||||
@@ -1038,9 +1048,11 @@ function installWireHarness(picked, stateOverrides = {}) {
|
||||
},
|
||||
};
|
||||
const viewer = {
|
||||
scene: { pick: () => picked },
|
||||
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();
|
||||
@@ -1666,7 +1678,7 @@ test('vessel host publication preserves the shipped grid winner and separation s
|
||||
},
|
||||
},
|
||||
});
|
||||
_setVesselOverlayHostForTest({
|
||||
useVesselHost({
|
||||
setEntries(sourceId, entries, options) {
|
||||
publications.push({ sourceId, entries, options });
|
||||
},
|
||||
@@ -1690,7 +1702,7 @@ test('vessel host publication preserves the shipped grid winner and separation s
|
||||
} finally {
|
||||
unbind();
|
||||
_setVesselStateForTest({ enabled: false });
|
||||
_setVesselOverlayHostForTest();
|
||||
useVesselHost();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1717,7 +1729,7 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
|
||||
globalThis.window.addEventListener('gev:world-request-focus', (event) => {
|
||||
focusRequests.push(event.detail);
|
||||
});
|
||||
_setVesselOverlayHostForTest(host);
|
||||
useVesselHost(host);
|
||||
_setVesselStateForTest({
|
||||
viewer: {
|
||||
get canvas() {
|
||||
@@ -1766,7 +1778,7 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
|
||||
);
|
||||
} finally {
|
||||
_setVesselStateForTest({ enabled: false });
|
||||
_setVesselOverlayHostForTest();
|
||||
useVesselHost();
|
||||
if (hadWindow) globalThis.window = priorWindow;
|
||||
else delete globalThis.window;
|
||||
globalThis.document = priorDocument;
|
||||
@@ -1872,17 +1884,31 @@ test('vessel interaction wire: a vessel with an id and no MMSI is selected by cl
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Hand the vessel layer an overlay host, and answer the pick registry's
|
||||
* card-on-top question from the same host, as the application does.
|
||||
*/
|
||||
function useVesselHost(host) {
|
||||
_setVesselOverlayHostForTest(host);
|
||||
setClickCardHitTest(host ? (x, y) => host.hitTest(x, y) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overlay-host recorder whose hitTest answers with one card id. The real host
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1898,9 +1924,7 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s
|
||||
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
|
||||
requests.push(event.detail),
|
||||
);
|
||||
_setVesselOverlayHostForTest(
|
||||
hostWithCardHit(`vessel:${harness.record.mmsi}`),
|
||||
);
|
||||
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(
|
||||
@@ -1911,7 +1935,7 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s
|
||||
assert.equal(requests[0].kind, 'vessel');
|
||||
assert.equal(requests[0].id, harness.record.mmsi);
|
||||
} finally {
|
||||
_setVesselOverlayHostForTest(null);
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -1926,9 +1950,7 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact
|
||||
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
|
||||
requests.push(event.detail),
|
||||
);
|
||||
_setVesselOverlayHostForTest(
|
||||
hostWithCardHit(`vessel:${harness.record.mmsi}`),
|
||||
);
|
||||
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(
|
||||
@@ -1939,11 +1961,36 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact
|
||||
assert.equal(requests[0].id, harness.record.mmsi);
|
||||
assert.equal(harness.trail.clearCalls, 0);
|
||||
} finally {
|
||||
_setVesselOverlayHostForTest(null);
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
// Another layer's card on top takes the click from the vessel card under it
|
||||
// and from a vessel icon under it alike.
|
||||
test('vessel interaction wire: a covered card and a covered vessel pick both yield', () => {
|
||||
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),
|
||||
);
|
||||
useVesselHost(
|
||||
hostWithCardHit(`vessel:${harness.record.mmsi}`, {
|
||||
sourceId: 'earthquakes', entryId: 'quake:cover',
|
||||
}),
|
||||
);
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(requests.length, 0, `own pick: ${ownPick}`);
|
||||
assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi);
|
||||
} finally {
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('vessel interaction wire: an unknown card id preserves selection and never flies', () => {
|
||||
const harness = installWireHarness({
|
||||
primitive: {},
|
||||
@@ -1955,7 +2002,7 @@ test('vessel interaction wire: an unknown card id preserves selection and never
|
||||
requests.push(event.detail),
|
||||
);
|
||||
// An evicted vessel's card id resolves to no live record.
|
||||
_setVesselOverlayHostForTest(hostWithCardHit('vessel:999999999'));
|
||||
useVesselHost(hostWithCardHit('vessel:999999999'));
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(
|
||||
@@ -1964,37 +2011,135 @@ test('vessel interaction wire: an unknown card id preserves selection and never
|
||||
);
|
||||
assert.equal(requests.length, 0);
|
||||
} finally {
|
||||
_setVesselOverlayHostForTest(null);
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('vessel interaction wire: a sibling-owned pick wins without selection mutation', () => {
|
||||
// Another layer is already acting on this click; two camera commands is the
|
||||
// worse failure, so the card is not consulted.
|
||||
test('vessel interaction wire: the vessel card on top wins over a sibling-owned pick', () => {
|
||||
// The card painted on top takes the click; the sibling (an aircraft)
|
||||
// stands aside under it, so there is one camera command, not two.
|
||||
registerPickOwner('flights', (pickedId) => pickedId === 'a1b2c3');
|
||||
const harness = installWireHarness({ id: 'a1b2c3' });
|
||||
const requests = [];
|
||||
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
|
||||
requests.push(event.detail),
|
||||
);
|
||||
_setVesselOverlayHostForTest(
|
||||
hostWithCardHit(`vessel:${harness.record.mmsi}`),
|
||||
);
|
||||
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(
|
||||
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
|
||||
harness.record.mmsi,
|
||||
);
|
||||
assert.equal(requests.length, 0);
|
||||
assert.equal(requests.length, 1);
|
||||
} finally {
|
||||
_setVesselOverlayHostForTest(null);
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
unregisterPickOwner('flights');
|
||||
}
|
||||
});
|
||||
|
||||
// The aircraft layer runs first. Under the vessel's card it stands aside, so
|
||||
// the card takes the click: one action.
|
||||
test('vessel interaction wire: a card over an aircraft takes the click; the aircraft does not track', (t) => {
|
||||
let tracked = null;
|
||||
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9');
|
||||
t.after(() => unregisterPickOwner('test-planes'));
|
||||
const harness = installWireHarness(
|
||||
{ id: 'plane:9' },
|
||||
{ selectedRecord: null },
|
||||
{},
|
||||
(event) => {
|
||||
if (isUnderOtherCard(event)) return;
|
||||
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
|
||||
},
|
||||
);
|
||||
const requests = [];
|
||||
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
|
||||
requests.push(event.detail),
|
||||
);
|
||||
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(tracked, null, 'the aircraft does not track');
|
||||
assert.equal(requests.length, 1, 'the vessel card acts');
|
||||
assert.equal(
|
||||
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
|
||||
harness.record.mmsi,
|
||||
);
|
||||
} finally {
|
||||
useVesselHost(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', () => {
|
||||
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),
|
||||
);
|
||||
useVesselHost(
|
||||
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 {
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// A coarse tap on the vessel's card over a fire, nearby or exact: the card on
|
||||
// top keeps the tap.
|
||||
test('vessel interaction wire: the card keeps a tap over a nearby or exact fire', (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),
|
||||
);
|
||||
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(requests.length, 1, `exact fire: ${exact}`);
|
||||
assert.equal(
|
||||
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
|
||||
harness.record.mmsi,
|
||||
);
|
||||
} finally {
|
||||
useVesselHost(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';
|
||||
@@ -2020,7 +2165,7 @@ for (const card of ['live', 'stale', 'absent', 'covered']) {
|
||||
);
|
||||
return { sourceId: 'cctv', entryId: 'vessel:999999999' };
|
||||
};
|
||||
_setVesselOverlayHostForTest(host);
|
||||
useVesselHost(host);
|
||||
try {
|
||||
harness.handler.click({ position: { x: 10, y: 20 } });
|
||||
assert.equal(
|
||||
@@ -2029,7 +2174,7 @@ for (const card of ['live', 'stale', 'absent', 'covered']) {
|
||||
);
|
||||
assert.equal(requests.length, card === 'live' ? 1 : 0);
|
||||
} finally {
|
||||
_setVesselOverlayHostForTest(null);
|
||||
useVesselHost(null);
|
||||
harness.cleanup();
|
||||
unregisterPickOwner('weather-cyclones');
|
||||
}
|
||||
|
||||
@@ -2959,11 +2959,12 @@ export function createBhoteKoshiEventLayer({
|
||||
: Number.isFinite(clientY) && bounds
|
||||
? clientY - bounds.top
|
||||
: Number.NaN;
|
||||
const hit = overlayHost.hitTest?.(x, y, {
|
||||
sourceId: BHOTE_KOSHI_OVERLAY_SOURCE_ID,
|
||||
filter: (entry) => String(entry?.id || '').startsWith('evidence-card-'),
|
||||
});
|
||||
if (typeof hit?.entry?.activate !== 'function') return;
|
||||
// Only the card painted on top acts: an evidence card covered by
|
||||
// another layer's card or label leaves the click to that card.
|
||||
const hit = overlayHost.hitTest?.(x, y);
|
||||
if (hit?.sourceId !== BHOTE_KOSHI_OVERLAY_SOURCE_ID) return;
|
||||
if (!String(hit.entry?.id || '').startsWith('evidence-card-')) return;
|
||||
if (typeof hit.entry.activate !== 'function') return;
|
||||
hit.entry.activate();
|
||||
}
|
||||
|
||||
|
||||
@@ -2114,6 +2114,7 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
|
||||
};
|
||||
const viewer = eventViewer();
|
||||
let activeCard = null;
|
||||
let coveredBy = null;
|
||||
const layer = createBhoteKoshiEventLayer({
|
||||
eventLoader: async () => event,
|
||||
imagerySpecFactory: async (url) => ({ url }),
|
||||
@@ -2131,9 +2132,11 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
|
||||
},
|
||||
setVisible() {},
|
||||
clearSource() {},
|
||||
// As the host does: unfiltered, the topmost entry.
|
||||
hitTest(_x, _y, options) {
|
||||
if (coveredBy && !options?.sourceId) return coveredBy;
|
||||
if (!activeCard || options?.filter?.(activeCard) === false) return null;
|
||||
return { entry: activeCard };
|
||||
return { sourceId: 'bhote-koshi-witnesses', entry: activeCard };
|
||||
},
|
||||
},
|
||||
renderHost: { request() {}, hold() {}, release() {} },
|
||||
@@ -2160,6 +2163,11 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
|
||||
} finally {
|
||||
releasePointer(lease);
|
||||
}
|
||||
// Another layer's card painted over the evidence card takes the click.
|
||||
coveredBy = { sourceId: 'earthquake-card', entryId: 'earthquake-card:q' };
|
||||
viewer._test.canvas.dispatch('click', { offsetX: 640, offsetY: 420 });
|
||||
assert.equal(opened.length, 0, 'a covered evidence card does not open');
|
||||
coveredBy = null;
|
||||
viewer._test.canvas.dispatch('click', { offsetX: 640, offsetY: 420 });
|
||||
assert.deepEqual(opened, [[
|
||||
event.evidenceSpine[1].media.sourceUrl,
|
||||
|
||||
@@ -2,6 +2,9 @@ import {
|
||||
clearOverlaySource,
|
||||
setOverlayEntries,
|
||||
} from '../overlays/worldOverlay.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { clickCard } 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 +282,11 @@ export function createBhoteKoshiLocatorLayer({
|
||||
cancelFrame = (handle) => cancelAnimationFrame(handle),
|
||||
scheduleDelay = (callback, delayMs) => setTimeout(callback, delayMs),
|
||||
cancelDelay = (handle) => clearTimeout(handle),
|
||||
input = inputFor,
|
||||
} = {}) {
|
||||
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 +1113,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 +1148,34 @@ 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, on top, takes the
|
||||
* click over whatever is drawn under it.
|
||||
*/
|
||||
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;
|
||||
// The card painted on top, read once per click so every layer agrees.
|
||||
const top = clickCard(event);
|
||||
if (top?.sourceId !== BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID) 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;
|
||||
|
||||
@@ -11,6 +11,11 @@ import {
|
||||
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
registerPickOwner,
|
||||
setClickCardHitTest,
|
||||
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 +1054,74 @@ 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;
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
setClickCardHitTest(() => 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');
|
||||
// On top, it takes the click over an aircraft or a camera under it, exact
|
||||
// or a touch contact: those layers stand aside under a card.
|
||||
registerPickOwner('test-planes', (id) => id === 'plane:1');
|
||||
try {
|
||||
const plane = { set: 'planes:1', id: 'plane:1' };
|
||||
const cam = { set: 'cams:1', id: 'cam:1' };
|
||||
click({ topHit: plane, hit: plane });
|
||||
click({ topHit: null, hit: plane });
|
||||
click({ topHit: cam, hit: cam });
|
||||
assert.equal(activated.length, 4, 'the callout on top acts each time');
|
||||
} finally {
|
||||
unregisterPickOwner('test-planes');
|
||||
setClickCardHitTest(null);
|
||||
}
|
||||
await layer.disable();
|
||||
assert.equal(onClick, null, 'disable removes the click handler');
|
||||
});
|
||||
+4
-11
@@ -1020,11 +1020,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
/_cctvOverlayHost\.hitTest/,
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
/sourceId: CCTV_OVERLAY_SOURCE_ID/,
|
||||
/clickCard\?\.\(event\)/,
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
@@ -1032,7 +1028,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
/activateCctvCameraFromWorldClick\(cardId, setActiveCamera\)/,
|
||||
/activateCctvCameraFromWorldClick\(\s*top\.entryId,/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
|
||||
@@ -28,6 +28,8 @@ import {
|
||||
createApplicationDirectionsLayer,
|
||||
} from './directions.js';
|
||||
import { GROUND_FLOOR_LIFT_M } from './groundFloor.js';
|
||||
import { isOwnedByOtherLayer, setClickCardHitTest } from './pickRegistry.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import { instructionFor } from './routeSteps.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
@@ -465,6 +467,65 @@ function ownershipFixture(t) {
|
||||
});
|
||||
}
|
||||
|
||||
// Directions owns its route, markers and steps while enabled: none of them
|
||||
// is empty space to other layers.
|
||||
test('enabled, directions owns its picks', (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);
|
||||
} finally {
|
||||
directionsLayer.disable(viewer);
|
||||
}
|
||||
assert.equal(isOwnedByOtherLayer('earthquakes', 'directions:route'), false);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: directions does not even
|
||||
// pick under another layer's card, so no step is selected or cleared there.
|
||||
test("another layer's card over directions keeps the click", (t) => {
|
||||
ownershipFixture(t);
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
canvas: { clientWidth: 100, clientHeight: 100 },
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
setClickCardHitTest(null);
|
||||
input.destroy();
|
||||
});
|
||||
directionsLayer.enable(viewer);
|
||||
try {
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
} finally {
|
||||
directionsLayer.disable(viewer);
|
||||
}
|
||||
});
|
||||
|
||||
test('placing an endpoint takes the pointer, and every exit path gives it back', (t) => {
|
||||
ownershipFixture(t);
|
||||
|
||||
|
||||
@@ -11,7 +11,12 @@ import {
|
||||
buildCellCard,
|
||||
} from './firmsHeatmap.js';
|
||||
import { fireDetectionKey } from './firmsLabels.js';
|
||||
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
|
||||
import {
|
||||
isUnderOtherCard,
|
||||
registerPickOwner,
|
||||
setClickCardHitTest,
|
||||
unregisterPickOwner,
|
||||
} from './pickRegistry.js';
|
||||
import { getSelectedEntityContext } from './contextStore.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { shownEntityLabel } from '../voice/speech.js';
|
||||
@@ -60,10 +65,13 @@ function harness({
|
||||
fires = [makeFire()],
|
||||
picked = null,
|
||||
cardHit = null,
|
||||
topCard = null,
|
||||
cameraPosition = null,
|
||||
withDataSource = false,
|
||||
withGlobe = false,
|
||||
feed = null,
|
||||
drilled = null,
|
||||
firstClick = null,
|
||||
} = {}) {
|
||||
const hadWindow = Object.hasOwn(globalThis, 'window');
|
||||
const priorWindow = globalThis.window;
|
||||
@@ -79,16 +87,24 @@ function harness({
|
||||
};
|
||||
|
||||
const published = [];
|
||||
const overlayHost = {
|
||||
setEntries: (sourceId, entries) => published.push(...entries),
|
||||
setVisible() {},
|
||||
clearSource() {},
|
||||
hitTest: (_x, _y, { sourceId } = {}) =>
|
||||
!sourceId && topCard
|
||||
? topCard
|
||||
: cardHit
|
||||
? { sourceId: 'firms', entryId: cardHit }
|
||||
: null,
|
||||
};
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
setClickCardHitTest((x, y) => overlayHost.hitTest(x, y));
|
||||
const layer = createFirmsHeatmapLayer({
|
||||
...(feed ? { feed } : {}),
|
||||
id: 'firms-test',
|
||||
name: 'Fires',
|
||||
overlayHost: {
|
||||
setEntries: (sourceId, entries) => published.push(...entries),
|
||||
setVisible() {},
|
||||
clearSource() {},
|
||||
hitTest: () => (cardHit ? { sourceId: 'firms', entryId: cardHit } : null),
|
||||
},
|
||||
overlayHost,
|
||||
});
|
||||
|
||||
const draw = fakeDrawPort();
|
||||
@@ -108,6 +124,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 },
|
||||
@@ -131,6 +148,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);
|
||||
@@ -155,7 +174,14 @@ function harness({
|
||||
(record) => record.kind === 'icons' && !record.disposed,
|
||||
),
|
||||
click: () => input.click({ x: 400, y: 300 }),
|
||||
cover: (hit) => {
|
||||
topCard = hit;
|
||||
},
|
||||
setPicked: (next) => {
|
||||
picked = next;
|
||||
},
|
||||
cleanup() {
|
||||
setClickCardHitTest(null);
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection;
|
||||
if (hadWindow) globalThis.window = priorWindow;
|
||||
else delete globalThis.window;
|
||||
@@ -310,8 +336,16 @@ 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 {
|
||||
// Under another layer's card the sprite is that card's click.
|
||||
h.click();
|
||||
assert.equal(h.requests.length, 0, 'covered: the card takes it');
|
||||
h.cover(null);
|
||||
h.click();
|
||||
assert.equal(h.requests.length, 1);
|
||||
assert.equal(h.requests[0].kind, 'fire');
|
||||
@@ -357,6 +391,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', () => {
|
||||
@@ -388,9 +450,9 @@ test('a click on neither sprite nor card clears without moving the camera', () =
|
||||
}
|
||||
});
|
||||
|
||||
// Sibling layers surface heterogeneous pick shapes. Reading `picked.id`
|
||||
// directly recognized only bare strings, so an AIS sprite (or satellite, or
|
||||
// entity) under a fire card let BOTH layers issue a camera command.
|
||||
// Sibling layers surface heterogeneous pick shapes. Whatever is drawn under
|
||||
// it, the fire card painted on top takes the click (those layers stand aside
|
||||
// under another layer's card, so one click does one thing).
|
||||
const SIBLING_PICKS = [
|
||||
['flights', 'a1b2c3', { id: 'a1b2c3' }],
|
||||
['flights', 'a1b2c3', { primitive: { id: 'a1b2c3' } }],
|
||||
@@ -400,7 +462,7 @@ const SIBLING_PICKS = [
|
||||
];
|
||||
|
||||
for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
|
||||
test(`a ${layerId} pick shaped ${JSON.stringify(picked)} wins over a card hit`, () => {
|
||||
test(`a fire card wins over a ${layerId} pick shaped ${JSON.stringify(picked)}`, () => {
|
||||
const fire = makeFire();
|
||||
registerPickOwner(layerId, (pickedId) => pickedId === ownedId);
|
||||
const h = harness({
|
||||
@@ -410,11 +472,7 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.equal(
|
||||
h.requests.length,
|
||||
0,
|
||||
`the ${layerId} layer is already acting on this click`,
|
||||
);
|
||||
assert.equal(h.requests.length, 1, 'the card on top acts');
|
||||
} finally {
|
||||
h.cleanup();
|
||||
unregisterPickOwner(layerId);
|
||||
@@ -422,6 +480,135 @@ 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');
|
||||
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 card on top takes it; the aircraft layer stands aside.
|
||||
test('a fire card takes a tap over 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');
|
||||
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, 1, 'the card takes the tap');
|
||||
assert.ok(h.layer.getSelectedInfo());
|
||||
} 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');
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
// The aircraft layer runs first. Under the fire card painted over its plane
|
||||
// it stands aside, so the card takes the click: one action, in either order.
|
||||
test('a fire card over an aircraft takes the click; the aircraft does not track', (t) => {
|
||||
const fire = makeFire();
|
||||
let tracked = null;
|
||||
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9');
|
||||
t.after(() => unregisterPickOwner('test-planes'));
|
||||
const h = harness({
|
||||
fires: [fire],
|
||||
picked: { id: 'plane:9' },
|
||||
cardHit: `fire:${fireDetectionKey(fire)}`,
|
||||
firstClick: (event) => {
|
||||
if (isUnderOtherCard(event)) return;
|
||||
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.equal(tracked, null, 'the aircraft does not track');
|
||||
assert.equal(h.requests.length, 1, 'the fire card acts');
|
||||
assert.ok(h.layer.getSelectedInfo());
|
||||
} finally {
|
||||
h.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a stale card id resolves to nothing instead of an arbitrary fire', () => {
|
||||
const h = harness({
|
||||
picked: { primitive: {}, content: {}, featureId: 0 },
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js';
|
||||
import { createGeojsonPins } from './geojsonPins.js';
|
||||
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from './pickRegistry.js';
|
||||
import {
|
||||
selectInfraLod,
|
||||
applyInfraEvictionGrace,
|
||||
@@ -1114,6 +1115,9 @@ export function createLocalGeoJsonLayer(
|
||||
const input = inputFor(viewer);
|
||||
_clickSubscription = input.onClick((event) => {
|
||||
if (!_enabled || !_drawn) return;
|
||||
// Another layer's card or label on top takes the click: the
|
||||
// item under it neither acts nor reads as empty space.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
const hit = event.drawHit;
|
||||
if (!hit || !hit.set.startsWith(`${setPrefix}:`)) return;
|
||||
const part = _drawn.parts.get(hit.id);
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from './localGeojsonCore.js';
|
||||
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
|
||||
import { getContextStore } from './contextStore.js';
|
||||
import { setClickCardHitTest } from './pickRegistry.js';
|
||||
import { readEntityRecord } from './entityRecords.js';
|
||||
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
|
||||
const feature = (id, geometry, properties = { name: `Feature ${id}` }) => ({
|
||||
@@ -161,6 +162,24 @@ test('polygons fill the ground, lines drape, points stand on pins, all shown', a
|
||||
assert.equal(record?.label, 'Feature p');
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a feature under another
|
||||
// layer's card is not selected.
|
||||
test("another layer's card over a drawn part keeps the click", async (t) => {
|
||||
const env = await enabledLayer(t, [
|
||||
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
|
||||
]);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const fills = env.fake.set('fills');
|
||||
const at = { x: 5, y: 5 };
|
||||
env.click({ screenPosition: at, drawHit: { set: fills.spec.id, id: 'p' } });
|
||||
assert.equal(env.fake.flights.length, 0, 'covered: not selected');
|
||||
top = null;
|
||||
env.click({ screenPosition: at, drawHit: { set: fills.spec.id, id: 'p' } });
|
||||
assert.equal(env.fake.flights.length, 1);
|
||||
});
|
||||
|
||||
test('a click on a drawn part selects its feature and flies above it', async (t) => {
|
||||
const env = await enabledLayer(t, [
|
||||
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
|
||||
|
||||
@@ -145,3 +145,59 @@ export function pickContact(query, position, options = {}) {
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
/**
|
||||
* The world overlay's hit test: the topmost interactive card or label painted
|
||||
* at CSS-pixel coordinates, or null. Set by the overlay host while it runs.
|
||||
* @type {((x: number, y: number) => {sourceId: string, entryId: string}|null)|null}
|
||||
*/
|
||||
let _overlayHitTest = null;
|
||||
/** @type {WeakMap<object, {sourceId: string, entryId: string}|null>} */
|
||||
const clickCards = new WeakMap();
|
||||
|
||||
/**
|
||||
* Sets (or with null, clears) the hit test that names the card or label
|
||||
* painted at a click. The world-overlay host sets it while it runs.
|
||||
* @param {((x: number, y: number) => object|null)|null} hitTest
|
||||
* @returns {void}
|
||||
*/
|
||||
export function setClickCardHitTest(hitTest) {
|
||||
_overlayHitTest = typeof hitTest === 'function' ? hitTest : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The topmost interactive card or label painted at a click, read once per
|
||||
* click so every handler of it sees the same one whatever ran first.
|
||||
* @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
|
||||
* @returns {{sourceId: string, entryId: string}|null}
|
||||
*/
|
||||
export function clickCard(click) {
|
||||
if (!click || typeof click !== 'object') return null;
|
||||
if (clickCards.has(click)) return clickCards.get(click);
|
||||
const at = click.screenPosition;
|
||||
let card = null;
|
||||
try {
|
||||
card = _overlayHitTest?.(at?.x, at?.y) ?? null;
|
||||
} catch {
|
||||
// a broken hit test must never break click handling
|
||||
}
|
||||
clickCards.set(click, card);
|
||||
return card;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when another layer's card or label is painted on top at a click. The
|
||||
* card on top takes the click: a scene item under it does not act, and is
|
||||
* not empty space either, so the layer leaves its selection alone.
|
||||
* @param {object} click The shared dispatcher event.
|
||||
* @param {Iterable<string>} [ownSourceIds] The asking layer's overlay
|
||||
* sources: its own card on top is its click.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isUnderOtherCard(click, ownSourceIds = []) {
|
||||
const card = clickCard(click);
|
||||
if (!card) return false;
|
||||
for (const sourceId of ownSourceIds)
|
||||
if (card.sourceId === sourceId) return false;
|
||||
return true;
|
||||
}
|
||||
@@ -17,6 +17,9 @@ import {
|
||||
isOwnedByOtherLayer,
|
||||
resolvePickId,
|
||||
pickContact,
|
||||
clickCard,
|
||||
isUnderOtherCard,
|
||||
setClickCardHitTest,
|
||||
} from './pickRegistry.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -197,3 +200,40 @@ test('touch picking tolerates a failing drill and preserves empty sky', (t) => {
|
||||
])
|
||||
assert.equal(pickContact(query(null, drillPick), { x: 1, y: 1 }), null);
|
||||
});
|
||||
|
||||
test("the card on top is read once per click, and only another layer's card counts", () => {
|
||||
let top = { sourceId: 'quake-card', entryId: 'q1' };
|
||||
let reads = 0;
|
||||
setClickCardHitTest((x, y) => {
|
||||
reads++;
|
||||
assert.deepEqual([x, y], [4, 5]);
|
||||
return top;
|
||||
});
|
||||
try {
|
||||
const click = { screenPosition: { x: 4, y: 5 } };
|
||||
assert.equal(isUnderOtherCard(click, ['vessel-card']), true);
|
||||
assert.equal(isUnderOtherCard(click, ['quake-card']), false, 'own card');
|
||||
// A card published later in the same click does not change it.
|
||||
top = { sourceId: 'vessel-card', entryId: 'v1' };
|
||||
assert.equal(clickCard(click).sourceId, 'quake-card');
|
||||
assert.equal(reads, 1);
|
||||
assert.equal(isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }), true);
|
||||
top = null;
|
||||
assert.equal(isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }), false);
|
||||
} finally {
|
||||
setClickCardHitTest(null);
|
||||
}
|
||||
assert.equal(
|
||||
isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }),
|
||||
false,
|
||||
'no host',
|
||||
);
|
||||
setClickCardHitTest(() => {
|
||||
throw new Error('broken');
|
||||
});
|
||||
try {
|
||||
assert.equal(clickCard({ screenPosition: { x: 1, y: 1 } }), null);
|
||||
} finally {
|
||||
setClickCardHitTest(null);
|
||||
}
|
||||
});
|
||||
@@ -681,6 +681,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})",
|
||||
@@ -2193,6 +2203,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": "اخرج من القمرة للانتقال إلى مشهد",
|
||||
@@ -3668,6 +3679,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": "بيانات حطام السفن غير متاحة",
|
||||
|
||||
@@ -646,6 +646,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)",
|
||||
@@ -2072,6 +2082,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",
|
||||
@@ -3324,6 +3335,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",
|
||||
|
||||
@@ -548,6 +548,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",
|
||||
@@ -2613,6 +2623,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",
|
||||
@@ -3410,6 +3421,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",
|
||||
|
||||
@@ -1498,6 +1498,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",
|
||||
@@ -1957,6 +1958,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)",
|
||||
@@ -3410,6 +3421,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",
|
||||
|
||||
@@ -1380,6 +1380,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": "צא מתא הטייס כדי לטוס אל מסלול",
|
||||
@@ -1794,6 +1795,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": "תנועה ברחובות",
|
||||
@@ -3552,6 +3563,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": "מ-",
|
||||
|
||||
@@ -1498,6 +1498,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",
|
||||
@@ -1957,6 +1958,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)",
|
||||
@@ -3410,6 +3421,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",
|
||||
|
||||
@@ -1452,6 +1452,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": "シーンへ移動するにはコックピットを終了してください",
|
||||
@@ -1879,6 +1880,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日)",
|
||||
@@ -3238,6 +3249,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": "難破船データを利用できません",
|
||||
|
||||
@@ -1498,6 +1498,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",
|
||||
@@ -1957,6 +1958,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)",
|
||||
@@ -3410,6 +3421,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",
|
||||
|
||||
@@ -654,6 +654,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 дн.)",
|
||||
@@ -2665,6 +2675,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": "Выйдите из кабины, чтобы перелететь к сцене",
|
||||
@@ -3496,6 +3507,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": "Данные о кораблекрушениях недоступны",
|
||||
|
||||
@@ -600,6 +600,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",
|
||||
@@ -1988,6 +1998,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",
|
||||
@@ -3237,6 +3248,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",
|
||||
|
||||
@@ -1520,6 +1520,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": "Вийдіть із кабіни, щоб перелетіти до сцени",
|
||||
@@ -1995,6 +1996,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 дн)",
|
||||
@@ -3496,6 +3507,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": "Дані про затонулі судна недоступні",
|
||||
|
||||
@@ -1427,6 +1427,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": "请先退出座舱,再飞往场景",
|
||||
@@ -1855,6 +1856,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 天)",
|
||||
@@ -3238,6 +3249,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": "沉船数据不可用",
|
||||
|
||||
@@ -1427,6 +1427,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": "請先退出座艙,再飛往場景",
|
||||
@@ -1855,6 +1856,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 天)",
|
||||
@@ -3238,6 +3249,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": "沉船數據不可用",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { isFollowing } from '../../data/followed.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
|
||||
import {
|
||||
LAYER_ID,
|
||||
@@ -581,6 +582,9 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
if (state.clickSubscription) return;
|
||||
state.clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!state.enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
// The painted overlay answers first; the scene is picked only if not.
|
||||
const hit = event.drawHit;
|
||||
const id =
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createAlprPresentation } from './presentation.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
|
||||
// The card or label painted on top takes the click: ALPR does not even pick
|
||||
// under another layer's card, so no camera is selected or released there.
|
||||
test("another layer's card over an ALPR camera keeps the click", (t) => {
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
canvas: new EventTarget(),
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const noop = () => {};
|
||||
const state = {
|
||||
enabled: true,
|
||||
viewer,
|
||||
clickSubscription: null,
|
||||
markers: { icons: null },
|
||||
recordById: new Map(),
|
||||
selectedId: null,
|
||||
};
|
||||
const presentation = createAlprPresentation({
|
||||
state,
|
||||
services: {
|
||||
render: { governorRequestRender: noop },
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer: noop,
|
||||
getSelectedEntityContext: () => null,
|
||||
registerEntityContext: noop,
|
||||
removeEntityContextsForLayer: noop,
|
||||
selectEntityContext: noop,
|
||||
},
|
||||
groundFloor: { cachedGroundFloor: () => null },
|
||||
},
|
||||
});
|
||||
presentation.installInteraction(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
setClickCardHitTest(null);
|
||||
state.clickSubscription?.();
|
||||
input.destroy();
|
||||
});
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
@@ -179,6 +180,9 @@ export function createSelection({
|
||||
if (layerState._clickSubscription) return;
|
||||
|
||||
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
const hit = event.drawHit;
|
||||
|
||||
if (hit) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createSelection } from './selection.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
|
||||
/** A station layer's selection on a viewer whose pick is scripted. */
|
||||
function harness(t) {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
let picked = null;
|
||||
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
|
||||
const input = fakeInput(viewer);
|
||||
const noop = () => {};
|
||||
const state = {
|
||||
_selectedKey: null,
|
||||
_clickSubscription: null,
|
||||
_stationRenderMap: new Map([['nyc:1', { position: { x: 1, y: 0, z: 0 } }]]),
|
||||
_stationSet: { id: 'bikeshare:stations', upsert: noop },
|
||||
_selectedSet: {
|
||||
id: 'bikeshare:selected',
|
||||
set: noop,
|
||||
size: () => 0,
|
||||
clear: noop,
|
||||
},
|
||||
_overlayHost: { setEntries: noop, clearSource: noop },
|
||||
};
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {},
|
||||
parts: { rendering: { stationItem: () => ({}) } },
|
||||
});
|
||||
selection._installClickHandler(viewer);
|
||||
t.after(() => {
|
||||
state._clickSubscription?.();
|
||||
input.destroy();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
return {
|
||||
state,
|
||||
click(hit) {
|
||||
picked = hit ? { id: hit } : null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// The card or label painted on top takes the click: a station under another
|
||||
// layer's card is neither selected nor let go.
|
||||
test("another layer's card over a station keeps the click", (t) => {
|
||||
const h = harness(t);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const station = { set: 'bikeshare:stations', id: 'nyc:1' };
|
||||
h.click(station);
|
||||
assert.equal(h.state._selectedKey, null, 'covered: not selected');
|
||||
top = null;
|
||||
h.click(station);
|
||||
assert.equal(h.state._selectedKey, 'nyc:1');
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
h.click(null);
|
||||
assert.equal(h.state._selectedKey, 'nyc:1', 'covered: kept');
|
||||
top = null;
|
||||
h.click(null);
|
||||
assert.equal(h.state._selectedKey, null, 'open map lets it go');
|
||||
});
|
||||
@@ -23,7 +23,7 @@ export function createLifecycle({
|
||||
source,
|
||||
}) {
|
||||
const { activateCctvCameraFromWorldClick } = services.activation;
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
|
||||
services.picking;
|
||||
const { onFocusTargetAppear } = services.focus;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
@@ -391,6 +391,20 @@ export function createLifecycle({
|
||||
(event) => {
|
||||
if (!layerState._enabled) return;
|
||||
const picked = event.topHit;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: a live card of ours acts whatever
|
||||
// is drawn under it; another layer's is that layer's click.
|
||||
const top = clickCard?.(event) ?? null;
|
||||
if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
|
||||
if (top) {
|
||||
// A card of ours that is going away is still not the scene.
|
||||
if (layerState._recordById.has(top.entryId))
|
||||
activateCctvCameraFromWorldClick(
|
||||
top.entryId,
|
||||
parts.selection.setActiveCamera,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const cameraId = parts.selection.extractPickedCameraId(
|
||||
event.drawHit ?? null,
|
||||
);
|
||||
@@ -401,29 +415,11 @@ 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(
|
||||
event.screenPosition.x,
|
||||
event.screenPosition.y,
|
||||
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
|
||||
)?.entryId;
|
||||
if (cardId && layerState._recordById.has(cardId)) {
|
||||
activateCctvCameraFromWorldClick(
|
||||
cardId,
|
||||
parts.selection.setActiveCamera,
|
||||
);
|
||||
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 the CCTV selection while ID-less globe, terrain
|
||||
// and tile surfaces remain eligible for empty-space deselection.
|
||||
if (resolvePickId(picked) !== null) return;
|
||||
if (
|
||||
parts.selection.cctvEmptyClickDeselects(picked, {
|
||||
activeCameraId: layerState._activeCameraId,
|
||||
|
||||
@@ -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,189 @@ 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('the card painted on top takes world clicks, whatever is drawn under it', async (t) => {
|
||||
const noop = () => {};
|
||||
const { viewer } = viewerWithCamera();
|
||||
let picked = null;
|
||||
viewer.scene = {
|
||||
canvas: {},
|
||||
pick: () => (picked ? { id: picked } : undefined),
|
||||
drillPick: () => drilled.map((id) => ({ id })),
|
||||
};
|
||||
let drilled = [];
|
||||
const input = fakeInput(viewer);
|
||||
// An aircraft layer that runs before ours and tracks the plane it was
|
||||
// clicked on, standing aside under another layer's card.
|
||||
let tracked = null;
|
||||
input.input.onClick((event) => {
|
||||
if (picking.isUnderOtherCard(event)) return;
|
||||
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
|
||||
});
|
||||
const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
|
||||
const foreignCard = {
|
||||
sourceId: 'earthquake-card',
|
||||
entryId: 'earthquake-card:qa',
|
||||
};
|
||||
let painted = [];
|
||||
const actions = [];
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
picking.setClickCardHitTest(() => painted[0] ?? null);
|
||||
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: { onFocusTargetAppear: () => noop },
|
||||
render: { releaseContinuousRender: noop },
|
||||
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.setClickCardHitTest(null);
|
||||
picking.unregisterPickOwner('area-control');
|
||||
picking.unregisterPickOwner('test-trails');
|
||||
picking.unregisterPickOwner('test-planes');
|
||||
picking.unregisterPickOwner('test-tracking');
|
||||
picking.unregisterPickOwner('test-exact');
|
||||
});
|
||||
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];
|
||||
for (const area of backgrounds) {
|
||||
click(area, [ownCard], ['cam-1']);
|
||||
click(area, [], []);
|
||||
click(area, [foreignCard, ownCard], []);
|
||||
}
|
||||
// The live top card acts over anything drawn under it; with no card an
|
||||
// identified object is not empty map.
|
||||
for (const hit of [
|
||||
{ set: 'flights:1', id: 'aircraft', surface: false },
|
||||
{ set: '', id: 'unregistered-local-entity', surface: false },
|
||||
{ ...drone, set: 'unrelated:1:fills' },
|
||||
{ ...drone, id: 'unregistered-local-entity' },
|
||||
]) {
|
||||
click(hit, [ownCard], ['cam-1']);
|
||||
click(hit, [], []);
|
||||
}
|
||||
// A trail under the live top card: the card keeps the click, and with no
|
||||
// card the owned 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);
|
||||
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) under a live CCTV card is the card's.
|
||||
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');
|
||||
drilled = ['plane:1'];
|
||||
click(null, [ownCard], ['cam-1']);
|
||||
// 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');
|
||||
restoreMatch();
|
||||
// The live card over an aircraft takes the click; the aircraft layer,
|
||||
// run first, stands aside and does not track.
|
||||
picking.registerPickOwner('test-tracking', (id) => id === 'plane:9');
|
||||
click(
|
||||
{ set: 'flights:1', id: 'plane:9', surface: false },
|
||||
[ownCard],
|
||||
['cam-1'],
|
||||
);
|
||||
assert.equal(tracked, null, 'the aircraft did not track');
|
||||
picking.unregisterPickOwner('test-tracking');
|
||||
picking.registerPickOwner('area-control', (id) => id === drone.id);
|
||||
click(drone, [ownCard], ['cam-1']);
|
||||
picking.unregisterPickOwner('area-control');
|
||||
click(null, [foreignCard, ownCard], []);
|
||||
click(null, [ownCard], ['cam-1']);
|
||||
click(null, [], ['clear']);
|
||||
click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
|
||||
// A card of ours that is going away is still not the scene under it: no
|
||||
// camera beneath it activates, and nothing clears.
|
||||
const staleCard = { ...ownCard, entryId: 'stale-camera' };
|
||||
click({ set: 'cctv:fixture', id: 'cam-1' }, [staleCard], []);
|
||||
click(null, [staleCard], []);
|
||||
// A camera icon under another layer's card is that card's click.
|
||||
click({ set: 'cctv:fixture', id: 'cam-1' }, [foreignCard, ownCard], []);
|
||||
click({ set: 'cctv:fixture', id: 'cam-1' }, [], ['cam-1']);
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
|
||||
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
clickCard,
|
||||
registerPickOwner,
|
||||
unregisterPickOwner,
|
||||
} from '../../data/pickRegistry.js';
|
||||
@@ -79,7 +78,6 @@ const intensityText = (storm) => {
|
||||
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
|
||||
export function createCyclonesLayer({
|
||||
feed,
|
||||
hitTestOverlay = hitTestWorldOverlay,
|
||||
overlayHost,
|
||||
context = null,
|
||||
createRendering = createCycloneRendering,
|
||||
@@ -97,8 +95,7 @@ export function createCyclonesLayer({
|
||||
selectionIntent = 'auto',
|
||||
navigationGeneration = 0,
|
||||
selectionOwner = null,
|
||||
selectedContextStormId = null,
|
||||
removeClickCapture = null;
|
||||
selectedContextStormId = null;
|
||||
let enabled = false,
|
||||
loading = false,
|
||||
error = null,
|
||||
@@ -169,75 +166,28 @@ export function createCyclonesLayer({
|
||||
rendering?.setSelection(id);
|
||||
}
|
||||
function installSelection() {
|
||||
const canvas = canvasOf(viewer);
|
||||
if (selectionOwner || !canvas) return;
|
||||
if (selectionOwner || !canvasOf(viewer)) return;
|
||||
const owner = {};
|
||||
selectionOwner = owner;
|
||||
// Snapshot before sibling bubble listeners can rebuild the overlay hit
|
||||
// rectangles. A vessel selection does that synchronously in the same click.
|
||||
let capturedHit = null;
|
||||
const overlayHit = (x, y) => {
|
||||
const hit = hitTestOverlay(x, y);
|
||||
return { sourceId: hit?.sourceId, entryId: hit?.entryId };
|
||||
};
|
||||
const capture = (event) => {
|
||||
capturedHit = null;
|
||||
const point = event.changedTouches?.[0] || event;
|
||||
if (!Number.isFinite(point.clientX) || !Number.isFinite(point.clientY))
|
||||
return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = point.clientX - rect.left,
|
||||
y = point.clientY - rect.top;
|
||||
capturedHit = { x, y, ...overlayHit(x, y) };
|
||||
};
|
||||
const resetCapture = () => {
|
||||
capturedHit = null;
|
||||
};
|
||||
const resetEvents = [
|
||||
'pointerdown',
|
||||
'mousedown',
|
||||
'touchstart',
|
||||
'pointercancel',
|
||||
'touchcancel',
|
||||
];
|
||||
for (const type of resetEvents)
|
||||
canvas.addEventListener?.(type, resetCapture, { capture: true });
|
||||
const events = ['pointerup', 'mouseup', 'touchend'];
|
||||
for (const type of events)
|
||||
canvas.addEventListener?.(type, capture, { capture: true });
|
||||
removeClickCapture = () => {
|
||||
for (const type of events)
|
||||
canvas.removeEventListener?.(type, capture, { capture: true });
|
||||
for (const type of resetEvents)
|
||||
canvas.removeEventListener?.(type, resetCapture, { capture: true });
|
||||
capturedHit = null;
|
||||
};
|
||||
const unsubscribe = inputFor(viewer).onClick((event) => {
|
||||
const nativeHit = capturedHit;
|
||||
capturedHit = null;
|
||||
// Ambient selection yields to draw tools and Director (the dispatcher
|
||||
// skips a held pointer); it never claims the pointer, camera, or
|
||||
// tracking state.
|
||||
const position = event.screenPosition;
|
||||
if (!enabled || destroyed || selectionOwner !== owner || !position)
|
||||
return;
|
||||
// AIS cards paint above the globe on a pointer-events:none canvas. The
|
||||
// vessel handler resolves this same topmost hit before cyclone geometry.
|
||||
const captureMatches =
|
||||
nativeHit &&
|
||||
Math.abs(nativeHit.x - position.x) < 1 &&
|
||||
Math.abs(nativeHit.y - position.y) < 1;
|
||||
const hit = captureMatches
|
||||
? nativeHit
|
||||
: overlayHit(position.x, position.y);
|
||||
if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
|
||||
// The card or label painted on top, as it was when the click landed.
|
||||
const card = clickCard(event);
|
||||
// Storm cards and lead-hour labels paint on the same canvas; a click on
|
||||
// one selects its storm. An id from a superseded advisory changes nothing.
|
||||
if (hit.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
|
||||
const id = cycloneStormIdFromEntryId(hit.entryId);
|
||||
if (card?.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
|
||||
const id = cycloneStormIdFromEntryId(card.entryId);
|
||||
if (id) layer.setParams({ stormId: id });
|
||||
return;
|
||||
}
|
||||
// Another layer's card on top takes the click: the storm under it does
|
||||
// not act, and the click is not empty map either.
|
||||
if (card) return;
|
||||
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
|
||||
// clears the selection.
|
||||
const id = rendering?.pickStorm(event.drawHit);
|
||||
@@ -249,8 +199,6 @@ export function createCyclonesLayer({
|
||||
function removeSelection() {
|
||||
const owner = selectionOwner;
|
||||
selectionOwner = null;
|
||||
removeClickCapture?.();
|
||||
removeClickCapture = null;
|
||||
owner?.unsubscribe?.();
|
||||
}
|
||||
const layer = {
|
||||
|
||||
@@ -6,7 +6,10 @@ import {
|
||||
releasePointer,
|
||||
isPointerFree,
|
||||
} from '../../data/inputOwnership.js';
|
||||
import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
|
||||
import {
|
||||
isOwnedByOtherLayer,
|
||||
setClickCardHitTest,
|
||||
} from '../../data/pickRegistry.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
@@ -77,7 +80,7 @@ const deferred = () => {
|
||||
return { promise, resolve };
|
||||
};
|
||||
|
||||
test('map selection yields to pointer owners and owns only its enabled handler', async () => {
|
||||
test('map selection yields to pointer owners and owns only its enabled handler', async (t) => {
|
||||
const handlers = [],
|
||||
// A pick of an item in one of the layer's draw sets, and one of another
|
||||
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
|
||||
@@ -109,11 +112,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
const layer = createCyclonesLayer({
|
||||
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
|
||||
createRendering: () => rendering,
|
||||
hitTestOverlay: () => {
|
||||
overlayTests++;
|
||||
return overlayHit;
|
||||
},
|
||||
});
|
||||
setClickCardHitTest(() => {
|
||||
overlayTests++;
|
||||
return overlayHit;
|
||||
});
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const canvas = new EventTarget();
|
||||
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
|
||||
const viewer = {
|
||||
@@ -180,41 +184,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
'foreground AIS card wins before scene picking',
|
||||
);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
|
||||
// A native capture runs before an earlier sibling handler clears hit rects.
|
||||
const up = new Event('pointerup');
|
||||
Object.assign(up, { clientX: 110, clientY: 220 });
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = null;
|
||||
// Any other layer's card on top takes the click, not only a vessel's.
|
||||
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
|
||||
handlers[0].click(click);
|
||||
assert.equal(
|
||||
layer.getDiagnostics().selectedId,
|
||||
'ep152026',
|
||||
'captured AIS hit survives synchronous sibling overlay rebuild',
|
||||
'a camera card over the storm keeps the click',
|
||||
);
|
||||
// A captured background hit remains background even if a sibling adds a card.
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
layer.setParams({ stormId: 'ep152026' });
|
||||
// A new gesture clears an unconsumed release snapshot.
|
||||
canvas.dispatchEvent(up);
|
||||
canvas.dispatchEvent(new Event('pointerdown'));
|
||||
overlayHit = null;
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
layer.setParams({ stormId: 'ep152026' });
|
||||
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = null;
|
||||
handlers[0].click({ position: { x: 15, y: 25 } });
|
||||
assert.equal(
|
||||
layer.getDiagnostics().selectedId,
|
||||
'ep162026',
|
||||
'a different click cannot reuse the captured card',
|
||||
);
|
||||
layer.setParams({ stormId: 'ep152026' });
|
||||
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
|
||||
const before = notices;
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
@@ -264,13 +242,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
assert.equal(layer.getDiagnostics().selectionActive, false);
|
||||
const afterDisable = picks;
|
||||
const afterDisableOverlay = overlayTests;
|
||||
canvas.dispatchEvent(up);
|
||||
handlers[0].click(click);
|
||||
assert.equal(
|
||||
overlayTests,
|
||||
afterDisableOverlay,
|
||||
'disable removes native capture listeners',
|
||||
'a disabled layer reads no card',
|
||||
);
|
||||
handlers[0].click(click);
|
||||
assert.equal(picks, afterDisable, 'queued disabled callback is inert');
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
@@ -289,7 +266,7 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
);
|
||||
assert.equal(handlers[1].destroyed, true);
|
||||
});
|
||||
test('a click on a storm card or lead-hour label selects that storm without picking', async () => {
|
||||
test('a click on a storm card or lead-hour label selects that storm without picking', async (t) => {
|
||||
const handlers = [];
|
||||
let picks = 0,
|
||||
overlayHit = null,
|
||||
@@ -309,8 +286,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
|
||||
getDiagnostics: () => ({}),
|
||||
};
|
||||
},
|
||||
hitTestOverlay: () => overlayHit,
|
||||
});
|
||||
setClickCardHitTest(() => overlayHit);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const canvas = new EventTarget();
|
||||
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
|
||||
const viewer = {
|
||||
@@ -343,15 +321,11 @@ test('a click on a storm card or lead-hour label selects that storm without pick
|
||||
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:al019999' };
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
|
||||
// The native release snapshot carries the card identity too.
|
||||
const up = new Event('pointerup');
|
||||
Object.assign(up, { clientX: 10, clientY: 20 });
|
||||
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:ep162026' };
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = null;
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
assert.equal(picks, 0, 'card clicks never fall through to the scene');
|
||||
overlayHit = null;
|
||||
handlers[0].click(click);
|
||||
assert.equal(picks, 1);
|
||||
assert.equal(layer.getDiagnostics().selectedId, null, 'empty map clears');
|
||||
|
||||
@@ -1584,6 +1584,9 @@ export function createDirectionsLayer({ services, source }) {
|
||||
// yields the moment a tool (this one included) owns the click.
|
||||
const offSelect = input.onClick((event) => {
|
||||
if (!_enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (services.picking?.isUnderOtherCard?.(event)) return;
|
||||
let hit = null;
|
||||
try {
|
||||
hit = event.drawHit;
|
||||
|
||||
@@ -130,12 +130,11 @@ export function createDroneAirspaceLayer({
|
||||
// cards inert anywhere over a zone. Unowned, our picks read as
|
||||
// "empty space" to siblings — the same contract as fire perimeters.
|
||||
_clickSubscription = inputFor(_viewer).onClick((event) => {
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) return;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: this area's shapes are background to
|
||||
// another layer's card or label painted over them, and a click on our
|
||||
// own card leaves the selection as it is.
|
||||
if (picking.clickCard?.(event)) return;
|
||||
const picked = event.topHit;
|
||||
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
|
||||
if (zoneId) {
|
||||
|
||||
@@ -47,6 +47,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),
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
clickCard: (click) =>
|
||||
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
|
||||
},
|
||||
});
|
||||
layer.init(viewer);
|
||||
@@ -143,6 +146,52 @@ 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.
|
||||
// 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' }
|
||||
: 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 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 () => {
|
||||
for (const action of ['disable', 'destroy']) {
|
||||
let resolve, signal;
|
||||
|
||||
+416
-30
@@ -1,6 +1,10 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
import {
|
||||
isTrackingClickGesture,
|
||||
isTrackingSelectionGesture,
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import {
|
||||
EARTHQUAKE_OVERLAY_SOURCE_ID,
|
||||
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
|
||||
@@ -11,6 +15,11 @@ import {
|
||||
selectEarthquakeOverlayCohort,
|
||||
mapAnalystRecord,
|
||||
earthquakeCoverage,
|
||||
earthquakeMarkLabel,
|
||||
earthquakeMagnitudeTitle,
|
||||
earthquakeZoomLabel,
|
||||
earthquakeDiscRadiusM,
|
||||
describeEarthquake,
|
||||
} from './model.js';
|
||||
export * from './model.js';
|
||||
export { createUsgsEarthquakeSource } from './source.js';
|
||||
@@ -25,6 +34,20 @@ 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:';
|
||||
/** 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({
|
||||
cohortLimit: 1,
|
||||
collisionCapacity: 1,
|
||||
moving: false,
|
||||
});
|
||||
let instances = 0;
|
||||
|
||||
/**
|
||||
@@ -33,8 +56,48 @@ 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.
|
||||
* @param {(viewer: object) => {onClick: Function}} [options.input] The
|
||||
* viewer's click dispatcher.
|
||||
* @param {{resolvePickId: Function, isOwnedByOtherLayer: Function,
|
||||
* clickCard?: Function}} [options.picking] The pick
|
||||
* registry; `clickCard` names the card or label painted on top of a
|
||||
* click, which takes it (the quake card and labels need it to act).
|
||||
* @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,
|
||||
* 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({ source, overlayHost } = {}) {
|
||||
export function createEarthquakesLayer({
|
||||
source,
|
||||
overlayHost,
|
||||
input = null,
|
||||
picking = null,
|
||||
context = null,
|
||||
pointer = null,
|
||||
openExternal = null,
|
||||
focus = null,
|
||||
ripples = null,
|
||||
groundHeight = 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 +123,307 @@ 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) {
|
||||
// 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, canOpen: Boolean(openExternal) },
|
||||
);
|
||||
_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;
|
||||
};
|
||||
} 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(
|
||||
EARTHQUAKE_CARD_SOURCE_ID,
|
||||
[card],
|
||||
CARD_HOST_OPTIONS,
|
||||
);
|
||||
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),
|
||||
},
|
||||
{ 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({ evicted = false } = {}) {
|
||||
if (!context || !_contextId) return;
|
||||
try {
|
||||
context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID, {
|
||||
evicted,
|
||||
});
|
||||
context.getContextStore().entities.delete(_contextId);
|
||||
} catch {
|
||||
// store unavailable: nothing to clean
|
||||
}
|
||||
_contextId = null;
|
||||
}
|
||||
|
||||
function clearSelection({ evicted = false } = {}) {
|
||||
const had = _selectedId || _selectedCardId;
|
||||
_selectedId = null;
|
||||
_selectedCardId = null;
|
||||
_selectedLink = null;
|
||||
clearContext({ evicted });
|
||||
ripples?.hide?.();
|
||||
fadeDisc(null);
|
||||
if (had)
|
||||
overlayHost.setEntries(EARTHQUAKE_CARD_SOURCE_ID, [], CARD_HOST_OPTIONS);
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
if (!canSelect() || _clickHandler || !_viewer) return;
|
||||
// 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 {
|
||||
clicks = input(_viewer) ?? null;
|
||||
} catch {
|
||||
clicks = null;
|
||||
}
|
||||
if (!clicks) return;
|
||||
_clickHandler = clicks.onClick((click) => {
|
||||
if (!_enabled || (pointer && !pointer.isPointerFree())) return;
|
||||
// A pan that ends near where it began still raises a click. As for the
|
||||
// tracking layers and Context, a press that travelled is a drag, not a
|
||||
// pick; opening the source and clearing also need a short press.
|
||||
if (!isTrackingSelectionGesture(click.gesture)) return;
|
||||
const clean = isTrackingClickGesture(click.gesture);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: another layer's is that layer's click
|
||||
// (the disc under it is background), and ours acts whatever is drawn
|
||||
// under it.
|
||||
const top = picking.clickCard?.(click) ?? null;
|
||||
if (top?.sourceId === EARTHQUAKE_CARD_SOURCE_ID) {
|
||||
// The card's action, as its keyboard action: open the source, or
|
||||
// with none, fly to the quake.
|
||||
if (top.entryId !== _selectedCardId) return;
|
||||
if (_selectedLink) {
|
||||
if (clean) openExternal(_selectedLink);
|
||||
} else if (focus?.requestWorldFocus && _selectedId)
|
||||
selectAndFocus(_selectedId);
|
||||
return;
|
||||
}
|
||||
// A magnitude label is what a far view (the whole globe) can click:
|
||||
// it selects the quake and flies to it.
|
||||
if (top?.sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) {
|
||||
if (_eventById.has(top.entryId)) selectAndFocus(top.entryId);
|
||||
return;
|
||||
}
|
||||
if (top) return;
|
||||
// Another layer's pick (an aircraft, a camera, a flight trail) is not
|
||||
// empty space and not this layer's: leave the selection alone.
|
||||
const hit = click.hit;
|
||||
const pickId = picking.resolvePickId(hit);
|
||||
if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
|
||||
return;
|
||||
const event = pickedEvent(hit);
|
||||
if (event) {
|
||||
_selectedId = event.stableId;
|
||||
publishCard({ user: true });
|
||||
return;
|
||||
}
|
||||
if (clean) 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),
|
||||
// The whole disc in view: the framing's range fits an M6 disc, so only
|
||||
// a larger one asks for its own range (the framing stays the floor).
|
||||
radiusM: earthquakeDiscRadiusM(event.mag),
|
||||
rangeM:
|
||||
event.mag > 6
|
||||
? earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS
|
||||
: undefined,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
_clickHandler?.();
|
||||
_clickHandler = null;
|
||||
}
|
||||
|
||||
const layer = {
|
||||
id: 'earthquakes',
|
||||
@@ -93,6 +457,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 +466,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 +501,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 +579,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;
|
||||
|
||||
@@ -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) =>
|
||||
@@ -123,6 +129,332 @@ 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.
|
||||
* @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` 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,
|
||||
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)) {
|
||||
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) {
|
||||
// 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);
|
||||
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: opens
|
||||
? t('Open the source for {title}, {details}', summary)
|
||||
: t('Focus earthquake {title}, {details}', summary),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<typeof earthquakeContourShape>} 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,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -13,7 +13,7 @@ export function createSelection({
|
||||
config,
|
||||
feed,
|
||||
}) {
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, clickCard } = services.picking;
|
||||
const { requestWorldFocus } = services.focus;
|
||||
const {
|
||||
selectEntityContext,
|
||||
@@ -21,7 +21,7 @@ export function createSelection({
|
||||
getContextStore,
|
||||
registerEntityContext,
|
||||
} = services.context;
|
||||
const { id, name, overlayHost } = config;
|
||||
const { id, name } = config;
|
||||
|
||||
/**
|
||||
* Install the LEFT_CLICK handler for fire selection (enable-time only,
|
||||
@@ -34,10 +34,19 @@ export function createSelection({
|
||||
if (layerState._clickSubscription || !layerState._viewer) return;
|
||||
const input = inputFor(layerState._viewer);
|
||||
layerState._clickSubscription = input.onClick((event) => {
|
||||
const picked = event.topHit;
|
||||
const pickedId = picked ? resolvePickId(picked) : null;
|
||||
// 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.
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours acts whatever is drawn under it;
|
||||
// another layer's is that layer's click.
|
||||
const top = clickCard?.(event) ?? null;
|
||||
if (top) {
|
||||
if (top.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return;
|
||||
const carded = layerState._fireByCardId.get(top.entryId);
|
||||
if (carded) selectAndFocusFire(carded);
|
||||
return;
|
||||
}
|
||||
const pickedId = resolvePickId(event.topHit ?? null);
|
||||
// A pick that belongs to a sibling layer (an aircraft, a flight trail)
|
||||
// is not "empty space": leave the selection alone.
|
||||
const otherLayer = Boolean(pickedId && isOwnedByOtherLayer(id, pickedId));
|
||||
// The stand-in is asked where markers are picked: the click corrected
|
||||
// for the sensor style (`event.position`), and only when no sibling
|
||||
@@ -52,18 +61,6 @@ export function createSelection({
|
||||
return;
|
||||
}
|
||||
if (otherLayer) return;
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{
|
||||
sourceId: FIRMS_OVERLAY_SOURCE_ID,
|
||||
},
|
||||
);
|
||||
if (cardHit) {
|
||||
const carded = layerState._fireByCardId.get(cardHit.entryId);
|
||||
if (carded) selectAndFocusFire(carded);
|
||||
return;
|
||||
}
|
||||
clearFireSelection();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import { createCivilFlightLayer } from './index.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createEnrichment } from './enrichment.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { LiveSourceError } from '../../sources/live/contract.js';
|
||||
|
||||
function services() {
|
||||
@@ -609,6 +611,50 @@ test('a route answer for a callsign the plane no longer flies is dropped', async
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: an aircraft under another
|
||||
// layer's card is not even picked, so it is neither tracked nor released.
|
||||
test("another layer's card over an aircraft keeps the click", (t) => {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
body: { classList: { contains: () => false } },
|
||||
});
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
canvas: new EventTarget(),
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const flightState = createFlightState({ services: services() });
|
||||
flightState._trackedEntityChangedRemove = () => {};
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: { ...services(), picking },
|
||||
parts: {},
|
||||
layer: {},
|
||||
});
|
||||
tracking._installClickHandler(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
picking.setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
picking.setClickCardHitTest(null);
|
||||
flightState._clickSubscription?.();
|
||||
input.destroy();
|
||||
flightState.lifetime.abort();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
});
|
||||
|
||||
test("a type lookup overrides the feed's type and fills the type name", async () => {
|
||||
const queries = [];
|
||||
const source = {
|
||||
|
||||
@@ -88,7 +88,8 @@ export function createTracking({
|
||||
const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout;
|
||||
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
|
||||
services.camera;
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
|
||||
services.picking;
|
||||
const flightsLayer = layer;
|
||||
/** The tracked contact's billboard (an icon set on the draw port). */
|
||||
const trackedIcon = createTrackedAircraftIcon({
|
||||
@@ -1316,6 +1317,9 @@ export function createTracking({
|
||||
// first-person reference. A globe click must not fall through to the
|
||||
// normal empty-space deselection path; cockpit has explicit exit controls.
|
||||
if (document.body.classList.contains('cockpit-mode')) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard?.(event)) return;
|
||||
const picked = event.hit;
|
||||
|
||||
if (picked) {
|
||||
|
||||
@@ -707,13 +707,19 @@ export function createGhostMapsLayer({
|
||||
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
|
||||
);
|
||||
_clickSubscription = inputFor(_viewer).onClick((event) => {
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{ sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours opens its source whatever is drawn
|
||||
// under it; another layer's is that layer's click, so the maps under
|
||||
// it do not act and the selection stays.
|
||||
const cardHit = picking.clickCard?.(event) ?? null;
|
||||
if (cardHit) {
|
||||
if (
|
||||
cardHit.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID &&
|
||||
cardHit.entryId === _selectedCardId &&
|
||||
_selectedLink &&
|
||||
openExternal
|
||||
)
|
||||
openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = event.topHit;
|
||||
|
||||
@@ -672,3 +672,58 @@ 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: '<a href="https://example.com/first">Source</a>',
|
||||
},
|
||||
{
|
||||
name: 'Second',
|
||||
description: '<a href="https://example.com/second">Source</a>',
|
||||
},
|
||||
],
|
||||
controls: {
|
||||
overlayHost: {
|
||||
setEntries: (_id, entries) => cards.push(entries),
|
||||
hitTest: (_x, _y, { sourceId } = {}) =>
|
||||
painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null,
|
||||
},
|
||||
picking: {
|
||||
resolvePickId: (picked) => picked,
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
clickCard: () => painted[0] ?? null,
|
||||
},
|
||||
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);
|
||||
// A marker under another layer's card is that card's click too.
|
||||
click('ghostmaps:cip:1:0');
|
||||
assert.equal(cards.at(-1)[0].id, first.id, 'a covered marker yields');
|
||||
painted = [];
|
||||
click('ghostmaps:cip:1:0');
|
||||
const second = cards.at(-1)[0];
|
||||
assert.notEqual(second.id, first.id, 'a bare marker selects');
|
||||
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');
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { LAYER_ID } from './policy.js';
|
||||
|
||||
export function createSelection({
|
||||
@@ -52,6 +53,9 @@ export function createSelection({
|
||||
const input = inputFor(viewer);
|
||||
layerState.clickSubscription = input.onClick((event) => {
|
||||
if (!layerState.enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
// A site's dot, outline or fill, or a named marker: each draw item
|
||||
// names its installation in its `meta`.
|
||||
const hit = event.drawHit;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
|
||||
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
|
||||
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
|
||||
function harness(t) {
|
||||
const previousWindow = globalThis.window;
|
||||
@@ -186,6 +187,30 @@ test('a click on a named marker point selects its site; again releases it', (t)
|
||||
h.assertSelected(false);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a site under another
|
||||
// layer's card neither selects nor releases.
|
||||
test("another layer's card over a site keeps the click", (t) => {
|
||||
const h = harness(t);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const setId = h.parts.namedMarkers.setId;
|
||||
const item = h.draw.set(setId).items.get(namedPointId('base'));
|
||||
const pointPick = { id: { set: setId, id: item.id, meta: item.meta } };
|
||||
h.click(pointPick);
|
||||
h.assertSelected(true);
|
||||
h.click(undefined);
|
||||
h.assertSelected(true);
|
||||
h.state.selectedId = null;
|
||||
context.clearSelectedEntityContextForLayer('military-installations');
|
||||
h.parts.rendering.renderRecords();
|
||||
h.click(pointPick);
|
||||
h.assertSelected(false);
|
||||
top = null;
|
||||
h.click(pointPick);
|
||||
h.assertSelected(true);
|
||||
});
|
||||
|
||||
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
|
||||
const h = harness(t);
|
||||
h.state.selectedId = null;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
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() {} },
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
picking: { ...picking, clickCard: () => top },
|
||||
},
|
||||
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',
|
||||
);
|
||||
} finally {
|
||||
state._inputSubscription?.();
|
||||
input.destroy();
|
||||
}
|
||||
});
|
||||
@@ -255,7 +255,14 @@ export function createLifecycle({
|
||||
return focusLaunch(markerLaunchId(hit));
|
||||
});
|
||||
const unsubscribeClick = input.onClick((event) => {
|
||||
if (!missionsShown() || overlayClicks.has(event)) return;
|
||||
// Another layer's card or label on top is that layer's click, read
|
||||
// once per click as every layer reads it.
|
||||
if (
|
||||
!missionsShown() ||
|
||||
overlayClicks.has(event) ||
|
||||
services.picking?.clickCard?.(event)
|
||||
)
|
||||
return;
|
||||
focusLaunch(
|
||||
parts.rendering.launchIdFromPicks(
|
||||
parts.rendering.missionHitsAt(event.position, 12),
|
||||
|
||||
@@ -703,6 +703,9 @@ export function createLocalAdsbLayer({
|
||||
if (clickSubscription || !viewer) return;
|
||||
clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (services.picking.isUnderOtherCard?.(event)) return;
|
||||
const target = clickTarget(event);
|
||||
// Clicking a local aircraft always (re)selects it and republishes its
|
||||
// card, including the one already selected: its card may have been
|
||||
|
||||
@@ -15,7 +15,11 @@ import {
|
||||
} from './index.js';
|
||||
import { createLocalAdsbModels } from './models.js';
|
||||
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
|
||||
import { resolvePickId } from '../../data/pickRegistry.js';
|
||||
import {
|
||||
isUnderOtherCard,
|
||||
resolvePickId,
|
||||
setClickCardHitTest,
|
||||
} from '../../data/pickRegistry.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
@@ -1213,6 +1217,41 @@ test('clicking the selected aircraft keeps it selected and republishes its card'
|
||||
assert.deepEqual(calls.cleared, []);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a local aircraft under
|
||||
// another layer's card is neither selected nor released.
|
||||
test("another layer's card over a local aircraft keeps the click", async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
const harness = clickHarness();
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
|
||||
viewer: harness.viewer,
|
||||
services: {
|
||||
picking: {
|
||||
registerPickOwner() {},
|
||||
unregisterPickOwner() {},
|
||||
resolvePickId,
|
||||
isUnderOtherCard,
|
||||
},
|
||||
},
|
||||
});
|
||||
t.after(() => layer.destroy());
|
||||
receiver.set({ aircraft: [record()] });
|
||||
await layer.update();
|
||||
harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
|
||||
harness.click();
|
||||
assert.deepEqual(calls.selected, [], 'covered: not selected');
|
||||
top = null;
|
||||
harness.click();
|
||||
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
harness.scene.pickResult = null;
|
||||
harness.click();
|
||||
assert.deepEqual(calls.cleared, [], 'covered: the selection stays');
|
||||
});
|
||||
|
||||
test('a click on a local aircraft under an unowned or trail pick still selects it', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
|
||||
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
|
||||
import { createMilitaryFlightLayer } from './index.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
|
||||
function services() {
|
||||
const names = [
|
||||
@@ -294,3 +296,47 @@ test('a military layer without an icon set declines contact refreshes', () => {
|
||||
assert.equal(layer.refreshTr3b('abc123'), false);
|
||||
assert.equal(layer.trackById('abc123'), false);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: an aircraft under another
|
||||
// layer's card is not even picked, so it is neither tracked nor released.
|
||||
test("another layer's card over an aircraft keeps the click", (t) => {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
body: { classList: { contains: () => false } },
|
||||
});
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
canvas: new EventTarget(),
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const flightState = createFlightState({ services: services() });
|
||||
flightState._trackedEntityChangedRemove = () => {};
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: { ...services(), picking },
|
||||
parts: {},
|
||||
layer: {},
|
||||
});
|
||||
tracking._installClickHandler(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
picking.setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
picking.setClickCardHitTest(null);
|
||||
flightState._clickSubscription?.();
|
||||
input.destroy();
|
||||
flightState.lifetime.abort();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
});
|
||||
@@ -86,7 +86,8 @@ export function createTracking({
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
|
||||
services.camera;
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
|
||||
services.picking;
|
||||
/** The tracked contact's billboard (an icon set on the draw port). */
|
||||
const trackedIcon = createTrackedAircraftIcon({
|
||||
viewer: () => flightState._viewer,
|
||||
@@ -1229,6 +1230,9 @@ export function createTracking({
|
||||
// first-person reference. Empty globe clicks are inert until the user
|
||||
// exits with C, Escape, or the dedicated button.
|
||||
if (document.body.classList.contains('cockpit-mode')) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard?.(event)) return;
|
||||
const picked = event.hit;
|
||||
|
||||
if (picked) {
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
findFrame,
|
||||
rendererOf,
|
||||
} from '../../render/rendererOf.js';
|
||||
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
|
||||
import {
|
||||
clickCard,
|
||||
isOwnedByOtherLayer,
|
||||
registerPickOwner,
|
||||
resolvePickId,
|
||||
@@ -203,7 +203,6 @@ export function createNewsLayer({
|
||||
inputFor = defaultInputFor,
|
||||
matchMedia = globalThis.matchMedia?.bind(globalThis),
|
||||
now = () => Date.now(),
|
||||
hitTestOverlay = hitTestWorldOverlay,
|
||||
openUrl = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
|
||||
getViewCentre = viewCentre,
|
||||
registerCredit = registerDynamicCredit,
|
||||
@@ -1348,11 +1347,13 @@ 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) {
|
||||
card.entry.activate();
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: our own card acts whatever is drawn
|
||||
// under it; another layer's is that layer's click, so the pins under
|
||||
// it do not act and the selection stays.
|
||||
const card = clickCard(event);
|
||||
if (card) {
|
||||
if (card.sourceId === NEWS_OVERLAY_SOURCE_ID) card.entry?.activate?.();
|
||||
return;
|
||||
}
|
||||
// What is on top under the click: a draw-set item, or null for the
|
||||
|
||||
@@ -5,6 +5,14 @@ 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,
|
||||
setClickCardHitTest,
|
||||
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 +59,7 @@ function fixture(
|
||||
now = () => NOW,
|
||||
quality,
|
||||
pictureCards,
|
||||
hitTestOverlay = () => null,
|
||||
} = {},
|
||||
) {
|
||||
const calls = { feed: [], hotspots: 0, outline: 0 };
|
||||
@@ -137,11 +146,12 @@ function fixture(
|
||||
for (const fn of [...clickHandlers])
|
||||
fn({ screenPosition: { x: 10, y: 10 }, topHit });
|
||||
};
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
setClickCardHitTest((x, y) => hitTestOverlay(x, y));
|
||||
const layer = createNewsLayer({
|
||||
source,
|
||||
overlayHost,
|
||||
inputFor: () => input,
|
||||
hitTestOverlay: () => null,
|
||||
now,
|
||||
matchMedia: () => ({ matches: reduced }),
|
||||
getViewCentre: () => centre(),
|
||||
@@ -158,6 +168,7 @@ function fixture(
|
||||
layer.attachShellServices({ runNavigation: (navigate) => navigate() });
|
||||
t.after(() => {
|
||||
layer.destroy();
|
||||
setClickCardHitTest(null);
|
||||
unbind();
|
||||
if (originalWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = originalWindow;
|
||||
@@ -1285,6 +1296,70 @@ 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 and pin yield; the top news card acts over a trail or a vessel', 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);
|
||||
// A news pin under another layer's card is that card's click too.
|
||||
layer.setParams({ clear: true });
|
||||
click({ set: 'news:1:points', id: marker.id, surface: false });
|
||||
assert.equal(layer.getRowControls().feed.selected, null, 'covered pin');
|
||||
hits = [];
|
||||
click({ set: 'news:1:points', id: marker.id, surface: false });
|
||||
assert.equal(layer.getRowControls().feed.selected.id, 'major');
|
||||
hits = [{ sourceId: 'news', entry: card }];
|
||||
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');
|
||||
// Over a vessel (a layer that acts on its pick) the card on top acts too;
|
||||
// the vessel layer stands aside under it, so one click does one thing.
|
||||
registerPickOwner('test-vessels', (id) => id === '353136000');
|
||||
try {
|
||||
click({ set: 'vessels:1', id: '353136000', surface: false });
|
||||
assert.equal(activations, 3, 'the news card acts over a vessel');
|
||||
} finally {
|
||||
unregisterPickOwner('test-vessels');
|
||||
}
|
||||
});
|
||||
|
||||
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'), []);
|
||||
|
||||
@@ -218,13 +218,18 @@ export function createFirePerimetersLayer({
|
||||
_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 },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: this area's shapes are background to
|
||||
// another layer's card or label painted over them.
|
||||
const cardHit = picking.clickCard?.(event) ?? null;
|
||||
if (cardHit) {
|
||||
if (
|
||||
cardHit.sourceId === PERIMETER_OVERLAY_SOURCE_ID &&
|
||||
cardHit.entryId === _selectedCardId &&
|
||||
_selectedLink &&
|
||||
openExternal
|
||||
)
|
||||
openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = event.topHit;
|
||||
|
||||
@@ -58,6 +58,9 @@ function harness(
|
||||
String(pickedId).startsWith('other-layer:'),
|
||||
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
|
||||
unregisterPickOwner: (layerId) => owners.delete(layerId),
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
clickCard: (click) =>
|
||||
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
|
||||
},
|
||||
inciwebSource: inciwebIndex
|
||||
? { getIndex: async () => inciwebIndex }
|
||||
@@ -243,6 +246,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] },
|
||||
@@ -279,12 +319,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);
|
||||
@@ -299,9 +343,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(
|
||||
@@ -328,7 +378,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, []);
|
||||
|
||||
@@ -15,6 +15,7 @@ export function createInteraction({
|
||||
const {
|
||||
resolvePickId,
|
||||
isOwnedByOtherLayer,
|
||||
isUnderOtherCard,
|
||||
registerPickOwner,
|
||||
unregisterPickOwner,
|
||||
} = services.picking;
|
||||
@@ -29,6 +30,9 @@ export function createInteraction({
|
||||
*/
|
||||
function pickedRadioStationAt(event) {
|
||||
if (!event) return null;
|
||||
// Another layer's card or label painted on top is that layer's click,
|
||||
// read once per click so every layer agrees: no station under it acts.
|
||||
if (isUnderOtherCard?.(event, [RADIO_OVERLAY_SOURCE_ID])) return null;
|
||||
|
||||
const stationFromPick = (picked) => {
|
||||
const stationId = parts.rendering.radioStationIdFromPick(picked);
|
||||
|
||||
@@ -62,3 +62,49 @@ test('a direct hit needs no drill, and another layer’s contact keeps its click
|
||||
});
|
||||
assert.equal(pickedRadioStationAt(other), null);
|
||||
});
|
||||
|
||||
// Another layer's card or label painted on top takes the click: no station
|
||||
// under it acts, whether radio found it through its window, as the tap's touch
|
||||
// contact or as the exact pick. Radio's own card on top is radio's click.
|
||||
test("a station under another layer's card does not act", () => {
|
||||
let top = null;
|
||||
const radio = createInteraction({
|
||||
state: {
|
||||
_stationById: new Map([
|
||||
['kexp', {}],
|
||||
['kuow', {}],
|
||||
]),
|
||||
},
|
||||
services: {
|
||||
picking: {
|
||||
resolvePickId: (picked) => picked?.id ?? null,
|
||||
isOwnedByOtherLayer: () => false,
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
isUnderOtherCard: (_click, own = []) =>
|
||||
Boolean(top) && !own.includes(top.sourceId),
|
||||
registerPickOwner() {},
|
||||
unregisterPickOwner() {},
|
||||
},
|
||||
overlays: { setOverlaySourceVisible() {} },
|
||||
},
|
||||
parts: { rendering: { radioStationIdFromPick } },
|
||||
});
|
||||
const station = hit('radio:kexp');
|
||||
const tap = (contact = null, pick = null) => ({
|
||||
...clickEvent({ pick, windowHits: [station] }),
|
||||
hit: contact,
|
||||
screenPosition: { x: 5, y: 5 },
|
||||
});
|
||||
assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'open map');
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
assert.equal(radio.pickedRadioStationAt(tap()), null, 'window only');
|
||||
assert.equal(radio.pickedRadioStationAt(tap(station)), null, 'contact');
|
||||
assert.equal(
|
||||
radio.pickedRadioStationAt(tap(hit('radio:kuow'))),
|
||||
null,
|
||||
'another contact station',
|
||||
);
|
||||
assert.equal(radio.pickedRadioStationAt(tap(null, station)), null, 'exact');
|
||||
top = { sourceId: 'radio', entryId: 'radio:kexp' };
|
||||
assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'our own card');
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
SELECTION_FOLLOW_TRANSITION_S,
|
||||
} from '../../data/trackedCamera.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import {
|
||||
ACTIVATION_EXIT_ALTITUDE_M,
|
||||
@@ -203,6 +204,25 @@ test('a click on a train selects it; a click on the map lets it go', async (t) =
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a train under another
|
||||
// layer's card is neither selected nor let go.
|
||||
test("another layer's card over a train keeps the click", async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
const icons = app.drawn('icons');
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
app.click({ set: icons.spec.id, id: key, surface: false });
|
||||
assert.equal(app.state()._selectedKey ?? null, null, 'covered: not selected');
|
||||
top = null;
|
||||
app.click({ set: icons.spec.id, id: key, surface: false });
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
app.click(null);
|
||||
assert.equal(app.state()._selectedKey, key, 'covered: kept');
|
||||
});
|
||||
|
||||
test('a parked train, or one known from a single report, is flown to once', async (t) => {
|
||||
const app = harness(t);
|
||||
await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from './policy.js';
|
||||
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
@@ -173,6 +174,9 @@ export function createSelection({ state, services, parts }) {
|
||||
if (!state._enabled) return;
|
||||
// A held train keeps the selection until its view lets it go.
|
||||
if (state._cockpitSubjectKey) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
const key = trainKeyOf(event.drawHit);
|
||||
if (key) selectAndFocusTrain(key);
|
||||
else if (state._selectedKey) clearSelection();
|
||||
|
||||
@@ -7,7 +7,8 @@ export function createInteraction({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
|
||||
services.picking;
|
||||
|
||||
function _onKeyDown(e) {
|
||||
// The Cockpit owns Escape while it rides the tracked satellite.
|
||||
@@ -50,6 +51,9 @@ export function createInteraction({
|
||||
// The Cockpit camera rides the tracked satellite: a click on the
|
||||
// picture below must not untrack it or switch satellites.
|
||||
if (parts.cockpit?._cockpitHeld()) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard?.(event)) return;
|
||||
const picked = event.topHit;
|
||||
const hit = event.drawHit;
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createInteraction } from './interaction.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
|
||||
// The card or label painted on top takes the click: a satellite under another
|
||||
// layer's card is neither tracked nor let go.
|
||||
test("another layer's card over a satellite keeps the click", (t) => {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
let picked = null;
|
||||
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
|
||||
const input = fakeInput(viewer);
|
||||
const calls = [];
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_trackedNorad: null,
|
||||
_clickSubscription: null,
|
||||
_trackedEntityChangedRemove: () => {},
|
||||
_catalog: new Map([[25544, {}]]),
|
||||
};
|
||||
const interaction = createInteraction({
|
||||
state,
|
||||
services: { picking },
|
||||
parts: {
|
||||
rendering: {
|
||||
_hitIsTracked: () => false,
|
||||
_hitPointId: (hit) =>
|
||||
hit?.set === 'satellites:dots' ? Number(hit.id) : null,
|
||||
},
|
||||
tracking: {
|
||||
_cancelPendingTrackingRestore() {},
|
||||
_trackSatellite: (id) => calls.push(['track', id]),
|
||||
_clearTracking: () => calls.push(['clear']),
|
||||
},
|
||||
},
|
||||
});
|
||||
interaction._installClickHandler(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
picking.setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
picking.setClickCardHitTest(null);
|
||||
state._clickSubscription?.();
|
||||
input.destroy();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
const click = (hit) => {
|
||||
picked = hit ? { id: hit } : null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
};
|
||||
const dot = { set: 'satellites:dots', id: '25544' };
|
||||
click(dot);
|
||||
assert.deepEqual(calls, [], 'covered: not tracked');
|
||||
state._trackedNorad = 1;
|
||||
click(null);
|
||||
assert.deepEqual(calls, [], 'covered: tracking kept');
|
||||
top = null;
|
||||
click(null);
|
||||
assert.deepEqual(calls, [['clear']], 'open map lets it go');
|
||||
state._trackedNorad = null;
|
||||
click(dot);
|
||||
assert.deepEqual(calls.at(-1), ['track', 25544]);
|
||||
});
|
||||
@@ -277,12 +277,18 @@ export function createShipwrecksLayer({
|
||||
if (!clicks) return;
|
||||
_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) {
|
||||
if (_selectedLink) openExternal(_selectedLink);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours opens its source whatever is drawn
|
||||
// under it; another layer's is that layer's click, so the markers
|
||||
// under it do not act and the selection stays.
|
||||
const cardHit = picking.clickCard?.(click) ?? null;
|
||||
if (cardHit) {
|
||||
if (
|
||||
cardHit.sourceId === SHIPWRECKS_OVERLAY_SOURCE_ID &&
|
||||
cardHit.entryId === _selectedCardId &&
|
||||
_selectedLink
|
||||
)
|
||||
openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
// A marker's item id is its pick id, `shipwreck:<id>`. Read from what is
|
||||
|
||||
@@ -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 = [];
|
||||
@@ -47,6 +47,8 @@ function harness({ snapshots, now = () => 1 } = {}) {
|
||||
const { draw } = bindFakeDraw(viewer);
|
||||
const queue = [...(snapshots || [])];
|
||||
const requests = [];
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
picking.setClickCardHitTest((x, y) => cardHit(x, y));
|
||||
const layer = createShipwrecksLayer({
|
||||
source: {
|
||||
getSnapshot({ signal }) {
|
||||
@@ -59,7 +61,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 +395,49 @@ 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 and covered markers yield; bare markers 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);
|
||||
// A marker under another layer's card is that card's click too.
|
||||
h.pick('b');
|
||||
click();
|
||||
assert.equal(h.lastCard()[0].id, first.id, 'a covered marker yields');
|
||||
painted = [];
|
||||
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();
|
||||
}
|
||||
});
|
||||
@@ -23,8 +23,22 @@ export function createSelection({ state, parts }) {
|
||||
/** The id carries a provider's prefix: that provider handles the pick. */
|
||||
function onClick(event) {
|
||||
if (!state.viewer || !state.enabled) return;
|
||||
// Another layer's card or label painted on top takes the click, read once
|
||||
// per click so every layer agrees: no image, sequence or ground under it
|
||||
// opens. Street Level paints no cards of its own.
|
||||
if (picking?.isUnderOtherCard?.(event)) 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: an item of ours there is still ours.
|
||||
const contact = event.hit;
|
||||
const contactId =
|
||||
contact && !contact.surface
|
||||
? pickIdOf({ drawHit: contact.set ? contact : null, id: event.id })
|
||||
: null;
|
||||
const route =
|
||||
parts.router.resolve(windowId) ??
|
||||
(contactId ? parts.router.resolve(contactId) : null);
|
||||
// Not ours: the ground handler decides whether it is the map itself.
|
||||
if (!route) {
|
||||
parts.openAtGround?.({ surface: hit.surface, ground: groundOf(event) });
|
||||
|
||||
@@ -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({
|
||||
@@ -47,11 +48,13 @@ function harness({
|
||||
...sceneExtras,
|
||||
},
|
||||
};
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
pickRegistry.setClickCardHitTest(services.overlayHit ?? null);
|
||||
const state = {
|
||||
viewer,
|
||||
enabled: true,
|
||||
clickSubscription: null,
|
||||
services: { picking: null, input: null, ...services },
|
||||
services: { picking: pickRegistry, input: null, ...services },
|
||||
providers: new Map([
|
||||
[
|
||||
'mapillary',
|
||||
@@ -105,6 +108,7 @@ function harness({
|
||||
return event;
|
||||
},
|
||||
restore() {
|
||||
pickRegistry.setClickCardHitTest(null);
|
||||
selection.uninstall();
|
||||
globalThis.document = saved;
|
||||
},
|
||||
@@ -289,3 +293,179 @@ 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();
|
||||
}
|
||||
});
|
||||
|
||||
// The map itself under another layer's card or label is that card's click:
|
||||
// a ground click there must not also open the nearest street image.
|
||||
test("a click on the map under another layer's card opens no ground image", () => {
|
||||
let top = null;
|
||||
const h = harness({ services: { overlayHit: () => top } });
|
||||
try {
|
||||
h.click();
|
||||
assert.equal(
|
||||
h.groundClicks.length,
|
||||
1,
|
||||
'open map: the ground handler decides',
|
||||
);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
h.click();
|
||||
assert.equal(h.groundClicks.length, 1, 'under a card: the card keeps it');
|
||||
assert.deepEqual(h.opened, []);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// A coarse tap's touch contact reaches farther than this window: on open map
|
||||
// Street Level takes it; under another layer's card the card does.
|
||||
test('a coarse touch contact beyond our window is ours to open, unless a card is on top', (t) => {
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
const h = harness({
|
||||
services: { picking: pickRegistry, overlayHit: () => top },
|
||||
sceneExtras: {
|
||||
pick: () => null,
|
||||
drillPick: () => [{ id: 'mly:img:contact' }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, [], 'under a card: the card keeps it');
|
||||
top = null;
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['contact']);
|
||||
assert.equal(h.groundClicks.length, 0);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// The exact hit or the touch contact on our line part under another layer's
|
||||
// card is that card's click; on open map it selects the sequence its part
|
||||
// picks as.
|
||||
test('an exact or contact hit on our line part acts only with no card on top', (t) => {
|
||||
const part = {
|
||||
set: 'street-level:mapillary-coverage:1',
|
||||
id: 'mly:seq:abc#2',
|
||||
meta: { pick: 'mly:seq:abc' },
|
||||
};
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
const card = () => top;
|
||||
const exact = harness({ services: { overlayHit: card } });
|
||||
try {
|
||||
exact.scene.under = part;
|
||||
exact.click();
|
||||
assert.deepEqual(exact.sequences.selects, [], 'under a card');
|
||||
top = null;
|
||||
exact.click();
|
||||
assert.deepEqual(exact.sequences.selects, ['abc'], 'mouse, exact part');
|
||||
} finally {
|
||||
top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
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, [], 'coarse, under a card');
|
||||
top = null;
|
||||
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.
|
||||
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 },
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
// Under another layer's card nothing of ours opens, whatever our window or the
|
||||
// tap's touch contact names; on open map our window's item opens.
|
||||
test('under a card, neither our window item nor our touch contact opens', (t) => {
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
const h = harness({
|
||||
services: { picking: pickRegistry, overlayHit: () => top },
|
||||
sceneExtras: {
|
||||
pick: (_position, width = 3) =>
|
||||
width >= 9 ? { id: 'mly:img:window' } : null,
|
||||
drillPick: () => [{ id: 'mly:img:contact' }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, []);
|
||||
assert.equal(h.groundClicks.length, 0);
|
||||
top = null;
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['window']);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
@@ -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,7 @@ export function createSubmarineCableLayer({
|
||||
parts,
|
||||
source,
|
||||
inputFor,
|
||||
picking,
|
||||
mapStackEventTarget,
|
||||
};
|
||||
parts.rendering = createRendering(context);
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { toRadians } from '../../geo/vector.js';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
|
||||
export function createInteraction({ state, parts, inputFor }) {
|
||||
export function createInteraction({ state, parts, inputFor, picking }) {
|
||||
function beginInteraction(viewer) {
|
||||
if (state._clickSubscription) return;
|
||||
state._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!state._enabled) return;
|
||||
// Cable labels are not interactive, so any card or label painted on
|
||||
// top is another layer's, painted over the cable: its click.
|
||||
if (picking?.clickCard?.(event)) return;
|
||||
const record = resolvePickRecord(event.drawHit);
|
||||
if (!record?.reference) return;
|
||||
flyToReference(viewer, record.reference);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
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 },
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
picking: { clickCard: () => 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',
|
||||
);
|
||||
});
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
uninstallRenderGovernor,
|
||||
} from '../../renderGovernor.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { bindRenderer, rendererOf } from '../../render/rendererOf.js';
|
||||
@@ -3745,6 +3746,30 @@ test('click handler selects a migrated scripted billboard and prepares its drape
|
||||
assert.equal(entry.marker.show, true);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a vehicle under another
|
||||
// layer's card is neither selected nor released.
|
||||
test("another layer's card over a vehicle keeps the click", async (t) => {
|
||||
const app = harness(t, { floorAt: () => undefined });
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
app.layer.enable(app.viewer);
|
||||
app.layer._loadTransitFleetForTest(4, BOSTON, 70);
|
||||
const [first, second] = app.vehicles();
|
||||
app.viewer.scene.pick = () => app.pickOf(first);
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
assert.equal(app.state()._selectedKey, null, 'covered: not selected');
|
||||
top = null;
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
assert.equal(app.state()._selectedKey, first.key);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
app.viewer.scene.pick = () => app.pickOf(second);
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
app.viewer.scene.pick = () => undefined;
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
assert.equal(app.state()._selectedKey, first.key, 'covered: kept');
|
||||
});
|
||||
|
||||
test('intercepted scripted reports resolve their explicit floor and wake without a preRender bootstrap', async (t) => {
|
||||
const app = harness(t, { floorAt: () => undefined });
|
||||
app.layer._setTransitFixtureFloorsForTest(['mbta:sim-straight'], 20);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from './policy.js';
|
||||
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
@@ -151,6 +152,9 @@ export function createSelection({ state, services, parts }) {
|
||||
collection:
|
||||
set === 'moving' ? 'animated' : set === 'still' ? 'stationary' : null,
|
||||
};
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
if (key) {
|
||||
selectVehicle(key, { byUser: true });
|
||||
return;
|
||||
|
||||
@@ -30,8 +30,23 @@ export function createSelection({
|
||||
// The bridge view owns the selection: a click on open water must not
|
||||
// deselect the vessel the camera is riding.
|
||||
if (state.cockpitSubjectId) return;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: a card of ours acts whatever is drawn
|
||||
// under it; another layer's is that layer's click.
|
||||
const top = services.picking.clickCard?.(event) ?? null;
|
||||
if (top) {
|
||||
if (top.sourceId !== VESSEL_OVERLAY_SOURCE_ID) return;
|
||||
const id = String(top.entryId || '').startsWith('vessel:')
|
||||
? top.entryId.slice('vessel:'.length)
|
||||
: null;
|
||||
const carded = id ? state.records.byId.get(id) || null : null;
|
||||
// A stale card id is not empty terrain and must not clear a newer
|
||||
// selection. The next paint will evict its hit rectangle.
|
||||
if (carded) selectAndFocusVessel(carded);
|
||||
return;
|
||||
}
|
||||
const pickedId = event.id;
|
||||
let record = pickedId ? state.records.byId.get(pickedId) : null;
|
||||
const record = pickedId ? state.records.byId.get(pickedId) : null;
|
||||
// A vessel icon's pick is an item of the layer's icon set, whose id is
|
||||
// its row id: the record's id, or an unkeyed row's. Removing a row
|
||||
// removes its item, so an evicted vessel cannot be picked at all; a
|
||||
@@ -44,49 +59,19 @@ export function createSelection({
|
||||
|
||||
// An own-layer row without a live map key is a strict no-op (FB-1
|
||||
// residual). Trails carry no layer identity and hug their contacts, so any
|
||||
// `gev-trail:*` pick is also a no-op. Every other non-vessel pick — sibling
|
||||
// unowned scene picks dismiss the current vessel inspection.
|
||||
// `gev-trail:*` pick is also a no-op. A pick a sibling layer owns (an
|
||||
// aircraft, a route, a cyclone) is that layer's: preserve the current
|
||||
// vessel selection and do not compete with its camera command. Every
|
||||
// other non-vessel pick dismisses the current vessel inspection.
|
||||
if (ownRecordPick && (!pickedId || !record)) return;
|
||||
if (pickedId && !record && String(pickedId).startsWith('gev-trail:'))
|
||||
if (
|
||||
!record &&
|
||||
pickedId &&
|
||||
(String(pickedId).startsWith('gev-trail:') ||
|
||||
isOwnedByOtherLayer('ais-live-vessels', pickedId))
|
||||
)
|
||||
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);
|
||||
// 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;
|
||||
|
||||
// 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
|
||||
// actionable hit rectangles before treating the click as empty space.
|
||||
const cardHit = !record
|
||||
? vesselState._vesselOverlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{
|
||||
...(cycloneBackground
|
||||
? {}
|
||||
: { sourceId: VESSEL_OVERLAY_SOURCE_ID }),
|
||||
},
|
||||
)
|
||||
: null;
|
||||
if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
|
||||
return;
|
||||
if (!record && cardHit) {
|
||||
const id = String(cardHit.entryId || '').startsWith('vessel:')
|
||||
? cardHit.entryId.slice('vessel:'.length)
|
||||
: null;
|
||||
record = id ? state.records.byId.get(id) || null : null;
|
||||
// A stale card id is not empty terrain and must not clear a newer
|
||||
// selection. The next paint will evict its hit rectangle.
|
||||
if (!record) return;
|
||||
}
|
||||
|
||||
if (record) {
|
||||
// A valid sprite or card click always transfers the camera exactly once,
|
||||
// including a second click on the already-selected vessel.
|
||||
|
||||
@@ -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) {
|
||||
@@ -220,6 +221,8 @@ function harness(
|
||||
unregisterPickOwner: (id) => owners.delete(id),
|
||||
resolvePickId: (pick) => pick?.id ?? pick?.primitive?.id,
|
||||
isOwnedByOtherLayer: (_layerId, id) => id?.startsWith('other:'),
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
clickCard: () => cardHit,
|
||||
},
|
||||
sprites: { spriteDrawOrder: () => -9 },
|
||||
render: { governorRequestRender: (reason) => renders.push(reason) },
|
||||
|
||||
@@ -482,19 +482,13 @@ export function createSelection({ state, services, parts }) {
|
||||
state.clickHandler = input.onClick((click) => {
|
||||
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,
|
||||
});
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours acts whatever is drawn under it;
|
||||
// another layer's is that layer's click, so the sightings under it do
|
||||
// not act and the selection stays.
|
||||
const hit = services.picking?.clickCard?.(click) ?? null;
|
||||
if (hit) {
|
||||
hit.entry?.activate?.();
|
||||
if (sourceIds.includes(hit.sourceId)) hit.entry?.activate?.();
|
||||
return;
|
||||
}
|
||||
// A sighting icon's item id is its pick id, `wildlife:<stableId>`.
|
||||
|
||||
@@ -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 = {
|
||||
@@ -42,16 +43,17 @@ function fixture(sighting = row, extraServices = {}) {
|
||||
},
|
||||
};
|
||||
bindWildlifeViewer(state.viewer);
|
||||
const overlayHost = {
|
||||
setEntries: (id, value) => entries.set(id, value),
|
||||
clearSource: (id) => entries.delete(id),
|
||||
setVisible() {},
|
||||
hitTest: (_x, _y, { sourceId } = {}) =>
|
||||
sourceId ? (hit?.sourceId === sourceId ? hit : null) : coveringHit || hit,
|
||||
};
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {
|
||||
overlayHost: {
|
||||
setEntries: (id, value) => entries.set(id, value),
|
||||
clearSource: (id) => entries.delete(id),
|
||||
setVisible() {},
|
||||
hitTest: (_x, _y, { sourceId }) =>
|
||||
hit?.sourceId === sourceId ? hit : null,
|
||||
},
|
||||
overlayHost,
|
||||
now: () => row.observedAt + 60_000,
|
||||
project: (_scene, anchor) => {
|
||||
projections++;
|
||||
@@ -66,6 +68,12 @@ function fixture(sighting = row, extraServices = {}) {
|
||||
}),
|
||||
eventTarget: new EventTarget(),
|
||||
...extraServices,
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
picking: {
|
||||
clickCard: (c) =>
|
||||
overlayHost.hitTest(c.screenPosition?.x, c.screenPosition?.y),
|
||||
...extraServices.picking,
|
||||
},
|
||||
},
|
||||
parts: {
|
||||
rendering: {
|
||||
@@ -94,6 +102,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 +190,38 @@ test('selected photo and name cards use the selected lane, select on click and n
|
||||
}
|
||||
});
|
||||
|
||||
test('a covered sighting label and icon yield; 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);
|
||||
// A sighting icon under another layer's card is that card's click too.
|
||||
f.click();
|
||||
assert.equal(f.flights.length, 1, 'a covered sighting does not act');
|
||||
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, 2, 'the label acts over a flight trail');
|
||||
// And over another layer's scene item.
|
||||
f.click('other:aircraft');
|
||||
assert.equal(f.flights.length, 3, '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,
|
||||
|
||||
@@ -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'),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WORLD_OVERLAY_OCCLUDER_SELECTORS } from './worldOverlayChrome.js';
|
||||
import { setClickCardHitTest } from '../data/pickRegistry.js';
|
||||
export { WORLD_OVERLAY_OCCLUDER_SELECTORS } from './worldOverlayChrome.js';
|
||||
import {
|
||||
createCyberSonarSampler,
|
||||
@@ -884,7 +885,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 +2786,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;
|
||||
}
|
||||
@@ -2868,6 +2870,8 @@ export function initWorldOverlay(viewer) {
|
||||
};
|
||||
window.addEventListener('gev:cockpit-mode-changed', _cockpitModeHandler);
|
||||
_removePostRender = frame.on('postRender', () => drawWorldOverlay());
|
||||
// Click handlers read the card painted on top through the pick registry.
|
||||
setClickCardHitTest(hitTestWorldOverlay);
|
||||
_removeMoveEnd = camera.on('moveEnd', () => invalidateHost());
|
||||
installUiOccluderObservers();
|
||||
// The backing store and the occluder inventory are both deferred to the
|
||||
@@ -2953,6 +2957,7 @@ export function destroyWorldOverlay() {
|
||||
_paintCount = 0;
|
||||
_paintRectCount = 0;
|
||||
_hitRectCount = 0;
|
||||
setClickCardHitTest(null);
|
||||
_uiOcclusionRects.length = 0;
|
||||
_uiOcclusionRectPool.length = 0;
|
||||
_destroyed = hadHost || _destroyed;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -2,15 +2,93 @@ import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { recordCameraGoldens } from './cameraGoldens.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.
|
||||
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);
|
||||
// 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') {
|
||||
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));
|
||||
});
|
||||
|
||||
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 }));
|
||||
});
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { nextTick } from 'vue';
|
||||
import { isPointerFree } from '../data/inputOwnership.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../data/pickRegistry.js';
|
||||
import { createInteractionSession } from '../director/interactions/session.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
|
||||
@@ -119,6 +120,9 @@ export function createSceneInteractions(
|
||||
session.activate(items);
|
||||
unsubscribeClick = inputFor(viewer).onClick((event) => {
|
||||
if (panel?.owner !== owner || !shown() || !available()) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
// A pack feature is its draw set's item (see dataPacks/presentation.js).
|
||||
const hit = event.drawHit;
|
||||
if (!hit) return;
|
||||
|
||||
@@ -10,6 +10,8 @@ import { createPinia } from 'pinia';
|
||||
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
|
||||
import SceneInteractions from '../ui/views/panels/SceneInteractions.vue';
|
||||
import { createSceneInteractions } from './interactions.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../data/pickRegistry.js';
|
||||
|
||||
const target = (featureId) => ({ packId: 'qa', featureId });
|
||||
const key = (featureId) => JSON.stringify(['qa', featureId]);
|
||||
@@ -192,3 +194,39 @@ test("an earlier owner leaves a later owner's panel alone", async (t) => {
|
||||
await settle();
|
||||
assert.equal(later.getState().selected, 'fly');
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a pack feature under
|
||||
// another layer's card is not selected for its actions.
|
||||
test("another layer's card over a pack feature keeps the click", async (t) => {
|
||||
document.body.replaceChildren();
|
||||
const container = document.body.appendChild(document.createElement('div'));
|
||||
const canvas = container.appendChild(document.createElement('canvas'));
|
||||
const pinia = createPinia();
|
||||
const app = createApp(SceneInteractions).use(pinia);
|
||||
app.mount(document.body.appendChild(document.createElement('div')));
|
||||
let picked = null;
|
||||
const viewer = { container, scene: { canvas, pick: () => picked } };
|
||||
const input = fakeInput(viewer);
|
||||
const store = useSceneInteractionsStore(pinia);
|
||||
const interactions = createSceneInteractions(viewer, {
|
||||
execute: async () => true,
|
||||
store,
|
||||
});
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
setClickCardHitTest(null);
|
||||
interactions.destroy();
|
||||
input.destroy();
|
||||
app.unmount();
|
||||
});
|
||||
const feature = { set: 'qa:points', id: 'point' };
|
||||
interactions.activate(SHOT, new Map([[key('point'), feature]]));
|
||||
await nextTick();
|
||||
picked = { id: feature, primitive: {} };
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.deepEqual(store.panel?.outlined ?? [], [], 'covered: not selected');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.deepEqual(store.panel.outlined, ['card', 'fly']);
|
||||
});
|
||||
@@ -219,7 +219,6 @@ export class StyleManager extends ShellFacade {
|
||||
pinia: applicationPinia(),
|
||||
pickWorld: services.pickWorldFromScreen,
|
||||
regionalBrief: services.fetchRegionalBrief,
|
||||
overlayHit: services.hitTestWorldOverlay,
|
||||
});
|
||||
this.mapStackController = mapStackController;
|
||||
this.placeSearch = placeSearch;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../data/pickRegistry.js';
|
||||
import { findQuery } from '../render/rendererOf.js';
|
||||
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
|
||||
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
|
||||
@@ -286,7 +287,12 @@ export function routeSceneClick() {
|
||||
// A viewer with no input (headless tools, partial stubs) has no clicks.
|
||||
return () => {};
|
||||
}
|
||||
return input.onClick((event) => this.onOrbitalClick(event?.position));
|
||||
return input.onClick((event) => {
|
||||
// Another layer's card or label painted on top takes the click: the site
|
||||
// under it does not focus, and the click does not end a held focus.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
this.onOrbitalClick(event?.position);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -31,6 +31,7 @@ import CockpitView from './views/CockpitView.vue';
|
||||
import ContextView from './views/ContextView.vue';
|
||||
import IntelHudView from './views/IntelHudView.vue';
|
||||
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
|
||||
import { setClickCardHitTest } from '../data/pickRegistry.js';
|
||||
import { ORBITAL_FOCUS_EASE_TAU_MS } from '../cockpitOrbitalFocus.js';
|
||||
import { ORBITAL_HOP_MS } from '../cockpitOrbitalSatellites.js';
|
||||
|
||||
@@ -648,6 +649,23 @@ test('a click a tool owns is left alone', async (t) => {
|
||||
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'kept while drawing');
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a site under another
|
||||
// layer's card does not focus, and a click there does not end a held focus.
|
||||
test('another layer\'s card over the orbital view keeps the click', async (t) => {
|
||||
const scene = await inOrbit(t);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
scene.click(SITES.alpha.at);
|
||||
assert.equal(scene.cockpit.orbital.focus ?? null, null, 'covered: no focus');
|
||||
top = null;
|
||||
scene.click(SITES.alpha.at);
|
||||
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
scene.click(EMPTY_GROUND);
|
||||
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'covered: kept');
|
||||
});
|
||||
|
||||
test('a double-click on a site focuses it and keeps the orbital view', async (t) => {
|
||||
const scene = await inOrbit(t);
|
||||
const { cockpit, viewer, handler } = scene;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { resolvePickedContext } from '../data/pickedContext.js';
|
||||
import { clickCard } from '../data/pickRegistry.js';
|
||||
import { followedOf, onFollowChanged } from '../data/followed.js';
|
||||
import { fromDegreesInto } from '../geo/ellipsoid.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
@@ -45,8 +46,6 @@ const FOLLOWABLE = new Set(['flights', 'military', 'satellites']);
|
||||
* to the point under the camera without it.
|
||||
* @param {(lat: number, lon: number) => Promise<object>} [options.regionalBrief]
|
||||
* The app's regional brief service, for the weather and news Context shows.
|
||||
* @param {(x: number, y: number) => object|null} [options.overlayHit]
|
||||
* The overlay card under a screen point, if any (a vessel's, a fire's).
|
||||
* @returns {() => void} disconnects
|
||||
*/
|
||||
export function installEntityContext({
|
||||
@@ -55,7 +54,6 @@ export function installEntityContext({
|
||||
pinia,
|
||||
pickWorld,
|
||||
regionalBrief,
|
||||
overlayHit,
|
||||
}) {
|
||||
const store = useEntityCardStore(pinia);
|
||||
const omnibar = useOmnibarStore(pinia);
|
||||
@@ -318,6 +316,10 @@ export function installEntityContext({
|
||||
// Cockpit has its own picks, and Context is hidden while it runs. A
|
||||
// camera drag never selects, even if it ends over something.
|
||||
if (inCockpit() || !isTrackingSelectionGesture(event.gesture)) return;
|
||||
// A card or label painted on top is its layer's click, read once per
|
||||
// click so every layer agrees: Context names nothing under it and keeps
|
||||
// its own card as it is.
|
||||
if (clickCard(event)) return;
|
||||
const identity = resolvePickedContext(event.hit, {
|
||||
dataManager: getDataManager(),
|
||||
});
|
||||
@@ -331,14 +333,8 @@ export function installEntityContext({
|
||||
// A click on open ground, sea or sky lets go of what was selected. A
|
||||
// click on something else Context cannot describe (a label, a trail)
|
||||
// leaves the card as it is.
|
||||
// Only a clean click lets go, as the layers' own clicks do; a card
|
||||
// painted on the overlay (a vessel's, a fire's) is not open map.
|
||||
if (
|
||||
event.surface &&
|
||||
isTrackingClickGesture(event.gesture) &&
|
||||
!overlayHit?.(event.screenPosition?.x, event.screenPosition?.y)
|
||||
)
|
||||
store.clear();
|
||||
// Only a clean click lets go, as the layers' own clicks do.
|
||||
if (event.surface && isTrackingClickGesture(event.gesture)) store.clear();
|
||||
});
|
||||
|
||||
// Layers that select through the context store (GeoJSON sites, fires,
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
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,
|
||||
setClickCardHitTest,
|
||||
unregisterPickOwner,
|
||||
} from '../data/pickRegistry.js';
|
||||
|
||||
// The card or label painted on top takes the click: Context names nothing
|
||||
// under it, exact or nearby, an acting owner's item or a passive one, and
|
||||
// keeps its own card. On open map it names what the click found.
|
||||
test('Context names nothing under a card painted on top, and keeps its card', (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' };
|
||||
const plane = { set: 'test-planes:1', id: 'plane:1' };
|
||||
const route = { set: 'test-route:1', id: 'route:line' };
|
||||
registerPickOwner('test-fires', (id) => id === fire.id);
|
||||
registerPickOwner('test-planes', (id) => id === plane.id);
|
||||
registerPickOwner('test-route', (id) => id.startsWith('route:'));
|
||||
let cardOnTop = false;
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
setClickCardHitTest(() =>
|
||||
cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
|
||||
);
|
||||
t.after(() => {
|
||||
setClickCardHitTest(null);
|
||||
unregisterPickOwner('test-fires');
|
||||
unregisterPickOwner('test-planes');
|
||||
unregisterPickOwner('test-route');
|
||||
});
|
||||
let exact = null;
|
||||
let near = null;
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => (exact ? { id: exact } : null),
|
||||
drillPick: () => (near ? [{ id: near }] : []),
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const pinia = createPinia();
|
||||
const disconnect = installEntityContext({
|
||||
viewer,
|
||||
getDataManager: () => ({
|
||||
isEnabled: () => true,
|
||||
layers: new Map(),
|
||||
getAll: () => [],
|
||||
}),
|
||||
pinia,
|
||||
});
|
||||
t.after(() => {
|
||||
disconnect();
|
||||
input.destroy();
|
||||
});
|
||||
const store = useEntityCardStore(pinia);
|
||||
const named = [];
|
||||
let clears = 0;
|
||||
store.select = (identity) => named.push(identity.id);
|
||||
store.clear = () => clears++;
|
||||
const tap = (hitExact, hitNear) => {
|
||||
exact = hitExact;
|
||||
near = hitNear;
|
||||
named.length = 0;
|
||||
input.click();
|
||||
return [...named];
|
||||
};
|
||||
assert.deepEqual(tap(null, fire), ['fire:1'], 'open map: a near fire');
|
||||
assert.deepEqual(tap(route, null), ['route:line'], 'open map: a route');
|
||||
cardOnTop = true;
|
||||
assert.deepEqual(tap(null, fire), [], 'under a card: a near fire');
|
||||
assert.deepEqual(tap(fire, fire), [], 'under a card: an exact fire');
|
||||
assert.deepEqual(tap(plane, plane), [], 'under a card: an aircraft');
|
||||
assert.deepEqual(tap(route, null), [], 'under a card: a route');
|
||||
const cleared = clears;
|
||||
tap(null, null);
|
||||
assert.equal(clears, cleared, 'a card over open map is not open map');
|
||||
});
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user