Merge origin/main into space-missions-fixes

Main's single click rule (the card or label on top takes the click, read
once per click through clickCard and isUnderOtherCard in
src/data/pickRegistry.js) covers a click on a Space Missions label: a
mission marker label is an interactive world-overlay entry, so the
host's hit test names it as the card on top for every other layer. The
per-layer label guards in CCTV, Drone Airspace, FIRMS, Ghost Maps, News,
Perimeters, Shipwrecks, Vessels, Wildlife Sightings, ALPR, Local ADS-B
and the cockpit orbital focus are dropped for main's versions.

The mission-label tests are kept on main's API: fakeInputUnderLabel now
also names the label as the card on top, and each test shows a click on
the label never acts on the card, camera, vessel, fire, reader, aircraft
or report under it, and leaves the selection as it is. A launches test
checks that a mission label is interactive and is the card on top for
every other layer. Docs, changelog and the dispatcher's `overlay` note
describe the merged behaviour.

Co-authored-by: Manjunath Paparaju <[email protected]>
This commit is contained in:
Sameh KhamisandManjunath Paparaju committed 2026-11-18 20:00:25 -08:00
commit 0e5c5e624c
146 files changed
+9734 -1157

No files matched your search

+5 -2
View File
@@ -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,11 +582,13 @@ 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.
// A click a label painted over both took is on neither.
const hit = event.drawHit;
const id =
(!event.overlay && overlay.pick(event.screenPosition)) ||
overlay.pick(event.screenPosition) ||
(hit && hit.set === markers.icons?.id ? hit.id : null);
if (
id &&
+57 -3
View File
@@ -1,7 +1,8 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { createAlprMarkerSet } from './markerState.js';
@@ -105,7 +106,7 @@ function harness(t) {
return { state, fake, at: { x: 100, y: 100 } };
}
test('a click a label painted over a camera takes never selects it, and lets go of the selected camera', (t) => {
test('a click on a mission label over a camera never selects it, and keeps the selected camera', (t) => {
const h = harness(t);
h.fake.label.over = true;
h.fake.click(h.at);
@@ -116,7 +117,60 @@ test('a click a label painted over a camera takes never selects it, and lets go
h.fake.click(h.at);
assert.equal(h.state.selectedId, 'camera:0');
// The label on top is its own click: the selection stays.
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, null, 'the selection is let go');
assert.equal(h.state.selectedId, 'camera:0', 'the selection stays');
});
// 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');
});
+4
View File
@@ -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) {
+68
View File
@@ -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');
});
+20 -27
View File
@@ -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,32 +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. A
// click a label painted over the cards took is not on a card.
const cardId = event.overlay
? null
: 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,
+198 -13
View File
@@ -1,11 +1,12 @@
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, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
function viewerWithCamera() {
const camera = fakeCameraPort();
@@ -83,10 +84,13 @@ const inert = (own = {}) =>
get: (target, name) => (name in target ? target[name] : () => {}),
});
test("a click a label painted over a camera's card takes never turns that camera on, and lets go of the active one", async (t) => {
test("a click on a mission label over a camera's card never turns that camera on, and keeps the active one", async (t) => {
const { viewer } = viewerWithCamera();
viewer.scene = { canvas: {}, pick: () => null };
const fake = fakeInputUnderLabel(viewer);
// The card of camera `cam-1` lies under every click, under the label.
const fake = fakeInputUnderLabel(viewer, {
beneath: () => ({ sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }),
});
t.after(() => fake.destroy());
const activated = [];
const deactivated = [];
@@ -97,7 +101,7 @@ test("a click a label painted over a camera's card takes never turns that camera
activation: {
activateCctvCameraFromWorldClick: (id) => activated.push(id),
},
picking: { resolvePickId },
picking,
focus: {},
render: {},
},
@@ -125,7 +129,7 @@ test("a click a label painted over a camera's card takes never turns that camera
bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick),
extractPickedCameraId: () => null,
cctvEmptyClickDeselects: (picked, { activeCameraId }) =>
Boolean(activeCameraId) && resolvePickId(picked) === null,
Boolean(activeCameraId) && picking.resolvePickId(picked) === null,
deactivateActiveCamera: () => deactivated.push(state._activeCameraId),
},
},
@@ -137,19 +141,200 @@ test("a click a label painted over a camera's card takes never turns that camera
state._enabled = true;
state._activeCameraId = 'cam-0';
state._recordById.set('cam-1', {});
// The card of camera `cam-1` lies under every click.
state._cctvOverlayHost = {
hitTest: (_x, _y, { sourceId }) =>
sourceId === CCTV_OVERLAY_SOURCE_ID ? { entryId: 'cam-1' } : null,
};
fake.label.over = true;
fake.click();
assert.deepEqual(activated, [], 'the camera under the label stays off');
assert.deepEqual(deactivated, ['cam-0'], 'the active camera is let go');
assert.deepEqual(deactivated, [], 'the active camera stays on');
// Off the label, a click on the card turns its camera on.
fake.label.over = false;
fake.click();
assert.deepEqual(activated, ['cam-1']);
});
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']);
});
+10 -62
View File
@@ -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 = {
+19 -45
View File
@@ -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');
+3
View File
@@ -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;
+5 -9
View File
@@ -130,15 +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) => {
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: 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) {
+68 -11
View File
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createDroneAirspaceLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -48,6 +49,11 @@ 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.
// A mission label painted over everything comes first.
clickCard: (click) =>
clickCard(click) ??
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
});
layer.init(viewer);
@@ -146,7 +152,7 @@ test('clicking a zone publishes its card; empty space clears it', async () => {
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
});
test('a click a label painted over the open zone card takes closes the card, as a click beside it does', async () => {
test('a click on a mission label over the open zone card keeps it open and takes no zone beneath', async () => {
let pickResult = null;
let cardHitResult = null;
const h = harness(
@@ -158,23 +164,74 @@ test('a click a label painted over the open zone card takes closes the card, as
h.clicks.handler({ position: { x: 10, y: 10 } });
const [card] = h.overlay.entries.get('drone-airspace');
// Off the label, a click on the open card keeps it open.
pickResult = null;
cardHitResult = { entryId: card.id };
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.length, 1);
// The open card lies under the label: the click is not on the card.
// The open card and its zone lie under the label: the label on top is
// its own click, so the card stays open.
cardHitResult = { sourceId: 'drone-airspace', entryId: card.id };
h.label.over = true;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.[0]?.id, card.id);
pickResult = null;
cardHitResult = null;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(
h.overlay.entries.get('drone-airspace')?.length ?? 0,
0,
'the card is closed',
h.overlay.entries.get('drone-airspace')?.[0]?.id,
card.id,
'a label over bare map is not empty space either',
);
// Off the label, the same click on bare map closes the card.
h.label.over = false;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
h.layer.destroy();
});
// 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
View File
@@ -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;
+332
View File
@@ -23,6 +23,12 @@ export const EARTHQUAKE_MARK_MAGNITUDE = 6;
/** The longest place a timeline mark's label carries, ellipsis and all. */
const MARK_PLACE_LENGTH = 40;
/**
* The longest place line the detail card shows, ellipsis and all, so a long
* place or translation keeps the card inside a phone's width. The card's
* accessible name carries the whole place.
*/
const CARD_PLACE_LENGTH = 48;
/** A magnitude as the map's labels show it: `M6.4`. */
export const earthquakeMagnitudeTitle = (magnitude) =>
@@ -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,
+9 -4
View File
@@ -28,10 +28,15 @@ export function normalizeEarthquakeSnapshot(geojson) {
return null;
// A missing magnitude cannot establish that this event meets M2.5+.
if (mag == null || mag < 2.5) continue;
const stableId =
feature.id == null || feature.id === ''
? `event-${index + 1}`
: String(feature.id);
// An id-less event is named by what it is (time, position, depth and
// magnitude), not by its row, so a refresh that inserts a row keeps the
// selection on the same quake; a revision to any of those names a new
// one. Two id-less events that match exactly fall back to the row.
const idless = feature.id == null || feature.id === '';
let stableId = idless
? `event-${[properties.time ?? 'na', lon, lat, depthKm ?? 'na', mag].join(':')}`
: String(feature.id);
if (idless && ids.has(stableId)) stableId = `${stableId}:${index + 1}`;
if (ids.has(stableId)) return null;
ids.add(stableId);
rows.push({
+28 -3
View File
@@ -37,7 +37,7 @@ test('normalizeEarthquakeSnapshot parses valid GeoJSON earthquake features', ()
});
});
test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is missing or blank', () => {
test('normalizeEarthquakeSnapshot names id-less events by their content, not their row', () => {
const geojson = {
features: [
{
@@ -55,10 +55,35 @@ test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is mi
const rows = normalizeEarthquakeSnapshot(geojson);
assert.equal(rows.length, 2);
assert.equal(rows[0].stableId, 'event-1');
assert.equal(rows[0].stableId, 'event-1711930000000:139.6917:35.6895:25:3.5');
assert.equal(rows[0].usgsId, null);
assert.equal(rows[1].stableId, 'event-2');
assert.equal(
rows[1].stableId,
'event-1711931000000:-70.6693:-33.4489:45.2:5.1',
);
assert.equal(rows[1].usgsId, '');
// A row inserted ahead of them keeps each id-less quake's id, so a selected
// one stays selected across the refresh.
const inserted = normalizeEarthquakeSnapshot({
features: [
{
id: 'us7000new',
geometry: { type: 'Point', coordinates: [10, 20, 5] },
properties: { mag: 4, place: 'New', time: 1711932000000 },
},
...geojson.features,
],
});
assert.deepEqual(
inserted.map((row) => row.stableId).slice(1),
rows.map((row) => row.stableId),
);
// Two id-less events that match exactly stay apart.
const twins = normalizeEarthquakeSnapshot({
features: [geojson.features[0], geojson.features[0]],
});
assert.equal(twins.length, 2);
assert.notEqual(twins[0].stableId, twins[1].stableId);
});
test('normalizeEarthquakeSnapshot filters events below M2.5 without dropping the feed', () => {
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -76,7 +76,10 @@ export function createCards({
const height = canvas.clientHeight;
let ambientCount = 0;
for (const candidate of layerState._labelCandidates) {
// An application drawing the detections in place of the markers draws
// them unlabelled: only the selected fire's card shows then.
const candidates = layerState._standIn ? [] : layerState._labelCandidates;
for (const candidate of candidates) {
if (ambientCount >= MAX_AMBIENT_LABELS) break;
if (candidate.fire && candidate.fire === layerState._selectedFire)
continue;
+31 -2
View File
@@ -52,10 +52,12 @@ export function createLifecycle({
if (layerState._cells) layerState._cells.show = true;
// The GPU culls the far side each frame, so retained rows are right
// for wherever the camera went while the layer was off.
if (layerState._icons) layerState._icons.show = true;
if (layerState._icons) layerState._icons.show = !layerState._standIn;
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, true);
// A filter can leave an old raster cached while the current set is empty.
layerState._heatImagery?.setShow(layerState._fires.length > 0);
layerState._heatImagery?.setShow(
layerState._fires.length > 0 && !layerState._standIn,
);
// The camera can have crossed the hand-off while the layer was off.
components.rendering.applyHandoffFade(true);
components.viewport.installLodWatcher();
@@ -68,6 +70,32 @@ export function createLifecycle({
await components.ingestion.loadHeatmap();
},
/**
* Let an application draw the detections in place of the layer's
* markers. While a stand-in is set, the glows, the heatmap and the
* ambient cards are hidden and everything else works as before: a click
* on a fire the stand-in draws (`standIn.hitTest(screenPosition)`, which
* answers a detection record from the same source, or null) selects it
* and moves the camera to it as a click on its marker does, the selected
* fire's card shows, and a click on empty space clears the selection.
* Its optional `focusRangeM(record)` gives how far, in metres, the camera
* stands from a fire it draws when moving to it, for fires drawn larger
* than a marker; without one, or for null, the usual fire framing holds.
* `null` brings the markers back. The selection is kept either way.
* @param {?{hitTest: (screenPosition: {x: number, y: number}) => ?Object, focusRangeM?: (record: Object) => ?number}} standIn
*/
setMarkerStandIn(standIn) {
layerState._standIn =
typeof standIn?.hitTest === 'function' ? standIn : null;
layerState._heatImagery?.setShow(
layerState._enabled &&
layerState._fires.length > 0 &&
!layerState._standIn,
);
components.rendering.applyHandoffFade(true);
components.cards.rebuildAmbientLabels();
},
disable() {
layerState.request?.abort();
layerState.request = null;
@@ -129,6 +157,7 @@ export function createLifecycle({
layerState._currentLodIndex = -1;
layerState._lastViewRect = null;
layerState._selectedFire = null;
layerState._standIn = null;
layerState._labelCandidates = [];
layerState._labelLodDistance = 0;
layerState._pickIndexById.clear();
+6 -3
View File
@@ -122,7 +122,7 @@ export function createRendering({
glowAlpha = alpha;
const set = layerState._icons;
if (!set) return;
set.show = layerState._enabled && heat < 1;
set.show = layerState._enabled && !layerState._standIn && heat < 1;
if (!changed || !drawnGlows.size) return;
const faded = [];
for (const drawn of drawnGlows.values()) {
@@ -273,7 +273,7 @@ export function createRendering({
// The map stack may have changed since the last render.
imagery.rehome();
ensureHeatRaster(now);
imagery.setShow(layerState._enabled);
imagery.setShow(layerState._enabled && !layerState._standIn);
}
/**
@@ -469,7 +469,10 @@ export function createRendering({
// Blended as one translucent pass, as its billboards were.
blend: 'translucent',
horizonCull: true,
show: layerState._enabled && !(layerState._handoffHeat >= 1),
show:
layerState._enabled &&
!layerState._standIn &&
!(layerState._handoffHeat >= 1),
drawOrder: spriteDrawOrder?.('firms') ?? 0,
});
// Columns of no rows put the set's host in the scene now, rather than
+56 -25
View File
@@ -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,33 +34,33 @@ export function createSelection({
if (layerState._clickSubscription || !layerState._viewer) return;
const input = inputFor(layerState._viewer);
layerState._clickSubscription = input.onClick((event) => {
const picked = event.topHit;
const fire = pickedFire(event.drawHit);
// 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
// layer's item is on top, as a marker under that item would not be hit.
const fire = layerState._standIn
? otherLayer
? null
: standInFire(event.position ?? event.screenPosition)
: pickedFire(event.drawHit);
if (fire) {
selectAndFocusFire(fire);
return;
}
// 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.
if (picked) {
const pickedId = resolvePickId(picked);
if (pickedId && isOwnedByOtherLayer(id, pickedId)) return;
}
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: 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;
}
if (otherLayer) return;
clearFireSelection();
});
}
@@ -74,11 +74,15 @@ export function createSelection({
function selectAndFocusFire(fire) {
selectFire(fire);
// A stand-in that draws the fire larger than a marker says how far the
// camera stands from it (`setMarkerStandIn`).
const rangeM = layerState._standIn?.focusRangeM?.(fire);
requestWorldFocus({
kind: 'fire',
id: fireDetectionKey(fire),
label: t('FIRE'),
position: components.model.firePosition(fire),
...(Number.isFinite(rangeM) && rangeM > 0 ? { rangeM } : {}),
});
}
@@ -96,6 +100,32 @@ export function createSelection({
return layerState._pickIndexById.get(hit.id) ?? null;
}
/** The shown detections by their key, for the shown set they were made from. */
let keyed = { fires: null, byKey: null };
/**
* Resolve a click to one of this layer's fire records through the
* application's stand-in for its markers (`setMarkerStandIn`), or null:
* the record its hit test answers, matched by its detection key to a fire
* the layer shows now (so one the filter hides is not selected).
* @param {?{x: number, y: number}} screenPosition - Where the user clicked.
* @returns {?Object} Fire record.
*/
function standInFire(screenPosition) {
if (!screenPosition) return null;
const record = layerState._standIn?.hitTest(screenPosition);
if (!record) return null;
if (keyed.fires !== layerState._fires)
keyed = {
fires: layerState._fires,
byKey: new Map(
layerState._fires.map((fire) => [fireDetectionKey(fire), fire]),
),
};
return keyed.byKey.get(fireDetectionKey(record)) ?? null;
}
/**
* Select a fire: show its detail label and mark it selected in the shared
* context store so voice "what's selected" resolves to it.
@@ -232,6 +262,7 @@ export function createSelection({
removeClickHandler,
selectAndFocusFire,
pickedFire,
standInFire,
selectFire,
clearFireSelection,
refreshContextRegistrations,
+15 -15
View File
@@ -1,15 +1,20 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import { clickCard, resolvePickId } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { createSelection } from './selection.js';
/** The fire selection over a viewer whose clicks a label may take, with a
* fire's card under every click. */
/** The fire selection over a viewer whose clicks a Space Missions label may
* take, with a fire's card under every click. */
function selectionHarness(t) {
const viewer = { scene: { canvas: {}, pick: () => null } };
const fake = fakeInputUnderLabel(viewer);
const fake = fakeInputUnderLabel(viewer, {
beneath: () => ({
sourceId: FIRMS_OVERLAY_SOURCE_ID,
entryId: 'firms-card:1',
}),
});
t.after(() => fake.destroy());
const fire = { lat: 1, lon: 2, acqMs: 3, frp: 40, satellite: 'N' };
const focused = [];
@@ -25,7 +30,7 @@ function selectionHarness(t) {
const selection = createSelection({
layerState,
services: {
picking: { resolvePickId, isOwnedByOtherLayer: () => false },
picking: { resolvePickId, isOwnedByOtherLayer: () => false, clickCard },
focus: { requestWorldFocus: (request) => focused.push(request.kind) },
context: {
selectEntityContext() {},
@@ -45,12 +50,6 @@ function selectionHarness(t) {
config: {
id: 'firms',
name: 'Fires',
overlayHost: {
hitTest: (_x, _y, { sourceId }) =>
sourceId === FIRMS_OVERLAY_SOURCE_ID
? { entryId: 'firms-card:1' }
: null,
},
},
});
selection.installClickHandler();
@@ -58,7 +57,7 @@ function selectionHarness(t) {
return { fake, layerState, fire, focused, cleared };
}
test("a click a label painted over a fire's card takes never selects or focuses the fire", (t) => {
test("a click on a mission label over a fire's card never selects or focuses the fire", (t) => {
const h = selectionHarness(t);
h.fake.label.over = true;
h.fake.click();
@@ -66,15 +65,16 @@ test("a click a label painted over a fire's card takes never selects or focuses
assert.deepEqual(h.focused, [], 'the camera is not sent to the fire');
});
test('a click a label painted over the map takes lets go of the selected fire', (t) => {
test('a click on a mission label keeps the selected fire', (t) => {
const h = selectionHarness(t);
// Off the label, a click on the card selects and focuses its fire.
h.fake.click();
assert.equal(h.layerState._selectedFire, h.fire);
assert.deepEqual(h.focused, ['fire']);
// The label on top is its own click: the fire stays selected.
h.fake.label.over = true;
h.fake.click();
assert.equal(h.layerState._selectedFire, null);
assert.deepEqual(h.cleared, ['firms']);
assert.equal(h.layerState._selectedFire, h.fire);
assert.deepEqual(h.cleared, []);
assert.deepEqual(h.focused, ['fire']);
});
+8
View File
@@ -98,6 +98,14 @@ export function createFirmsState({ services, config }) {
layerState._selectedFire = null;
/**
* What an application draws in place of the markers (`setMarkerStandIn`):
* while set, the glows, heatmap and ambient cards are hidden and clicks
* resolve through its `hitTest`.
*/
layerState._standIn = null;
/** Priority-ordered label candidates from the last rebuild (detections or cells). */
layerState._labelCandidates = [];
+46
View File
@@ -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 = {
+5 -1
View File
@@ -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) {
+13 -10
View File
@@ -707,16 +707,19 @@ export function createGhostMapsLayer({
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: 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;
+75 -13
View File
@@ -1,9 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { setLocale } from '../../i18n/index.js';
import { createGhostMapsLayer } from './index.js';
import { createGhostMapsLayer, GHOSTMAPS_OVERLAY_SOURCE_ID } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { inputFor } from '../../input/dispatcher.js';
import { MISSION_LABEL } from '../../input/testDoubles.mjs';
import { clickCard, setClickCardHitTest } from '../../data/pickRegistry.js';
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
function element(localName, children = [], value = '', attributes = {}) {
@@ -674,10 +676,21 @@ test('narrowing to a window the loaded data covers clears a failed wider reload'
assert.equal(layer.getStats().count, 1);
});
test("a click a label painted over the open card takes never opens the card's link, and closes the card", async (t) => {
test("a click on a mission label over the open card never opens the card's link, and keeps the card open", async (t) => {
const cards = [];
const opened = [];
let cardUnder = null;
// A Space Missions label painted over the map: while it is over, it takes
// each click and is the card on top; under it may lie our open card.
let labelOver = false;
setClickCardHitTest(() =>
labelOver
? MISSION_LABEL
: cardUnder
? { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID, entryId: cardUnder }
: null,
);
t.after(() => setClickCardHitTest(null));
const { layer, viewer, click } = fixture(t, {
now: () => Date.UTC(2026, 10, 3, 12),
reports: [
@@ -689,33 +702,82 @@ test("a click a label painted over the open card takes never opens the card's li
},
],
controls: {
overlayHost: {
setEntries: (_id, entries) => cards.push(entries),
hitTest: () => (cardUnder ? { entryId: cardUnder } : null),
},
picking: { resolvePickId: (picked) => picked?.id ?? null },
overlayHost: { setEntries: (_id, entries) => cards.push(entries) },
picking: { resolvePickId: (picked) => picked?.id ?? null, clickCard },
openExternal: (url) => opened.push(url),
},
});
// A label painted over the map, as a Space Missions label is: while it is
// over, it takes each click.
let labelOver = false;
inputFor(viewer).onOverlayClick(() => labelOver);
await layer.update(viewer);
click('ghostmaps:cip:0:0');
const [card] = cards.at(-1);
assert.equal(card.interactive, true);
// The open card lies under the label: the click opens nothing.
// The open card lies under the label: the click opens nothing, and the
// label on top is its own click, so the card stays open.
cardUnder = card.id;
labelOver = true;
click(null);
assert.deepEqual(opened, [], 'the link beneath the label is not opened');
assert.deepEqual(cards.at(-1), [], 'the card is closed');
assert.equal(cards.at(-1)[0]?.id, card.id, 'the card stays open');
// Off the label, a click on the open card opens its link.
labelOver = false;
click('ghostmaps:cip:0:0');
click(null);
assert.deepEqual(opened, ['https://example.com/report']);
});
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');
});
+4
View File
@@ -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;
+109
View File
@@ -0,0 +1,109 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createLifecycle } from './lifecycle.js';
import { createOverlays } from './overlays.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.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),
});
// A mission label on top takes its click through the overlay handler first;
// here 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();
}
});
// A mission label is an interactive world-overlay entry, so the host's hit
// test names it and every other layer reads it as the card on top: a click
// on it never acts on what lies under it.
test('a mission label is the card on top for every other layer', (t) => {
const overlays = createOverlays({
state: {},
services: {},
parts: {},
source: {},
});
const launch = {
id: 'L1',
name: 'Starlink Group 1',
launchTime: '2026-11-01T00:00:00Z',
};
for (const selected of [false, true]) {
const entry = overlays.createRocketMissionMarkerOverlayEntry(
launch,
{ x: 1, y: 2, z: 3 },
selected,
);
assert.equal(entry.interactive, true, `selected: ${selected}`);
}
for (const sourceId of [
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
]) {
picking.setClickCardHitTest(() => ({ sourceId, entryId: 'launch:L1' }));
t.after(() => picking.setClickCardHitTest(null));
const click = { screenPosition: { x: 10, y: 10 } };
assert.equal(picking.isUnderOtherCard(click, ['vessels']), true);
assert.equal(picking.isUnderOtherCard(click, [sourceId]), false);
}
});
+8 -1
View File
@@ -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),
+13 -3
View File
@@ -8,7 +8,12 @@ import {
} from '../../data/screenRotation.js';
import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js';
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js';
import {
drawOf,
findCamera,
findFrame,
findQuery,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { routePlausible } from '../../data/routePlausible.js';
@@ -677,8 +682,10 @@ export function createLocalAdsbLayer({
if (ownedElsewhere(topId) && !trail) return 'other';
let hits = [];
try {
// The click's own drill: none under a label painted over the map.
hits = event.drill(CLICK_DRILL_LIMIT);
hits =
findQuery(viewer)?.drillPick(event.position.x, event.position.y, {
limit: CLICK_DRILL_LIMIT,
}) ?? [];
} catch {
hits = [];
}
@@ -696,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
+58 -6
View File
@@ -15,10 +15,14 @@ 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 { inputFor } from '../../input/dispatcher.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { MISSION_LABEL, fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -1217,6 +1221,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 };
@@ -1269,17 +1308,29 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
assert.equal(calls.selected.length, 2, 'the Flights contact is not taken');
});
test('a click a label painted over a local aircraft takes never selects the aircraft, and lets go of the selection', async (t) => {
test('a click on a mission label over a local aircraft never selects the aircraft, and keeps the selection', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const harness = clickHarness();
// A Space Missions label painted over the map: while it is over, it takes
// each click and is the card on top.
const label = { over: true };
setClickCardHitTest(() => (label.over ? MISSION_LABEL : null));
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();
const label = { over: true };
inputFor(harness.viewer.viewer).onOverlayClick(() => label.over);
const model = {
set: layerSet(draw, ':models').spec.id,
@@ -1292,14 +1343,15 @@ test('a click a label painted over a local aircraft takes never selects the airc
harness.click();
assert.deepEqual(calls.selected, [], 'the aircraft beneath is not taken');
// Off the label the same click selects it; on the label it lets go.
// Off the label the same click selects it; the label on top is its own
// click, so the selection stays.
label.over = false;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
label.over = true;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
assert.equal(calls.cleared.length, 1, 'the selection is released');
assert.equal(calls.cleared.length, 0, 'the selection stays');
});
test('a grounded aircraft changing type keeps its drawn model on its own belly offset until the new one is ready', () => {
+46
View File
@@ -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');
});
+5 -1
View File
@@ -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 -10
View File
@@ -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,14 +1347,13 @@ export function createNewsLayer({
clickOff = inputFor(viewer).onClick((event) => {
const at = event?.screenPosition;
if (!enabled || destroyed || !isPointerFree() || !at) return;
// A click a label painted over the cards took is not on a card.
const card = event.overlay
? null
: 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
+96 -9
View File
@@ -5,8 +5,19 @@ 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';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import {
MISSION_LABEL,
fakeInputUnderLabel,
} from '../../input/testDoubles.mjs';
import { NEWS_OVERLAY_SOURCE_ID } from './model.js';
const NOW = Date.parse('2026-10-28T10:00:00Z');
@@ -141,18 +152,22 @@ function fixture(
for (const fn of [...clickHandlers])
fn({ screenPosition: { x: 10, y: 10 }, topHit });
};
// Or the scene's own dispatcher, with a label that may be painted over
// the map (`fake.label.over`).
// Or the scene's own dispatcher, with a Space Missions label that may be
// painted over the map (`fake.label.over`).
let fake = null;
if (underLabel) {
viewer.scene = { canvas: {}, pick: () => null };
fake = fakeInputUnderLabel(viewer);
}
// The card on top at a click, as the host answers the pick registry: a
// mission label painted over the map comes first.
setClickCardHitTest((x, y) =>
fake?.label.over ? MISSION_LABEL : hitTestOverlay(x, y),
);
const layer = createNewsLayer({
source,
overlayHost,
inputFor: () => fake?.input ?? input,
hitTestOverlay,
now,
matchMedia: () => ({ matches: reduced }),
getViewCentre: () => centre(),
@@ -170,6 +185,7 @@ function fixture(
t.after(() => {
layer.destroy();
fake?.destroy();
setClickCardHitTest(null);
unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
@@ -1298,15 +1314,18 @@ test('a click on a marker selects its report, on a beacon chooses its hotspot, o
assert.equal(clickHandlers.size, 0);
});
test("a click a label painted over a report's card takes never opens the card, and lets go of the report", async (t) => {
test("a click on a mission label over a report's card never opens the card, and keeps the report", async (t) => {
let activated = 0;
const { layer, fake } = fixture(t, {
height: 500_000,
underLabel: true,
// A report's card lies under every click.
hitTestOverlay: (_x, _y, { sourceId }) =>
sourceId === NEWS_OVERLAY_SOURCE_ID
? { entry: { activate: () => activated++ } }
hitTestOverlay: (_x, _y, { sourceId } = {}) =>
!sourceId || sourceId === NEWS_OVERLAY_SOURCE_ID
? {
sourceId: NEWS_OVERLAY_SOURCE_ID,
entry: { activate: () => activated++ },
}
: null,
});
layer.enable();
@@ -1318,7 +1337,11 @@ test("a click a label painted over a report's card takes never opens the card, a
fake.label.over = true;
fake.click();
assert.equal(activated, 0, 'the card beneath the label is not opened');
assert.equal(layer.getRowControls().feed.selected, null);
assert.equal(
layer.getRowControls().feed.selected.id,
'major',
'the label on top is its own click: the report stays selected',
);
// Off the label, the same click opens the card.
fake.label.over = false;
@@ -1326,6 +1349,70 @@ test("a click a label painted over a report's card takes never opens the card, a
assert.equal(activated, 1);
});
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'), []);
+12 -10
View File
@@ -218,16 +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.
// A click a label painted over the cards took is not on a card.
const cardHit = event.overlay
? null
: 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;
+64 -19
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFirePerimetersLayer } from './index.js';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -59,6 +60,11 @@ 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;
// a mission label painted over everything comes first.
clickCard: (click) =>
clickCard(click) ??
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
inciwebSource: inciwebIndex
? { getIndex: async () => inciwebIndex }
@@ -79,7 +85,8 @@ function harness(
clicks,
owners,
opened,
/** A label painted over the map: while `over`, it takes each click. */
/** A Space Missions label painted over the map: while `over`, it takes
* each click and is the card on top. */
label: input.label,
};
}
@@ -246,6 +253,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] },
@@ -282,12 +326,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);
@@ -302,9 +350,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(
@@ -314,7 +368,7 @@ test('a matched incident card carries the InciWeb line and click-through', async
);
});
test('a click a label painted over the incident card takes never opens its InciWeb page, and closes the card', async () => {
test('a click on a mission label over the incident card never opens its InciWeb page, and keeps the card open', async () => {
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
@@ -336,26 +390,17 @@ test('a click a label painted over the incident card takes never opens its InciW
const [card] = h.overlay.entries.get('fire-perimeters');
assert.equal(card.details.at(-1), 'InciWeb ↗ · click card to open');
// The open card lies under the label: the click opens nothing.
cardHitResult = { entryId: card.id };
// The open card lies under the label: the click opens nothing, and the
// label on top is its own click, so the card stays open.
cardHitResult = { sourceId: 'fire-perimeters', entryId: card.id };
h.viewer.scene.pick = () => null;
h.label.over = true;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, [], 'the page beneath the label is not opened');
assert.equal(
h.overlay.entries.get('fire-perimeters')?.length ?? 0,
0,
'the card is closed',
);
assert.equal(h.overlay.entries.get('fire-perimeters')?.[0]?.id, card.id);
// Off the label, a click on the open card opens its page.
h.label.over = false;
h.viewer.scene.pick = () =>
perimeterPick('fire-perimeter:2026-NMGNF-000123:0');
h.clicks.handler({ position: { x: 10, y: 10 } });
await new Promise((done) => setTimeout(done, 0));
cardHitResult = { entryId: h.overlay.entries.get('fire-perimeters')[0].id };
h.viewer.scene.pick = () => null;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']);
h.layer.destroy();
@@ -378,7 +423,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, []);
+4
View File
@@ -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);
+46
View File
@@ -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');
});
+20
View File
@@ -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);
+4
View File
@@ -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();
+5 -1
View File
@@ -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]);
});
+12 -9
View File
@@ -277,15 +277,18 @@ export function createShipwrecksLayer({
if (!clicks) return;
_clickHandler = clicks.onClick((click) => {
if (pointer && !pointer.isPointerFree()) return;
const at = click.screenPosition;
// A click a label painted over the cards took is not on a card.
const cardHit = click.overlay
? null
: 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
+59 -11
View File
@@ -37,7 +37,7 @@ function deferred() {
return { promise, resolve };
}
function harness({ snapshots, now = () => 1 } = {}) {
function harness({ snapshots, now = () => 1, cardHit = () => null } = {}) {
const cards = [];
const handlers = [];
const opened = [];
@@ -48,6 +48,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 }) {
@@ -60,7 +62,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: () => ({
@@ -395,21 +397,23 @@ test('the page deadline subtracts the newest available source age from the limit
assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults');
});
test("a click a label painted over the open card takes never opens the card's link, and closes the card", async (t) => {
test("a click on a mission label over the open card never opens the card's link, and keeps the card open", async (t) => {
let picked = null;
const viewer = { scene: { canvas: {}, pick: () => picked } };
bindFakeDraw(viewer);
const fake = fakeInputUnderLabel(viewer);
let cardUnder = null;
const fake = fakeInputUnderLabel(viewer, {
beneath: () =>
cardUnder ? { sourceId: 'shipwrecks', entryId: cardUnder } : null,
});
t.after(() => fake.destroy());
const cards = [];
const opened = [];
let cardUnder = null;
const layer = createShipwrecksLayer({
source: { getSnapshot: () => Promise.resolve(snapshot([wreck('a')])) },
overlayHost: {
setEntries: (_source, entries) => cards.push(entries),
setVisible() {},
hitTest: () => (cardUnder ? { entryId: cardUnder } : null),
},
input: () => fake.input,
picking,
@@ -426,19 +430,63 @@ test("a click a label painted over the open card takes never opens the card's li
const [card] = cards.at(-1);
assert.equal(card.id, 'shipwreck-card:a');
// The open card lies under the label: the click opens nothing.
// The open card lies under the label: the click opens nothing, and the
// label on top is its own click, so the card stays open.
picked = null;
cardUnder = card.id;
fake.label.over = true;
fake.click();
assert.deepEqual(opened, [], 'the link beneath the label is not opened');
assert.deepEqual(cards.at(-1), [], 'the card is closed');
assert.equal(cards.at(-1)[0]?.id, card.id, 'the card stays open');
// Off the label, a click on the open card opens its link.
fake.label.over = false;
picked = { primitive: {}, id: { set: 'shipwrecks:', id: 'shipwreck:a' } };
fake.click();
picked = null;
fake.click();
assert.equal(opened.length, 1);
});
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();
}
});
+15 -1
View File
@@ -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) });
+181 -1
View File
@@ -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();
}
});
+2
View File
@@ -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);
+4 -1
View File
@@ -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',
);
});
+25
View File
@@ -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);
+4
View File
@@ -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;
+26 -43
View File
@@ -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,51 +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.
// A click a label painted over the cards took is not on a card.
const cardHit =
!record && !event.overlay
? 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.
+16 -17
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { createSelection } from './selection.js';
@@ -17,12 +18,18 @@ function recorder(calls) {
);
}
/** The vessel selection over a viewer whose clicks a label may take. */
/** The vessel selection over a viewer whose clicks a Space Missions label
* may take, with the vessel's card under every click. */
function selectionHarness(t) {
const viewer = { scene: { canvas: {}, pick: () => null } };
const fake = fakeInputUnderLabel(viewer);
t.after(() => fake.destroy());
const vessel = { id: 'v1', name: 'NORTHERN STAR', lat: 0, lon: 0 };
const fake = fakeInputUnderLabel(viewer, {
beneath: () => ({
sourceId: VESSEL_OVERLAY_SOURCE_ID,
entryId: `vessel:${vessel.id}`,
}),
});
t.after(() => fake.destroy());
const focused = [];
const calls = [];
const state = {
@@ -32,20 +39,11 @@ function selectionHarness(t) {
selectedRecord: null,
interactionKeyTarget: new EventTarget(),
};
const vesselState = {
state,
// The vessel's card lies under the click.
_vesselOverlayHost: {
hitTest: (_x, _y, { sourceId } = {}) =>
sourceId === VESSEL_OVERLAY_SOURCE_ID
? { sourceId, entryId: `vessel:${vessel.id}` }
: null,
},
};
const vesselState = { state };
const selection = createSelection({
vesselState,
services: {
picking: { isOwnedByOtherLayer: () => false },
picking: { isOwnedByOtherLayer: () => false, clickCard },
worldFocus: { requestWorldFocus: (request) => focused.push(request.id) },
context: recorder(calls),
},
@@ -68,7 +66,7 @@ function selectionHarness(t) {
return { fake, state, vessel, focused };
}
test("a click a label painted over a vessel's card takes never selects or focuses the vessel", (t) => {
test("a click on a mission label over a vessel's card never selects or focuses the vessel", (t) => {
const h = selectionHarness(t);
h.fake.label.over = true;
h.fake.click();
@@ -76,14 +74,15 @@ test("a click a label painted over a vessel's card takes never selects or focuse
assert.deepEqual(h.focused, [], 'the camera is not sent to the vessel');
});
test('a click a label painted over the map takes lets go of the selected vessel', (t) => {
test('a click on a mission label keeps the selected vessel', (t) => {
const h = selectionHarness(t);
// Off the label, a click on the card selects and focuses its vessel.
h.fake.click();
assert.equal(h.state.selectedRecord, h.vessel);
assert.deepEqual(h.focused, ['v1']);
// The label on top is its own click: the vessel stays selected.
h.fake.label.over = true;
h.fake.click();
assert.equal(h.state.selectedRecord, null);
assert.equal(h.state.selectedRecord, h.vessel);
assert.deepEqual(h.focused, ['v1']);
});
@@ -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) },
+6 -14
View File
@@ -482,21 +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;
// A click a label painted over the cards took is not on a card.
const hit =
!click.overlay &&
(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>`.
+65 -10
View File
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createSelection } from './selection.js';
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
const row = {
@@ -22,6 +23,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 = {
@@ -43,16 +45,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++;
@@ -67,6 +70,14 @@ function fixture(sighting = row, extraServices = {}) {
}),
eventTarget: new EventTarget(),
...extraServices,
// The card on top at a click, as the registry answers from the host;
// a mission label painted over everything comes first.
picking: {
clickCard: (c) =>
clickCard(c) ??
overlayHost.hitTest(c.screenPosition?.x, c.screenPosition?.y),
...extraServices.picking,
},
},
parts: {
rendering: {
@@ -95,6 +106,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);
@@ -180,6 +194,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,
@@ -305,7 +351,7 @@ test('empty clicks and layer removal release the selected row and its overlay',
assert.equal(f.entries.size, 0);
});
test("a click a label painted over a sighting's card takes never selects the sighting, and lets go of the selected one", (t) => {
test("a click on a mission label over a sighting's card never selects the sighting, and keeps the selected one", (t) => {
let fake = null;
const f = fixture(row, {
input: (viewer) => {
@@ -322,15 +368,24 @@ test("a click a label painted over a sighting's card takes never selects the sig
// The sighting's name card lies under every click.
f.hit('wildlife-sightings-labels', 'wildlife-sightings-label:inat:123');
// Under the label, the card beneath it selects nothing.
fake.label.over = true;
fake.click();
assert.equal(f.state.selectedId, null);
assert.equal(f.flights.length, 0);
// Off the label, a click on the card selects and focuses the sighting.
fake.label.over = false;
fake.click();
assert.equal(f.state.selectedId, row.stableId);
assert.equal(f.flights.length, 1);
// The label on top is its own click: the sighting stays selected, and
// the camera is not sent to it again.
fake.label.over = true;
fake.click();
assert.equal(f.state.selectedId, null, 'the selected sighting is let go');
assert.equal(f.state.selectedRow, null);
assert.equal(f.state.selectedId, row.stableId, 'the sighting stays');
assert.equal(f.state.selectedRow, row);
assert.equal(f.flights.length, 1, 'the camera is not sent to the sighting');
});