mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 18:22:25 +00:00
Merge origin/main into byrdit/cctv-visible-only-fetch
This commit is contained in:
commit
d19ae89630
445 files changed
+27359
-9232
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { isFollowing } from '../../data/followed.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
|
||||
import {
|
||||
LAYER_ID,
|
||||
@@ -581,6 +582,9 @@ export function createAlprPresentation({ state, services, source }) {
|
||||
if (state.clickSubscription) return;
|
||||
state.clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!state.enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
// The painted overlay answers first; the scene is picked only if not.
|
||||
const hit = event.drawHit;
|
||||
const id =
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
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';
|
||||
import { createAlprPresentation } from './presentation.js';
|
||||
|
||||
/** One camera drawn and painted at (100, 100), over a viewer whose clicks a
|
||||
* label may take. */
|
||||
function harness(t) {
|
||||
const previousImage = globalThis.Image;
|
||||
const project = Cesium.SceneTransforms.worldToWindowCoordinates;
|
||||
globalThis.Image = class {
|
||||
complete = true;
|
||||
naturalWidth = 128;
|
||||
};
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 100, y: 100 });
|
||||
const record = {
|
||||
id: 'camera:0',
|
||||
latitude: 30,
|
||||
longitude: -97,
|
||||
directionDeg: 90,
|
||||
};
|
||||
const drawPort = fakeDrawPort();
|
||||
const markers = createAlprMarkerSet();
|
||||
markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
|
||||
const viewer = {
|
||||
camera: {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500),
|
||||
pickEllipsoid: () => Cesium.Cartesian3.fromDegrees(-97, 30),
|
||||
},
|
||||
scene: {
|
||||
canvas: { clientWidth: 800, clientHeight: 600 },
|
||||
globe: { show: true, getHeight: () => 150 },
|
||||
pick: () => null,
|
||||
},
|
||||
};
|
||||
const { unbind } = bindFakeCesiumScene(viewer, { draw: drawPort });
|
||||
const fake = fakeInputUnderLabel(viewer);
|
||||
const state = {
|
||||
viewer,
|
||||
enabled: true,
|
||||
selectedId: null,
|
||||
markers,
|
||||
records: [record],
|
||||
recordById: new Map([[record.id, record]]),
|
||||
renderRevision: 0,
|
||||
lastAnchorSampleAt: 0,
|
||||
};
|
||||
let selected = null;
|
||||
let paint;
|
||||
const presentation = createAlprPresentation({
|
||||
state,
|
||||
source: { label: 'Test cameras' },
|
||||
services: {
|
||||
render: { governorRequestRender() {} },
|
||||
context: {
|
||||
clearSelectedEntityContextForLayer() {
|
||||
selected = null;
|
||||
},
|
||||
getSelectedEntityContext: () => selected,
|
||||
registerEntityContext() {},
|
||||
removeEntityContextsForLayer() {},
|
||||
selectEntityContext(carrier) {
|
||||
selected = { id: carrier.id, layerId: 'alpr-cameras' };
|
||||
},
|
||||
},
|
||||
groundFloor: { cachedGroundFloor: () => 150 },
|
||||
overlays: {
|
||||
registerPaintLane(_lane, painter) {
|
||||
paint = painter;
|
||||
return { setActive() {}, requestPaint() {}, unregister() {} };
|
||||
},
|
||||
keyholeAlpha: () => 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
presentation.initOverlay();
|
||||
presentation.installInteraction(viewer);
|
||||
t.after(() => {
|
||||
presentation.destroyOverlay();
|
||||
fake.destroy();
|
||||
unbind();
|
||||
if (previousImage === undefined) delete globalThis.Image;
|
||||
else globalThis.Image = previousImage;
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = project;
|
||||
});
|
||||
presentation.renderRecords();
|
||||
const ctx = {
|
||||
globalAlpha: 1,
|
||||
save() {},
|
||||
restore() {},
|
||||
beginPath() {},
|
||||
moveTo() {},
|
||||
lineTo() {},
|
||||
closePath() {},
|
||||
stroke() {},
|
||||
fill() {},
|
||||
createLinearGradient: () => ({ addColorStop() {} }),
|
||||
drawImage() {},
|
||||
};
|
||||
paint({ ctx, width: 800, height: 600 });
|
||||
return { state, fake, at: { x: 100, y: 100 } };
|
||||
}
|
||||
|
||||
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);
|
||||
assert.equal(h.state.selectedId, null, 'the camera under the label');
|
||||
|
||||
// Off the label, the same click selects the camera.
|
||||
h.fake.label.over = false;
|
||||
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, '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');
|
||||
});
|
||||
@@ -96,7 +96,7 @@ export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
|
||||
* (tracking, cockpit, orbit, a fly-to) do not. Below the band's height they
|
||||
* rest too. While they run they never hold
|
||||
* continuous rendering; each drawn frame arms one more step after the
|
||||
* Cyber sonar's 80 ms cadence, so the two never beat. Fronts and band,
|
||||
* sonar's 80 ms cadence, so the two never beat. Fronts and band,
|
||||
* fixed in the world, step at that cadence however many frames are
|
||||
* drawn, so they look the same whether the camera moves or not; crossing
|
||||
* the rim height shows or hides them at once.
|
||||
|
||||
@@ -430,7 +430,7 @@ export function createRangeRing({
|
||||
* Run the range pulses again for `activeMs`, after a camera move. Call it
|
||||
* during a frame (lifecycle's preRender): that frame's postRender arms the
|
||||
* next request, so waking asks for no extra frame of its own. Pulses at
|
||||
* rest start in this frame; running ones keep their Cyber sonar interval,
|
||||
* rest start in this frame; running ones keep their sonar interval,
|
||||
* however many frames a drag draws.
|
||||
*/
|
||||
function wakePulses() {
|
||||
@@ -506,7 +506,7 @@ export function createRangeRing({
|
||||
const { lines, band } = setsOn(viewer);
|
||||
const frame = findFrame(viewer);
|
||||
// A renderer without frame hooks gets the static ring only, as the
|
||||
// Cyber sonar scene does. So does a viewer who prefers reduced motion.
|
||||
// sonar scene does. So does a viewer who prefers reduced motion.
|
||||
const animate = Boolean(!reducedMotion && frame?.on);
|
||||
// Pulses run from now until `wake.untilMs`, then rest.
|
||||
const wake = animate
|
||||
@@ -681,7 +681,7 @@ export function createRangeRing({
|
||||
bandShown = false;
|
||||
return;
|
||||
}
|
||||
// The soft band is painted at most once a Cyber sonar interval;
|
||||
// The soft band is painted at most once a sonar interval;
|
||||
// the fronts, crisp lines, move on every step.
|
||||
if (
|
||||
bandShown &&
|
||||
@@ -726,7 +726,7 @@ export function createRangeRing({
|
||||
// Whether the camera was below the rim at the last step.
|
||||
let wasBelow = belowRim();
|
||||
// The fronts and band are fixed in the world: a camera move needs
|
||||
// nothing of them, so they step a Cyber sonar interval apart however
|
||||
// nothing of them, so they step a sonar interval apart however
|
||||
// many frames are drawn, and look the same parked or moving. Each
|
||||
// frame checks only whether the camera crossed the rim height, which
|
||||
// shows or hides them at once. A step asks for the frame that draws
|
||||
@@ -746,8 +746,8 @@ export function createRangeRing({
|
||||
stepRunning(nowMs);
|
||||
}
|
||||
});
|
||||
// Each drawn frame, whoever asked for it, arms one step a Cyber
|
||||
// sonar interval later, as the Cyber sonar scene does, whose changes
|
||||
// Each drawn frame, whoever asked for it, arms one step a
|
||||
// sonar interval later, as the sonar scene does, whose changes
|
||||
// ask for the frame that draws them. Requests never land within
|
||||
// 80 ms of a frame, so they cannot beat the detection lane's 80 ms
|
||||
// gate, and they stop once the pulses rest.
|
||||
|
||||
@@ -488,7 +488,7 @@ test('pulses ask for a frame 80 ms after each drawn frame instead of holding con
|
||||
const { rendering, pulseFrames } = ring;
|
||||
const loop = frameLoop(t, ring);
|
||||
rendering.renderVisual(flight(3));
|
||||
// A Contacts view repaints at the Cyber sonar cadence, ~12.5 fps, while
|
||||
// A Contacts view repaints at the sonar cadence, ~12.5 fps, while
|
||||
// the pulses run, never every display frame.
|
||||
assert.equal(pulseFrames(), 0);
|
||||
loop.advance(1); // the frame the new ring asked for arms the first request
|
||||
@@ -972,14 +972,14 @@ test('disabling the layer tears the pulses down completely', (t) => {
|
||||
);
|
||||
});
|
||||
|
||||
test('pulse requests wait 80 ms after any frame, so they cannot beat the Cyber sonar', (t) => {
|
||||
test('pulse requests wait 80 ms after any frame, so they cannot beat the sonar', (t) => {
|
||||
const ring = ringRendering(t);
|
||||
const { rendering, pulseFrames } = ring;
|
||||
const loop = frameLoop(t, ring);
|
||||
rendering.renderVisual(flight(3));
|
||||
loop.advance(1);
|
||||
const frames = pulseFrames();
|
||||
// Another owner (the Cyber sonar, a data update) draws 67 ms after ours.
|
||||
// Another owner (the sonar, a data update) draws 67 ms after ours.
|
||||
loop.advance(67);
|
||||
loop.draw();
|
||||
loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS - 1);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
@@ -179,6 +180,9 @@ export function createSelection({
|
||||
if (layerState._clickSubscription) return;
|
||||
|
||||
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
const hit = event.drawHit;
|
||||
|
||||
if (hit) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createSelection } from './selection.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
|
||||
/** A station layer's selection on a viewer whose pick is scripted. */
|
||||
function harness(t) {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
let picked = null;
|
||||
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
|
||||
const input = fakeInput(viewer);
|
||||
const noop = () => {};
|
||||
const state = {
|
||||
_selectedKey: null,
|
||||
_clickSubscription: null,
|
||||
_stationRenderMap: new Map([['nyc:1', { position: { x: 1, y: 0, z: 0 } }]]),
|
||||
_stationSet: { id: 'bikeshare:stations', upsert: noop },
|
||||
_selectedSet: {
|
||||
id: 'bikeshare:selected',
|
||||
set: noop,
|
||||
size: () => 0,
|
||||
clear: noop,
|
||||
},
|
||||
_overlayHost: { setEntries: noop, clearSource: noop },
|
||||
};
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {},
|
||||
parts: { rendering: { stationItem: () => ({}) } },
|
||||
});
|
||||
selection._installClickHandler(viewer);
|
||||
t.after(() => {
|
||||
state._clickSubscription?.();
|
||||
input.destroy();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
return {
|
||||
state,
|
||||
click(hit) {
|
||||
picked = hit ? { id: hit } : null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// The card or label painted on top takes the click: a station under another
|
||||
// layer's card is neither selected nor let go.
|
||||
test("another layer's card over a station keeps the click", (t) => {
|
||||
const h = harness(t);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const station = { set: 'bikeshare:stations', id: 'nyc:1' };
|
||||
h.click(station);
|
||||
assert.equal(h.state._selectedKey, null, 'covered: not selected');
|
||||
top = null;
|
||||
h.click(station);
|
||||
assert.equal(h.state._selectedKey, 'nyc:1');
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
h.click(null);
|
||||
assert.equal(h.state._selectedKey, 'nyc:1', 'covered: kept');
|
||||
top = null;
|
||||
h.click(null);
|
||||
assert.equal(h.state._selectedKey, null, 'open map lets it go');
|
||||
});
|
||||
@@ -23,7 +23,7 @@ export function createLifecycle({
|
||||
source,
|
||||
}) {
|
||||
const { activateCctvCameraFromWorldClick } = services.activation;
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
|
||||
services.picking;
|
||||
const { onFocusTargetAppear } = services.focus;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
@@ -391,6 +391,20 @@ export function createLifecycle({
|
||||
(event) => {
|
||||
if (!layerState._enabled) return;
|
||||
const picked = event.topHit;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: a live card of ours acts whatever
|
||||
// is drawn under it; another layer's is that layer's click.
|
||||
const top = clickCard?.(event) ?? null;
|
||||
if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
|
||||
if (top) {
|
||||
// A card of ours that is going away is still not the scene.
|
||||
if (layerState._recordById.has(top.entryId))
|
||||
activateCctvCameraFromWorldClick(
|
||||
top.entryId,
|
||||
parts.selection.setActiveCamera,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const cameraId = parts.selection.extractPickedCameraId(
|
||||
event.drawHit ?? null,
|
||||
);
|
||||
@@ -401,29 +415,11 @@ export function createLifecycle({
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Any identified scene object owns this click even if its layer does not
|
||||
// register a shared pick predicate. This keeps selectable siblings ahead
|
||||
// of an overlapping CCTV card while ID-less globe/terrain/tile surfaces
|
||||
// remain eligible for true empty-space deselection.
|
||||
const pickedId = resolvePickId(picked);
|
||||
if (pickedId !== null) return;
|
||||
// Item A (owner round 2): the scene pick found no camera — try the
|
||||
// painted ambient cards. The cards canvas is pointer-events:none (this
|
||||
// handler owns the events), so a click landing on a card's rect selects
|
||||
// its camera exactly like a click on the icon. Click positions
|
||||
// and the recorded rects are both CSS px — direct comparison.
|
||||
const cardId = layerState._cctvOverlayHost.hitTest(
|
||||
event.screenPosition.x,
|
||||
event.screenPosition.y,
|
||||
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
|
||||
)?.entryId;
|
||||
if (cardId && layerState._recordById.has(cardId)) {
|
||||
activateCctvCameraFromWorldClick(
|
||||
cardId,
|
||||
parts.selection.setActiveCamera,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Any identified scene object owns this click even if its layer
|
||||
// does not register a shared pick predicate. This keeps selectable
|
||||
// siblings ahead of the CCTV selection while ID-less globe, terrain
|
||||
// and tile surfaces remain eligible for empty-space deselection.
|
||||
if (resolvePickId(picked) !== null) return;
|
||||
if (
|
||||
parts.selection.cctvEmptyClickDeselects(picked, {
|
||||
activeCameraId: layerState._activeCameraId,
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createSelection } from './selection.js';
|
||||
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
|
||||
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
@@ -72,3 +76,265 @@ test('the view listeners follow the camera port and let go on teardown', () => {
|
||||
assert.deepEqual(counts(second.camera), [0, 0]);
|
||||
assert.equal(state._viewListenerCamera, null);
|
||||
});
|
||||
|
||||
/** A part whose members are `own`'s, and any other a function that does
|
||||
* nothing. */
|
||||
const inert = (own = {}) =>
|
||||
new Proxy(own, {
|
||||
get: (target, name) => (name in target ? target[name] : () => {}),
|
||||
});
|
||||
|
||||
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 };
|
||||
// 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 = [];
|
||||
const state = {};
|
||||
const lifecycle = createLifecycle({
|
||||
state,
|
||||
services: {
|
||||
activation: {
|
||||
activateCctvCameraFromWorldClick: (id) => activated.push(id),
|
||||
},
|
||||
picking,
|
||||
focus: {},
|
||||
render: {},
|
||||
},
|
||||
parts: {
|
||||
calibration: { loadCalibrationStore: () => new Map() },
|
||||
catalog: {
|
||||
loadCameraSources: async () => [],
|
||||
buildCatalogFromSources: () => [],
|
||||
seedCatalog: () => [],
|
||||
},
|
||||
ground: {
|
||||
resolveGroundPriors: async () => [],
|
||||
currentSurfaceRegime: () => null,
|
||||
},
|
||||
rendering: inert({ refreshHorizonCulling: () => false }),
|
||||
health: { syncHealthState: async () => {} },
|
||||
geometryQueue: inert(),
|
||||
cards: inert(),
|
||||
projection: inert(),
|
||||
presentation: inert(),
|
||||
navigation: inert(),
|
||||
hover: inert(),
|
||||
selection: {
|
||||
// The camera's own gate takes only clean clicks; these are.
|
||||
bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick),
|
||||
extractPickedCameraId: () => null,
|
||||
cctvEmptyClickDeselects: (picked, { activeCameraId }) =>
|
||||
Boolean(activeCameraId) && picking.resolvePickId(picked) === null,
|
||||
deactivateActiveCamera: () => deactivated.push(state._activeCameraId),
|
||||
},
|
||||
},
|
||||
});
|
||||
// Init's bounded wait for ground heights never runs out here: they are in.
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
await lifecycle.methods.init(viewer);
|
||||
t.after(() => state._clickSubscription?.());
|
||||
state._enabled = true;
|
||||
state._activeCameraId = 'cam-0';
|
||||
state._recordById.set('cam-1', {});
|
||||
|
||||
fake.label.over = true;
|
||||
fake.click();
|
||||
assert.deepEqual(activated, [], 'the camera under the label stays off');
|
||||
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']);
|
||||
});
|
||||
@@ -1,7 +1,6 @@
|
||||
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
|
||||
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
clickCard,
|
||||
registerPickOwner,
|
||||
unregisterPickOwner,
|
||||
} from '../../data/pickRegistry.js';
|
||||
@@ -79,7 +78,6 @@ const intensityText = (storm) => {
|
||||
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
|
||||
export function createCyclonesLayer({
|
||||
feed,
|
||||
hitTestOverlay = hitTestWorldOverlay,
|
||||
overlayHost,
|
||||
context = null,
|
||||
createRendering = createCycloneRendering,
|
||||
@@ -97,8 +95,7 @@ export function createCyclonesLayer({
|
||||
selectionIntent = 'auto',
|
||||
navigationGeneration = 0,
|
||||
selectionOwner = null,
|
||||
selectedContextStormId = null,
|
||||
removeClickCapture = null;
|
||||
selectedContextStormId = null;
|
||||
let enabled = false,
|
||||
loading = false,
|
||||
error = null,
|
||||
@@ -169,75 +166,28 @@ export function createCyclonesLayer({
|
||||
rendering?.setSelection(id);
|
||||
}
|
||||
function installSelection() {
|
||||
const canvas = canvasOf(viewer);
|
||||
if (selectionOwner || !canvas) return;
|
||||
if (selectionOwner || !canvasOf(viewer)) return;
|
||||
const owner = {};
|
||||
selectionOwner = owner;
|
||||
// Snapshot before sibling bubble listeners can rebuild the overlay hit
|
||||
// rectangles. A vessel selection does that synchronously in the same click.
|
||||
let capturedHit = null;
|
||||
const overlayHit = (x, y) => {
|
||||
const hit = hitTestOverlay(x, y);
|
||||
return { sourceId: hit?.sourceId, entryId: hit?.entryId };
|
||||
};
|
||||
const capture = (event) => {
|
||||
capturedHit = null;
|
||||
const point = event.changedTouches?.[0] || event;
|
||||
if (!Number.isFinite(point.clientX) || !Number.isFinite(point.clientY))
|
||||
return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const x = point.clientX - rect.left,
|
||||
y = point.clientY - rect.top;
|
||||
capturedHit = { x, y, ...overlayHit(x, y) };
|
||||
};
|
||||
const resetCapture = () => {
|
||||
capturedHit = null;
|
||||
};
|
||||
const resetEvents = [
|
||||
'pointerdown',
|
||||
'mousedown',
|
||||
'touchstart',
|
||||
'pointercancel',
|
||||
'touchcancel',
|
||||
];
|
||||
for (const type of resetEvents)
|
||||
canvas.addEventListener?.(type, resetCapture, { capture: true });
|
||||
const events = ['pointerup', 'mouseup', 'touchend'];
|
||||
for (const type of events)
|
||||
canvas.addEventListener?.(type, capture, { capture: true });
|
||||
removeClickCapture = () => {
|
||||
for (const type of events)
|
||||
canvas.removeEventListener?.(type, capture, { capture: true });
|
||||
for (const type of resetEvents)
|
||||
canvas.removeEventListener?.(type, resetCapture, { capture: true });
|
||||
capturedHit = null;
|
||||
};
|
||||
const unsubscribe = inputFor(viewer).onClick((event) => {
|
||||
const nativeHit = capturedHit;
|
||||
capturedHit = null;
|
||||
// Ambient selection yields to draw tools and Director (the dispatcher
|
||||
// skips a held pointer); it never claims the pointer, camera, or
|
||||
// tracking state.
|
||||
const position = event.screenPosition;
|
||||
if (!enabled || destroyed || selectionOwner !== owner || !position)
|
||||
return;
|
||||
// AIS cards paint above the globe on a pointer-events:none canvas. The
|
||||
// vessel handler resolves this same topmost hit before cyclone geometry.
|
||||
const captureMatches =
|
||||
nativeHit &&
|
||||
Math.abs(nativeHit.x - position.x) < 1 &&
|
||||
Math.abs(nativeHit.y - position.y) < 1;
|
||||
const hit = captureMatches
|
||||
? nativeHit
|
||||
: overlayHit(position.x, position.y);
|
||||
if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
|
||||
// The card or label painted on top, as it was when the click landed.
|
||||
const card = clickCard(event);
|
||||
// Storm cards and lead-hour labels paint on the same canvas; a click on
|
||||
// one selects its storm. An id from a superseded advisory changes nothing.
|
||||
if (hit.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
|
||||
const id = cycloneStormIdFromEntryId(hit.entryId);
|
||||
if (card?.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
|
||||
const id = cycloneStormIdFromEntryId(card.entryId);
|
||||
if (id) layer.setParams({ stormId: id });
|
||||
return;
|
||||
}
|
||||
// Another layer's card on top takes the click: the storm under it does
|
||||
// not act, and the click is not empty map either.
|
||||
if (card) return;
|
||||
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
|
||||
// clears the selection.
|
||||
const id = rendering?.pickStorm(event.drawHit);
|
||||
@@ -249,8 +199,6 @@ export function createCyclonesLayer({
|
||||
function removeSelection() {
|
||||
const owner = selectionOwner;
|
||||
selectionOwner = null;
|
||||
removeClickCapture?.();
|
||||
removeClickCapture = null;
|
||||
owner?.unsubscribe?.();
|
||||
}
|
||||
const layer = {
|
||||
|
||||
@@ -6,7 +6,10 @@ import {
|
||||
releasePointer,
|
||||
isPointerFree,
|
||||
} from '../../data/inputOwnership.js';
|
||||
import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
|
||||
import {
|
||||
isOwnedByOtherLayer,
|
||||
setClickCardHitTest,
|
||||
} from '../../data/pickRegistry.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
@@ -77,7 +80,7 @@ const deferred = () => {
|
||||
return { promise, resolve };
|
||||
};
|
||||
|
||||
test('map selection yields to pointer owners and owns only its enabled handler', async () => {
|
||||
test('map selection yields to pointer owners and owns only its enabled handler', async (t) => {
|
||||
const handlers = [],
|
||||
// A pick of an item in one of the layer's draw sets, and one of another
|
||||
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
|
||||
@@ -109,11 +112,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
const layer = createCyclonesLayer({
|
||||
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
|
||||
createRendering: () => rendering,
|
||||
hitTestOverlay: () => {
|
||||
overlayTests++;
|
||||
return overlayHit;
|
||||
},
|
||||
});
|
||||
setClickCardHitTest(() => {
|
||||
overlayTests++;
|
||||
return overlayHit;
|
||||
});
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const canvas = new EventTarget();
|
||||
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
|
||||
const viewer = {
|
||||
@@ -180,41 +184,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
'foreground AIS card wins before scene picking',
|
||||
);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
|
||||
// A native capture runs before an earlier sibling handler clears hit rects.
|
||||
const up = new Event('pointerup');
|
||||
Object.assign(up, { clientX: 110, clientY: 220 });
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = null;
|
||||
// Any other layer's card on top takes the click, not only a vessel's.
|
||||
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
|
||||
handlers[0].click(click);
|
||||
assert.equal(
|
||||
layer.getDiagnostics().selectedId,
|
||||
'ep152026',
|
||||
'captured AIS hit survives synchronous sibling overlay rebuild',
|
||||
'a camera card over the storm keeps the click',
|
||||
);
|
||||
// A captured background hit remains background even if a sibling adds a card.
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
layer.setParams({ stormId: 'ep152026' });
|
||||
// A new gesture clears an unconsumed release snapshot.
|
||||
canvas.dispatchEvent(up);
|
||||
canvas.dispatchEvent(new Event('pointerdown'));
|
||||
overlayHit = null;
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
layer.setParams({ stormId: 'ep152026' });
|
||||
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = null;
|
||||
handlers[0].click({ position: { x: 15, y: 25 } });
|
||||
assert.equal(
|
||||
layer.getDiagnostics().selectedId,
|
||||
'ep162026',
|
||||
'a different click cannot reuse the captured card',
|
||||
);
|
||||
layer.setParams({ stormId: 'ep152026' });
|
||||
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
|
||||
const before = notices;
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
@@ -264,13 +242,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
assert.equal(layer.getDiagnostics().selectionActive, false);
|
||||
const afterDisable = picks;
|
||||
const afterDisableOverlay = overlayTests;
|
||||
canvas.dispatchEvent(up);
|
||||
handlers[0].click(click);
|
||||
assert.equal(
|
||||
overlayTests,
|
||||
afterDisableOverlay,
|
||||
'disable removes native capture listeners',
|
||||
'a disabled layer reads no card',
|
||||
);
|
||||
handlers[0].click(click);
|
||||
assert.equal(picks, afterDisable, 'queued disabled callback is inert');
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
@@ -289,7 +266,7 @@ test('map selection yields to pointer owners and owns only its enabled handler',
|
||||
);
|
||||
assert.equal(handlers[1].destroyed, true);
|
||||
});
|
||||
test('a click on a storm card or lead-hour label selects that storm without picking', async () => {
|
||||
test('a click on a storm card or lead-hour label selects that storm without picking', async (t) => {
|
||||
const handlers = [];
|
||||
let picks = 0,
|
||||
overlayHit = null,
|
||||
@@ -309,8 +286,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
|
||||
getDiagnostics: () => ({}),
|
||||
};
|
||||
},
|
||||
hitTestOverlay: () => overlayHit,
|
||||
});
|
||||
setClickCardHitTest(() => overlayHit);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const canvas = new EventTarget();
|
||||
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
|
||||
const viewer = {
|
||||
@@ -343,15 +321,11 @@ test('a click on a storm card or lead-hour label selects that storm without pick
|
||||
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:al019999' };
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
|
||||
// The native release snapshot carries the card identity too.
|
||||
const up = new Event('pointerup');
|
||||
Object.assign(up, { clientX: 10, clientY: 20 });
|
||||
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:ep162026' };
|
||||
canvas.dispatchEvent(up);
|
||||
overlayHit = null;
|
||||
handlers[0].click(click);
|
||||
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
|
||||
assert.equal(picks, 0, 'card clicks never fall through to the scene');
|
||||
overlayHit = null;
|
||||
handlers[0].click(click);
|
||||
assert.equal(picks, 1);
|
||||
assert.equal(layer.getDiagnostics().selectedId, null, 'empty map clears');
|
||||
|
||||
@@ -1584,6 +1584,9 @@ export function createDirectionsLayer({ services, source }) {
|
||||
// yields the moment a tool (this one included) owns the click.
|
||||
const offSelect = input.onClick((event) => {
|
||||
if (!_enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (services.picking?.isUnderOtherCard?.(event)) return;
|
||||
let hit = null;
|
||||
try {
|
||||
hit = event.drawHit;
|
||||
|
||||
@@ -130,12 +130,11 @@ export function createDroneAirspaceLayer({
|
||||
// cards inert anywhere over a zone. Unowned, our picks read as
|
||||
// "empty space" to siblings — the same contract as fire perimeters.
|
||||
_clickSubscription = inputFor(_viewer).onClick((event) => {
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) return;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: this area's shapes are background to
|
||||
// another layer's card or label painted over them, and a click on our
|
||||
// own card leaves the selection as it is.
|
||||
if (picking.clickCard?.(event)) return;
|
||||
const picked = event.topHit;
|
||||
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
|
||||
if (zoneId) {
|
||||
|
||||
@@ -2,7 +2,8 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createDroneAirspaceLayer } from './index.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { clickCard } from '../../data/pickRegistry.js';
|
||||
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
// The fills set of the layer the last harness made: zone picks name it.
|
||||
@@ -19,11 +20,12 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
|
||||
const owners = new Map();
|
||||
const viewer = { scene: { pick } };
|
||||
const { draw } = bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
const input = fakeInputUnderLabel(viewer);
|
||||
const clicks = {
|
||||
handler: (click) => input.click(click.position),
|
||||
// Only the label's own overlay handler is left.
|
||||
get destroyed() {
|
||||
return input.input.subscriberCount() === 0 ? 1 : 0;
|
||||
return input.input.subscriberCount() === 1 ? 1 : 0;
|
||||
},
|
||||
};
|
||||
const layer = createDroneAirspaceLayer({
|
||||
@@ -47,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);
|
||||
@@ -61,6 +68,8 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
|
||||
overlay,
|
||||
clicks,
|
||||
owners,
|
||||
/** A label painted over the map: while `over`, it takes each click. */
|
||||
label: input.label,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -143,6 +152,86 @@ 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 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(
|
||||
{ getSnapshot: async () => [row] },
|
||||
{ pick: () => pickResult, cardHit: () => cardHitResult },
|
||||
);
|
||||
await h.layer.update(h.viewer);
|
||||
pickResult = zonePick('drone-airspace:310:0');
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
const [card] = h.overlay.entries.get('drone-airspace');
|
||||
|
||||
// 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')?.[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
@@ -1,6 +1,10 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
import {
|
||||
isTrackingClickGesture,
|
||||
isTrackingSelectionGesture,
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import {
|
||||
EARTHQUAKE_OVERLAY_SOURCE_ID,
|
||||
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
|
||||
@@ -11,6 +15,11 @@ import {
|
||||
selectEarthquakeOverlayCohort,
|
||||
mapAnalystRecord,
|
||||
earthquakeCoverage,
|
||||
earthquakeMarkLabel,
|
||||
earthquakeMagnitudeTitle,
|
||||
earthquakeZoomLabel,
|
||||
earthquakeDiscRadiusM,
|
||||
describeEarthquake,
|
||||
} from './model.js';
|
||||
export * from './model.js';
|
||||
export { createUsgsEarthquakeSource } from './source.js';
|
||||
@@ -25,6 +34,20 @@ const msg = (text) => text;
|
||||
* as `Hit.set`.
|
||||
*/
|
||||
export const EARTHQUAKE_DISC_SET_ID = 'earthquakes';
|
||||
export const EARTHQUAKES_LAYER_ID = 'earthquakes';
|
||||
/** The overlay source the clicked quake's detail card is shown in. */
|
||||
export const EARTHQUAKE_CARD_SOURCE_ID = 'earthquake-card';
|
||||
/** A disc's item id is this prefix and the event's stable id. */
|
||||
const PICK_PREFIX = 'earthquake:';
|
||||
/** Fly-to range per metre of disc radius: 220 km frames an M6 (64 km). */
|
||||
const EARTHQUAKE_FOCUS_RANGE_PER_RADIUS = 3.5;
|
||||
/** The selected quake's flat fill, faint under the painted gradient. */
|
||||
const SELECTED_DISC_ALPHA = 0.04;
|
||||
const CARD_HOST_OPTIONS = Object.freeze({
|
||||
cohortLimit: 1,
|
||||
collisionCapacity: 1,
|
||||
moving: false,
|
||||
});
|
||||
let instances = 0;
|
||||
|
||||
/**
|
||||
@@ -33,8 +56,48 @@ let instances = 0;
|
||||
* The discs are one renderer draw set (`drawOf(viewer)`), made at `init`.
|
||||
* Given a Cesium viewer with no renderer bound, the
|
||||
* caller loads the package's `./render/cesium/unbound` export first.
|
||||
*
|
||||
* Clicking a disc shows that quake's detail card and selects it in the
|
||||
* shared context. The application gives the click and selection services;
|
||||
* without `input` and `picking` the discs are drawn but take no clicks.
|
||||
* @param {object} options
|
||||
* @param {object} options.source Snapshot source.
|
||||
* @param {object} options.overlayHost World-overlay host.
|
||||
* @param {(viewer: object) => {onClick: Function}} [options.input] The
|
||||
* viewer's click dispatcher.
|
||||
* @param {{resolvePickId: Function, isOwnedByOtherLayer: Function,
|
||||
* clickCard?: Function}} [options.picking] The pick
|
||||
* registry; `clickCard` names the card or label painted on top of a
|
||||
* click, which takes it (the quake card and labels need it to act).
|
||||
* @param {{registerEntityContext: Function, selectEntityContext: Function,
|
||||
* clearSelectedEntityContextForLayer: Function,
|
||||
* getContextStore: Function}} [options.context] Shared selection store.
|
||||
* @param {{isPointerFree: () => boolean}} [options.pointer]
|
||||
* @param {(url: string) => void} [options.openExternal]
|
||||
* @param {{requestWorldFocus: (detail: object) => boolean}} [options.focus]
|
||||
* The camera transfer a clicked magnitude label asks for.
|
||||
* @param {{show: (target: {id: string, lon: number, lat: number,
|
||||
* heightM?: number, heightAt?: () => number|null, radiusM: number,
|
||||
* color: string}) => void, hide: () => void}} [options.ripples]
|
||||
* The selected quake's animated contour rings.
|
||||
* @param {(viewer: object, lon: number, lat: number) => number|null} [options.groundHeight]
|
||||
* The loaded ground height under a point, so the rings sit on the disc
|
||||
* that is draped there; null (or no service) draws them at sea level.
|
||||
* @param {object} [options.text] Card formatters (see describeEarthquake).
|
||||
*/
|
||||
export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
export function createEarthquakesLayer({
|
||||
source,
|
||||
overlayHost,
|
||||
input = null,
|
||||
picking = null,
|
||||
context = null,
|
||||
pointer = null,
|
||||
openExternal = null,
|
||||
focus = null,
|
||||
ripples = null,
|
||||
groundHeight = null,
|
||||
text = undefined,
|
||||
} = {}) {
|
||||
if (typeof source?.getSnapshot !== 'function')
|
||||
throw new TypeError('Earthquakes require a snapshot source');
|
||||
if (!overlayHost) throw new TypeError('Earthquakes require an overlay host');
|
||||
@@ -60,6 +123,307 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
_marksKey = key;
|
||||
worldClock.coverageChanged();
|
||||
};
|
||||
// The drawn events by stable id, for clicks; the selected one's id, card
|
||||
// and the context record it was published as.
|
||||
let _eventById = new Map();
|
||||
let _selectedId = null;
|
||||
let _selectedCardId = null;
|
||||
let _selectedLink = null;
|
||||
let _contextId = null;
|
||||
let _clickHandler = null;
|
||||
const canSelect = () => Boolean(input && picking);
|
||||
// The disc whose flat fill is faded while the painter draws its gradient.
|
||||
let _fadedDiscId = null;
|
||||
|
||||
/**
|
||||
* A quake's disc: filled on the ground, with static axes (re-tessellating
|
||||
* clamped ground geometry every frame is what once cost 30 fps). No
|
||||
* outline: clamped to the ground, Cesium never drew one. A selected
|
||||
* quake's disc is all but clear: the ripples painter fills it with a
|
||||
* gradient instead, and the faint fill keeps it pickable.
|
||||
*/
|
||||
function discItem(event, faded = false) {
|
||||
const radius = earthquakeDiscRadiusM(event.mag);
|
||||
const [r, g, b] = depthColor(event.depthKm || 0);
|
||||
const fillAlpha = faded
|
||||
? SELECTED_DISC_ALPHA
|
||||
: event.mag >= 5.0
|
||||
? 0.4
|
||||
: 0.3;
|
||||
return {
|
||||
id: `${PICK_PREFIX}${event.stableId}`,
|
||||
geometry: {
|
||||
kind: 'ellipse',
|
||||
center: { lon: event.lon, lat: event.lat },
|
||||
semiMajor: radius,
|
||||
semiMinor: radius,
|
||||
},
|
||||
fill: [r, g, b, fillAlpha],
|
||||
height: 'clampGround',
|
||||
clampTo: 'both',
|
||||
};
|
||||
}
|
||||
|
||||
/** Fade one disc's flat fill (and restore the one faded before). */
|
||||
function fadeDisc(stableId) {
|
||||
if (!ripples || !_discs || _fadedDiscId === stableId) return;
|
||||
const changed = [];
|
||||
const before = _eventById.get(_fadedDiscId);
|
||||
if (before) changed.push(discItem(before, false));
|
||||
const next = _eventById.get(stableId);
|
||||
if (next) changed.push(discItem(next, true));
|
||||
_fadedDiscId = next ? stableId : null;
|
||||
if (changed.length) _discs.upsert(changed);
|
||||
}
|
||||
|
||||
/** The drawn event a pick id names, or null. */
|
||||
function eventOfPickId(pickId) {
|
||||
if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
|
||||
return null;
|
||||
return _eventById.get(pickId.slice(PICK_PREFIX.length)) ?? null;
|
||||
}
|
||||
|
||||
/** The drawn event a click's draw hit is on: an item of this layer's set. */
|
||||
function pickedEvent(hit) {
|
||||
if (!hit || hit.surface || !_discs || hit.set !== _discs.id) return null;
|
||||
return eventOfPickId(hit.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the selected quake's card, context and contours. `user`: a click or
|
||||
* a label's activation, which claims the shared selection and runs the
|
||||
* contours again; a feed refresh only brings them up to date, so it never
|
||||
* takes back a selection made since, nor restarts the animation.
|
||||
*/
|
||||
function publishCard({ user = false } = {}) {
|
||||
const event = _selectedId ? _eventById.get(_selectedId) : null;
|
||||
if (!_enabled || !event) {
|
||||
// A refresh that no longer carries the selected quake evicts it, as
|
||||
// other feeds report; anything else is a deliberate clear.
|
||||
clearSelection({ evicted: _enabled && Boolean(_selectedId) && !user });
|
||||
return;
|
||||
}
|
||||
const { title, details, link, accessibilityLabel } = describeEarthquake(
|
||||
event,
|
||||
{ ...text, canOpen: Boolean(openExternal) },
|
||||
);
|
||||
_selectedLink = link && openExternal ? link : null;
|
||||
const card = {
|
||||
id: `earthquake-card:${event.stableId}`,
|
||||
selected: true,
|
||||
// Always hit-testable (the host only hit-tests interactive entries),
|
||||
// so a click on a card with no link keeps it rather than falling
|
||||
// through to the ground under it and clearing the selection.
|
||||
interactive: true,
|
||||
title,
|
||||
details,
|
||||
accent: depthAccent(event.depthKm || 0),
|
||||
priority: Number.MAX_SAFE_INTEGER,
|
||||
gapPx: 15,
|
||||
verticalOnly: true,
|
||||
placement: 'above',
|
||||
stateless: true,
|
||||
horizonCull: true,
|
||||
position: fromDegrees(event.lon, event.lat),
|
||||
};
|
||||
if (_selectedLink) {
|
||||
const target = _selectedLink;
|
||||
card.accessibilityLabel = accessibilityLabel;
|
||||
card.activate = () => {
|
||||
openExternal(target);
|
||||
return true;
|
||||
};
|
||||
} else if (focus?.requestWorldFocus) {
|
||||
// No source to open: the card's keyboard action flies to its quake,
|
||||
// as a fire card's focuses its fire, so it stays in the action list.
|
||||
const stableId = event.stableId;
|
||||
card.accessibilityLabel = accessibilityLabel;
|
||||
card.activate = () => selectAndFocus(stableId);
|
||||
}
|
||||
_selectedCardId = card.id;
|
||||
overlayHost.setEntries(
|
||||
EARTHQUAKE_CARD_SOURCE_ID,
|
||||
[card],
|
||||
CARD_HOST_OPTIONS,
|
||||
);
|
||||
overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, true);
|
||||
publishContext(event, user);
|
||||
fadeDisc(event.stableId);
|
||||
let heightM = null;
|
||||
try {
|
||||
heightM = groundHeight?.(_viewer, event.lon, event.lat) ?? null;
|
||||
} catch {
|
||||
heightM = null;
|
||||
}
|
||||
ripples?.show?.(
|
||||
{
|
||||
id: event.stableId,
|
||||
lon: event.lon,
|
||||
lat: event.lat,
|
||||
heightM: Number.isFinite(heightM) ? heightM : 0,
|
||||
// Read again as the ground loads: a label's fly-to starts far away.
|
||||
heightAt: groundHeight
|
||||
? () => groundHeight(_viewer, event.lon, event.lat)
|
||||
: null,
|
||||
radiusM: earthquakeDiscRadiusM(event.mag),
|
||||
color: depthAccent(event.depthKm || 0),
|
||||
},
|
||||
{ restart: user },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the event in the shared context store, so "what's selected"
|
||||
* (voice, the Cockpit) answers with it, as a clicked fire does.
|
||||
*/
|
||||
function publishContext(event, select) {
|
||||
if (!context) return;
|
||||
const id = `${PICK_PREFIX}${event.stableId}`;
|
||||
try {
|
||||
if (_contextId && _contextId !== id)
|
||||
context.getContextStore().entities.delete(_contextId);
|
||||
const carrier = { show: true };
|
||||
context.registerEntityContext(carrier, {
|
||||
id,
|
||||
layerId: EARTHQUAKES_LAYER_ID,
|
||||
layerName: layer.name,
|
||||
source: 'USGS',
|
||||
// Hidden with the layer: the context store reads its `show`.
|
||||
dataSource: _discs,
|
||||
targetPosition: fromDegrees(event.lon, event.lat),
|
||||
// i18n-ignore: English entity label, as the analyst records are
|
||||
label: `Earthquake · ${earthquakeMarkLabel(event)}`,
|
||||
latitude: event.lat,
|
||||
longitude: event.lon,
|
||||
properties: {
|
||||
magnitude: event.mag,
|
||||
depthKm: event.depthKm ?? null,
|
||||
place: event.place ?? null,
|
||||
time: Number.isFinite(event.time)
|
||||
? new Date(event.time).toISOString()
|
||||
: null,
|
||||
usgsId: event.usgsId ?? null,
|
||||
},
|
||||
});
|
||||
_contextId = id;
|
||||
if (select) context.selectEntityContext(carrier);
|
||||
} catch {
|
||||
// No context store (no window): the card still shows.
|
||||
}
|
||||
}
|
||||
|
||||
function clearContext({ evicted = false } = {}) {
|
||||
if (!context || !_contextId) return;
|
||||
try {
|
||||
context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID, {
|
||||
evicted,
|
||||
});
|
||||
context.getContextStore().entities.delete(_contextId);
|
||||
} catch {
|
||||
// store unavailable: nothing to clean
|
||||
}
|
||||
_contextId = null;
|
||||
}
|
||||
|
||||
function clearSelection({ evicted = false } = {}) {
|
||||
const had = _selectedId || _selectedCardId;
|
||||
_selectedId = null;
|
||||
_selectedCardId = null;
|
||||
_selectedLink = null;
|
||||
clearContext({ evicted });
|
||||
ripples?.hide?.();
|
||||
fadeDisc(null);
|
||||
if (had)
|
||||
overlayHost.setEntries(EARTHQUAKE_CARD_SOURCE_ID, [], CARD_HOST_OPTIONS);
|
||||
}
|
||||
|
||||
function installClickHandler() {
|
||||
if (!canSelect() || _clickHandler || !_viewer) return;
|
||||
// Deliberately NOT registered in the pick-ownership registry, like drone
|
||||
// airspace and fire perimeters: siblings yield to owned picks before
|
||||
// their own card hit-tests and treat an owned pick as not empty space,
|
||||
// so claiming these large discs would make their cards inert and their
|
||||
// selections stick anywhere over a quake. Unowned, a disc reads as
|
||||
// empty space to them; this handler finds its own discs by draw set.
|
||||
// A viewer with no renderer input bound takes no clicks.
|
||||
let clicks = null;
|
||||
try {
|
||||
clicks = input(_viewer) ?? null;
|
||||
} catch {
|
||||
clicks = null;
|
||||
}
|
||||
if (!clicks) return;
|
||||
_clickHandler = clicks.onClick((click) => {
|
||||
if (!_enabled || (pointer && !pointer.isPointerFree())) return;
|
||||
// A pan that ends near where it began still raises a click. As for the
|
||||
// tracking layers and Context, a press that travelled is a drag, not a
|
||||
// pick; opening the source and clearing also need a short press.
|
||||
if (!isTrackingSelectionGesture(click.gesture)) return;
|
||||
const clean = isTrackingClickGesture(click.gesture);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: another layer's is that layer's click
|
||||
// (the disc under it is background), and ours acts whatever is drawn
|
||||
// under it.
|
||||
const top = picking.clickCard?.(click) ?? null;
|
||||
if (top?.sourceId === EARTHQUAKE_CARD_SOURCE_ID) {
|
||||
// The card's action, as its keyboard action: open the source, or
|
||||
// with none, fly to the quake.
|
||||
if (top.entryId !== _selectedCardId) return;
|
||||
if (_selectedLink) {
|
||||
if (clean) openExternal(_selectedLink);
|
||||
} else if (focus?.requestWorldFocus && _selectedId)
|
||||
selectAndFocus(_selectedId);
|
||||
return;
|
||||
}
|
||||
// A magnitude label is what a far view (the whole globe) can click:
|
||||
// it selects the quake and flies to it.
|
||||
if (top?.sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) {
|
||||
if (_eventById.has(top.entryId)) selectAndFocus(top.entryId);
|
||||
return;
|
||||
}
|
||||
if (top) return;
|
||||
// Another layer's pick (an aircraft, a camera, a flight trail) is not
|
||||
// empty space and not this layer's: leave the selection alone.
|
||||
const hit = click.hit;
|
||||
const pickId = picking.resolvePickId(hit);
|
||||
if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
|
||||
return;
|
||||
const event = pickedEvent(hit);
|
||||
if (event) {
|
||||
_selectedId = event.stableId;
|
||||
publishCard({ user: true });
|
||||
return;
|
||||
}
|
||||
if (clean) clearSelection();
|
||||
});
|
||||
}
|
||||
|
||||
/** Select a drawn quake, show its card, and ask the camera to go there. */
|
||||
function selectAndFocus(stableId) {
|
||||
const event = _eventById.get(stableId);
|
||||
if (!_enabled || !event) return false;
|
||||
_selectedId = stableId;
|
||||
publishCard({ user: true });
|
||||
focus?.requestWorldFocus?.({
|
||||
kind: 'earthquake',
|
||||
id: `${PICK_PREFIX}${stableId}`,
|
||||
label: earthquakeMagnitudeTitle(event.mag),
|
||||
position: fromDegrees(event.lon, event.lat),
|
||||
// The whole disc in view: the framing's range fits an M6 disc, so only
|
||||
// a larger one asks for its own range (the framing stays the floor).
|
||||
radiusM: earthquakeDiscRadiusM(event.mag),
|
||||
rangeM:
|
||||
event.mag > 6
|
||||
? earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS
|
||||
: undefined,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
_clickHandler?.();
|
||||
_clickHandler = null;
|
||||
}
|
||||
|
||||
const layer = {
|
||||
id: 'earthquakes',
|
||||
@@ -93,6 +457,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
// layer has no per-frame animator to keep the render loop alive for.
|
||||
if (_discs) _discs.show = true;
|
||||
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
|
||||
installClickHandler();
|
||||
coverageChanged();
|
||||
},
|
||||
|
||||
@@ -101,6 +466,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
_request = null;
|
||||
_enabled = false;
|
||||
if (_discs) _discs.show = false;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID);
|
||||
overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false);
|
||||
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
|
||||
coverageChanged();
|
||||
@@ -132,41 +501,52 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
time,
|
||||
} of rows) {
|
||||
count++;
|
||||
const baseRadius = Math.pow(2, mag) * 1000;
|
||||
const color = depthColor(depthKm || 0);
|
||||
const [r, g, b] = color;
|
||||
const isSignificant = mag >= 5.0;
|
||||
const fillAlpha = isSignificant ? 0.4 : 0.3;
|
||||
|
||||
const position = fromDegrees(lon, lat);
|
||||
nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat });
|
||||
// A filled disc on the ground, with static axes: re-tessellating
|
||||
// clamped ground geometry every frame is what once cost 30 fps.
|
||||
// No outline: clamped to the ground, Cesium never drew one.
|
||||
nextDiscs.push({
|
||||
id: `earthquake:${stableId}`,
|
||||
geometry: {
|
||||
kind: 'ellipse',
|
||||
center: { lon, lat },
|
||||
semiMajor: baseRadius,
|
||||
semiMinor: baseRadius,
|
||||
},
|
||||
fill: [r, g, b, fillAlpha],
|
||||
height: 'clampGround',
|
||||
clampTo: 'both',
|
||||
});
|
||||
overlayEntries.push(
|
||||
createEarthquakeOverlayEntry({
|
||||
id: String(stableId),
|
||||
position,
|
||||
magnitude: mag,
|
||||
accent: depthAccent(depthKm || 0),
|
||||
}),
|
||||
const event = {
|
||||
stableId: String(stableId),
|
||||
usgsId,
|
||||
mag,
|
||||
place,
|
||||
time,
|
||||
depthKm,
|
||||
lon,
|
||||
lat,
|
||||
};
|
||||
nextEvents.push(event);
|
||||
nextDiscs.push(
|
||||
discItem(event, Boolean(ripples) && event.stableId === _selectedId),
|
||||
);
|
||||
const label = createEarthquakeOverlayEntry({
|
||||
id: String(stableId),
|
||||
position,
|
||||
magnitude: mag,
|
||||
accent: depthAccent(depthKm || 0),
|
||||
});
|
||||
if (canSelect()) {
|
||||
const id = String(stableId);
|
||||
label.interactive = true;
|
||||
label.accessibilityLabel = earthquakeZoomLabel(
|
||||
{ mag, place },
|
||||
text,
|
||||
);
|
||||
label.activate = () => selectAndFocus(id);
|
||||
}
|
||||
overlayEntries.push(label);
|
||||
}
|
||||
|
||||
// Bigger quakes first, so a small quake inside a big one's disc is
|
||||
// drawn, and picked, on top of it.
|
||||
nextDiscs.sort((a, b) => b.geometry.semiMajor - a.geometry.semiMajor);
|
||||
_discs.set(nextDiscs);
|
||||
_events = nextEvents;
|
||||
_eventById = new Map(
|
||||
nextEvents.map((event) => [event.stableId, event]),
|
||||
);
|
||||
_fadedDiscId =
|
||||
ripples && _eventById.has(_selectedId) ? _selectedId : null;
|
||||
// A selected quake still in the feed keeps its card, refreshed; one
|
||||
// that left the 24 h window loses it.
|
||||
if (_selectedId) publishCard();
|
||||
coverageChanged();
|
||||
if (_enabled) {
|
||||
overlayHost.setEntries(
|
||||
@@ -199,13 +579,19 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
|
||||
destroy(viewer = _viewer) {
|
||||
_request?.abort();
|
||||
_request = null;
|
||||
removeClickHandler();
|
||||
clearSelection();
|
||||
ripples?.dispose?.();
|
||||
_viewer = null;
|
||||
_enabled = false;
|
||||
overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID);
|
||||
overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false);
|
||||
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
|
||||
_discs?.dispose();
|
||||
_discs = null;
|
||||
_events = [];
|
||||
_eventById = new Map();
|
||||
_uncover?.();
|
||||
_uncover = null;
|
||||
_marksKey = null;
|
||||
|
||||
@@ -23,6 +23,12 @@ export const EARTHQUAKE_MARK_MAGNITUDE = 6;
|
||||
|
||||
/** The longest place a timeline mark's label carries, ellipsis and all. */
|
||||
const MARK_PLACE_LENGTH = 40;
|
||||
/**
|
||||
* The longest place line the detail card shows, ellipsis and all, so a long
|
||||
* place or translation keeps the card inside a phone's width. The card's
|
||||
* accessible name carries the whole place.
|
||||
*/
|
||||
const CARD_PLACE_LENGTH = 48;
|
||||
|
||||
/** A magnitude as the map's labels show it: `M6.4`. */
|
||||
export const earthquakeMagnitudeTitle = (magnitude) =>
|
||||
@@ -123,6 +129,332 @@ export function createEarthquakeOverlayEntry({
|
||||
};
|
||||
}
|
||||
|
||||
/** Where USGS publishes one event's page, its event id appended. */
|
||||
export const USGS_EVENT_PAGE_URL =
|
||||
'https://earthquake.usgs.gov/earthquakes/eventpage/';
|
||||
|
||||
/**
|
||||
* The USGS page for an event id, or null when there is no usable id (a
|
||||
* fallback `event-N` id never names a USGS page, and is never sent).
|
||||
* @param {unknown} usgsId
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function earthquakeEventLink(usgsId) {
|
||||
const id =
|
||||
typeof usgsId === 'string' || typeof usgsId === 'number'
|
||||
? String(usgsId).trim()
|
||||
: '';
|
||||
return /^[A-Za-z0-9_-]{1,64}$/.test(id)
|
||||
? `${USGS_EVENT_PAGE_URL}${id}`
|
||||
: null;
|
||||
}
|
||||
|
||||
// The package carries no i18n: with no translator given, the card stays
|
||||
// English, its `{name}` slots filled in.
|
||||
const english = (text, values) =>
|
||||
String(text).replace(/\{(\w+)\}/g, (all, key) =>
|
||||
values && Object.hasOwn(values, key) ? String(values[key]) : all,
|
||||
);
|
||||
const utcMinute = (time) =>
|
||||
`${new Date(time).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
||||
const oneDecimal = (value) => String(Math.round(value * 10) / 10);
|
||||
|
||||
/**
|
||||
* The detail card one clicked earthquake shows: its magnitude as the title,
|
||||
* then where, when and how deep, and the source. With a USGS event id the
|
||||
* card opens that event's page.
|
||||
* @param {{mag: number, place?: string|null, time?: number|null,
|
||||
* depthKm?: number|null, usgsId?: string|null}} event
|
||||
* @param {object} [text] The application's formatters.
|
||||
* @param {(text: string, values?: object) => string} [text.t] Translator.
|
||||
* @param {(time: number) => string} [text.formatTime] An event time.
|
||||
* @param {(value: number) => string} [text.formatDepth] A depth in km.
|
||||
* @param {boolean} [text.canOpen] Whether a link can be opened here (an
|
||||
* opener is injected); without one the card offers no link to click.
|
||||
* @returns {{title: string, details: string[], link: string|null,
|
||||
* accessibilityLabel: string}} `accessibilityLabel` names the card's
|
||||
* action, with its details: opening the source, or focusing the quake.
|
||||
*/
|
||||
export function describeEarthquake(
|
||||
event,
|
||||
{
|
||||
t = english,
|
||||
formatTime = utcMinute,
|
||||
formatDepth = oneDecimal,
|
||||
canOpen = true,
|
||||
} = {},
|
||||
) {
|
||||
const details = [];
|
||||
// What the card says, spoken: depth, the whole place, and the time.
|
||||
const spoken = [];
|
||||
// Severity at a glance, right under the title: the class meter, then
|
||||
// where in the crust it broke.
|
||||
const glance = [earthquakeSeverityMeter(event?.mag)];
|
||||
if (Number.isFinite(event?.depthKm)) {
|
||||
const depth = `${earthquakeDepthBandName(event.depthKm, t)} · ${t(
|
||||
'{km} km deep',
|
||||
{ km: formatDepth(event.depthKm) },
|
||||
)}`;
|
||||
glance.push(depth);
|
||||
spoken.push(depth);
|
||||
}
|
||||
details.push(glance.join(' '));
|
||||
const place =
|
||||
typeof event?.place === 'string'
|
||||
? event.place.replace(/\s+/g, ' ').trim()
|
||||
: '';
|
||||
if (place) {
|
||||
// Cut by characters, not UTF-16 units, so a pair is never split.
|
||||
const chars = Array.from(place);
|
||||
details.push(
|
||||
chars.length > CARD_PLACE_LENGTH
|
||||
? `${chars
|
||||
.slice(0, CARD_PLACE_LENGTH - 1)
|
||||
.join('')
|
||||
.trimEnd()}…`
|
||||
: place,
|
||||
);
|
||||
spoken.push(place);
|
||||
}
|
||||
if (Number.isFinite(event?.time)) {
|
||||
const time = formatTime(event.time);
|
||||
details.push(time);
|
||||
spoken.push(time);
|
||||
}
|
||||
const source = t('Source: {value}', { value: 'USGS' });
|
||||
details.push(source);
|
||||
// The source closes the spoken details, so they are never empty.
|
||||
spoken.push(source);
|
||||
const link = earthquakeEventLink(event?.usgsId);
|
||||
const opens = Boolean(link) && canOpen;
|
||||
if (opens) details.push(t('Click the card to open the source ↗'));
|
||||
const title = `${earthquakeMagnitudeTitle(event?.mag)} · ${earthquakeSeverityName(
|
||||
event?.mag,
|
||||
t,
|
||||
)}`;
|
||||
const summary = { title, details: spoken.join(', ') };
|
||||
return {
|
||||
title,
|
||||
details,
|
||||
link,
|
||||
accessibilityLabel: opens
|
||||
? t('Open the source for {title}, {details}', summary)
|
||||
: t('Focus earthquake {title}, {details}', summary),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* USGS's magnitude classes, weakest first: minor (under 4; the feed starts
|
||||
* at M2.5), light, moderate, strong, major, great (8 and up).
|
||||
*/
|
||||
export const EARTHQUAKE_SEVERITY_LEVELS = 6;
|
||||
|
||||
/**
|
||||
* A magnitude's USGS class, 0 (minor) to 5 (great).
|
||||
* @param {number} magnitude
|
||||
* @returns {number}
|
||||
*/
|
||||
export function earthquakeSeverityLevel(magnitude) {
|
||||
const mag = Number(magnitude);
|
||||
if (!Number.isFinite(mag) || mag < 4) return 0;
|
||||
return Math.min(EARTHQUAKE_SEVERITY_LEVELS - 1, Math.floor(mag) - 3);
|
||||
}
|
||||
|
||||
/** A magnitude's class, as a word in the page's language. */
|
||||
export function earthquakeSeverityName(magnitude, t = english) {
|
||||
switch (earthquakeSeverityLevel(magnitude)) {
|
||||
case 5:
|
||||
return t('Great', { context: 'earthquake' });
|
||||
case 4:
|
||||
return t('Major', { context: 'earthquake' });
|
||||
case 3:
|
||||
return t('Strong', { context: 'earthquake' });
|
||||
case 2:
|
||||
return t('Moderate', { context: 'earthquake' });
|
||||
case 1:
|
||||
return t('Light', { context: 'earthquake' });
|
||||
default:
|
||||
return t('Minor', { context: 'earthquake' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The class as a six-step meter, one filled block per class up to this one:
|
||||
* `■■□□□□` for a light quake. Plain text, so the card shows it as it is.
|
||||
* @param {number} magnitude
|
||||
* @returns {string}
|
||||
*/
|
||||
export function earthquakeSeverityMeter(magnitude) {
|
||||
const filled = earthquakeSeverityLevel(magnitude) + 1;
|
||||
return '■'.repeat(filled) + '□'.repeat(EARTHQUAKE_SEVERITY_LEVELS - filled);
|
||||
}
|
||||
|
||||
/**
|
||||
* The depth band the disc's colour shows, as a word: shallow (under 70 km,
|
||||
* red), intermediate (to 300 km, orange), deep (yellow).
|
||||
*/
|
||||
export function earthquakeDepthBandName(depthKm, t = english) {
|
||||
const band = depthBand(depthKm);
|
||||
if (band === SHALLOW) return t('Shallow', { context: 'earthquake' });
|
||||
if (band === INTERMEDIATE)
|
||||
return t('Intermediate', { context: 'earthquake' });
|
||||
return t('Deep', { context: 'earthquake' });
|
||||
}
|
||||
|
||||
/**
|
||||
* A quake's disc radius on the ground, in metres: it doubles with each
|
||||
* magnitude step (about 5.7 km at M2.5, 32 km at M5, 64 km at M6).
|
||||
* @param {number} magnitude
|
||||
* @returns {number}
|
||||
*/
|
||||
export const earthquakeDiscRadiusM = (magnitude) =>
|
||||
Math.pow(2, magnitude) * 1000;
|
||||
|
||||
/** How many contour lines run out from a selected quake at once. */
|
||||
export const EARTHQUAKE_RIPPLE_RINGS = 6;
|
||||
/** How long one contour line takes from the marker to the disc's edge. */
|
||||
export const EARTHQUAKE_RIPPLE_PERIOD_MS = 4800;
|
||||
/** Every this many lines one is an index contour, drawn heavier. */
|
||||
export const EARTHQUAKE_INDEX_CONTOUR_EVERY = 3;
|
||||
|
||||
/**
|
||||
* How far a contour line dents in from the circle, as a share of its
|
||||
* radius. Kept with the drift below so nested lines never cross: a line's
|
||||
* radius grows with `fraction` faster than its dents move (see
|
||||
* earthquakeContourScale).
|
||||
*/
|
||||
export const EARTHQUAKE_CONTOUR_WOBBLE = 0.24;
|
||||
const CONTOUR_HARMONICS = Object.freeze([2, 3, 5]);
|
||||
const CONTOUR_WEIGHTS = Object.freeze([1, 0.6, 0.3]);
|
||||
const CONTOUR_MAX_DRIFT = 1.5;
|
||||
|
||||
/** A stable 32-bit hash of a string (FNV-1a). */
|
||||
function hashString(text) {
|
||||
let h = 0x811c9dc5;
|
||||
for (const ch of String(text ?? '')) {
|
||||
h ^= ch.codePointAt(0);
|
||||
h = Math.imul(h, 0x01000193);
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* One quake's contour shape: a few harmonics around the circle, each with
|
||||
* its own phase and a drift that turns it as a line runs outward, seeded by
|
||||
* the quake's id so the same quake always draws the same contours.
|
||||
* @param {string} seed The quake's stable id.
|
||||
* @returns {ReadonlyArray<{harmonic: number, weight: number, phase: number, drift: number}>}
|
||||
*/
|
||||
export function earthquakeContourShape(seed) {
|
||||
let state = hashString(seed) || 1;
|
||||
// xorshift32: a small, stable stream from the seed.
|
||||
const next = () => {
|
||||
state ^= state << 13;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5;
|
||||
return (state >>> 0) / 0x100000000;
|
||||
};
|
||||
return Object.freeze(
|
||||
CONTOUR_HARMONICS.map((harmonic, i) =>
|
||||
Object.freeze({
|
||||
harmonic,
|
||||
weight: CONTOUR_WEIGHTS[i],
|
||||
phase: next() * 2 * Math.PI,
|
||||
drift: (next() * 2 - 1) * CONTOUR_MAX_DRIFT,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a contour line runs at `angle` (radians), as a share of a circle of
|
||||
* the same `fraction`: between 1 - EARTHQUAKE_CONTOUR_WOBBLE and 1, so the
|
||||
* outermost line never leaves the disc. The dents turn as `fraction` grows,
|
||||
* and no faster than the line grows, so lines never cross: with wobble A
|
||||
* and drift D, d(fraction · scale)/d(fraction) ≥ 1 - A - A·D/2 > 0.
|
||||
* @param {ReturnType<typeof earthquakeContourShape>} shape
|
||||
* @param {number} angle
|
||||
* @param {number} fraction 0 at the marker, 1 at the disc's edge.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function earthquakeContourScale(shape, angle, fraction) {
|
||||
let sum = 0;
|
||||
let total = 0;
|
||||
for (const { harmonic, weight, phase, drift } of shape) {
|
||||
sum += weight * Math.sin(harmonic * angle + phase + drift * fraction);
|
||||
total += weight;
|
||||
}
|
||||
const n = total > 0 ? sum / total : 0;
|
||||
return 1 - (EARTHQUAKE_CONTOUR_WOBBLE * (1 - n)) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* The selected quake's contour lines at a time: each runs from the marker
|
||||
* (`fraction` 0) out to the disc's edge (1), evenly staggered, fading in
|
||||
* just after it starts and out as it reaches the edge; every
|
||||
* EARTHQUAKE_INDEX_CONTOUR_EVERY-th is an index contour. Pure: the painter
|
||||
* gives the clock.
|
||||
* @param {number} timeMs Any steady clock, in milliseconds.
|
||||
* @param {{count?: number, periodMs?: number}} [options]
|
||||
* @returns {Array<{fraction: number, alpha: number, index: boolean}>}
|
||||
*/
|
||||
export function earthquakeRippleRings(
|
||||
timeMs,
|
||||
{
|
||||
count = EARTHQUAKE_RIPPLE_RINGS,
|
||||
periodMs = EARTHQUAKE_RIPPLE_PERIOD_MS,
|
||||
} = {},
|
||||
) {
|
||||
const phase = Number.isFinite(timeMs) && periodMs > 0 ? timeMs / periodMs : 0;
|
||||
const rings = [];
|
||||
for (let k = 0; k < count; k++) {
|
||||
const fraction = (((phase + k / count) % 1) + 1) % 1;
|
||||
rings.push({
|
||||
fraction,
|
||||
alpha: earthquakeRippleAlpha(fraction),
|
||||
index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0,
|
||||
});
|
||||
}
|
||||
return rings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Still contour lines, for viewers who ask for reduced motion: the same
|
||||
* lines as the animation, held evenly spaced out to the edge.
|
||||
* @param {number} [count]
|
||||
* @returns {Array<{fraction: number, alpha: number, index: boolean}>}
|
||||
*/
|
||||
export function earthquakeContourRings(count = EARTHQUAKE_RIPPLE_RINGS) {
|
||||
const rings = [];
|
||||
for (let k = 1; k <= count; k++)
|
||||
rings.push({
|
||||
fraction: k / count,
|
||||
alpha: 0.7,
|
||||
index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0,
|
||||
});
|
||||
return rings;
|
||||
}
|
||||
|
||||
const RIPPLE_FADE_IN = 0.12;
|
||||
/** A ring's opacity where it is: in from 0 near the marker, out to 0 at the edge. */
|
||||
function earthquakeRippleAlpha(fraction) {
|
||||
if (fraction <= 0 || fraction >= 1) return 0;
|
||||
return fraction < RIPPLE_FADE_IN
|
||||
? fraction / RIPPLE_FADE_IN
|
||||
: (1 - fraction) / (1 - RIPPLE_FADE_IN);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a magnitude label says to assistive technology: activating it zooms
|
||||
* to the quake (`Zoom to M5.0 · 42 km SW of Anchorage, Alaska`).
|
||||
* @param {{mag: number, place?: string|null}} event
|
||||
* @param {{t?: (text: string, values?: object) => string}} [text]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function earthquakeZoomLabel(event, { t = english } = {}) {
|
||||
return t('Zoom to {name}', { name: earthquakeMarkLabel(event) });
|
||||
}
|
||||
|
||||
/** Keep the largest events, with stable identity as the tie-break. */
|
||||
export function selectEarthquakeOverlayCohort(
|
||||
entries,
|
||||
|
||||
@@ -28,10 +28,15 @@ export function normalizeEarthquakeSnapshot(geojson) {
|
||||
return null;
|
||||
// A missing magnitude cannot establish that this event meets M2.5+.
|
||||
if (mag == null || mag < 2.5) continue;
|
||||
const stableId =
|
||||
feature.id == null || feature.id === ''
|
||||
? `event-${index + 1}`
|
||||
: String(feature.id);
|
||||
// An id-less event is named by what it is (time, position, depth and
|
||||
// magnitude), not by its row, so a refresh that inserts a row keeps the
|
||||
// selection on the same quake; a revision to any of those names a new
|
||||
// one. Two id-less events that match exactly fall back to the row.
|
||||
const idless = feature.id == null || feature.id === '';
|
||||
let stableId = idless
|
||||
? `event-${[properties.time ?? 'na', lon, lat, depthKm ?? 'na', mag].join(':')}`
|
||||
: String(feature.id);
|
||||
if (idless && ids.has(stableId)) stableId = `${stableId}:${index + 1}`;
|
||||
if (ids.has(stableId)) return null;
|
||||
ids.add(stableId);
|
||||
rows.push({
|
||||
|
||||
@@ -37,7 +37,7 @@ test('normalizeEarthquakeSnapshot parses valid GeoJSON earthquake features', ()
|
||||
});
|
||||
});
|
||||
|
||||
test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is missing or blank', () => {
|
||||
test('normalizeEarthquakeSnapshot names id-less events by their content, not their row', () => {
|
||||
const geojson = {
|
||||
features: [
|
||||
{
|
||||
@@ -55,10 +55,35 @@ test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is mi
|
||||
|
||||
const rows = normalizeEarthquakeSnapshot(geojson);
|
||||
assert.equal(rows.length, 2);
|
||||
assert.equal(rows[0].stableId, 'event-1');
|
||||
assert.equal(rows[0].stableId, 'event-1711930000000:139.6917:35.6895:25:3.5');
|
||||
assert.equal(rows[0].usgsId, null);
|
||||
assert.equal(rows[1].stableId, 'event-2');
|
||||
assert.equal(
|
||||
rows[1].stableId,
|
||||
'event-1711931000000:-70.6693:-33.4489:45.2:5.1',
|
||||
);
|
||||
assert.equal(rows[1].usgsId, '');
|
||||
// A row inserted ahead of them keeps each id-less quake's id, so a selected
|
||||
// one stays selected across the refresh.
|
||||
const inserted = normalizeEarthquakeSnapshot({
|
||||
features: [
|
||||
{
|
||||
id: 'us7000new',
|
||||
geometry: { type: 'Point', coordinates: [10, 20, 5] },
|
||||
properties: { mag: 4, place: 'New', time: 1711932000000 },
|
||||
},
|
||||
...geojson.features,
|
||||
],
|
||||
});
|
||||
assert.deepEqual(
|
||||
inserted.map((row) => row.stableId).slice(1),
|
||||
rows.map((row) => row.stableId),
|
||||
);
|
||||
// Two id-less events that match exactly stay apart.
|
||||
const twins = normalizeEarthquakeSnapshot({
|
||||
features: [geojson.features[0], geojson.features[0]],
|
||||
});
|
||||
assert.equal(twins.length, 2);
|
||||
assert.notEqual(twins[0].stableId, twins[1].stableId);
|
||||
});
|
||||
|
||||
test('normalizeEarthquakeSnapshot filters events below M2.5 without dropping the feed', () => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,30 +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;
|
||||
}
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{
|
||||
sourceId: FIRMS_OVERLAY_SOURCE_ID,
|
||||
},
|
||||
);
|
||||
if (cardHit) {
|
||||
const carded = layerState._fireByCardId.get(cardHit.entryId);
|
||||
if (carded) selectAndFocusFire(carded);
|
||||
return;
|
||||
}
|
||||
if (otherLayer) return;
|
||||
clearFireSelection();
|
||||
});
|
||||
}
|
||||
@@ -71,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 } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -93,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.
|
||||
@@ -229,6 +262,7 @@ export function createSelection({
|
||||
removeClickHandler,
|
||||
selectAndFocusFire,
|
||||
pickedFire,
|
||||
standInFire,
|
||||
selectFire,
|
||||
clearFireSelection,
|
||||
refreshContextRegistrations,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.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 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, {
|
||||
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 = [];
|
||||
const cleared = [];
|
||||
const layerState = {
|
||||
_viewer: viewer,
|
||||
_icons: { id: 'firms:icons' },
|
||||
_pickIndexById: new Map(),
|
||||
_fireByCardId: new Map([['firms-card:1', fire]]),
|
||||
_selectedFire: null,
|
||||
_contextIds: new Set(),
|
||||
};
|
||||
const selection = createSelection({
|
||||
layerState,
|
||||
services: {
|
||||
picking: { resolvePickId, isOwnedByOtherLayer: () => false, clickCard },
|
||||
focus: { requestWorldFocus: (request) => focused.push(request.kind) },
|
||||
context: {
|
||||
selectEntityContext() {},
|
||||
clearSelectedEntityContextForLayer: (id) => cleared.push(id),
|
||||
getContextStore() {},
|
||||
registerEntityContext() {},
|
||||
},
|
||||
},
|
||||
components: {
|
||||
model: {
|
||||
firePosition: () => ({ x: 0, y: 0, z: 0 }),
|
||||
formatFrp: String,
|
||||
confidenceBucket: String,
|
||||
},
|
||||
cards: { rebuildAmbientLabels() {} },
|
||||
},
|
||||
config: {
|
||||
id: 'firms',
|
||||
name: 'Fires',
|
||||
},
|
||||
});
|
||||
selection.installClickHandler();
|
||||
t.after(() => selection.removeClickHandler());
|
||||
return { fake, layerState, fire, focused, cleared };
|
||||
}
|
||||
|
||||
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();
|
||||
assert.equal(h.layerState._selectedFire, null);
|
||||
assert.deepEqual(h.focused, [], 'the camera is not sent to the fire');
|
||||
});
|
||||
|
||||
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, h.fire);
|
||||
assert.deepEqual(h.cleared, []);
|
||||
assert.deepEqual(h.focused, ['fire']);
|
||||
});
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -4,6 +4,8 @@ import { createCivilFlightLayer } from './index.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createEnrichment } from './enrichment.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { LiveSourceError } from '../../sources/live/contract.js';
|
||||
|
||||
function services() {
|
||||
@@ -609,6 +611,50 @@ test('a route answer for a callsign the plane no longer flies is dropped', async
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: an aircraft under another
|
||||
// layer's card is not even picked, so it is neither tracked nor released.
|
||||
test("another layer's card over an aircraft keeps the click", (t) => {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
body: { classList: { contains: () => false } },
|
||||
});
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
canvas: new EventTarget(),
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const flightState = createFlightState({ services: services() });
|
||||
flightState._trackedEntityChangedRemove = () => {};
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: { ...services(), picking },
|
||||
parts: {},
|
||||
layer: {},
|
||||
});
|
||||
tracking._installClickHandler(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
picking.setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
picking.setClickCardHitTest(null);
|
||||
flightState._clickSubscription?.();
|
||||
input.destroy();
|
||||
flightState.lifetime.abort();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
});
|
||||
|
||||
test("a type lookup overrides the feed's type and fills the type name", async () => {
|
||||
const queries = [];
|
||||
const source = {
|
||||
|
||||
@@ -88,7 +88,8 @@ export function createTracking({
|
||||
const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout;
|
||||
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
|
||||
services.camera;
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
|
||||
services.picking;
|
||||
const flightsLayer = layer;
|
||||
/** The tracked contact's billboard (an icon set on the draw port). */
|
||||
const trackedIcon = createTrackedAircraftIcon({
|
||||
@@ -1316,6 +1317,9 @@ export function createTracking({
|
||||
// first-person reference. A globe click must not fall through to the
|
||||
// normal empty-space deselection path; cockpit has explicit exit controls.
|
||||
if (document.body.classList.contains('cockpit-mode')) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard?.(event)) return;
|
||||
const picked = event.hit;
|
||||
|
||||
if (picked) {
|
||||
|
||||
@@ -707,13 +707,19 @@ export function createGhostMapsLayer({
|
||||
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
|
||||
);
|
||||
_clickSubscription = inputFor(_viewer).onClick((event) => {
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{ sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours opens its source whatever is drawn
|
||||
// under it; another layer's is that layer's click, so the maps under
|
||||
// it do not act and the selection stays.
|
||||
const cardHit = picking.clickCard?.(event) ?? null;
|
||||
if (cardHit) {
|
||||
if (
|
||||
cardHit.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID &&
|
||||
cardHit.entryId === _selectedCardId &&
|
||||
_selectedLink &&
|
||||
openExternal
|
||||
)
|
||||
openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = event.topHit;
|
||||
|
||||
@@ -1,8 +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 = {}) {
|
||||
@@ -672,3 +675,109 @@ test('narrowing to a window the loaded data covers clears a failed wider reload'
|
||||
assert.equal(layer.getStats().error, null);
|
||||
assert.equal(layer.getStats().count, 1);
|
||||
});
|
||||
|
||||
test("a 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: [
|
||||
{
|
||||
name: 'Linked',
|
||||
description:
|
||||
'<table><tr><td>Date</td><td>11/2/2026</td></tr>' +
|
||||
'<tr><td>Source</td><td><a href="https://example.com/report">report</a></td></tr></table>',
|
||||
},
|
||||
],
|
||||
controls: {
|
||||
overlayHost: { setEntries: (_id, entries) => cards.push(entries) },
|
||||
picking: { resolvePickId: (picked) => picked?.id ?? null, clickCard },
|
||||
openExternal: (url) => opened.push(url),
|
||||
},
|
||||
});
|
||||
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, 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.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(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');
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { LAYER_ID } from './policy.js';
|
||||
|
||||
export function createSelection({
|
||||
@@ -52,6 +53,9 @@ export function createSelection({
|
||||
const input = inputFor(viewer);
|
||||
layerState.clickSubscription = input.onClick((event) => {
|
||||
if (!layerState.enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
// A site's dot, outline or fill, or a named marker: each draw item
|
||||
// names its installation in its `meta`.
|
||||
const hit = event.drawHit;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
|
||||
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
|
||||
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
|
||||
function harness(t) {
|
||||
const previousWindow = globalThis.window;
|
||||
@@ -186,6 +187,30 @@ test('a click on a named marker point selects its site; again releases it', (t)
|
||||
h.assertSelected(false);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a site under another
|
||||
// layer's card neither selects nor releases.
|
||||
test("another layer's card over a site keeps the click", (t) => {
|
||||
const h = harness(t);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
const setId = h.parts.namedMarkers.setId;
|
||||
const item = h.draw.set(setId).items.get(namedPointId('base'));
|
||||
const pointPick = { id: { set: setId, id: item.id, meta: item.meta } };
|
||||
h.click(pointPick);
|
||||
h.assertSelected(true);
|
||||
h.click(undefined);
|
||||
h.assertSelected(true);
|
||||
h.state.selectedId = null;
|
||||
context.clearSelectedEntityContextForLayer('military-installations');
|
||||
h.parts.rendering.renderRecords();
|
||||
h.click(pointPick);
|
||||
h.assertSelected(false);
|
||||
top = null;
|
||||
h.click(pointPick);
|
||||
h.assertSelected(true);
|
||||
});
|
||||
|
||||
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
|
||||
const h = harness(t);
|
||||
h.state.selectedId = null;
|
||||
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
});
|
||||
Vendored
+106
-1
@@ -1,4 +1,35 @@
|
||||
import { formatNumber, t } from '../../i18n/index.js';
|
||||
|
||||
export function createControls({ state: layerState, services, parts, source }) {
|
||||
let unsubscribeRowControls = null;
|
||||
|
||||
function cycleMission(step) {
|
||||
const entries = layerState._missionRosterView?.entries;
|
||||
if (!layerState._enabled || !entries?.length) return;
|
||||
const index = entries.findIndex(
|
||||
({ id }) => id === layerState._selectedLaunchId,
|
||||
);
|
||||
const next =
|
||||
index < 0
|
||||
? step > 0
|
||||
? 0
|
||||
: entries.length - 1
|
||||
: (index + step + entries.length) % entries.length;
|
||||
parts.panel.selectMissionAt(entries[next].index);
|
||||
// Stepped from the Data Layers row: the panel opens, as for a globe pick.
|
||||
const id = layerState._selectedLaunchId;
|
||||
for (const listener of [...(layerState._globePickListeners || [])]) {
|
||||
try {
|
||||
listener(id);
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[Data:RocketLaunches] mission step listener failed',
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const methods = {
|
||||
id: 'rocket-launches',
|
||||
|
||||
@@ -10,6 +41,67 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
|
||||
updateInterval: 300000,
|
||||
|
||||
getRowControls() {
|
||||
const entries = layerState._missionRosterView?.entries;
|
||||
if (!layerState._enabled || !entries?.length) return null;
|
||||
const index = entries.findIndex(
|
||||
({ id }) => id === layerState._selectedLaunchId,
|
||||
);
|
||||
const disabled = entries.length === 1 && index >= 0;
|
||||
return {
|
||||
info:
|
||||
index < 0
|
||||
? t('SELECT A MISSION TO INSPECT')
|
||||
: `${formatNumber(index + 1)} / ${formatNumber(entries.length)} · ${entries[index].label}`,
|
||||
chips: [
|
||||
{
|
||||
id: 'previous-mission',
|
||||
label: t('Previous mission'),
|
||||
icon: 'chevron_left',
|
||||
action: true,
|
||||
disabled,
|
||||
onClick: () => cycleMission(-1),
|
||||
},
|
||||
{
|
||||
id: 'next-mission',
|
||||
label: t('Next mission'),
|
||||
icon: 'chevron_right',
|
||||
action: true,
|
||||
disabled,
|
||||
onClick: () => cycleMission(1),
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
|
||||
setRowControlsListener(listener) {
|
||||
unsubscribeRowControls?.();
|
||||
unsubscribeRowControls = null;
|
||||
if (!listener) return;
|
||||
let previousRoster;
|
||||
let previousSelection;
|
||||
unsubscribeRowControls = parts.panel.subscribePanel(({ roster }) => {
|
||||
// Replay and telemetry can update without changing the roster or pick.
|
||||
const selection = layerState._selectedLaunchId;
|
||||
if (roster === previousRoster && selection === previousSelection)
|
||||
return;
|
||||
previousRoster = roster;
|
||||
previousSelection = selection;
|
||||
listener();
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Hear each mission picked on the globe (a marker or its label), after
|
||||
* it is selected. The app reveals the Space Missions panel for it.
|
||||
* @param {(launchId: string) => void} listener
|
||||
* @returns {() => void} Unsubscribe.
|
||||
*/
|
||||
subscribeGlobePick(listener) {
|
||||
layerState._globePickListeners.add(listener);
|
||||
return () => layerState._globePickListeners.delete(listener);
|
||||
},
|
||||
|
||||
/** Release only Space Mission camera ownership, preserving layer and selection state. */
|
||||
releaseCameraOwnership() {
|
||||
// Navigation takes the camera; a failed entry must not restore the old view.
|
||||
@@ -54,19 +146,32 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
return result;
|
||||
},
|
||||
|
||||
/**
|
||||
* Why a start failed, for the person: the mission index never loaded.
|
||||
* Null when the failure is not the index's (the app then names it).
|
||||
* @returns {?string}
|
||||
*/
|
||||
enableFailureMessage() {
|
||||
return layerState._lastError && layerState._lastUpdate == null
|
||||
? t(
|
||||
'Space Missions unavailable: the mission index could not load. Try again later.',
|
||||
)
|
||||
: null;
|
||||
},
|
||||
|
||||
getStats() {
|
||||
return {
|
||||
count: layerState._count,
|
||||
orbitMatches: layerState._orbitMatches,
|
||||
lastUpdate: layerState._lastUpdate,
|
||||
error: layerState._lastError,
|
||||
errorAt: layerState._lastErrorAt,
|
||||
stale: layerState._stale,
|
||||
};
|
||||
},
|
||||
|
||||
attachDataManager(dataManager) {
|
||||
layerState._dataManager = dataManager;
|
||||
parts.satelliteIntents.connect(dataManager);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DataLayerManager } from '../../data/manager.js';
|
||||
import { ContextControls } from '../../ui/contextControls.js';
|
||||
import { spaceMissionsIndexFailure } from '../../ui/contextActions.js';
|
||||
import { createLaunchSource } from './source.js';
|
||||
import { createState } from './state.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createPolicyHelpers } from './policyHelpers.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createSatelliteIntents } from './satelliteIntents.js';
|
||||
import { createPanel } from './panel.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
@@ -98,7 +98,7 @@ function fakeCamera() {
|
||||
return camera;
|
||||
}
|
||||
|
||||
async function fixture(t) {
|
||||
async function fixture(t, { beforeConnect } = {}) {
|
||||
const upstream = { status: 429, results: [launchRecord] };
|
||||
const source = createLaunchSource({
|
||||
async fetchImpl(url) {
|
||||
@@ -191,6 +191,7 @@ async function fixture(t) {
|
||||
parts.panel = createPanel(context);
|
||||
parts.replay = createReplay(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.satelliteIntents = createSatelliteIntents(context);
|
||||
parts.controls = createControls(context);
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
const missions = Object.assign(
|
||||
@@ -206,6 +207,7 @@ async function fixture(t) {
|
||||
manager.register(plainLayer('earthquakes', 'Earthquakes (24h)'));
|
||||
manager.register(plainLayer('satellites', 'Satellites'));
|
||||
manager.register(plainLayer('wind', 'Wind'));
|
||||
manager.register(plainLayer('military-awareness', 'Global Context'));
|
||||
manager.register(missions);
|
||||
missions.attachDataManager(manager);
|
||||
|
||||
@@ -224,12 +226,19 @@ async function fixture(t) {
|
||||
setPanelCollapsed: noop,
|
||||
},
|
||||
});
|
||||
beforeConnect?.(manager);
|
||||
controls.connect(manager);
|
||||
|
||||
t.after(async () => {
|
||||
controls.stop();
|
||||
controls.disconnect();
|
||||
for (const id of ['rocket-launches', 'satellites', 'earthquakes', 'wind'])
|
||||
for (const id of [
|
||||
'rocket-launches',
|
||||
'satellites',
|
||||
'earthquakes',
|
||||
'wind',
|
||||
'military-awareness',
|
||||
])
|
||||
await manager.setEnabled(id, false);
|
||||
await missions.destroy(viewer);
|
||||
});
|
||||
@@ -257,46 +266,37 @@ async function fixture(t) {
|
||||
state,
|
||||
camera,
|
||||
rosters,
|
||||
panel: parts.panel,
|
||||
enabledIds,
|
||||
view,
|
||||
settle,
|
||||
};
|
||||
}
|
||||
|
||||
const entries = {
|
||||
direct: (f) =>
|
||||
f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
'Context-panel': async (f) =>
|
||||
(
|
||||
await f.controls.setContextMode('space-missions', {
|
||||
claimVisualAuthority: false,
|
||||
})
|
||||
).ok,
|
||||
};
|
||||
test('a Space Missions start that gets HTTP 429 rolls back and leaves other layers alone', async (t) => {
|
||||
const f = await fixture(t);
|
||||
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
const before = f.view();
|
||||
|
||||
for (const [path, enter] of Object.entries(entries))
|
||||
test(`a ${path} Space Missions entry that gets HTTP 429 rolls back instead of isolating`, async (t) => {
|
||||
const f = await fixture(t);
|
||||
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
const before = f.view();
|
||||
|
||||
const entered = await enter(f);
|
||||
await f.settle();
|
||||
|
||||
assert.equal(entered, false, 'a failed mission index fails the enable');
|
||||
assert.deepEqual(f.enabledIds(), ['earthquakes']);
|
||||
assert.equal(f.controls.getContextModeState().mode, null);
|
||||
assert.equal(f.controls.getContextModeState().active, false);
|
||||
assert.equal(f.missions.getStats().error, 'HTTP 429');
|
||||
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
|
||||
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
|
||||
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('wind', true, { origin: 'user' }),
|
||||
true,
|
||||
'an unrelated layer is not blocked after the failed entry',
|
||||
);
|
||||
const entered = await f.manager.setEnabled('rocket-launches', true, {
|
||||
origin: 'user',
|
||||
});
|
||||
await f.settle();
|
||||
|
||||
assert.equal(entered, false, 'a failed mission index fails the enable');
|
||||
assert.deepEqual(f.enabledIds(), ['earthquakes']);
|
||||
assert.equal(f.controls.getContextModeState().mode, null);
|
||||
assert.equal(f.controls.getContextModeState().active, false);
|
||||
assert.equal(f.missions.getStats().error, 'HTTP 429');
|
||||
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
|
||||
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
|
||||
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('wind', true, { origin: 'user' }),
|
||||
true,
|
||||
'an unrelated layer is not blocked after the failed entry',
|
||||
);
|
||||
});
|
||||
|
||||
// Holds the /api/launches reply until the returned release is called.
|
||||
function holdReply(f) {
|
||||
@@ -410,7 +410,12 @@ test('the roster reports a failed mission index instead of loading forever', asy
|
||||
await f.settle();
|
||||
assert.equal(f.rosters.slice(loadingFrom).includes(null), true);
|
||||
assert.equal(f.rosters.at(-1).entries.length, 1);
|
||||
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), true);
|
||||
assert.equal(
|
||||
f.controls.getContextModeState().mode,
|
||||
null,
|
||||
'not a Context mode',
|
||||
);
|
||||
});
|
||||
|
||||
test('a valid empty mission index is a successful entry', async (t) => {
|
||||
@@ -422,7 +427,7 @@ test('a valid empty mission index is a successful entry', async (t) => {
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), true);
|
||||
assert.equal(
|
||||
f.rosters.at(-1).empty,
|
||||
'NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW',
|
||||
@@ -430,7 +435,383 @@ test('a valid empty mission index is a successful entry', async (t) => {
|
||||
assert.ok(f.camera.flights > 0, 'a successful entry frames the globe');
|
||||
});
|
||||
|
||||
test('a refresh failure after a loaded index keeps the mode and its records', async (t) => {
|
||||
for (const phase of ['while starting', 'after start']) {
|
||||
test(`Space Missions runs beside Contacts and a later Satellites OFF ends it (${phase})`, async (t) => {
|
||||
const gate = Promise.withResolvers();
|
||||
const guardReached = Promise.withResolvers();
|
||||
const f = await fixture(t, {
|
||||
beforeConnect(manager) {
|
||||
if (phase !== 'while starting') return;
|
||||
manager.addVisibilityGuard(async ({ layerId, enabled }) => {
|
||||
if (layerId !== 'rocket-launches' || !enabled) return;
|
||||
guardReached.resolve();
|
||||
await gate.promise;
|
||||
});
|
||||
},
|
||||
});
|
||||
f.upstream.status = 200;
|
||||
await f.manager.setEnabled('satellites', true, { origin: 'user' });
|
||||
assert.equal(await f.controls._selectContextMode('flights'), true);
|
||||
await f.settle();
|
||||
assert.deepEqual(
|
||||
f.enabledIds(),
|
||||
['military-awareness', 'satellites'],
|
||||
'Contacts leaves Satellites alone',
|
||||
);
|
||||
|
||||
const launch = f.manager.setEnabled('rocket-launches', true, {
|
||||
origin: 'user',
|
||||
});
|
||||
try {
|
||||
if (phase === 'while starting') {
|
||||
await guardReached.promise;
|
||||
} else {
|
||||
assert.equal(await launch, true);
|
||||
assert.deepEqual(f.enabledIds(), [
|
||||
'military-awareness',
|
||||
'rocket-launches',
|
||||
'satellites',
|
||||
]);
|
||||
}
|
||||
assert.equal(
|
||||
f.controls.getContextModeState().mode,
|
||||
'flights',
|
||||
'starting Space Missions leaves Contacts on',
|
||||
);
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('satellites', false, { origin: 'voice' }),
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
gate.resolve();
|
||||
}
|
||||
assert.equal(await launch, phase === 'after start');
|
||||
await f.missions.waitForSatelliteIntents?.();
|
||||
await f.settle();
|
||||
assert.deepEqual(f.enabledIds(), ['military-awareness']);
|
||||
assert.equal(f.controls.getContextModeState().mode, 'flights');
|
||||
});
|
||||
}
|
||||
|
||||
test('Contacts started and ended while Space Missions runs leaves it and Satellites alone', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
const missionParams = f.manager.getLayerParams('satellites');
|
||||
assert.equal(missionParams.showPoints, false, 'the mission display applied');
|
||||
|
||||
assert.equal(await f.controls._selectContextMode('flights'), true);
|
||||
await f.settle();
|
||||
assert.deepEqual(f.enabledIds(), [
|
||||
'military-awareness',
|
||||
'rocket-launches',
|
||||
'satellites',
|
||||
]);
|
||||
assert.equal(await f.controls._selectContextMode(null), true);
|
||||
await f.settle();
|
||||
assert.deepEqual(f.enabledIds(), ['rocket-launches', 'satellites']);
|
||||
assert.deepEqual(f.manager.getLayerParams('satellites'), missionParams);
|
||||
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.deepEqual(f.enabledIds(), []);
|
||||
const after = f.manager.getLayerParams('satellites');
|
||||
assert.notEqual(after.showPoints, false, 'Satellites shows its points again');
|
||||
assert.notEqual(after.showOrbits, false, 'and its orbits');
|
||||
});
|
||||
|
||||
test('a Satellites OFF requested before Space Missions entry does not cancel it', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
await f.manager.setEnabled('satellites', true, { origin: 'user' });
|
||||
const satellites = f.manager.layers.get('satellites').module;
|
||||
const disable = satellites.disable;
|
||||
const gate = Promise.withResolvers();
|
||||
const disabling = Promise.withResolvers();
|
||||
satellites.disable = async () => {
|
||||
disabling.resolve();
|
||||
await gate.promise;
|
||||
};
|
||||
let entry;
|
||||
try {
|
||||
const off = f.manager.setEnabled('satellites', false, { origin: 'user' });
|
||||
await disabling.promise;
|
||||
// The entry is requested while the earlier OFF is still settling.
|
||||
entry = f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
|
||||
gate.resolve();
|
||||
assert.equal(await off, true);
|
||||
} finally {
|
||||
gate.resolve();
|
||||
satellites.disable = disable;
|
||||
}
|
||||
assert.equal(await entry, true, 'the later entry is not cancelled');
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), true);
|
||||
|
||||
// Leaving keeps the earlier Satellites OFF.
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), false);
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), false);
|
||||
});
|
||||
|
||||
test('Space Missions is an ordinary layer: it neither isolates nor opens a Context session', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
assert.deepEqual(f.enabledIds(), [
|
||||
'earthquakes',
|
||||
'rocket-launches',
|
||||
'satellites',
|
||||
]);
|
||||
assert.equal(f.controls._contextSessionSnapshot, null);
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('wind', true, { origin: 'user' }),
|
||||
true,
|
||||
'other layers are not refused while Space Missions is on',
|
||||
);
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.deepEqual(
|
||||
f.enabledIds(),
|
||||
['earthquakes', 'wind'],
|
||||
'Space Missions gives back only the Satellites it turned on',
|
||||
);
|
||||
});
|
||||
|
||||
test('a Satellites enable that never settles still lets mission disable complete', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
f.state.satelliteSettleTimeoutMs = 50;
|
||||
const satellites = f.manager.layers.get('satellites').module;
|
||||
const enable = satellites.enable;
|
||||
const stuck = Promise.withResolvers();
|
||||
satellites.enable = () => stuck.promise;
|
||||
try {
|
||||
// A programmatic Satellites restart whose enable hangs.
|
||||
await f.manager.setEnabled('satellites', false);
|
||||
void f.manager.setEnabled('satellites', true);
|
||||
const exit = f.manager.setEnabled('rocket-launches', false, {
|
||||
origin: 'user',
|
||||
});
|
||||
const outcome = await Promise.race([
|
||||
exit.then(() => 'settled'),
|
||||
new Promise((resolve) => setTimeout(() => resolve('hung'), 2000)),
|
||||
]);
|
||||
assert.equal(
|
||||
outcome,
|
||||
'settled',
|
||||
'the mission disable does not wait forever',
|
||||
);
|
||||
assert.equal(f.missions.getAnalystRecords().length, 0);
|
||||
} finally {
|
||||
satellites.enable = enable;
|
||||
stuck.resolve();
|
||||
}
|
||||
await f.settle();
|
||||
// The saved Satellites state was kept: turning Space Missions off again
|
||||
// once Satellites settles gives back the Satellites it turned on.
|
||||
assert.equal(f.manager.isEnabled('satellites'), true);
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), false);
|
||||
assert.equal(f.manager.isEnabled('satellites'), false);
|
||||
});
|
||||
|
||||
test('Space Missions turned on again after a busy restore switches Satellites on', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
f.state.satelliteSettleTimeoutMs = 50;
|
||||
const satellites = f.manager.layers.get('satellites').module;
|
||||
const enable = satellites.enable;
|
||||
const stuck = Promise.withResolvers();
|
||||
satellites.enable = () => stuck.promise;
|
||||
try {
|
||||
await f.manager.setEnabled('satellites', false);
|
||||
void f.manager.setEnabled('satellites', true);
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
} finally {
|
||||
satellites.enable = enable;
|
||||
stuck.resolve();
|
||||
}
|
||||
await f.settle();
|
||||
// Something else switches Satellites off, then Space Missions comes back.
|
||||
await f.manager.setEnabled('satellites', false);
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), false);
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), true);
|
||||
// Its own off still gives back the Satellites from before the first start.
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), false);
|
||||
});
|
||||
|
||||
test('a Satellites switch made between missions is what the next mission gives back', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
f.state.satelliteSettleTimeoutMs = 50;
|
||||
const satellites = f.manager.layers.get('satellites').module;
|
||||
const enable = satellites.enable;
|
||||
const stuck = Promise.withResolvers();
|
||||
satellites.enable = () => stuck.promise;
|
||||
try {
|
||||
await f.manager.setEnabled('satellites', false);
|
||||
void f.manager.setEnabled('satellites', true);
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
} finally {
|
||||
satellites.enable = enable;
|
||||
stuck.resolve();
|
||||
}
|
||||
await f.settle();
|
||||
// The person switches Satellites on, then something else switches it off.
|
||||
await f.manager.setEnabled('satellites', true, { origin: 'user' });
|
||||
await f.settle();
|
||||
await f.manager.setEnabled('satellites', false);
|
||||
await f.settle();
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), true);
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), false);
|
||||
});
|
||||
|
||||
test('a Satellites setting changed between missions survives the next one', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
f.state.satelliteSettleTimeoutMs = 50;
|
||||
const satellites = f.manager.layers.get('satellites').module;
|
||||
const enable = satellites.enable;
|
||||
const stuck = Promise.withResolvers();
|
||||
satellites.enable = () => stuck.promise;
|
||||
try {
|
||||
await f.manager.setEnabled('satellites', false);
|
||||
void f.manager.setEnabled('satellites', true);
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
} finally {
|
||||
satellites.enable = enable;
|
||||
stuck.resolve();
|
||||
}
|
||||
await f.settle();
|
||||
f.manager.setLayerParams(
|
||||
'satellites',
|
||||
{ showOrbits: false },
|
||||
{ origin: 'user' },
|
||||
);
|
||||
await f.settle();
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
|
||||
await f.settle();
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(f.manager.getLayerParams('satellites').showOrbits, false);
|
||||
});
|
||||
|
||||
test('tracking stopped by a place search during a mission stays stopped after it', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
f.manager.setLayerParams(
|
||||
'satellites',
|
||||
{ selectedSatTrackingId: 25544 },
|
||||
{ origin: 'voice' },
|
||||
);
|
||||
await f.settle();
|
||||
// A place search stops tracking with the tool origin.
|
||||
f.manager.setLayerParams(
|
||||
'satellites',
|
||||
{ selectedSatTrackingId: null },
|
||||
{ origin: 'tool' },
|
||||
);
|
||||
await f.settle();
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(
|
||||
f.manager.getLayerParams('satellites').selectedSatTrackingId ?? null,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('a failed Satellites restore still clears the selected mission panel', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
|
||||
true,
|
||||
);
|
||||
await f.settle();
|
||||
assert.equal(f.manager.isEnabled('satellites'), true);
|
||||
|
||||
let panelView;
|
||||
const unsubscribe = f.panel.subscribePanel((view) => {
|
||||
panelView = view;
|
||||
});
|
||||
const satellites = f.manager.layers.get('satellites').module;
|
||||
const disable = satellites.disable;
|
||||
try {
|
||||
f.state._selectedLaunchId = f.state._launches[0].id;
|
||||
f.panel.renderMissionPanel();
|
||||
assert.ok(panelView.mission);
|
||||
|
||||
satellites.disable = () => {
|
||||
throw new Error('injected Satellites restore failure');
|
||||
};
|
||||
assert.equal(
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' }),
|
||||
false,
|
||||
);
|
||||
const { enabled, uncertain } =
|
||||
f.manager.getLayerLifecycleState('rocket-launches');
|
||||
assert.equal(enabled, true);
|
||||
assert.equal(uncertain, true);
|
||||
assert.equal(panelView.mission, null);
|
||||
} finally {
|
||||
satellites.disable = disable;
|
||||
unsubscribe();
|
||||
}
|
||||
});
|
||||
|
||||
test('a refresh failure after a loaded index keeps the layer and its records', async (t) => {
|
||||
const f = await fixture(t);
|
||||
f.upstream.status = 200;
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
|
||||
@@ -442,12 +823,11 @@ test('a refresh failure after a loaded index keeps the mode and its records', as
|
||||
await f.settle();
|
||||
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), true);
|
||||
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
|
||||
assert.equal(f.missions.getStats().count, 1);
|
||||
assert.equal(f.missions.getStats().error, 'HTTP 429');
|
||||
assert.equal(f.rosters.at(-1).entries.length, 1);
|
||||
|
||||
// Leaving a loaded mode does not restore the pre-entry view.
|
||||
// Leaving after a loaded index does not restore the pre-entry view.
|
||||
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.deepEqual(f.view(), framed);
|
||||
@@ -475,11 +855,9 @@ test('a failed first load tells the user the mission index is unavailable', asyn
|
||||
const f = await fixture(t);
|
||||
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
|
||||
|
||||
await f.controls.setContextMode('space-missions', {
|
||||
claimVisualAuthority: false,
|
||||
});
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.equal(f.controls.getContextModeState().mode, null, 'rolled back');
|
||||
assert.equal(f.manager.isEnabled('rocket-launches'), false, 'rolled back');
|
||||
assert.ok(
|
||||
f.toasts.some((message) => /mission index/i.test(message)),
|
||||
`visible feedback names the failure, got ${JSON.stringify(f.toasts)}`,
|
||||
@@ -504,10 +882,17 @@ test('navigation taking the camera keeps a mission flight it asked to preserve',
|
||||
assert.equal(f.camera.flight, other);
|
||||
});
|
||||
|
||||
test("an earlier attempt's index error is not blamed for a later failure", async (t) => {
|
||||
test('a refresh error after a loaded index is not blamed on the index', async (t) => {
|
||||
const f = await fixture(t);
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
|
||||
await f.settle();
|
||||
assert.match(spaceMissionsIndexFailure(f.manager), /mission index/);
|
||||
assert.equal(spaceMissionsIndexFailure(f.manager, Date.now() + 1), null);
|
||||
assert.match(f.missions.enableFailureMessage(), /mission index/);
|
||||
|
||||
f.upstream.status = 200;
|
||||
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
|
||||
await f.settle();
|
||||
f.upstream.status = 429;
|
||||
await f.missions.update();
|
||||
assert.equal(f.missions.getStats().error, 'HTTP 429');
|
||||
assert.equal(f.missions.enableFailureMessage(), null);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createPolicyHelpers } from './policyHelpers.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createSatelliteIntents } from './satelliteIntents.js';
|
||||
import { createOrbitRendering } from './orbitRendering.js';
|
||||
import { createOverlays } from './overlays.js';
|
||||
import { createSelection } from './selection.js';
|
||||
@@ -24,6 +25,7 @@ export function createRocketLaunchesLayer({ services, source }) {
|
||||
const context = { state, services, parts, source };
|
||||
parts.policyHelpers = createPolicyHelpers(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.satelliteIntents = createSatelliteIntents(context);
|
||||
parts.orbitRendering = createOrbitRendering(context);
|
||||
parts.overlays = createOverlays(context);
|
||||
parts.selection = createSelection(context);
|
||||
@@ -45,6 +47,7 @@ export function createRocketLaunchesLayer({ services, source }) {
|
||||
parts.panel.commands,
|
||||
{
|
||||
subscribePanel: parts.panel.subscribePanel,
|
||||
waitForSatelliteIntents: parts.satelliteIntents.settled,
|
||||
subscribeReplayOverlay: parts.overlays.subscribeReplayOverlay,
|
||||
satelliteParamsForSpaceMissions:
|
||||
parts.policyHelpers.satelliteParamsForSpaceMissions,
|
||||
|
||||
@@ -1,4 +1,18 @@
|
||||
import { MAX_POST_TLE_RETRIES, POST_TLE_RETRY_DELAY_MS } from './policy.js';
|
||||
import {
|
||||
MAX_POST_TLE_RETRIES,
|
||||
POST_TLE_RETRY_DELAY_MS,
|
||||
cockpitActive,
|
||||
} from './policy.js';
|
||||
|
||||
/**
|
||||
* Let pending Satellites work finish, including requests that join it while
|
||||
* waiting, so the mission dependency cannot overtake it. Bounded: a
|
||||
* Satellites change that never settles cannot hold missions forever.
|
||||
*/
|
||||
async function waitForSatelliteVisibility(manager, { signal, timeoutMs }) {
|
||||
if (typeof manager.waitForLayerIdle !== 'function') return true;
|
||||
return manager.waitForLayerIdle('satellites', { signal, timeoutMs });
|
||||
}
|
||||
|
||||
export function createIngestion({
|
||||
state: layerState,
|
||||
@@ -97,28 +111,51 @@ export function createIngestion({
|
||||
}
|
||||
|
||||
async function captureSatelliteDependency() {
|
||||
if (!layerState._dataManager || layerState._satelliteStateBeforeMission)
|
||||
const manager = layerState._dataManager;
|
||||
if (!manager) return;
|
||||
const token = layerState._lifecycleToken;
|
||||
// Let a pending Satellites action finish before reserving dependency ON.
|
||||
// A successful explicit OFF can cancel this mission entry while we wait.
|
||||
const idle = await waitForSatelliteVisibility(manager, {
|
||||
signal: layerState._sourceController?.signal,
|
||||
timeoutMs: layerState.satelliteSettleTimeoutMs,
|
||||
});
|
||||
if (token !== layerState._lifecycleToken) return;
|
||||
if (!idle && layerState._enabled)
|
||||
throw new Error(
|
||||
'Space Missions could not start: the satellites layer did not settle',
|
||||
);
|
||||
if (
|
||||
!layerState._enabled ||
|
||||
(manager.layers?.has('rocket-launches') &&
|
||||
!manager.isEffectivelyEnabled('rocket-launches'))
|
||||
)
|
||||
return;
|
||||
layerState._satelliteStateBeforeMission = {
|
||||
// Effective visibility: a user enable still mid-activation is intent ON —
|
||||
// capturing settled false would restore the user's enable away on exit.
|
||||
enabled:
|
||||
layerState._dataManager.isEffectivelyEnabled?.('satellites') ??
|
||||
layerState._dataManager.isEnabled('satellites'),
|
||||
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
|
||||
layerState._dataManager.getLayerParams('satellites'),
|
||||
),
|
||||
};
|
||||
layerState._dataManager.setLayerParams(
|
||||
// A saved state kept by a restore that could not finish (Satellites was
|
||||
// busy) is still the one from before the mission: keep it, and switch
|
||||
// Satellites on for the mission again. A Satellites switch the person
|
||||
// made since (restoreVisibility false) settled its visibility, so it
|
||||
// is taken as it is now; its params are still the saved ones.
|
||||
const kept = layerState._satelliteStateBeforeMission;
|
||||
if (kept?.restoreVisibility === false)
|
||||
layerState._satelliteStateBeforeMission = {
|
||||
enabled: manager.isEnabled('satellites'),
|
||||
params: kept.params,
|
||||
};
|
||||
else if (!kept)
|
||||
layerState._satelliteStateBeforeMission = {
|
||||
enabled: manager.isEnabled('satellites'),
|
||||
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
|
||||
manager.getLayerParams('satellites'),
|
||||
),
|
||||
};
|
||||
manager.setLayerParams(
|
||||
'satellites',
|
||||
parts.policyHelpers.satelliteParamsForSpaceMissions(
|
||||
layerState._satelliteStateBeforeMission.params,
|
||||
),
|
||||
);
|
||||
const token = layerState._lifecycleToken;
|
||||
const activation = Promise.resolve(
|
||||
layerState._dataManager.setEnabled('satellites', true),
|
||||
);
|
||||
const activation = Promise.resolve(manager.setEnabled('satellites', true));
|
||||
layerState._satelliteActivationPromise = activation;
|
||||
try {
|
||||
const activated = await activation;
|
||||
@@ -128,8 +165,7 @@ export function createIngestion({
|
||||
if (
|
||||
token === layerState._lifecycleToken &&
|
||||
layerState._enabled &&
|
||||
(activated === false ||
|
||||
!layerState._dataManager.isEnabled('satellites'))
|
||||
(activated === false || !manager.isEnabled('satellites'))
|
||||
) {
|
||||
throw new Error(
|
||||
'Space Missions requires the satellites layer, which failed to start',
|
||||
@@ -146,21 +182,38 @@ export function createIngestion({
|
||||
}
|
||||
|
||||
async function restoreSatelliteDependency() {
|
||||
const manager = layerState._dataManager;
|
||||
const snapshot = layerState._satelliteStateBeforeMission;
|
||||
if (!snapshot || !layerState._dataManager) return;
|
||||
if (!snapshot || !manager) return;
|
||||
// Keep the snapshot available until any explicit Satellites action settles.
|
||||
const token = layerState._lifecycleToken;
|
||||
const idle = await waitForSatelliteVisibility(manager, {
|
||||
timeoutMs: layerState.satelliteSettleTimeoutMs,
|
||||
});
|
||||
if (
|
||||
token !== layerState._lifecycleToken ||
|
||||
layerState._satelliteStateBeforeMission !== snapshot
|
||||
)
|
||||
return;
|
||||
// An accepted Satellites action owns visibility through mission teardown.
|
||||
const restoreVisibility = snapshot.restoreVisibility !== false;
|
||||
// Satellites is still busy: change nothing and keep the saved state, so
|
||||
// turning Space Missions off again can finish the restore.
|
||||
if (restoreVisibility && !idle)
|
||||
throw new Error(
|
||||
'Space Missions could not restore the satellites layer: it did not settle',
|
||||
);
|
||||
layerState._satelliteStateBeforeMission = null;
|
||||
layerState._satelliteActivationPromise = null;
|
||||
layerState._dataManager.setLayerParams(
|
||||
manager.setLayerParams(
|
||||
'satellites',
|
||||
parts.policyHelpers.satelliteParamsAfterSpaceMissions(snapshot.params),
|
||||
);
|
||||
const restored = await layerState._dataManager.setEnabled(
|
||||
'satellites',
|
||||
snapshot.enabled,
|
||||
);
|
||||
if (!restoreVisibility) return;
|
||||
const restored = await manager.setEnabled('satellites', snapshot.enabled);
|
||||
if (
|
||||
restored === false ||
|
||||
layerState._dataManager.isEnabled('satellites') !== snapshot.enabled
|
||||
manager.isEnabled('satellites') !== snapshot.enabled
|
||||
) {
|
||||
throw new Error('Space Missions could not restore the satellites layer');
|
||||
}
|
||||
@@ -215,7 +268,9 @@ export function createIngestion({
|
||||
parts.selection.setSelectedMission(null, false);
|
||||
} else {
|
||||
parts.selection.setSelectedMission(layerState._selectedLaunchId, true);
|
||||
if (layerState._focusAfterActiveLookup) {
|
||||
// The cockpit holds the camera: a mission picked there is not flown
|
||||
// to when its orbit arrives.
|
||||
if (layerState._focusAfterActiveLookup && !cockpitActive()) {
|
||||
parts.selection.focusMission(
|
||||
launches.find(
|
||||
(launch) => launch.id === layerState._selectedLaunchId,
|
||||
@@ -230,7 +285,6 @@ export function createIngestion({
|
||||
} catch (error) {
|
||||
if (layerState._enabled && token === layerState._lifecycleToken) {
|
||||
layerState._lastError = error.message;
|
||||
layerState._lastErrorAt = Date.now();
|
||||
console.warn('[Data:RocketLaunches] Fetch error:', error);
|
||||
// No index yet: fail the enable so Context rolls back.
|
||||
// After a loaded index, a failed refresh keeps its records.
|
||||
|
||||
@@ -8,6 +8,7 @@ import { createLaunchSource } from './source.js';
|
||||
import { createState } from './state.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createSatelliteIntents } from './satelliteIntents.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
@@ -147,6 +148,7 @@ async function fixture({ legacySource = false } = {}) {
|
||||
const context = { state, services, parts, source };
|
||||
parts.model = createModel(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.satelliteIntents = createSatelliteIntents(context);
|
||||
parts.controls = createControls(context);
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
const current = () => {
|
||||
@@ -326,7 +328,11 @@ test('destroy followed by actual init starts a clean instance with owned handler
|
||||
assert.equal(typeof f.state._inputSubscription, 'function');
|
||||
await f.destroy();
|
||||
assert.equal(f.state._inputSubscription, null);
|
||||
assert.equal(input.subscriberCount(), before - 2, 'click and hover');
|
||||
assert.equal(
|
||||
input.subscriberCount(),
|
||||
before - 3,
|
||||
'label click, point click and hover',
|
||||
);
|
||||
|
||||
assert.equal(f.attachedSets(), 0);
|
||||
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
// Clicks on painted mission labels, routed through the real input dispatcher.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Event } from 'cesium';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createState } from './state.js';
|
||||
import {
|
||||
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
|
||||
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
|
||||
} from './policy.js';
|
||||
import {
|
||||
FAKE_EVENT_TYPES,
|
||||
FakeScreenSpaceEventHandler,
|
||||
fakeInput,
|
||||
} from '../../input/testDoubles.mjs';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
/** Parts whose every method is a no-op unless given. */
|
||||
function stub(methods = {}) {
|
||||
return new Proxy(methods, {
|
||||
get: (target, key) => (key in target ? target[key] : noop),
|
||||
});
|
||||
}
|
||||
|
||||
function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
|
||||
const stock = new FakeScreenSpaceEventHandler();
|
||||
stock.setInputAction(noop, FAKE_EVENT_TYPES.LEFT_CLICK);
|
||||
const viewer = bindFakeCesiumCamera({
|
||||
isDestroyed: () => false,
|
||||
screenSpaceEventHandler: stock,
|
||||
camera: {
|
||||
moveStart: new Event(),
|
||||
moveEnd: new Event(),
|
||||
pickEllipsoid: () => null,
|
||||
},
|
||||
scene: {
|
||||
canvas: { style: { cursor: '' } },
|
||||
screenSpaceCameraController: { enableInputs: true },
|
||||
pick: () => undefined,
|
||||
drillPick: () => [],
|
||||
},
|
||||
});
|
||||
const pointer = fakeInput(viewer);
|
||||
const services = {
|
||||
overlays: {
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
clearOverlaySource: noop,
|
||||
hitTestWorldOverlay: () => overlayHit,
|
||||
},
|
||||
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
|
||||
};
|
||||
const state = createState({ services });
|
||||
const focused = [];
|
||||
const moved = [];
|
||||
const restoreFailure = { error: null };
|
||||
const parts = {
|
||||
panel: stub(),
|
||||
overlays: stub(),
|
||||
replay: stub(),
|
||||
launchPad: stub(),
|
||||
orbitRendering: stub(),
|
||||
selection: stub({
|
||||
setSelectedMission: (id) => focused.push(id),
|
||||
focusMission: (launch) => moved.push(launch.id),
|
||||
}),
|
||||
satelliteIntents: stub(),
|
||||
ingestion: stub({
|
||||
async restoreSatelliteDependency() {
|
||||
if (restoreFailure.error) throw restoreFailure.error;
|
||||
},
|
||||
}),
|
||||
rendering: stub({
|
||||
missionsShown: () => true,
|
||||
missionHitsAt: () => [],
|
||||
launchIdFromPicks: () => geometryLaunchId,
|
||||
launchMarkerAt: () => null,
|
||||
}),
|
||||
};
|
||||
const lifecycle = createLifecycle({
|
||||
state,
|
||||
services,
|
||||
parts,
|
||||
source: {},
|
||||
}).methods;
|
||||
lifecycle.init(viewer);
|
||||
state._enabled = true;
|
||||
state._launches = [{ id: 'L1' }, { id: 'L2' }];
|
||||
// Another layer's ambient click handler, as aircraft or the cockpit has.
|
||||
const ambient = [];
|
||||
const offAmbient = pointer.input.onClick((event) => ambient.push(event));
|
||||
t.after(async () => {
|
||||
restoreFailure.error = null;
|
||||
offAmbient();
|
||||
await lifecycle.destroy(viewer);
|
||||
pointer.input.destroy();
|
||||
});
|
||||
return {
|
||||
focused,
|
||||
moved,
|
||||
ambient,
|
||||
state,
|
||||
lifecycle,
|
||||
viewer,
|
||||
input: pointer.input,
|
||||
restoreFailure,
|
||||
setHit(hit) {
|
||||
overlayHit = hit;
|
||||
},
|
||||
click: () => pointer.tap({ x: 40, y: 30 }),
|
||||
};
|
||||
}
|
||||
|
||||
const label = (
|
||||
entryId,
|
||||
sourceId = ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
|
||||
) => ({
|
||||
sourceId,
|
||||
entryId,
|
||||
});
|
||||
|
||||
test('a mission label click focuses its launch and covers the geometry beneath', (t) => {
|
||||
const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, ['L2'], 'the mission beneath is not picked');
|
||||
// Other layers still hear it, as a click on the label rather than on the
|
||||
// geometry beneath; the label is the card on top, so they keep their
|
||||
// selections.
|
||||
assert.equal(r.ambient.length, 1);
|
||||
assert.equal(r.ambient[0].overlay, true);
|
||||
assert.equal(r.ambient[0].drawHit, null);
|
||||
|
||||
r.setHit(label('launch:L1', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID));
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, ['L2', 'L1'], 'the selected label routes too');
|
||||
});
|
||||
|
||||
test('a mission picked on the globe is announced, after it is selected', (t) => {
|
||||
const r = rig(t, { overlayHit: label('launch:L2') });
|
||||
const picks = [];
|
||||
r.state._globePickListeners.add((id) => picks.push([id, [...r.focused]]));
|
||||
r.click();
|
||||
assert.deepEqual(picks, [['L2', ['L2']]], 'the label pick is announced');
|
||||
|
||||
r.setHit(null);
|
||||
r.click();
|
||||
assert.equal(picks.length, 1, 'a click on nothing announces nothing');
|
||||
});
|
||||
|
||||
test('a throwing globe-pick listener does not stop the pick', (t) => {
|
||||
const r = rig(t, { overlayHit: label('launch:L1') });
|
||||
const warn = console.warn;
|
||||
console.warn = noop;
|
||||
t.after(() => {
|
||||
console.warn = warn;
|
||||
});
|
||||
const heard = [];
|
||||
r.state._globePickListeners.add(() => {
|
||||
throw new Error('listener failure');
|
||||
});
|
||||
r.state._globePickListeners.add((id) => heard.push(id));
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, ['L1']);
|
||||
assert.deepEqual(heard, ['L1']);
|
||||
assert.equal(r.ambient.length, 1);
|
||||
assert.equal(r.ambient[0].overlay, true);
|
||||
});
|
||||
|
||||
test('a mission label for an unknown launch selects nothing', (t) => {
|
||||
const r = rig(t, {
|
||||
overlayHit: label('launch:gone'),
|
||||
geometryLaunchId: 'L1',
|
||||
});
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, [], 'nothing is focused');
|
||||
// Other layers hear the click; the label is still the card on top for
|
||||
// them (clickYield.test.mjs), so none acts under it.
|
||||
assert.equal(r.ambient.length, 1);
|
||||
});
|
||||
|
||||
test("another layer's label keeps the click above mission geometry", (t) => {
|
||||
// An aircraft label painted over a mission path.
|
||||
const r = rig(t, {
|
||||
overlayHit: { sourceId: 'aircraft-labels', entryId: 'launch:L1' },
|
||||
geometryLaunchId: 'L1',
|
||||
});
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, [], 'the mission under the label is not picked');
|
||||
assert.equal(r.ambient.length, 1, "the label's owner gets the click");
|
||||
|
||||
// With no label there, the same click picks the mission geometry.
|
||||
r.setHit(null);
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, ['L1']);
|
||||
});
|
||||
|
||||
test('in the cockpit a mission label or dot selects its mission without moving the camera', (t) => {
|
||||
const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
|
||||
},
|
||||
});
|
||||
try {
|
||||
r.click();
|
||||
} finally {
|
||||
if (previous) Object.defineProperty(globalThis, 'document', previous);
|
||||
else delete globalThis.document;
|
||||
}
|
||||
assert.deepEqual(r.focused, ['L2'], 'the mission is selected');
|
||||
assert.deepEqual(r.moved, [], 'the cockpit keeps the camera');
|
||||
// The dot, with no label over it, does the same.
|
||||
r.setHit(null);
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
|
||||
},
|
||||
});
|
||||
try {
|
||||
r.click();
|
||||
} finally {
|
||||
if (previous) Object.defineProperty(globalThis, 'document', previous);
|
||||
else delete globalThis.document;
|
||||
}
|
||||
assert.deepEqual(r.focused, ['L2', 'L1']);
|
||||
assert.deepEqual(r.moved, []);
|
||||
r.setHit(label('launch:L2'));
|
||||
// Out of the cockpit the same click moves there too.
|
||||
r.click();
|
||||
assert.deepEqual(r.moved, ['L2']);
|
||||
});
|
||||
|
||||
test('destroy releases the click handlers when the Satellites restore fails', async (t) => {
|
||||
const r = rig(t, { overlayHit: label('launch:L2') });
|
||||
const before = r.input.subscriberCount();
|
||||
r.restoreFailure.error = new Error('injected Satellites restore failure');
|
||||
await assert.rejects(r.lifecycle.destroy(r.viewer), /injected/);
|
||||
assert.equal(r.state._inputSubscription, null);
|
||||
// The rest of teardown still ran before the failure was reported.
|
||||
assert.equal(r.state._viewer, null, 'the viewer is released');
|
||||
assert.deepEqual(r.state._launches, [], 'the records are dropped');
|
||||
assert.equal(r.state._dataManager, null, 'the manager is released');
|
||||
assert.ok(r.input.subscriberCount() < before, 'the handlers unsubscribed');
|
||||
r.click();
|
||||
assert.deepEqual(r.focused, [], 'a later label click reaches no mission');
|
||||
assert.equal(r.ambient.length, 1);
|
||||
});
|
||||
@@ -2,6 +2,11 @@ import { isPointerFree } from '../../data/inputOwnership.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
import {
|
||||
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
|
||||
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
|
||||
cockpitActive,
|
||||
} from './policy.js';
|
||||
|
||||
const HOVER_PICK_INTERVAL_MS = 120;
|
||||
|
||||
@@ -150,6 +155,15 @@ function restoreCameraView(viewer, view, landedView) {
|
||||
/** The longest name a timeline mark carries, as in the mission index. */
|
||||
const MARK_LABEL_LENGTH = 27;
|
||||
|
||||
function markerLaunchId(hit) {
|
||||
if (
|
||||
hit?.sourceId !== ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID &&
|
||||
hit?.sourceId !== ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID
|
||||
)
|
||||
return null;
|
||||
return hit.entryId.startsWith('launch:') ? hit.entryId.slice(7) : null;
|
||||
}
|
||||
|
||||
export function createLifecycle({
|
||||
state: layerState,
|
||||
services,
|
||||
@@ -157,6 +171,25 @@ export function createLifecycle({
|
||||
source,
|
||||
}) {
|
||||
const { holdContinuousRender, releaseContinuousRender } = services.render;
|
||||
const overlayAt = (position) =>
|
||||
services.overlays?.hitTestWorldOverlay?.(position?.x, position?.y);
|
||||
const missionsShown = () =>
|
||||
layerState._enabled && parts.rendering.missionsShown();
|
||||
const focusLaunch = (id, { move = true } = {}) => {
|
||||
if (!id) return false;
|
||||
const launch = layerState._launches.find((entry) => entry.id === id);
|
||||
if (!launch) return false;
|
||||
parts.selection.setSelectedMission(launch.id);
|
||||
if (move) parts.selection.focusMission(launch);
|
||||
for (const listener of [...layerState._globePickListeners]) {
|
||||
try {
|
||||
listener(launch.id);
|
||||
} catch (error) {
|
||||
console.warn('[Data:RocketLaunches] globe pick listener failed', error);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
let hover = null;
|
||||
// While on, the launches loaded span the time from the first to the last,
|
||||
// each one a mark labelled with its mission's name (the launch's where it
|
||||
@@ -204,25 +237,48 @@ export function createLifecycle({
|
||||
layerState._orbitMatches = 0;
|
||||
parts.overlays.clearMissionOverlaySources();
|
||||
const input = inputFor(viewer);
|
||||
const overlayClicks = new WeakSet();
|
||||
const unsubscribeLabelClick = input.onOverlayClick((event) => {
|
||||
if (!missionsShown()) return false;
|
||||
const hit = overlayAt(event.screenPosition);
|
||||
if (!hit) return false;
|
||||
// Capture the painted hit before other handlers can invalidate the
|
||||
// overlay. An unrelated label keeps the click above mission geometry.
|
||||
overlayClicks.add(event);
|
||||
// The label is the card on top, so every other layer and the cockpit
|
||||
// leave its click alone. In the cockpit, which holds the camera, the
|
||||
// label and the dot select the mission without moving there.
|
||||
return focusLaunch(markerLaunchId(hit), { move: !cockpitActive() });
|
||||
});
|
||||
const unsubscribeClick = input.onClick((event) => {
|
||||
if (!layerState._enabled || !parts.rendering.missionsShown()) return;
|
||||
// The click's pick position (CSS px), as the click picked it.
|
||||
const launchId = parts.rendering.launchIdFromPicks(
|
||||
parts.rendering.missionHitsAt(event.position, 12),
|
||||
);
|
||||
if (!launchId) return;
|
||||
parts.selection.setSelectedMission(launchId);
|
||||
parts.selection.focusMission(
|
||||
layerState._launches.find((launch) => launch.id === launchId),
|
||||
// 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),
|
||||
),
|
||||
{ move: !cockpitActive() },
|
||||
);
|
||||
});
|
||||
hover = createLaunchHover({
|
||||
viewer,
|
||||
enabled: () => layerState._enabled && parts.rendering.missionsShown(),
|
||||
launchAt: parts.rendering.launchMarkerAt,
|
||||
enabled: missionsShown,
|
||||
launchAt(position) {
|
||||
const hit = overlayAt(position);
|
||||
return hit
|
||||
? Boolean(markerLaunchId(hit))
|
||||
: parts.rendering.launchMarkerAt(position);
|
||||
},
|
||||
});
|
||||
const unsubscribeHover = input.onPointer('move', hover.move);
|
||||
layerState._inputSubscription = () => {
|
||||
unsubscribeLabelClick();
|
||||
unsubscribeClick();
|
||||
unsubscribeHover();
|
||||
};
|
||||
@@ -321,8 +377,8 @@ export function createLifecycle({
|
||||
parts.overlays.hideReplayVehicleOverlay();
|
||||
layerState._selectedLaunchId = null;
|
||||
parts.overlays.clearMissionOverlaySources();
|
||||
await parts.ingestion.restoreSatelliteDependency();
|
||||
parts.panel.renderMissionPanel();
|
||||
await parts.ingestion.restoreSatelliteDependency();
|
||||
layerState.coverageChanged();
|
||||
},
|
||||
|
||||
@@ -336,14 +392,22 @@ export function createLifecycle({
|
||||
layerState._enabled = false;
|
||||
layerState._lifecycleToken++;
|
||||
layerState._updateDirty = false;
|
||||
await parts.ingestion.restoreSatelliteDependency();
|
||||
// A failed Satellites restore still tears everything else down; the
|
||||
// failure is reported once teardown is complete.
|
||||
let restoreError = null;
|
||||
try {
|
||||
await parts.ingestion.restoreSatelliteDependency();
|
||||
} catch (error) {
|
||||
restoreError = error;
|
||||
}
|
||||
layerState._inputSubscription?.();
|
||||
layerState._inputSubscription = null;
|
||||
parts.satelliteIntents.connect(null);
|
||||
parts.panel.clearMissionRosterHover();
|
||||
parts.replay.stopMissionReplay();
|
||||
layerState._cameraReleased = true;
|
||||
parts.selection.stopMissionZoomAnchor();
|
||||
parts.ingestion.clearPostTleRetry();
|
||||
layerState._inputSubscription?.();
|
||||
layerState._inputSubscription = null;
|
||||
if (layerState._declutterHandler) layerState._declutterHandler();
|
||||
layerState._declutterHandler = null;
|
||||
parts.launchPad.destroyLaunchPadZonePrimitive();
|
||||
@@ -370,6 +434,7 @@ export function createLifecycle({
|
||||
layerState._satelliteStateBeforeMission = null;
|
||||
layerState._satelliteActivationPromise = null;
|
||||
layerState._dataManager = null;
|
||||
if (restoreError) throw restoreError;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
// The Data Layers row's previous/next mission controls, and the Satellites
|
||||
// restore an explicit Satellites action takes over.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createControls } from './controls.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createSatelliteIntents } from './satelliteIntents.js';
|
||||
|
||||
const roster = (...ids) => ({
|
||||
entries: ids.map((id, index) => ({ id, index, label: `Mission ${id}` })),
|
||||
});
|
||||
|
||||
function rig({ ids = ['A', 'B', 'C'], selected = null, enabled = true } = {}) {
|
||||
const panelListeners = new Set();
|
||||
const state = {
|
||||
_enabled: enabled,
|
||||
_selectedLaunchId: selected,
|
||||
_missionRosterView: ids ? roster(...ids) : null,
|
||||
};
|
||||
const parts = {
|
||||
panel: {
|
||||
selectMissionAt(index) {
|
||||
state._selectedLaunchId = state._missionRosterView.entries[index].id;
|
||||
},
|
||||
subscribePanel(listener) {
|
||||
panelListeners.add(listener);
|
||||
return () => panelListeners.delete(listener);
|
||||
},
|
||||
},
|
||||
};
|
||||
const { methods } = createControls({ state, services: {}, parts });
|
||||
return {
|
||||
state,
|
||||
methods,
|
||||
chip: (id) => methods.getRowControls().chips.find((c) => c.id === id),
|
||||
publish: (view) => {
|
||||
for (const listener of [...panelListeners]) listener(view);
|
||||
},
|
||||
listenerCount: () => panelListeners.size,
|
||||
};
|
||||
}
|
||||
|
||||
test('next and previous wrap around the roster', () => {
|
||||
const r = rig({ selected: 'C' });
|
||||
r.chip('next-mission').onClick();
|
||||
assert.equal(
|
||||
r.state._selectedLaunchId,
|
||||
'A',
|
||||
'next after the last is the first',
|
||||
);
|
||||
r.chip('previous-mission').onClick();
|
||||
assert.equal(
|
||||
r.state._selectedLaunchId,
|
||||
'C',
|
||||
'previous before the first is the last',
|
||||
);
|
||||
r.chip('previous-mission').onClick();
|
||||
assert.equal(r.state._selectedLaunchId, 'B');
|
||||
assert.match(r.methods.getRowControls().info, /^2 \/ 3 · Mission B$/);
|
||||
});
|
||||
|
||||
test('with nothing selected, next picks the first mission and previous the last', () => {
|
||||
const next = rig();
|
||||
next.chip('next-mission').onClick();
|
||||
assert.equal(next.state._selectedLaunchId, 'A');
|
||||
const previous = rig();
|
||||
previous.chip('previous-mission').onClick();
|
||||
assert.equal(previous.state._selectedLaunchId, 'C');
|
||||
});
|
||||
|
||||
test('the controls disable only when the one mission is already selected', () => {
|
||||
const only = rig({ ids: ['A'], selected: 'A' });
|
||||
assert.equal(only.chip('next-mission').disabled, true);
|
||||
assert.equal(only.chip('previous-mission').disabled, true);
|
||||
// One mission, not yet picked: the controls can still select it.
|
||||
const unpicked = rig({ ids: ['A'] });
|
||||
assert.equal(unpicked.chip('next-mission').disabled, false);
|
||||
unpicked.chip('next-mission').onClick();
|
||||
assert.equal(unpicked.state._selectedLaunchId, 'A');
|
||||
assert.equal(rig({ selected: 'B' }).chip('next-mission').disabled, false);
|
||||
});
|
||||
|
||||
test('there are no controls while the layer is off or the roster is empty', () => {
|
||||
assert.equal(rig({ enabled: false }).methods.getRowControls(), null);
|
||||
assert.equal(rig({ ids: [] }).methods.getRowControls(), null);
|
||||
assert.equal(rig({ ids: null }).methods.getRowControls(), null);
|
||||
// A stale click after the layer stops selects nothing.
|
||||
const r = rig({ selected: 'A' });
|
||||
const next = r.chip('next-mission');
|
||||
r.state._enabled = false;
|
||||
next.onClick();
|
||||
assert.equal(r.state._selectedLaunchId, 'A');
|
||||
});
|
||||
|
||||
test('the row listener fires only when the roster or the selection changes', () => {
|
||||
const r = rig();
|
||||
let calls = 0;
|
||||
r.methods.setRowControlsListener(() => calls++);
|
||||
const view = r.state._missionRosterView;
|
||||
r.publish({ roster: view });
|
||||
assert.equal(calls, 1, 'the first view is a change');
|
||||
r.publish({ roster: view });
|
||||
assert.equal(calls, 1, 'a replay or telemetry update is not');
|
||||
r.state._selectedLaunchId = 'B';
|
||||
r.publish({ roster: view });
|
||||
assert.equal(calls, 2, 'a new selection is');
|
||||
r.publish({ roster: roster('A', 'B') });
|
||||
assert.equal(calls, 3, 'a new roster is');
|
||||
|
||||
// A new listener replaces the old one; null removes it.
|
||||
let replaced = 0;
|
||||
r.methods.setRowControlsListener(() => replaced++);
|
||||
assert.equal(r.listenerCount(), 1);
|
||||
r.methods.setRowControlsListener(null);
|
||||
assert.equal(r.listenerCount(), 0);
|
||||
r.publish({ roster: roster('C') });
|
||||
assert.equal(calls, 3);
|
||||
assert.equal(replaced, 0);
|
||||
});
|
||||
|
||||
function satelliteRig({ enabledBefore }) {
|
||||
const calls = [];
|
||||
let satellitesOn = true;
|
||||
const manager = {
|
||||
layers: new Map([['satellites', { toggleChain: null }]]),
|
||||
waitForLayerIdle: async () => true,
|
||||
isEnabled: () => satellitesOn,
|
||||
isEffectivelyEnabled: (id) =>
|
||||
id === 'satellites' ? satellitesOn : id === 'rocket-launches',
|
||||
setLayerParams: (id, params) => calls.push(['params', id, params]),
|
||||
async setEnabled(id, enabled) {
|
||||
calls.push(['enabled', id, enabled]);
|
||||
satellitesOn = enabled;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
const state = {
|
||||
_dataManager: manager,
|
||||
_satelliteStateBeforeMission: {
|
||||
enabled: enabledBefore,
|
||||
params: { mode: 'before' },
|
||||
},
|
||||
_satelliteActivationPromise: null,
|
||||
};
|
||||
const parts = {
|
||||
policyHelpers: { satelliteParamsAfterSpaceMissions: (params) => params },
|
||||
};
|
||||
const ingestion = createIngestion({ state, services: {}, parts, source: {} });
|
||||
parts.satelliteIntents = createSatelliteIntents({ state });
|
||||
const { methods } = createControls({ state, services: {}, parts });
|
||||
return { state, calls, ingestion, methods, intents: parts.satelliteIntents };
|
||||
}
|
||||
|
||||
test('an accepted Satellites action keeps its visibility through mission exit', async () => {
|
||||
const r = satelliteRig({ enabledBefore: false });
|
||||
// The person turns Satellites on themselves while the missions are on.
|
||||
r.intents.handleVisibility({
|
||||
type: 'visibility',
|
||||
layerId: 'satellites',
|
||||
enabled: true,
|
||||
origin: 'user',
|
||||
});
|
||||
await r.ingestion.restoreSatelliteDependency();
|
||||
assert.deepEqual(
|
||||
r.calls,
|
||||
[['params', 'satellites', { mode: 'before' }]],
|
||||
'the parameters come back, the visibility is left alone',
|
||||
);
|
||||
assert.equal(r.state._satelliteStateBeforeMission, null);
|
||||
});
|
||||
|
||||
test('without a Satellites action the exit restores the pre-mission visibility', async () => {
|
||||
const r = satelliteRig({ enabledBefore: false });
|
||||
await r.ingestion.restoreSatelliteDependency();
|
||||
assert.deepEqual(r.calls, [
|
||||
['params', 'satellites', { mode: 'before' }],
|
||||
['enabled', 'satellites', false],
|
||||
]);
|
||||
});
|
||||
|
||||
test('a Satellites layer that does not settle keeps the saved state for the next exit', async () => {
|
||||
const r = satelliteRig({ enabledBefore: false });
|
||||
let idle = false;
|
||||
r.state._dataManager.waitForLayerIdle = async () => idle;
|
||||
await assert.rejects(
|
||||
r.ingestion.restoreSatelliteDependency(),
|
||||
/did not settle/,
|
||||
);
|
||||
assert.deepEqual(r.calls, [], 'nothing changes while Satellites is busy');
|
||||
assert.deepEqual(r.state._satelliteStateBeforeMission, {
|
||||
enabled: false,
|
||||
params: { mode: 'before' },
|
||||
});
|
||||
|
||||
// Turning Space Missions off again once Satellites settles finishes it.
|
||||
idle = true;
|
||||
await r.ingestion.restoreSatelliteDependency();
|
||||
assert.deepEqual(r.calls, [
|
||||
['params', 'satellites', { mode: 'before' }],
|
||||
['enabled', 'satellites', false],
|
||||
]);
|
||||
assert.equal(r.state._satelliteStateBeforeMission, null);
|
||||
});
|
||||
|
||||
test('a Satellites action the person took still gets its parameters back when Satellites is busy', async () => {
|
||||
const r = satelliteRig({ enabledBefore: false });
|
||||
r.state._dataManager.waitForLayerIdle = async () => false;
|
||||
r.state._satelliteStateBeforeMission.restoreVisibility = false;
|
||||
await r.ingestion.restoreSatelliteDependency();
|
||||
assert.deepEqual(r.calls, [['params', 'satellites', { mode: 'before' }]]);
|
||||
assert.equal(r.state._satelliteStateBeforeMission, null);
|
||||
});
|
||||
@@ -135,7 +135,7 @@ export function createOverlays({ state: layerState, services, parts, source }) {
|
||||
protected: selected,
|
||||
paintLane: selected ? 'selected' : 'ambient-label',
|
||||
collisionGroup: 'ambient-label',
|
||||
interactive: false,
|
||||
interactive: true,
|
||||
distanceScale: {
|
||||
near: 1000,
|
||||
nearValue: 1.08,
|
||||
|
||||
@@ -380,14 +380,20 @@ export function createPanel({ state: layerState, services, parts, source }) {
|
||||
|
||||
function scheduleMissionRosterPreview(index) {
|
||||
const launch = layerState._launches[index];
|
||||
if (!launch || layerState._selectedLaunchId) return;
|
||||
// Once the layer is going off (its Satellites restore may still be
|
||||
// running) hovering or focusing a roster row moves no camera.
|
||||
if (!launch || layerState._selectedLaunchId || !layerState._enabled) return;
|
||||
if (layerState._missionRosterHoverTimer)
|
||||
clearTimeout(layerState._missionRosterHoverTimer);
|
||||
layerState._hoveredRosterLaunchId = launch.id;
|
||||
parts.overlays.syncMissionOverlayEntries();
|
||||
layerState._missionRosterHoverTimer = setTimeout(() => {
|
||||
layerState._missionRosterHoverTimer = null;
|
||||
if (layerState._hoveredRosterLaunchId !== launch.id) return;
|
||||
if (
|
||||
layerState._hoveredRosterLaunchId !== launch.id ||
|
||||
!layerState._enabled
|
||||
)
|
||||
return;
|
||||
const currentLaunch = resolveMissionRosterPreviewLaunch(
|
||||
layerState._launches,
|
||||
launch.id,
|
||||
|
||||
@@ -9,6 +9,7 @@ function fixture() {
|
||||
const state = createState({
|
||||
services: { overlays: {}, render: {} },
|
||||
});
|
||||
state._enabled = true;
|
||||
const calls = [];
|
||||
const parts = {
|
||||
overlays: {
|
||||
@@ -194,3 +195,26 @@ test('the panel commands act on the selected mission', () => {
|
||||
['select', null, undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
test('a roster row hovered or focused while the layer goes off moves no camera', async () => {
|
||||
const { state, panel, calls } = fixture();
|
||||
state._launches = [launch('a'), launch('b')];
|
||||
panel.createMissionPanel();
|
||||
panel.renderMissionRoster();
|
||||
|
||||
// Hovered just before the layer goes off: the pending preview is dropped.
|
||||
panel.commands.rosterPointerEnter(0);
|
||||
state._enabled = false;
|
||||
await new Promise((resolve) => setTimeout(resolve, 160));
|
||||
|
||||
// Hovered or focused after it went off, while the panel still shows.
|
||||
panel.commands.rosterPointerEnter(1);
|
||||
panel.commands.rosterFocus(1);
|
||||
assert.equal(state._missionRosterHoverTimer, null, 'no preview is pending');
|
||||
await new Promise((resolve) => setTimeout(resolve, 160));
|
||||
assert.deepEqual(
|
||||
calls.filter(([name]) => name === 'preview'),
|
||||
[],
|
||||
);
|
||||
panel.clearMissionPanel();
|
||||
});
|
||||
@@ -2,6 +2,9 @@ import { TWO_PI, toRadians } from '../../geo/vector.js';
|
||||
|
||||
export const WINDOW_DAYS = 30;
|
||||
|
||||
/** Longest Space Missions waits for pending Satellites work to settle. */
|
||||
export const SATELLITE_SETTLE_TIMEOUT_MS = 30000;
|
||||
|
||||
export const ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID = 'rocket-missions';
|
||||
|
||||
export const ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID =
|
||||
@@ -100,3 +103,10 @@ export const TRAJECTORY_STAGE_COLORS = [
|
||||
'#ffd166',
|
||||
'#60a5fa',
|
||||
];
|
||||
|
||||
/** Whether the cockpit view is on; it holds the camera while it is. */
|
||||
export function cockpitActive() {
|
||||
return Boolean(
|
||||
globalThis.document?.body?.classList?.contains?.('cockpit-mode'),
|
||||
);
|
||||
}
|
||||
@@ -336,6 +336,8 @@ export function createReplay({ state: layerState, services, parts, source }) {
|
||||
// The chase camera moves on the frame loop; without one, no replay.
|
||||
const frame = findFrame(layerState._viewer);
|
||||
if (!layerState._viewer || !launch || !track || !frame) return false;
|
||||
// Not while the layer is going off.
|
||||
if (!layerState._enabled) return false;
|
||||
if (layerState._replayCameraLaunchId === launchId) {
|
||||
stopMissionReplay();
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* Space Missions owns its Satellites dependency. While the layer is on or
|
||||
* starting, an explicit Satellites action from the person (a Data Layers
|
||||
* click, a voice command) wins over the dependency:
|
||||
* - the mission teardown leaves Satellites as that action set it, and
|
||||
* - a Satellites OFF asked for after the newest Space Missions ON ends Space
|
||||
* Missions, which cannot replay without it.
|
||||
* Whether an OFF ends the missions depends on which of the two was asked for
|
||||
* first, not on which settles first, so request order is recorded when each
|
||||
* intent is published.
|
||||
*/
|
||||
const ORDERED_REQUEST_LAYER_IDS = new Set(['rocket-launches', 'satellites']);
|
||||
const LAYER_ID = 'rocket-launches';
|
||||
|
||||
function isExplicitOrigin(origin) {
|
||||
return origin === 'user' || origin === 'voice';
|
||||
}
|
||||
|
||||
/**
|
||||
* A setting changed on purpose: by the person, by voice, or by a tool such
|
||||
* as a place search (the layer state's own rule, isExplicitLayerStateOrigin
|
||||
* in src/data/layerState.js).
|
||||
*/
|
||||
function isDeliberateOrigin(origin) {
|
||||
return isExplicitOrigin(origin) || origin === 'tool';
|
||||
}
|
||||
|
||||
export function createSatelliteIntents({ state: layerState }) {
|
||||
const requestOrder = new Map();
|
||||
let sequence = 0;
|
||||
let unsubscribe = null;
|
||||
/** The Space Missions stop a Satellites OFF started, while it runs. */
|
||||
let pendingStop = null;
|
||||
|
||||
/**
|
||||
* Whether an accepted Satellites OFF was requested after the newest Space
|
||||
* Missions ON. An OFF asked for before the entry belongs to the view the
|
||||
* entry started from, so the entry it races with is kept. Without request
|
||||
* records the OFF is treated as the newer action.
|
||||
*/
|
||||
function offFollowsMissionsEntry(change) {
|
||||
const satellites = requestOrder.get('satellites');
|
||||
const missions = requestOrder.get(LAYER_ID);
|
||||
if (satellites?.intentEpoch !== change.intentEpoch || !missions?.enabled)
|
||||
return true;
|
||||
return satellites.sequence > missions.sequence;
|
||||
}
|
||||
|
||||
function recordRequest(change) {
|
||||
if (!ORDERED_REQUEST_LAYER_IDS.has(change?.layerId)) return;
|
||||
requestOrder.set(change.layerId, {
|
||||
enabled: change.enabled,
|
||||
intentEpoch: change.intentEpoch,
|
||||
sequence: ++sequence,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand an explicit Satellites action its visibility while Space Missions is
|
||||
* on or starting.
|
||||
* @returns {Promise<boolean>|boolean} Whether Space Missions was asked to stop.
|
||||
*/
|
||||
function handleVisibility(change) {
|
||||
const manager = layerState._dataManager;
|
||||
if (
|
||||
!manager ||
|
||||
change?.type !== 'visibility' ||
|
||||
change.layerId !== 'satellites' ||
|
||||
!isExplicitOrigin(change.origin)
|
||||
)
|
||||
return false;
|
||||
const missionsRequested = manager.isEffectivelyEnabled(LAYER_ID);
|
||||
if (!missionsRequested && !layerState._satelliteStateBeforeMission)
|
||||
return false;
|
||||
// A newer Satellites request is queued; it will report for itself.
|
||||
if (manager.isEffectivelyEnabled('satellites') !== change.enabled)
|
||||
return false;
|
||||
// The person's choice survives the mission teardown.
|
||||
const previous = layerState._satelliteStateBeforeMission;
|
||||
if (previous) previous.restoreVisibility = false;
|
||||
if (
|
||||
change.enabled ||
|
||||
!missionsRequested ||
|
||||
!offFollowsMissionsEntry(change)
|
||||
)
|
||||
return false;
|
||||
const stop = Promise.resolve(
|
||||
manager.setEnabled(LAYER_ID, false, { origin: change.origin }),
|
||||
)
|
||||
.then(() => true)
|
||||
.catch((error) => {
|
||||
console.warn(
|
||||
'[Data:RocketLaunches] Satellites OFF could not stop Space Missions',
|
||||
error,
|
||||
);
|
||||
return false;
|
||||
})
|
||||
.finally(() => {
|
||||
if (pendingStop === stop) pendingStop = null;
|
||||
});
|
||||
pendingStop = stop;
|
||||
return stop;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a Satellites setting changed on purpose while Space Missions holds
|
||||
* its saved state ("show orbits" off, tracking a satellite, or a place
|
||||
* search that stops tracking): it survives the mission teardown, as a
|
||||
* visibility choice does.
|
||||
*/
|
||||
function handleParams(change) {
|
||||
if (
|
||||
change?.type !== 'params' ||
|
||||
change.layerId !== 'satellites' ||
|
||||
!isDeliberateOrigin(change.origin)
|
||||
)
|
||||
return;
|
||||
const previous = layerState._satelliteStateBeforeMission;
|
||||
const requested = change.requestedParams;
|
||||
if (!previous || !requested || typeof requested !== 'object') return;
|
||||
previous.params = { ...previous.params, ...requested };
|
||||
}
|
||||
|
||||
/** Settle once a Satellites OFF has finished stopping Space Missions. */
|
||||
function settled() {
|
||||
return pendingStop ?? Promise.resolve(false);
|
||||
}
|
||||
|
||||
/** Follow the manager the layer is attached to; null detaches. */
|
||||
function connect(manager) {
|
||||
unsubscribe?.();
|
||||
unsubscribe = null;
|
||||
requestOrder.clear();
|
||||
if (!manager) return;
|
||||
const unsubscribeRequests =
|
||||
manager.subscribeVisibilityRequests?.(recordRequest) ?? null;
|
||||
const unsubscribeChanges =
|
||||
manager.subscribe?.((change) => {
|
||||
handleParams(change);
|
||||
void handleVisibility(change);
|
||||
}) ?? null;
|
||||
unsubscribe = () => {
|
||||
unsubscribeRequests?.();
|
||||
unsubscribeChanges?.();
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
connect,
|
||||
settled,
|
||||
handleVisibility,
|
||||
handleParams,
|
||||
recordRequest,
|
||||
offFollowsMissionsEntry,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// An explicit Satellites action while Space Missions is on or starting.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createSatelliteIntents } from './satelliteIntents.js';
|
||||
|
||||
/** A manager whose effective and settled state can differ. */
|
||||
function rig({ effective, snapshot = { enabled: false } } = {}) {
|
||||
const calls = [];
|
||||
const listeners = { requests: new Set(), changes: new Set() };
|
||||
const manager = {
|
||||
isEffectivelyEnabled: (id) => Boolean(effective[id]),
|
||||
async setEnabled(id, enabled, options) {
|
||||
calls.push([id, enabled, options?.origin]);
|
||||
return true;
|
||||
},
|
||||
subscribeVisibilityRequests(listener) {
|
||||
listeners.requests.add(listener);
|
||||
return () => listeners.requests.delete(listener);
|
||||
},
|
||||
subscribe(listener) {
|
||||
listeners.changes.add(listener);
|
||||
return () => listeners.changes.delete(listener);
|
||||
},
|
||||
};
|
||||
const state = {
|
||||
_dataManager: manager,
|
||||
_satelliteStateBeforeMission: snapshot,
|
||||
};
|
||||
const intents = createSatelliteIntents({ state });
|
||||
intents.connect(manager);
|
||||
const request = (layerId, enabled, intentEpoch) => {
|
||||
for (const listener of listeners.requests)
|
||||
listener({
|
||||
type: 'visibility-requested',
|
||||
layerId,
|
||||
enabled,
|
||||
intentEpoch,
|
||||
});
|
||||
};
|
||||
const settle = (change) => {
|
||||
for (const listener of listeners.changes) listener(change);
|
||||
};
|
||||
return { calls, intents, listeners, manager, state, request, settle };
|
||||
}
|
||||
|
||||
const satellitesOff = {
|
||||
type: 'visibility',
|
||||
layerId: 'satellites',
|
||||
enabled: false,
|
||||
origin: 'user',
|
||||
intentEpoch: 7,
|
||||
};
|
||||
|
||||
test('a Satellites OFF asked for after the mission start ends Space Missions', async () => {
|
||||
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
|
||||
r.request('rocket-launches', true, 3);
|
||||
r.request('satellites', false, 7);
|
||||
r.settle(satellitesOff);
|
||||
assert.equal(await r.intents.settled(), true);
|
||||
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
|
||||
assert.equal(
|
||||
r.state._satelliteStateBeforeMission.restoreVisibility,
|
||||
false,
|
||||
'the teardown leaves Satellites as the person set it',
|
||||
);
|
||||
});
|
||||
|
||||
test('a Satellites OFF asked for before the mission start leaves the start alone', () => {
|
||||
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
|
||||
r.request('satellites', false, 7);
|
||||
r.request('rocket-launches', true, 3);
|
||||
r.settle(satellitesOff);
|
||||
assert.deepEqual(r.calls, []);
|
||||
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
|
||||
});
|
||||
|
||||
test('a Satellites OFF without request records is treated as the newer action', async () => {
|
||||
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
|
||||
assert.equal(await r.intents.handleVisibility(satellitesOff), true);
|
||||
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
|
||||
});
|
||||
|
||||
test('a superseded Satellites event is left to the newer request', () => {
|
||||
// A newer Satellites ON is queued, but this OFF has already settled.
|
||||
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
|
||||
assert.equal(r.intents.handleVisibility(satellitesOff), false);
|
||||
assert.deepEqual(r.calls, []);
|
||||
assert.equal(
|
||||
r.state._satelliteStateBeforeMission.restoreVisibility,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test('a Satellites ON while the missions are on is kept through their exit', () => {
|
||||
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
|
||||
assert.equal(
|
||||
r.intents.handleVisibility({ ...satellitesOff, enabled: true }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(r.calls, []);
|
||||
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
|
||||
});
|
||||
|
||||
test('only direct user and voice Satellites actions count', () => {
|
||||
// Settled: a scene, story, preset or other programmatic Satellites OFF
|
||||
// neither ends Space Missions nor survives its teardown.
|
||||
for (const origin of [
|
||||
'programmatic',
|
||||
'context-restore',
|
||||
'dependency',
|
||||
'scene',
|
||||
'tool',
|
||||
]) {
|
||||
const r = rig({
|
||||
effective: { satellites: false, 'rocket-launches': true },
|
||||
});
|
||||
assert.equal(
|
||||
r.intents.handleVisibility({ ...satellitesOff, origin }),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(r.calls, []);
|
||||
assert.equal(
|
||||
r.state._satelliteStateBeforeMission.restoreVisibility,
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
const voice = rig({
|
||||
effective: { satellites: false, 'rocket-launches': true },
|
||||
});
|
||||
voice.settle({ ...satellitesOff, origin: 'voice' });
|
||||
assert.deepEqual(voice.calls, [['rocket-launches', false, 'voice']]);
|
||||
});
|
||||
|
||||
test('with Space Missions off, a Satellites action is not its business', () => {
|
||||
const r = rig({ effective: { satellites: false }, snapshot: null });
|
||||
assert.equal(r.intents.handleVisibility(satellitesOff), false);
|
||||
assert.deepEqual(r.calls, []);
|
||||
});
|
||||
|
||||
test('reconnecting and detaching release each manager subscription', () => {
|
||||
const r = rig({ effective: {} });
|
||||
assert.equal(r.listeners.requests.size, 1);
|
||||
assert.equal(r.listeners.changes.size, 1);
|
||||
r.intents.connect(r.manager);
|
||||
assert.equal(r.listeners.requests.size, 1, 'no duplicate subscription');
|
||||
assert.equal(r.listeners.changes.size, 1);
|
||||
r.intents.connect(null);
|
||||
assert.equal(r.listeners.requests.size, 0);
|
||||
assert.equal(r.listeners.changes.size, 0);
|
||||
});
|
||||
|
||||
test('a failed stop is reported, not thrown', async () => {
|
||||
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
|
||||
r.manager.setEnabled = async () => {
|
||||
throw new Error('injected stop failure');
|
||||
};
|
||||
const warn = console.warn;
|
||||
const warnings = [];
|
||||
console.warn = (...args) => warnings.push(args);
|
||||
try {
|
||||
assert.equal(await r.intents.handleVisibility(satellitesOff), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
assert.equal(warnings.length, 1);
|
||||
assert.equal(await r.intents.settled(), false, 'nothing left pending');
|
||||
});
|
||||
@@ -11,7 +11,11 @@ import {
|
||||
toRadians,
|
||||
vec,
|
||||
} from '../../geo/vector.js';
|
||||
import { MISSION_GLOBE_VIEW_RANGE_M, MISSION_FOCUS_RANGE_M } from './policy.js';
|
||||
import {
|
||||
MISSION_GLOBE_VIEW_RANGE_M,
|
||||
MISSION_FOCUS_RANGE_M,
|
||||
cockpitActive,
|
||||
} from './policy.js';
|
||||
import { cameraOf, canvasOf, findCamera } from '../../render/rendererOf.js';
|
||||
|
||||
export function createSelection({
|
||||
@@ -66,6 +70,9 @@ export function createSelection({
|
||||
}
|
||||
|
||||
function setSelectedMission(launchId, isolate = true) {
|
||||
// Once the layer is going off (its Satellites restore may still be
|
||||
// running) a roster click selects nothing and moves no camera.
|
||||
if (launchId && !layerState._enabled) return;
|
||||
if (launchId) parts.panel.clearMissionRosterHover();
|
||||
if (
|
||||
layerState._replayCameraLaunchId &&
|
||||
@@ -118,7 +125,10 @@ export function createSelection({
|
||||
}
|
||||
|
||||
function focusMission(launch) {
|
||||
if (!layerState._viewer || !launch) return;
|
||||
if (!layerState._viewer || !launch || !layerState._enabled) return;
|
||||
// The cockpit holds the camera: a mission chosen there, by its label,
|
||||
// its dot or the layer row's arrows, is selected without flying to it.
|
||||
if (cockpitActive()) return;
|
||||
stopMissionZoomAnchor();
|
||||
parts.rendering.selectLaunchEntity(launch.id);
|
||||
const camera = cameraOf(layerState._viewer);
|
||||
@@ -163,7 +173,7 @@ export function createSelection({
|
||||
}
|
||||
|
||||
function focusLaunchSite(launch) {
|
||||
if (!layerState._viewer || !launch) return;
|
||||
if (!layerState._viewer || !launch || !layerState._enabled) return;
|
||||
parts.replay.stopMissionReplay();
|
||||
stopMissionZoomAnchor();
|
||||
parts.rendering.selectLaunchEntity(launch.id);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
|
||||
import { SATELLITE_SETTLE_TIMEOUT_MS } from './policy.js';
|
||||
|
||||
export function createState({ services }) {
|
||||
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
|
||||
@@ -20,8 +21,6 @@ export function createState({ services }) {
|
||||
|
||||
state._lastError = null;
|
||||
|
||||
state._lastErrorAt = null;
|
||||
|
||||
state._entryCameraView = null;
|
||||
|
||||
state._entryLandedView = null;
|
||||
@@ -53,6 +52,9 @@ export function createState({ services }) {
|
||||
|
||||
state._lifecycleToken = 0;
|
||||
|
||||
/** Bound on waiting for pending Satellites work around a mission. */
|
||||
state.satelliteSettleTimeoutMs = SATELLITE_SETTLE_TIMEOUT_MS;
|
||||
|
||||
state._enabled = false;
|
||||
|
||||
state._selectedLaunchId = null;
|
||||
@@ -68,6 +70,7 @@ export function createState({ services }) {
|
||||
state._missionPanelSignature = null;
|
||||
|
||||
state._missionPanelListeners = new Set();
|
||||
state._globePickListeners = new Set();
|
||||
|
||||
state._missionRosterView = null;
|
||||
|
||||
|
||||
@@ -36,10 +36,14 @@ function scene(t) {
|
||||
],
|
||||
};
|
||||
const viewer = { scene: {} };
|
||||
const flights = [];
|
||||
const { draw, unbind } = bindFakeDraw(viewer, {
|
||||
camera: {
|
||||
pose: () => ({ position: { x: 2e7, y: 0, z: 0 } }),
|
||||
on: () => () => {},
|
||||
flyTo: (...args) => flights.push(args),
|
||||
lookAt: noop,
|
||||
release: noop,
|
||||
},
|
||||
});
|
||||
t.after(unbind);
|
||||
@@ -69,6 +73,7 @@ function scene(t) {
|
||||
};
|
||||
parts.selection = createSelection({ state, services, parts });
|
||||
const rendering = createRendering({ state, services, parts });
|
||||
parts.rendering = rendering;
|
||||
rendering.attach(viewer);
|
||||
rendering.showMissions(true);
|
||||
rendering.addLaunchEntity(launch, null);
|
||||
@@ -88,7 +93,7 @@ function scene(t) {
|
||||
path: item(`rocket-trajectory:${launch.id}:0`).show,
|
||||
};
|
||||
};
|
||||
return { state, rendering, launch, syncs, shown, draw };
|
||||
return { state, rendering, launch, syncs, shown, draw, parts, flights };
|
||||
}
|
||||
|
||||
test('live shows every launch in the window, lifted off or not', (t) => {
|
||||
@@ -127,3 +132,21 @@ test('the live orbit rings turn at the frame time, not the wall clock', (t) => {
|
||||
);
|
||||
assert.deepEqual(orbits.spec.motionClock, { kind: 'scene' });
|
||||
});
|
||||
|
||||
test('in the cockpit a chosen mission is not flown to', (t) => {
|
||||
const { launch, parts, flights } = scene(t);
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
|
||||
},
|
||||
});
|
||||
try {
|
||||
parts.selection.focusMission(launch);
|
||||
} finally {
|
||||
if (previous) Object.defineProperty(globalThis, 'document', previous);
|
||||
else delete globalThis.document;
|
||||
}
|
||||
assert.deepEqual(flights, [], 'the cockpit keeps the camera');
|
||||
});
|
||||
@@ -703,6 +703,9 @@ export function createLocalAdsbLayer({
|
||||
if (clickSubscription || !viewer) return;
|
||||
clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!enabled) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (services.picking.isUnderOtherCard?.(event)) return;
|
||||
const target = clickTarget(event);
|
||||
// Clicking a local aircraft always (re)selects it and republishes its
|
||||
// card, including the one already selected: its card may have been
|
||||
|
||||
@@ -15,9 +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 { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
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';
|
||||
@@ -1174,7 +1179,8 @@ function iconPick(draw, id) {
|
||||
return { primitive: {}, id: { set: layerSet(draw, ':markers').spec.id, id } };
|
||||
}
|
||||
|
||||
/** A viewer with a canvas and scripted picks, plus the layer's click action. */
|
||||
/** A viewer with a canvas and scripted picks, plus the layer's click action.
|
||||
* A click drills through the viewer's `drillHits`. */
|
||||
function clickHarness() {
|
||||
const scene = {
|
||||
canvas: {},
|
||||
@@ -1182,6 +1188,8 @@ function clickHarness() {
|
||||
pick() {
|
||||
return scene.pickResult;
|
||||
},
|
||||
drillPick: () =>
|
||||
(base.viewer.drillHits ?? []).map((hit) => ({ primitive: {}, id: hit })),
|
||||
};
|
||||
const base = fakeViewer({ scene });
|
||||
return {
|
||||
@@ -1213,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 };
|
||||
@@ -1265,6 +1308,52 @@ 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 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();
|
||||
inputFor(harness.viewer.viewer).onOverlayClick(() => label.over);
|
||||
const model = {
|
||||
set: layerSet(draw, ':models').spec.id,
|
||||
id: 'local-adsb:abc123',
|
||||
surface: false,
|
||||
};
|
||||
// The aircraft is under the label, both exactly and in the drill.
|
||||
harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
|
||||
harness.viewer.viewer.drillHits = [model];
|
||||
harness.click();
|
||||
assert.deepEqual(calls.selected, [], 'the aircraft beneath is not taken');
|
||||
|
||||
// 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, 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', () => {
|
||||
const { draw, viewer, camera } = modelViewer();
|
||||
const models = createLocalAdsbModels({
|
||||
|
||||
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
|
||||
import { createMilitaryFlightLayer } from './index.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
|
||||
function services() {
|
||||
const names = [
|
||||
@@ -294,3 +296,47 @@ test('a military layer without an icon set declines contact refreshes', () => {
|
||||
assert.equal(layer.refreshTr3b('abc123'), false);
|
||||
assert.equal(layer.trackById('abc123'), false);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: an aircraft under another
|
||||
// layer's card is not even picked, so it is neither tracked nor released.
|
||||
test("another layer's card over an aircraft keeps the click", (t) => {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = Object.assign(new EventTarget(), {
|
||||
body: { classList: { contains: () => false } },
|
||||
});
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
canvas: new EventTarget(),
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
const flightState = createFlightState({ services: services() });
|
||||
flightState._trackedEntityChangedRemove = () => {};
|
||||
const tracking = createTracking({
|
||||
flightState,
|
||||
services: { ...services(), picking },
|
||||
parts: {},
|
||||
layer: {},
|
||||
});
|
||||
tracking._installClickHandler(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
picking.setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
picking.setClickCardHitTest(null);
|
||||
flightState._clickSubscription?.();
|
||||
input.destroy();
|
||||
flightState.lifetime.abort();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
});
|
||||
@@ -86,7 +86,8 @@ export function createTracking({
|
||||
const { clearFocusTarget } = services.focus;
|
||||
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
|
||||
services.camera;
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
|
||||
services.picking;
|
||||
/** The tracked contact's billboard (an icon set on the draw port). */
|
||||
const trackedIcon = createTrackedAircraftIcon({
|
||||
viewer: () => flightState._viewer,
|
||||
@@ -1229,6 +1230,9 @@ export function createTracking({
|
||||
// first-person reference. Empty globe clicks are inert until the user
|
||||
// exits with C, Escape, or the dedicated button.
|
||||
if (document.body.classList.contains('cockpit-mode')) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard?.(event)) return;
|
||||
const picked = event.hit;
|
||||
|
||||
if (picked) {
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
findFrame,
|
||||
rendererOf,
|
||||
} from '../../render/rendererOf.js';
|
||||
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
|
||||
import {
|
||||
clickCard,
|
||||
isOwnedByOtherLayer,
|
||||
registerPickOwner,
|
||||
resolvePickId,
|
||||
@@ -203,7 +203,6 @@ export function createNewsLayer({
|
||||
inputFor = defaultInputFor,
|
||||
matchMedia = globalThis.matchMedia?.bind(globalThis),
|
||||
now = () => Date.now(),
|
||||
hitTestOverlay = hitTestWorldOverlay,
|
||||
openUrl = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
|
||||
getViewCentre = viewCentre,
|
||||
registerCredit = registerDynamicCredit,
|
||||
@@ -1348,11 +1347,13 @@ export function createNewsLayer({
|
||||
clickOff = inputFor(viewer).onClick((event) => {
|
||||
const at = event?.screenPosition;
|
||||
if (!enabled || destroyed || !isPointerFree() || !at) return;
|
||||
const card = hitTestOverlay(at.x, at.y, {
|
||||
sourceId: NEWS_OVERLAY_SOURCE_ID,
|
||||
});
|
||||
if (card?.entry?.activate) {
|
||||
card.entry.activate();
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: our own card acts whatever is drawn
|
||||
// under it; another layer's is that layer's click, so the pins under
|
||||
// it do not act and the selection stays.
|
||||
const card = clickCard(event);
|
||||
if (card) {
|
||||
if (card.sourceId === NEWS_OVERLAY_SOURCE_ID) card.entry?.activate?.();
|
||||
return;
|
||||
}
|
||||
// What is on top under the click: a draw-set item, or null for the
|
||||
|
||||
@@ -5,7 +5,20 @@ 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 {
|
||||
MISSION_LABEL,
|
||||
fakeInputUnderLabel,
|
||||
} from '../../input/testDoubles.mjs';
|
||||
import { NEWS_OVERLAY_SOURCE_ID } from './model.js';
|
||||
|
||||
const NOW = Date.parse('2026-10-28T10:00:00Z');
|
||||
const hotspotsPayload = {
|
||||
@@ -51,6 +64,8 @@ function fixture(
|
||||
now = () => NOW,
|
||||
quality,
|
||||
pictureCards,
|
||||
underLabel = false,
|
||||
hitTestOverlay = () => null,
|
||||
} = {},
|
||||
) {
|
||||
const calls = { feed: [], hotspots: 0, outline: 0 };
|
||||
@@ -137,11 +152,22 @@ function fixture(
|
||||
for (const fn of [...clickHandlers])
|
||||
fn({ screenPosition: { x: 10, y: 10 }, topHit });
|
||||
};
|
||||
// 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: () => input,
|
||||
hitTestOverlay: () => null,
|
||||
inputFor: () => fake?.input ?? input,
|
||||
now,
|
||||
matchMedia: () => ({ matches: reduced }),
|
||||
getViewCentre: () => centre(),
|
||||
@@ -158,6 +184,8 @@ function fixture(
|
||||
layer.attachShellServices({ runNavigation: (navigate) => navigate() });
|
||||
t.after(() => {
|
||||
layer.destroy();
|
||||
fake?.destroy();
|
||||
setClickCardHitTest(null);
|
||||
unbind();
|
||||
if (originalWindow === undefined) delete globalThis.window;
|
||||
else globalThis.window = originalWindow;
|
||||
@@ -172,6 +200,7 @@ function fixture(
|
||||
items,
|
||||
click,
|
||||
clickHandlers,
|
||||
fake,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1285,6 +1314,105 @@ test('a click on a marker selects its report, on a beacon chooses its hotspot, o
|
||||
assert.equal(clickHandlers.size, 0);
|
||||
});
|
||||
|
||||
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 || sourceId === NEWS_OVERLAY_SOURCE_ID
|
||||
? {
|
||||
sourceId: NEWS_OVERLAY_SOURCE_ID,
|
||||
entry: { activate: () => activated++ },
|
||||
}
|
||||
: null,
|
||||
});
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
await flush();
|
||||
layer.setParams({ reportId: 'major', pin: 0 });
|
||||
assert.equal(layer.getRowControls().feed.selected.id, 'major');
|
||||
|
||||
fake.label.over = true;
|
||||
fake.click();
|
||||
assert.equal(activated, 0, 'the card beneath the label is not opened');
|
||||
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;
|
||||
fake.click();
|
||||
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'), []);
|
||||
|
||||
@@ -218,13 +218,18 @@ export function createFirePerimetersLayer({
|
||||
_clickSubscription = inputFor(_viewer).onClick((event) => {
|
||||
// A click on the incident card itself opens its InciWeb page (when the
|
||||
// incident has one) and never disturbs the selection.
|
||||
const cardHit = overlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{ sourceId: PERIMETER_OVERLAY_SOURCE_ID },
|
||||
);
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink && openExternal) openExternal(_selectedLink);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: this area's shapes are background to
|
||||
// another layer's card or label painted over them.
|
||||
const cardHit = picking.clickCard?.(event) ?? null;
|
||||
if (cardHit) {
|
||||
if (
|
||||
cardHit.sourceId === PERIMETER_OVERLAY_SOURCE_ID &&
|
||||
cardHit.entryId === _selectedCardId &&
|
||||
_selectedLink &&
|
||||
openExternal
|
||||
)
|
||||
openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
const picked = event.topHit;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createFirePerimetersLayer } from './index.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { clickCard } from '../../data/pickRegistry.js';
|
||||
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
// The fills set of the layer the last harness made: perimeter picks name it.
|
||||
@@ -30,11 +31,12 @@ function harness(
|
||||
const opened = [];
|
||||
const viewer = { scene: { pick } };
|
||||
const { draw } = bindFakeDraw(viewer);
|
||||
const input = fakeInput(viewer);
|
||||
const input = fakeInputUnderLabel(viewer);
|
||||
const clicks = {
|
||||
handler: (click) => input.click(click.position),
|
||||
// Only the label's own overlay handler is left.
|
||||
get destroyed() {
|
||||
return input.input.subscriberCount() === 0 ? 1 : 0;
|
||||
return input.input.subscriberCount() === 1 ? 1 : 0;
|
||||
},
|
||||
};
|
||||
const layer = createFirePerimetersLayer({
|
||||
@@ -58,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 }
|
||||
@@ -78,6 +85,9 @@ function harness(
|
||||
clicks,
|
||||
owners,
|
||||
opened,
|
||||
/** A Space Missions label painted over the map: while `over`, it takes
|
||||
* each click and is the card on top. */
|
||||
label: input.label,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -243,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] },
|
||||
@@ -279,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);
|
||||
@@ -299,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(
|
||||
@@ -311,6 +368,44 @@ test('a matched incident card carries the InciWeb line and click-through', 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] },
|
||||
{
|
||||
pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
|
||||
inciwebIndex: [
|
||||
{
|
||||
incident_id: '329300',
|
||||
tau: 'NMGNF Fixture Fire',
|
||||
incident_title: 'Fixture Fire',
|
||||
},
|
||||
],
|
||||
cardHit: () => cardHitResult,
|
||||
},
|
||||
);
|
||||
await h.layer.update(h.viewer);
|
||||
h.clicks.handler({ position: { x: 10, y: 10 } });
|
||||
await new Promise((done) => setTimeout(done, 0));
|
||||
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, 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')?.[0]?.id, card.id);
|
||||
|
||||
// Off the label, a click on the open card opens its page.
|
||||
h.label.over = false;
|
||||
h.clicks.handler({ position: { x: 12, y: 12 } });
|
||||
assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']);
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
test('an unmatched incident renders no InciWeb line and card clicks stay inert', async () => {
|
||||
let cardHitResult = null;
|
||||
const h = harness(
|
||||
@@ -328,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, []);
|
||||
|
||||
@@ -15,6 +15,7 @@ export function createInteraction({
|
||||
const {
|
||||
resolvePickId,
|
||||
isOwnedByOtherLayer,
|
||||
isUnderOtherCard,
|
||||
registerPickOwner,
|
||||
unregisterPickOwner,
|
||||
} = services.picking;
|
||||
@@ -29,6 +30,9 @@ export function createInteraction({
|
||||
*/
|
||||
function pickedRadioStationAt(event) {
|
||||
if (!event) return null;
|
||||
// Another layer's card or label painted on top is that layer's click,
|
||||
// read once per click so every layer agrees: no station under it acts.
|
||||
if (isUnderOtherCard?.(event, [RADIO_OVERLAY_SOURCE_ID])) return null;
|
||||
|
||||
const stationFromPick = (picked) => {
|
||||
const stationId = parts.rendering.radioStationIdFromPick(picked);
|
||||
|
||||
@@ -62,3 +62,49 @@ test('a direct hit needs no drill, and another layer’s contact keeps its click
|
||||
});
|
||||
assert.equal(pickedRadioStationAt(other), null);
|
||||
});
|
||||
|
||||
// Another layer's card or label painted on top takes the click: no station
|
||||
// under it acts, whether radio found it through its window, as the tap's touch
|
||||
// contact or as the exact pick. Radio's own card on top is radio's click.
|
||||
test("a station under another layer's card does not act", () => {
|
||||
let top = null;
|
||||
const radio = createInteraction({
|
||||
state: {
|
||||
_stationById: new Map([
|
||||
['kexp', {}],
|
||||
['kuow', {}],
|
||||
]),
|
||||
},
|
||||
services: {
|
||||
picking: {
|
||||
resolvePickId: (picked) => picked?.id ?? null,
|
||||
isOwnedByOtherLayer: () => false,
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
isUnderOtherCard: (_click, own = []) =>
|
||||
Boolean(top) && !own.includes(top.sourceId),
|
||||
registerPickOwner() {},
|
||||
unregisterPickOwner() {},
|
||||
},
|
||||
overlays: { setOverlaySourceVisible() {} },
|
||||
},
|
||||
parts: { rendering: { radioStationIdFromPick } },
|
||||
});
|
||||
const station = hit('radio:kexp');
|
||||
const tap = (contact = null, pick = null) => ({
|
||||
...clickEvent({ pick, windowHits: [station] }),
|
||||
hit: contact,
|
||||
screenPosition: { x: 5, y: 5 },
|
||||
});
|
||||
assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'open map');
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
assert.equal(radio.pickedRadioStationAt(tap()), null, 'window only');
|
||||
assert.equal(radio.pickedRadioStationAt(tap(station)), null, 'contact');
|
||||
assert.equal(
|
||||
radio.pickedRadioStationAt(tap(hit('radio:kuow'))),
|
||||
null,
|
||||
'another contact station',
|
||||
);
|
||||
assert.equal(radio.pickedRadioStationAt(tap(null, station)), null, 'exact');
|
||||
top = { sourceId: 'radio', entryId: 'radio:kexp' };
|
||||
assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'our own card');
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
SELECTION_FOLLOW_TRANSITION_S,
|
||||
} from '../../data/trackedCamera.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import {
|
||||
ACTIVATION_EXIT_ALTITUDE_M,
|
||||
@@ -203,6 +204,25 @@ test('a click on a train selects it; a click on the map lets it go', async (t) =
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a train under another
|
||||
// layer's card is neither selected nor let go.
|
||||
test("another layer's card over a train keeps the click", async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
const icons = app.drawn('icons');
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
app.click({ set: icons.spec.id, id: key, surface: false });
|
||||
assert.equal(app.state()._selectedKey ?? null, null, 'covered: not selected');
|
||||
top = null;
|
||||
app.click({ set: icons.spec.id, id: key, surface: false });
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
app.click(null);
|
||||
assert.equal(app.state()._selectedKey, key, 'covered: kept');
|
||||
});
|
||||
|
||||
test('a parked train, or one known from a single report, is flown to once', async (t) => {
|
||||
const app = harness(t);
|
||||
await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from './policy.js';
|
||||
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
@@ -173,6 +174,9 @@ export function createSelection({ state, services, parts }) {
|
||||
if (!state._enabled) return;
|
||||
// A held train keeps the selection until its view lets it go.
|
||||
if (state._cockpitSubjectKey) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
const key = trainKeyOf(event.drawHit);
|
||||
if (key) selectAndFocusTrain(key);
|
||||
else if (state._selectedKey) clearSelection();
|
||||
|
||||
@@ -7,7 +7,8 @@ export function createInteraction({
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
|
||||
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
|
||||
services.picking;
|
||||
|
||||
function _onKeyDown(e) {
|
||||
// The Cockpit owns Escape while it rides the tracked satellite.
|
||||
@@ -50,6 +51,9 @@ export function createInteraction({
|
||||
// The Cockpit camera rides the tracked satellite: a click on the
|
||||
// picture below must not untrack it or switch satellites.
|
||||
if (parts.cockpit?._cockpitHeld()) return;
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard?.(event)) return;
|
||||
const picked = event.topHit;
|
||||
const hit = event.drawHit;
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createInteraction } from './interaction.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
|
||||
// The card or label painted on top takes the click: a satellite under another
|
||||
// layer's card is neither tracked nor let go.
|
||||
test("another layer's card over a satellite keeps the click", (t) => {
|
||||
const previousDocument = globalThis.document;
|
||||
globalThis.document = new EventTarget();
|
||||
let picked = null;
|
||||
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
|
||||
const input = fakeInput(viewer);
|
||||
const calls = [];
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_trackedNorad: null,
|
||||
_clickSubscription: null,
|
||||
_trackedEntityChangedRemove: () => {},
|
||||
_catalog: new Map([[25544, {}]]),
|
||||
};
|
||||
const interaction = createInteraction({
|
||||
state,
|
||||
services: { picking },
|
||||
parts: {
|
||||
rendering: {
|
||||
_hitIsTracked: () => false,
|
||||
_hitPointId: (hit) =>
|
||||
hit?.set === 'satellites:dots' ? Number(hit.id) : null,
|
||||
},
|
||||
tracking: {
|
||||
_cancelPendingTrackingRestore() {},
|
||||
_trackSatellite: (id) => calls.push(['track', id]),
|
||||
_clearTracking: () => calls.push(['clear']),
|
||||
},
|
||||
},
|
||||
});
|
||||
interaction._installClickHandler(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
picking.setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
picking.setClickCardHitTest(null);
|
||||
state._clickSubscription?.();
|
||||
input.destroy();
|
||||
if (previousDocument === undefined) delete globalThis.document;
|
||||
else globalThis.document = previousDocument;
|
||||
});
|
||||
const click = (hit) => {
|
||||
picked = hit ? { id: hit } : null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
};
|
||||
const dot = { set: 'satellites:dots', id: '25544' };
|
||||
click(dot);
|
||||
assert.deepEqual(calls, [], 'covered: not tracked');
|
||||
state._trackedNorad = 1;
|
||||
click(null);
|
||||
assert.deepEqual(calls, [], 'covered: tracking kept');
|
||||
top = null;
|
||||
click(null);
|
||||
assert.deepEqual(calls, [['clear']], 'open map lets it go');
|
||||
state._trackedNorad = null;
|
||||
click(dot);
|
||||
assert.deepEqual(calls.at(-1), ['track', 25544]);
|
||||
});
|
||||
@@ -277,12 +277,18 @@ export function createShipwrecksLayer({
|
||||
if (!clicks) return;
|
||||
_clickHandler = clicks.onClick((click) => {
|
||||
if (pointer && !pointer.isPointerFree()) return;
|
||||
const at = click.screenPosition;
|
||||
const cardHit = overlayHost.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID,
|
||||
});
|
||||
if (cardHit && cardHit.entryId === _selectedCardId) {
|
||||
if (_selectedLink) openExternal(_selectedLink);
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours opens its source whatever is drawn
|
||||
// under it; another layer's is that layer's click, so the markers
|
||||
// under it do not act and the selection stays.
|
||||
const cardHit = picking.clickCard?.(click) ?? null;
|
||||
if (cardHit) {
|
||||
if (
|
||||
cardHit.sourceId === SHIPWRECKS_OVERLAY_SOURCE_ID &&
|
||||
cardHit.entryId === _selectedCardId &&
|
||||
_selectedLink
|
||||
)
|
||||
openExternal(_selectedLink);
|
||||
return;
|
||||
}
|
||||
// A marker's item id is its pick id, `shipwreck:<id>`. Read from what is
|
||||
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
|
||||
import {
|
||||
createShipwrecksLayer,
|
||||
markerPixelSize,
|
||||
@@ -36,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 = [];
|
||||
@@ -47,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 }) {
|
||||
@@ -59,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: () => ({
|
||||
@@ -393,3 +396,97 @@ 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 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);
|
||||
let cardUnder = null;
|
||||
const fake = fakeInputUnderLabel(viewer, {
|
||||
beneath: () =>
|
||||
cardUnder ? { sourceId: 'shipwrecks', entryId: cardUnder } : null,
|
||||
});
|
||||
t.after(() => fake.destroy());
|
||||
const cards = [];
|
||||
const opened = [];
|
||||
const layer = createShipwrecksLayer({
|
||||
source: { getSnapshot: () => Promise.resolve(snapshot([wreck('a')])) },
|
||||
overlayHost: {
|
||||
setEntries: (_source, entries) => cards.push(entries),
|
||||
setVisible() {},
|
||||
},
|
||||
input: () => fake.input,
|
||||
picking,
|
||||
pointer: { isPointerFree: () => true },
|
||||
openExternal: (url) => opened.push(url),
|
||||
now: () => 1,
|
||||
});
|
||||
layer.init(viewer);
|
||||
t.after(() => layer.destroy());
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
picked = { primitive: {}, id: { set: 'shipwrecks:', id: 'shipwreck:a' } };
|
||||
fake.click();
|
||||
const [card] = cards.at(-1);
|
||||
assert.equal(card.id, 'shipwreck-card:a');
|
||||
|
||||
// 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.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;
|
||||
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();
|
||||
}
|
||||
});
|
||||
@@ -23,8 +23,22 @@ export function createSelection({ state, parts }) {
|
||||
/** The id carries a provider's prefix: that provider handles the pick. */
|
||||
function onClick(event) {
|
||||
if (!state.viewer || !state.enabled) return;
|
||||
// Another layer's card or label painted on top takes the click, read once
|
||||
// per click so every layer agrees: no image, sequence or ground under it
|
||||
// opens. Street Level paints no cards of its own.
|
||||
if (picking?.isUnderOtherCard?.(event)) return;
|
||||
const hit = event.windowHit(CLICK_PICK_WINDOW_PX, CLICK_PICK_WINDOW_PX);
|
||||
const route = parts.router.resolve(pickIdOf(hit));
|
||||
const windowId = pickIdOf(hit);
|
||||
// A coarse tap's touch contact (event.hit) reaches farther than this
|
||||
// window: an item of ours there is still ours.
|
||||
const contact = event.hit;
|
||||
const contactId =
|
||||
contact && !contact.surface
|
||||
? pickIdOf({ drawHit: contact.set ? contact : null, id: event.id })
|
||||
: null;
|
||||
const route =
|
||||
parts.router.resolve(windowId) ??
|
||||
(contactId ? parts.router.resolve(contactId) : null);
|
||||
// Not ours: the ground handler decides whether it is the map itself.
|
||||
if (!route) {
|
||||
parts.openAtGround?.({ surface: hit.surface, ground: groundOf(event) });
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Cesium from 'cesium';
|
||||
import { createSelection } from './selection.js';
|
||||
import { createPickRouter } from './pickRouter.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import * as pickRegistry from '../../data/pickRegistry.js';
|
||||
|
||||
/** The selection installed on a stand-in viewer, with what its clicks reach. */
|
||||
function harness({
|
||||
@@ -47,11 +48,13 @@ function harness({
|
||||
...sceneExtras,
|
||||
},
|
||||
};
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
pickRegistry.setClickCardHitTest(services.overlayHit ?? null);
|
||||
const state = {
|
||||
viewer,
|
||||
enabled: true,
|
||||
clickSubscription: null,
|
||||
services: { picking: null, input: null, ...services },
|
||||
services: { picking: pickRegistry, input: null, ...services },
|
||||
providers: new Map([
|
||||
[
|
||||
'mapillary',
|
||||
@@ -105,6 +108,7 @@ function harness({
|
||||
return event;
|
||||
},
|
||||
restore() {
|
||||
pickRegistry.setClickCardHitTest(null);
|
||||
selection.uninstall();
|
||||
globalThis.document = saved;
|
||||
},
|
||||
@@ -289,3 +293,179 @@ test('a click on a provider line hands it the ground under the click, measured o
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// An image found only through Street Level's own window (not the exact pick)
|
||||
// under another layer's card or label is that card's click: its layer never
|
||||
// sees this window.
|
||||
test('an item found only in our window yields to a card painted over it', () => {
|
||||
let top = null;
|
||||
const h = harness({
|
||||
services: { overlayHit: () => top },
|
||||
sceneExtras: {
|
||||
pick: (_position, width = 3) =>
|
||||
width >= 9 ? { id: 'mly:img:near' } : null,
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['near'], 'open map: the window finds it');
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['near'], 'under a card: the card keeps it');
|
||||
assert.equal(h.groundClicks.length, 0);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// The map itself under another layer's card or label is that card's click:
|
||||
// a ground click there must not also open the nearest street image.
|
||||
test("a click on the map under another layer's card opens no ground image", () => {
|
||||
let top = null;
|
||||
const h = harness({ services: { overlayHit: () => top } });
|
||||
try {
|
||||
h.click();
|
||||
assert.equal(
|
||||
h.groundClicks.length,
|
||||
1,
|
||||
'open map: the ground handler decides',
|
||||
);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
h.click();
|
||||
assert.equal(h.groundClicks.length, 1, 'under a card: the card keeps it');
|
||||
assert.deepEqual(h.opened, []);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// A coarse tap's touch contact reaches farther than this window: on open map
|
||||
// Street Level takes it; under another layer's card the card does.
|
||||
test('a coarse touch contact beyond our window is ours to open, unless a card is on top', (t) => {
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
const h = harness({
|
||||
services: { picking: pickRegistry, overlayHit: () => top },
|
||||
sceneExtras: {
|
||||
pick: () => null,
|
||||
drillPick: () => [{ id: 'mly:img:contact' }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, [], 'under a card: the card keeps it');
|
||||
top = null;
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['contact']);
|
||||
assert.equal(h.groundClicks.length, 0);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// The exact hit or the touch contact on our line part under another layer's
|
||||
// card is that card's click; on open map it selects the sequence its part
|
||||
// picks as.
|
||||
test('an exact or contact hit on our line part acts only with no card on top', (t) => {
|
||||
const part = {
|
||||
set: 'street-level:mapillary-coverage:1',
|
||||
id: 'mly:seq:abc#2',
|
||||
meta: { pick: 'mly:seq:abc' },
|
||||
};
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
const card = () => top;
|
||||
const exact = harness({ services: { overlayHit: card } });
|
||||
try {
|
||||
exact.scene.under = part;
|
||||
exact.click();
|
||||
assert.deepEqual(exact.sequences.selects, [], 'under a card');
|
||||
top = null;
|
||||
exact.click();
|
||||
assert.deepEqual(exact.sequences.selects, ['abc'], 'mouse, exact part');
|
||||
} finally {
|
||||
top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
exact.restore();
|
||||
}
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
const contact = harness({
|
||||
services: { picking: pickRegistry, overlayHit: card },
|
||||
sceneExtras: {
|
||||
pick: (_position, width = 3) => (width >= 9 ? { id: part } : null),
|
||||
drillPick: () => [{ id: part }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
contact.click();
|
||||
assert.deepEqual(contact.sequences.selects, [], 'coarse, under a card');
|
||||
top = null;
|
||||
contact.click();
|
||||
assert.deepEqual(contact.sequences.selects, ['abc'], 'coarse contact');
|
||||
} finally {
|
||||
contact.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// Our window catching another layer's item says nothing about our own touch
|
||||
// contact beyond it: that contact is still ours.
|
||||
test('a contact of ours acts even when our window finds another item', (t) => {
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
const h = harness({
|
||||
services: { picking: pickRegistry },
|
||||
sceneExtras: {
|
||||
pick: (_position, width = 3) =>
|
||||
width >= 9 ? { id: { set: 'flights:1', id: 'flight:9' } } : null,
|
||||
drillPick: () => [{ id: 'mly:img:contact' }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['contact']);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
// Under another layer's card nothing of ours opens, whatever our window or the
|
||||
// tap's touch contact names; on open map our window's item opens.
|
||||
test('under a card, neither our window item nor our touch contact opens', (t) => {
|
||||
const previous = globalThis.matchMedia;
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
t.after(() => {
|
||||
if (previous) globalThis.matchMedia = previous;
|
||||
else delete globalThis.matchMedia;
|
||||
});
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'q' };
|
||||
const h = harness({
|
||||
services: { picking: pickRegistry, overlayHit: () => top },
|
||||
sceneExtras: {
|
||||
pick: (_position, width = 3) =>
|
||||
width >= 9 ? { id: 'mly:img:window' } : null,
|
||||
drillPick: () => [{ id: 'mly:img:contact' }],
|
||||
},
|
||||
});
|
||||
try {
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, []);
|
||||
assert.equal(h.groundClicks.length, 0);
|
||||
top = null;
|
||||
h.click();
|
||||
assert.deepEqual(h.opened, ['window']);
|
||||
} finally {
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
|
||||
export function createSubmarineCableLayer({
|
||||
source,
|
||||
overlayHost,
|
||||
picking = null,
|
||||
inputFor = defaultInputFor,
|
||||
mapStackEventTarget = null,
|
||||
sweepClock = defaultSweepClock,
|
||||
@@ -23,6 +24,7 @@ export function createSubmarineCableLayer({
|
||||
parts,
|
||||
source,
|
||||
inputFor,
|
||||
picking,
|
||||
mapStackEventTarget,
|
||||
};
|
||||
parts.rendering = createRendering(context);
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { toRadians } from '../../geo/vector.js';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
|
||||
export function createInteraction({ state, parts, inputFor }) {
|
||||
export function createInteraction({ state, parts, inputFor, picking }) {
|
||||
function beginInteraction(viewer) {
|
||||
if (state._clickSubscription) return;
|
||||
state._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!state._enabled) return;
|
||||
// Cable labels are not interactive, so any card or label painted on
|
||||
// top is another layer's, painted over the cable: its click.
|
||||
if (picking?.clickCard?.(event)) return;
|
||||
const record = resolvePickRecord(event.drawHit);
|
||||
if (!record?.reference) return;
|
||||
flyToReference(viewer, record.reference);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createInteraction } from './interaction.js';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
|
||||
/** The cable click handler, with its click and overlay seams faked. */
|
||||
function harness({ overlayTop = null } = {}) {
|
||||
let onClick = null;
|
||||
const picked = [];
|
||||
let top = overlayTop;
|
||||
const interaction = createInteraction({
|
||||
state: { _enabled: true, _clickSubscription: null },
|
||||
parts: {
|
||||
rendering: {
|
||||
pickInfo: (hit) => {
|
||||
picked.push(hit);
|
||||
return null;
|
||||
},
|
||||
},
|
||||
},
|
||||
inputFor: () => ({
|
||||
onClick: (fn) => {
|
||||
onClick = fn;
|
||||
return () => (onClick = null);
|
||||
},
|
||||
}),
|
||||
overlayHost: { hitTest: () => top },
|
||||
// The card on top at a click, as the registry answers from the host.
|
||||
picking: { clickCard: () => top },
|
||||
});
|
||||
interaction.beginInteraction({});
|
||||
return {
|
||||
picked,
|
||||
setTop: (next) => {
|
||||
top = next;
|
||||
},
|
||||
click: () =>
|
||||
onClick({
|
||||
screenPosition: { x: 5, y: 5 },
|
||||
drawHit: { set: 'c', id: 'x' },
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// Cable labels are not interactive: an overlay entry under the pointer is
|
||||
// another layer's card or label painted over the cable (a quake card), and
|
||||
// that layer takes the click, so the cable does not also fly the camera.
|
||||
test('a card painted over a cable keeps its click; with none the cable reads the pick', () => {
|
||||
const h = harness({
|
||||
overlayTop: { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' },
|
||||
});
|
||||
h.click();
|
||||
assert.equal(h.picked.length, 0, 'the cable stands aside');
|
||||
h.setTop(null);
|
||||
h.click();
|
||||
assert.equal(
|
||||
h.picked.length,
|
||||
1,
|
||||
'with no card on top, the cable reads its pick',
|
||||
);
|
||||
});
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
uninstallRenderGovernor,
|
||||
} from '../../renderGovernor.js';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
import { setClickCardHitTest } from '../../data/pickRegistry.js';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { bindRenderer, rendererOf } from '../../render/rendererOf.js';
|
||||
@@ -3745,6 +3746,30 @@ test('click handler selects a migrated scripted billboard and prepares its drape
|
||||
assert.equal(entry.marker.show, true);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: a vehicle under another
|
||||
// layer's card is neither selected nor released.
|
||||
test("another layer's card over a vehicle keeps the click", async (t) => {
|
||||
const app = harness(t, { floorAt: () => undefined });
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => setClickCardHitTest(null));
|
||||
app.layer.enable(app.viewer);
|
||||
app.layer._loadTransitFleetForTest(4, BOSTON, 70);
|
||||
const [first, second] = app.vehicles();
|
||||
app.viewer.scene.pick = () => app.pickOf(first);
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
assert.equal(app.state()._selectedKey, null, 'covered: not selected');
|
||||
top = null;
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
assert.equal(app.state()._selectedKey, first.key);
|
||||
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
app.viewer.scene.pick = () => app.pickOf(second);
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
app.viewer.scene.pick = () => undefined;
|
||||
app.input.click(new Cesium.Cartesian2(500, 400));
|
||||
assert.equal(app.state()._selectedKey, first.key, 'covered: kept');
|
||||
});
|
||||
|
||||
test('intercepted scripted reports resolve their explicit floor and wake without a preRender bootstrap', async (t) => {
|
||||
const app = harness(t, { floorAt: () => undefined });
|
||||
app.layer._setTransitFixtureFloorsForTest(['mbta:sim-straight'], 20);
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
} from './policy.js';
|
||||
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { isUnderOtherCard } from '../../data/pickRegistry.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
@@ -151,6 +152,9 @@ export function createSelection({ state, services, parts }) {
|
||||
collection:
|
||||
set === 'moving' ? 'animated' : set === 'still' ? 'stationary' : null,
|
||||
};
|
||||
// Another layer's card or label painted on top takes the click: the item
|
||||
// under it does not act, and the click is not empty space either.
|
||||
if (isUnderOtherCard(event)) return;
|
||||
if (key) {
|
||||
selectVehicle(key, { byUser: true });
|
||||
return;
|
||||
|
||||
@@ -30,8 +30,23 @@ export function createSelection({
|
||||
// The bridge view owns the selection: a click on open water must not
|
||||
// deselect the vessel the camera is riding.
|
||||
if (state.cockpitSubjectId) return;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: a card of ours acts whatever is drawn
|
||||
// under it; another layer's is that layer's click.
|
||||
const top = services.picking.clickCard?.(event) ?? null;
|
||||
if (top) {
|
||||
if (top.sourceId !== VESSEL_OVERLAY_SOURCE_ID) return;
|
||||
const id = String(top.entryId || '').startsWith('vessel:')
|
||||
? top.entryId.slice('vessel:'.length)
|
||||
: null;
|
||||
const carded = id ? state.records.byId.get(id) || null : null;
|
||||
// A stale card id is not empty terrain and must not clear a newer
|
||||
// selection. The next paint will evict its hit rectangle.
|
||||
if (carded) selectAndFocusVessel(carded);
|
||||
return;
|
||||
}
|
||||
const pickedId = event.id;
|
||||
let record = pickedId ? state.records.byId.get(pickedId) : null;
|
||||
const record = pickedId ? state.records.byId.get(pickedId) : null;
|
||||
// A vessel icon's pick is an item of the layer's icon set, whose id is
|
||||
// its row id: the record's id, or an unkeyed row's. Removing a row
|
||||
// removes its item, so an evicted vessel cannot be picked at all; a
|
||||
@@ -44,49 +59,19 @@ export function createSelection({
|
||||
|
||||
// An own-layer row without a live map key is a strict no-op (FB-1
|
||||
// residual). Trails carry no layer identity and hug their contacts, so any
|
||||
// `gev-trail:*` pick is also a no-op. Every other non-vessel pick — sibling
|
||||
// unowned scene picks dismiss the current vessel inspection.
|
||||
// `gev-trail:*` pick is also a no-op. A pick a sibling layer owns (an
|
||||
// aircraft, a route, a cyclone) is that layer's: preserve the current
|
||||
// vessel selection and do not compete with its camera command. Every
|
||||
// other non-vessel pick dismisses the current vessel inspection.
|
||||
if (ownRecordPick && (!pickedId || !record)) return;
|
||||
if (pickedId && !record && String(pickedId).startsWith('gev-trail:'))
|
||||
if (
|
||||
!record &&
|
||||
pickedId &&
|
||||
(String(pickedId).startsWith('gev-trail:') ||
|
||||
isOwnedByOtherLayer('ais-live-vessels', pickedId))
|
||||
)
|
||||
return;
|
||||
|
||||
// A sibling layer already owns this click. Preserve the current vessel
|
||||
// selection and do not compete with its camera command.
|
||||
const siblingOwned =
|
||||
pickedId && isOwnedByOtherLayer('ais-live-vessels', pickedId);
|
||||
// Cyclone geometry is ambient context behind painted cards. Its handler
|
||||
// yields to the same foreground AIS hit. Keep moving-contact precedence
|
||||
// unchanged: those handlers may issue their own camera command.
|
||||
const cycloneBackground =
|
||||
siblingOwned && !isOwnedByOtherLayer('weather-cyclones', pickedId);
|
||||
if (siblingOwned && !cycloneBackground) return;
|
||||
|
||||
// Cards are painted on a pointer-events:none canvas, so the scene pick is
|
||||
// usually terrain behind the card. Resolve against the host's current
|
||||
// actionable hit rectangles before treating the click as empty space.
|
||||
const cardHit = !record
|
||||
? vesselState._vesselOverlayHost.hitTest?.(
|
||||
event.screenPosition?.x,
|
||||
event.screenPosition?.y,
|
||||
{
|
||||
...(cycloneBackground
|
||||
? {}
|
||||
: { sourceId: VESSEL_OVERLAY_SOURCE_ID }),
|
||||
},
|
||||
)
|
||||
: null;
|
||||
if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
|
||||
return;
|
||||
if (!record && cardHit) {
|
||||
const id = String(cardHit.entryId || '').startsWith('vessel:')
|
||||
? cardHit.entryId.slice('vessel:'.length)
|
||||
: null;
|
||||
record = id ? state.records.byId.get(id) || null : null;
|
||||
// A stale card id is not empty terrain and must not clear a newer
|
||||
// selection. The next paint will evict its hit rectangle.
|
||||
if (!record) return;
|
||||
}
|
||||
|
||||
if (record) {
|
||||
// A valid sprite or card click always transfers the camera exactly once,
|
||||
// including a second click on the already-selected vessel.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
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';
|
||||
|
||||
/** Calls on any member are recorded by name and do nothing else. */
|
||||
function recorder(calls) {
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get:
|
||||
(_target, name) =>
|
||||
(...args) =>
|
||||
calls.push([name, ...args]),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 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 = {
|
||||
feed: { enabled: true },
|
||||
records: { byId: new Map([[vessel.id, vessel]]) },
|
||||
icons: { setId: 'vessels:icons', has: () => false },
|
||||
selectedRecord: null,
|
||||
interactionKeyTarget: new EventTarget(),
|
||||
};
|
||||
const vesselState = { state };
|
||||
const selection = createSelection({
|
||||
vesselState,
|
||||
services: {
|
||||
picking: { isOwnedByOtherLayer: () => false, clickCard },
|
||||
worldFocus: { requestWorldFocus: (request) => focused.push(request.id) },
|
||||
context: recorder(calls),
|
||||
},
|
||||
parts: {
|
||||
queries: {
|
||||
reduceVesselSelection: ({ selectedId, pickedId }) =>
|
||||
pickedId
|
||||
? { action: pickedId === selectedId ? 'none' : 'select' }
|
||||
: { action: selectedId ? 'deselect' : 'none' },
|
||||
},
|
||||
rendering: recorder(calls),
|
||||
cards: recorder(calls),
|
||||
photos: recorder(calls),
|
||||
tracking: recorder(calls),
|
||||
},
|
||||
layer: { source: 'AIS' },
|
||||
});
|
||||
selection.installInteraction(viewer);
|
||||
t.after(() => selection.removeVesselInteraction());
|
||||
return { fake, state, vessel, focused };
|
||||
}
|
||||
|
||||
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();
|
||||
assert.equal(h.state.selectedRecord, null);
|
||||
assert.deepEqual(h.focused, [], 'the camera is not sent to the vessel');
|
||||
});
|
||||
|
||||
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, 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) },
|
||||
|
||||
@@ -482,19 +482,13 @@ export function createSelection({ state, services, parts }) {
|
||||
state.clickHandler = input.onClick((click) => {
|
||||
if (!state.enabled || services.pointer?.isPointerFree?.() === false)
|
||||
return;
|
||||
const at = click.screenPosition;
|
||||
const hit =
|
||||
overlay?.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: WILDLIFE_SELECTED_SOURCE_ID,
|
||||
}) ||
|
||||
overlay?.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: WILDLIFE_OVERLAY_SOURCE_ID,
|
||||
}) ||
|
||||
overlay?.hitTest?.(at?.x, at?.y, {
|
||||
sourceId: WILDLIFE_LABEL_SOURCE_ID,
|
||||
});
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: ours acts whatever is drawn under it;
|
||||
// another layer's is that layer's click, so the sightings under it do
|
||||
// not act and the selection stays.
|
||||
const hit = services.picking?.clickCard?.(click) ?? null;
|
||||
if (hit) {
|
||||
hit.entry?.activate?.();
|
||||
if (sourceIds.includes(hit.sourceId)) hit.entry?.activate?.();
|
||||
return;
|
||||
}
|
||||
// A sighting icon's item id is its pick id, `wildlife:<stableId>`.
|
||||
|
||||
@@ -2,6 +2,8 @@ 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 = {
|
||||
stableId: 'inat:123',
|
||||
@@ -21,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 = {
|
||||
@@ -42,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++;
|
||||
@@ -66,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: {
|
||||
@@ -94,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);
|
||||
@@ -179,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,
|
||||
@@ -304,6 +351,44 @@ test('empty clicks and layer removal release the selected row and its overlay',
|
||||
assert.equal(f.entries.size, 0);
|
||||
});
|
||||
|
||||
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) => {
|
||||
fake ??= fakeInputUnderLabel(viewer);
|
||||
return fake.input;
|
||||
},
|
||||
});
|
||||
f.selection.install();
|
||||
t.after(() => {
|
||||
f.selection.remove();
|
||||
fake.destroy();
|
||||
});
|
||||
f.selection.refreshAmbient();
|
||||
// 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, 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');
|
||||
});
|
||||
|
||||
test('a tap selects only a sighting exactly under it, not one the touch search found near it', () => {
|
||||
const f = fixture();
|
||||
f.selection.install();
|
||||
|
||||
Reference in new issue
Block a user