fix(picking): arbitrate card clicks over passive and background shapes

Flight trails register their ids so every layer reads a trail click as a
no-op, and the directions route claims its line and markers though it acts
only on its maneuver steps. The quake card and magnitude labels yielded to
any registered owner, so over a trail or a route they did nothing. Pick
owners can now name the picks they never act on (registerPickOwner(...,
{ passive })); isActedOnByOtherLayer leaves those out while
isOwnedByOtherLayer is unchanged, so they are still not empty space.

Submarine cables and rocket launches acted on any scene pick, so a card or
label over a cable or a launch marker made both layers act. Both now stand
aside when a world-overlay entry is under the click, as drone airspace and
fire perimeters do through the top-entry check. Each of these layers, and
the quake discs, registers its shapes with registerCardBackground. CCTV
asks isCardBackground instead of matching other layers' set and id formats,
so a live top CCTV card acts once over any of them, while unknown
identified objects and registered owners still block it.
This commit is contained in:
manjunath22466 committed 2026-11-17 01:33:06 +05:30
1 parent 836daf82b3
commit 133d022b29
23 files changed
+825 -78

No files matched your search

+24 -2
View File
@@ -1874,11 +1874,33 @@ layer's card or label is the topmost overlay entry, so a quake card or
magnitude label over one of them acts once, as the quake's. Items of layers
that never act on clicks (air-quality stations, traffic lines, OSM places) do
not block the quake card or labels. A bare area click with nothing painted on
top still selects the area and clears the quake selection. These rules hold in any
listener order because world-overlay hit rectangles are what is painted on
top still selects the area and clears the quake selection. These rules hold in
any listener order because world-overlay hit rectangles are what is painted on
screen until the next paint: an overlay change (a click subscriber publishing
its selection card) no longer clears them mid-click, and a paint that draws
nothing clears them (`src/overlays/worldOverlay.js`).
Card consumers resolve the unfiltered top painted entry before acting, so a
covered vessel, fire, wildlife, news, CCTV, perimeter, ghost-map or shipwreck
card does not act alongside the card above it; drone-airspace shapes use the
same top-entry check (their cards are not interactive). A top news or wildlife
card still acts over another layer's scene item, as before, so a card over a
flight trail (registered as a no-op for every layer) or a directions route is
never a dead click. A click on another layer's card does not activate a covered
card of these layers or clear their selection; a marker of theirs under that
card is still theirs to select. Flight trails and the directions route line and
markers are passive pick owners (`registerPickOwner(…, { passive })`): still
not empty space (`isOwnedByOtherLayer`), but `isActedOnByOtherLayer` leaves
them out, so the quake card and magnitude labels act over them. Directions
selects only its maneuver steps, though any other click still clears a selected
step. Fire, vessel and CCTV cards over a trail or the route stay as they were
(no action). Submarine cables and rocket launches, whose own overlays are not
interactive, stand aside when any overlay entry is under the click, so a card
or label over a cable or a launch marker acts once. Layers whose shapes stand
aside like this (drone airspace, fire perimeters, quake discs, cables,
launches) register them with `registerCardBackground`, and a live top CCTV card
acts over any shape `isCardBackground` names; unknown identified objects and
registered foreign owners still block it. An empty-map click keeps its existing
deselection behavior.
Air quality (`./layers/air-quality`) draws its station discs as one renderer
draw set of ground-clamped fills and reads the view through the camera port; it
+2
View File
@@ -435,6 +435,8 @@
"src/layers/earthquakes/source.js",
"src/layers/earthquakes/ownership.test.mjs",
"src/layers/earthquakes/selection.test.mjs",
"src/layers/submarineCables/interaction.test.mjs",
"src/layers/launches/clickYield.test.mjs",
"src/app/layers/earthquakeRipples.js",
"src/app/layers/earthquakeRipples.test.mjs",
"src/layers/perimeters/index.js",
+2 -1
View File
@@ -2,11 +2,12 @@ import { createRocketLaunchesLayer } from '../../layers/launches/index.js';
import * as geometry from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import * as render from '../../renderGovernor.js';
import * as picking from '../../data/pickRegistry.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationLaunches({ source, satellites }) {
return createRocketLaunchesLayer({
source,
services: { satellites, geometry, overlays, render },
services: { satellites, geometry, overlays, render, picking },
});
}
+5 -1
View File
@@ -1,9 +1,13 @@
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
import { overlayHost } from './overlayHost.js';
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import * as picking from '../../data/pickRegistry.js';
/** Wire cable source geometry to the application overlay host. */
export function createApplicationCables(options) {
return createSubmarineCableLayer({
overlayHost,
// Hit-testing lets a card painted over a cable keep its click.
overlayHost: { ...overlayHost, hitTest: hitTestWorldOverlay },
picking,
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
});
+2 -9
View File
@@ -1022,10 +1022,6 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
componentFunctionSource(cctvLayer.init),
/_cctvOverlayHost\.hitTest/,
);
assert.match(
componentFunctionSource(cctvLayer.init),
/sourceId: CCTV_OVERLAY_SOURCE_ID/,
);
assert.match(
componentFunctionSource(cctvLayer.init),
/activateCctvCameraFromWorldClick\(cameraId, setActiveCamera\)/,
@@ -1157,11 +1153,8 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
const initSource = componentFunctionSource(cctvLayer.init);
assert.ok(
initSource.indexOf('if (pickedId !== null) return') <
initSource.indexOf('_cctvOverlayHost.hitTest'),
'every identified sibling must win before an overlapping CCTV card hit test',
);
// The real init-bound click route, including identified-object barriers,
// is exercised in layers/cctv/lifecycle.test.mjs.
assert.match(initSource, /activeCameraId: _activeCameraId/);
assert.match(initSource, /calibrationMode: _calibrationMode/);
});
+41
View File
@@ -28,6 +28,8 @@ import {
createApplicationDirectionsLayer,
} from './directions.js';
import { GROUND_FLOOR_LIFT_M } from './groundFloor.js';
import { isActedOnByOtherLayer, isOwnedByOtherLayer } from './pickRegistry.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { instructionFor } from './routeSteps.js';
import { setLocale } from '../i18n/index.js';
import {
@@ -465,6 +467,45 @@ function ownershipFixture(t) {
});
}
// Directions acts only on its maneuver steps. The route line and the A/B
// markers are passive picks: still not empty space to other layers, but a
// card painted over them (a quake card) keeps its click.
test('enabled, directions owns its picks and acts only on its steps', (t) => {
ownershipFixture(t);
const viewer = {
scene: {
pick: () => null,
canvas: { clientWidth: 100, clientHeight: 100 },
},
};
const input = fakeInput(viewer);
t.after(() => input.destroy());
directionsLayer.enable(viewer);
try {
for (const id of [
'directions:route',
'directions:marker:a',
'directions:step:3',
])
assert.equal(isOwnedByOtherLayer('earthquakes', id), true, id);
assert.equal(
isActedOnByOtherLayer('earthquakes', 'directions:route'),
false,
);
assert.equal(
isActedOnByOtherLayer('earthquakes', 'directions:marker:a'),
false,
);
assert.equal(
isActedOnByOtherLayer('earthquakes', 'directions:step:3'),
true,
);
} finally {
directionsLayer.disable(viewer);
}
assert.equal(isOwnedByOtherLayer('earthquakes', 'directions:route'), false);
});
test('placing an endpoint takes the pointer, and every exit path gives it back', (t) => {
ownershipFixture(t);
+86 -1
View File
@@ -26,6 +26,19 @@ const isSurface = (hit) => !hit || hit.surface === true;
/** @type {Map<string, (pickedId: string) => boolean>} layerId -> ownership predicate */
const _owners = new Map();
/**
* Owners that claim picks but never act on a click on them (flight trails, a
* directions route line): `true` for all of an owner's picks, or a predicate
* naming which. Their picks are still not empty space to other layers.
* @type {Map<string, true | ((pickedId: string) => boolean)>}
*/
const _passive = new Map();
/**
* Layers whose shapes are background to any card painted over them: their
* click handlers stand aside under a card, so the card's layer may act there.
* @type {Map<string, (hit: import('../render/contract/query').Hit) => boolean>}
*/
const _cardBackgrounds = new Map();
/**
* A hit's canonical pick id, for the ownership scan: its item's id. Layers'
@@ -47,11 +60,17 @@ export function resolvePickId(hit) {
* @param {string} layerId - Owning layer id (e.g. 'flights').
* @param {(pickedId: string) => boolean} predicate - Returns true when the
* picked primitive/entity id belongs to this layer.
* @param {{passive?: boolean | ((pickedId: string) => boolean)}} [options]
* `passive`: the layer never acts on a click on these picks (all of them,
* or those the predicate names). See {@link isActedOnByOtherLayer}.
* @returns {void}
*/
export function registerPickOwner(layerId, predicate) {
export function registerPickOwner(layerId, predicate, { passive } = {}) {
if (!layerId || typeof predicate !== 'function') return;
_owners.set(layerId, predicate);
if (passive === true || typeof passive === 'function')
_passive.set(layerId, passive);
else _passive.delete(layerId);
}
/**
@@ -61,6 +80,7 @@ export function registerPickOwner(layerId, predicate) {
*/
export function unregisterPickOwner(layerId) {
_owners.delete(layerId);
_passive.delete(layerId);
}
/**
@@ -99,6 +119,31 @@ export function isOwnedByOtherLayer(layerId, pickedId) {
return false;
}
/**
* True when some OTHER registered layer owns the picked id and acts on a
* click on it: {@link isOwnedByOtherLayer} without passive owners. A card
* painted over a passive pick (a flight trail) is still the card's click.
* @param {string} layerId - The asking layer's id (excluded from the scan).
* @param {string} pickedId - Picked primitive/entity id.
* @returns {boolean}
*/
export function isActedOnByOtherLayer(layerId, pickedId) {
if (!pickedId) return false;
for (const [ownerId, predicate] of _owners) {
if (ownerId === layerId) continue;
try {
if (!predicate(pickedId)) continue;
const passive = _passive.get(ownerId);
if (passive === true) continue;
if (typeof passive === 'function' && passive(pickedId)) continue;
return true;
} catch {
// a broken predicate must never break click handling
}
}
return false;
}
/**
* Resolve a moving-contact click without letting map tiles hide a nearby touch
* target. Exact picks always win; only a coarse primary pointer may expand a
@@ -145,3 +190,43 @@ export function pickContact(query, position, options = {}) {
}
return picked;
}
/**
* Registers a layer's unowned shapes that stand aside for a card painted over
* them (its click handler returns when a world-overlay entry is on top).
* @param {string} layerId - Registering layer id.
* @param {(hit: import('../render/contract/query').Hit) => boolean} predicate
* True when a click's draw hit is one of this layer's shapes.
* @returns {void}
*/
export function registerCardBackground(layerId, predicate) {
if (!layerId || typeof predicate !== 'function') return;
_cardBackgrounds.set(layerId, predicate);
}
/**
* Removes a layer's card-background predicate (call when its clicks stop).
* @param {string} layerId - Registering layer id.
* @returns {void}
*/
export function unregisterCardBackground(layerId) {
_cardBackgrounds.delete(layerId);
}
/**
* True when a click's draw hit is a shape whose layer stands aside for a card
* painted over it, so that card may act on the click.
* @param {import('../render/contract/query').Hit|null|undefined} hit
* @returns {boolean}
*/
export function isCardBackground(hit) {
if (isSurface(hit)) return false;
for (const predicate of _cardBackgrounds.values()) {
try {
if (predicate(hit)) return true;
} catch {
// a broken predicate must never break click handling
}
}
return false;
}
+99 -10
View File
@@ -15,8 +15,13 @@ import {
registerPickOwner,
unregisterPickOwner,
isOwnedByOtherLayer,
isActedOnByOtherLayer,
resolvePickId,
pickContact,
findPickOwner,
registerCardBackground,
unregisterCardBackground,
isCardBackground,
} from './pickRegistry.js';
// ---------------------------------------------------------------------------
@@ -49,8 +54,11 @@ test('resolvePickId: the map and nothing → null', () => {
// ---------------------------------------------------------------------------
test('ownership: sibling layers recognize each other via String-coerced ids', () => {
const points = new Map([[25544, {}], [43013, {}]]); // satellites: numeric keys
const vessels = new Map([['367123450', {}]]); // AIS: string id keys
const points = new Map([
[25544, {}],
[43013, {}],
]); // satellites: numeric keys
const vessels = new Map([['367123450', {}]]); // AIS: string id keys
registerPickOwner('satellites', (pickedId) => {
const norad = Number(pickedId);
return Number.isFinite(norad) && points.has(norad);
@@ -58,9 +66,15 @@ test('ownership: sibling layers recognize each other via String-coerced ids', ()
registerPickOwner('ais-live-vessels', (pickedId) => vessels.has(pickedId));
try {
// Flights asking about a satellite pick (raw numeric id → String upstream)
assert.equal(isOwnedByOtherLayer('flights', resolvePickId(item('sat:1', '25544'))), true);
assert.equal(
isOwnedByOtherLayer('flights', resolvePickId(item('sat:1', '25544'))),
true,
);
// Flights asking about a vessel pick (an icon row id: the vessel's id)
assert.equal(isOwnedByOtherLayer('flights', resolvePickId(item('ais:1', '367123450'))), true);
assert.equal(
isOwnedByOtherLayer('flights', resolvePickId(item('ais:1', '367123450'))),
true,
);
// A layer never owns its own pick via the sibling scan
assert.equal(isOwnedByOtherLayer('satellites', '25544'), false);
// Unknown ids belong to nobody
@@ -73,7 +87,9 @@ test('ownership: sibling layers recognize each other via String-coerced ids', ()
});
test('ownership: a throwing predicate never breaks click handling', () => {
registerPickOwner('broken', () => { throw new Error('boom'); });
registerPickOwner('broken', () => {
throw new Error('boom');
});
registerPickOwner('cctv', (pickedId) => pickedId === 'atx-cam-3');
try {
assert.equal(isOwnedByOtherLayer('flights', 'atx-cam-3'), true);
@@ -121,6 +137,49 @@ function query(picked, drillPick = () => assert.fail('must not drill')) {
};
}
test('ownership: passive owners still own their picks but act on none of them', () => {
registerPickOwner('test-trails', (id) => id.startsWith('trail:'), {
passive: true,
});
registerPickOwner('test-route', (id) => id.startsWith('route:'), {
passive: (id) => !id.startsWith('route:step:'),
});
registerPickOwner('test-plane', (id) => id === 'plane:1');
registerPickOwner('test-broken', () => {
throw new Error('broken');
});
try {
assert.equal(
isOwnedByOtherLayer('cards', 'trail:9'),
true,
'not empty space',
);
assert.equal(isActedOnByOtherLayer('cards', 'trail:9'), false);
assert.equal(isActedOnByOtherLayer('cards', 'route:line'), false);
assert.equal(isActedOnByOtherLayer('cards', 'route:step:3'), true);
assert.equal(isActedOnByOtherLayer('cards', 'plane:1'), true);
assert.equal(
isActedOnByOtherLayer('test-plane', 'plane:1'),
false,
'never the asker',
);
assert.equal(isActedOnByOtherLayer('cards', null), false);
// Registering again without the option makes the owner act.
registerPickOwner('test-trails', (id) => id.startsWith('trail:'));
assert.equal(isActedOnByOtherLayer('cards', 'trail:9'), true);
// Unregistering drops the option with the predicate.
registerPickOwner('test-trails', (id) => id.startsWith('trail:'), {
passive: true,
});
unregisterPickOwner('test-trails');
registerPickOwner('test-trails', (id) => id.startsWith('trail:'));
assert.equal(isActedOnByOtherLayer('cards', 'trail:9'), true);
} finally {
for (const id of ['test-trails', 'test-route', 'test-plane', 'test-broken'])
unregisterPickOwner(id);
}
});
test('touch contact pick expands only a surface miss, bounded to 8 hits in 14 CSS pixels', (t) => {
primaryPointer(t, true);
contactOwners(t);
@@ -141,10 +200,14 @@ test("touch contact pick uses the click's own pick and drill", (t) => {
contactOwners(t);
const contact = item('flights:1', 'civil');
const asked = [];
const found = pickContact(query(null), { x: 1, y: 1 }, {
picked: null,
drill: (...args) => (asked.push(args), [contact]),
});
const found = pickContact(
query(null),
{ x: 1, y: 1 },
{
picked: null,
drill: (...args) => (asked.push(args), [contact]),
},
);
assert.equal(found, contact);
assert.deepEqual(asked, [[8, 14, 14]]);
});
@@ -177,7 +240,13 @@ test('touch expansion stops at an unowned item and respects the drill bound', (t
[...Array(8).fill(item('notes:1', 'x')), item('flights:1', 'civil')],
[],
])
assert.equal(pickContact(query(SURFACE, () => hits), { x: 1, y: 1 }), SURFACE);
assert.equal(
pickContact(
query(SURFACE, () => hits),
{ x: 1, y: 1 },
),
SURFACE,
);
});
test('fine primary pointers keep the exact mouse pick without a drill', (t) => {
@@ -197,3 +266,23 @@ test('touch picking tolerates a failing drill and preserves empty sky', (t) => {
])
assert.equal(pickContact(query(null, drillPick), { x: 1, y: 1 }), null);
});
test('card backgrounds: a registered shape, never the map, and safe to break', () => {
const shape = { set: 'zones:1:fills', id: 'zone:1', surface: false };
assert.equal(isCardBackground(shape), false);
registerCardBackground('test-zones', (hit) => hit.set === shape.set);
registerCardBackground('test-broken', () => {
throw new Error('broken predicate');
});
try {
assert.equal(isCardBackground(shape), true);
assert.equal(isCardBackground({ ...shape, set: 'other:1' }), false);
assert.equal(isCardBackground({ surface: true }), false);
assert.equal(isCardBackground(null), false);
assert.equal(findPickOwner(shape.id), null, 'not an owner');
} finally {
unregisterCardBackground('test-zones');
unregisterCardBackground('test-broken');
}
assert.equal(isCardBackground(shape), false);
});
+6 -2
View File
@@ -36,8 +36,12 @@ import { registerPickOwner } from './pickRegistry.js';
// plane being tracked. Claiming the 'gev-trail:' id namespace makes
// isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op
// everywhere. Registered once at module load; the predicate is pure.
registerPickOwner('trails', (pickedId) =>
String(pickedId).startsWith('gev-trail:'),
// Passive: no layer acts on a trail click, so a card painted over a trail
// still takes its click (isActedOnByOtherLayer).
registerPickOwner(
'trails',
(pickedId) => String(pickedId).startsWith('gev-trail:'),
{ passive: true },
);
/** @type {number} Uniquifier for trail set and line ids. */
+31 -17
View File
@@ -23,8 +23,13 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
services.picking;
const {
resolvePickId,
registerPickOwner,
unregisterPickOwner,
isOwnedByOtherLayer,
isCardBackground,
} = services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -401,23 +406,32 @@ export function createLifecycle({
);
return;
}
// Any identified scene object owns this click even if its layer does not
// register a shared pick predicate. This keeps selectable siblings ahead
// of an overlapping CCTV card while ID-less globe/terrain/tile surfaces
// remain eligible for true empty-space deselection.
const pickedId = resolvePickId(picked);
if (pickedId !== null) return;
// Item A (owner round 2): the scene pick found no camera — try the
// painted ambient cards. The cards canvas is pointer-events:none (this
// handler owns the events), so a click landing on a card's rect selects
// its camera exactly like a click on the icon. Click positions
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
// Cards use the last-painted top hit, never an obscured card from
// our own source. Actual camera icons above keep their normal route.
const cardHit = layerState._cctvOverlayHost.hitTest(
event.screenPosition.x,
event.screenPosition.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
if (cardId && layerState._recordById.has(cardId)) {
{},
);
const cardId =
cardHit?.sourceId === CCTV_OVERLAY_SOURCE_ID &&
layerState._recordById.has(cardHit.entryId)
? cardHit.entryId
: null;
const pickedId = resolvePickId(picked);
const hit = event.drawHit;
// A live top CCTV card acts over shapes whose layers stand aside
// for a painted card (drone zones, fire perimeters, quake discs,
// cables, launch markers), as each registers them. Unknown
// identified objects and registered owners remain barriers.
const cardBackground =
cardId &&
typeof pickedId === 'string' &&
!isOwnedByOtherLayer?.('cctv', pickedId) &&
Boolean(isCardBackground?.(hit));
if (pickedId !== null && !cardBackground) return;
if (cardHit && cardHit.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
if (cardId) {
activateCctvCameraFromWorldClick(
cardId,
parts.selection.setActiveCamera,
+131
View File
@@ -1,6 +1,10 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { createSelection } from './selection.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
@@ -72,3 +76,130 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.deepEqual(counts(second.camera), [0, 0]);
assert.equal(state._viewListenerCamera, null);
});
test('world clicks respect the painted top card and registered card backgrounds', async (t) => {
const noop = () => {};
const { viewer } = viewerWithCamera();
let picked = null;
viewer.scene = {
canvas: {},
pick: () => (picked ? { id: picked } : undefined),
};
const input = fakeInput(viewer);
const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
const foreignCard = {
sourceId: 'earthquake-card',
entryId: 'earthquake-card:qa',
};
let painted = [];
const actions = [];
const state = {
_cctvOverlayHost: {
hitTest: (_x, _y, options = {}) =>
painted.find(
(hit) => !options.sourceId || hit.sourceId === options.sourceId,
) ?? null,
},
};
const parts = {
calibration: { loadCalibrationStore: () => new Map() },
catalog: {
loadCameraSources: async () => [],
buildCatalogFromSources: () => [],
seedCatalog: () => [],
},
ground: {
resolveGroundPriors: async () => [],
currentSurfaceRegime: () => 'terrain-globe',
},
cards: { teardownAmbientCards: noop },
projection: { clearProjectionOverlay: noop },
geometryQueue: { stopGeometryLoadQueue: noop },
rendering: {
createCameraIcons: noop,
refreshHorizonCulling: () => false,
refreshCoverageStyles: noop,
extractPickedCameraId: (hit) =>
hit?.set === 'cctv:fixture' ? hit.id : null,
},
hover: { handleHoverMove: noop },
health: { syncHealthState: async () => {} },
presentation: { notifyListeners: noop },
};
const services = {
sprites: {},
focus: {},
render: {},
picking,
activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) },
};
parts.selection = createSelection({ state, services, parts });
parts.selection.deactivateActiveCamera = () => actions.push('clear');
const lifecycle = createLifecycle({ state, services, parts });
t.after(() => {
state._clickSubscription?.();
lifecycle.detachViewListeners();
input.destroy();
picking.unregisterPickOwner('area-control');
picking.unregisterCardBackground('area-fixture');
});
await lifecycle.methods.init(viewer);
state._enabled = true;
state._activeCameraId = 'cam-1';
state._recordById.set('cam-1', { camera: { id: 'cam-1' } });
const click = (hit, cards, expected) => {
picked = hit;
painted = cards;
actions.length = 0;
input.tap();
assert.deepEqual(actions, expected, JSON.stringify({ hit, cards }));
};
const drone = {
set: 'drone-airspace:1:fills',
id: 'drone-airspace:zone:0',
surface: false,
};
const perimeter = {
set: 'fire-perimeters:1:lines',
id: 'fire-perimeter:incident:0',
surface: false,
};
const quake = { set: 'earthquakes:1', id: 'earthquake:q1', surface: false };
const cable = { set: 'submarine-cables:1:lines', id: 'c:0', surface: false };
const launch = {
set: 'launches:1:markers',
id: 'rocket-x:1',
surface: false,
};
const backgrounds = [drone, perimeter, quake, cable, launch];
// Each of those layers registers its own shapes this way (their tests
// check the real predicates); CCTV only asks the registry.
picking.registerCardBackground('area-fixture', (hit) =>
backgrounds.some((b) => b.set === hit.set && b.id === hit.id),
);
for (const area of backgrounds) {
click(area, [ownCard], ['cam-1']);
click(area, [], []);
click(area, [foreignCard, ownCard], []);
}
for (const hit of [
{ set: 'flights:1', id: 'aircraft', surface: false },
{ set: '', id: 'unregistered-local-entity', surface: false },
{ set: '', id: '', surface: false },
{ ...drone, set: 'unrelated:1:fills' },
{ ...drone, id: 'unregistered-local-entity' },
])
click(hit, [ownCard], []);
picking.registerPickOwner('area-control', (id) => id === drone.id);
click(drone, [ownCard], []);
picking.unregisterPickOwner('area-control');
click(null, [foreignCard, ownCard], []);
click(null, [ownCard], ['cam-1']);
click(null, [], ['clear']);
click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
click(
{ set: 'cctv:fixture', id: 'cam-1' },
[foreignCard, ownCard],
['cam-1'],
);
});
+3
View File
@@ -1672,10 +1672,13 @@ export function createDirectionsLayer({ services, source }) {
_overlayHost.setVisible(DIRECTIONS_STEP_OVERLAY_SOURCE_ID, true);
_overlayHost.setVisible(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID, true);
_installClickHandler(viewer);
// Only the maneuver steps act on a click; the route line and the A/B
// markers are passive, so a card painted over them keeps its click.
services.picking.registerPickOwner(
'directions',
(pickedId) =>
typeof pickedId === 'string' && pickedId.startsWith('directions:'),
{ passive: (pickedId) => !pickedId.startsWith('directions:step:') },
);
syncRenderHold();
},
+12 -10
View File
@@ -129,25 +129,26 @@ export function createDroneAirspaceLayer({
// so claiming these large ground polygons would make FIRMS/vessel/CCTV
// cards inert anywhere over a zone. Unowned, our picks read as
// "empty space" to siblings — the same contract as fire perimeters.
// Our shapes stand aside for a card painted over them (below), so that
// card's layer may act on the click; without a hit-test they cannot.
if (overlayHost?.hitTest)
picking?.registerCardBackground?.(
layer.id,
(hit) => pickedZoneId(hit) !== null,
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
);
// Only the top painted card owns the click; this area's shapes are
// background when another layer has painted a card or label over them.
if (cardHit && cardHit.sourceId !== DRONE_AIRSPACE_OVERLAY_SOURCE_ID)
return;
if (cardHit && cardHit.entryId === _selectedCardId) return;
const picked = event.topHit;
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
if (zoneId) {
// Another layer's card or label painted over the zone (a quake's
// card or magnitude label, a fire card) is that layer's click: under
// it the zone is background, as it is to siblings, so it stays as is.
const top = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{},
);
if (top && top.sourceId !== DRONE_AIRSPACE_OVERLAY_SOURCE_ID) return;
_selectedId = zoneId;
publishSelectedCard();
return;
@@ -166,6 +167,7 @@ export function createDroneAirspaceLayer({
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
picking?.unregisterCardBackground?.(layer.id);
}
function clearSelection() {
+33 -1
View File
@@ -17,6 +17,7 @@ const liveSet = (draw, suffix) =>
function harness(source, { pick = () => null, cardHit = () => null } = {}) {
const overlay = { entries: new Map(), visible: null };
const owners = new Map();
const backgrounds = new Map();
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
const input = fakeInput(viewer);
@@ -47,6 +48,9 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
registerCardBackground: (layerId, predicate) =>
backgrounds.set(layerId, predicate),
unregisterCardBackground: (layerId) => backgrounds.delete(layerId),
},
});
layer.init(viewer);
@@ -61,6 +65,7 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
overlay,
clicks,
owners,
backgrounds,
};
}
@@ -153,6 +158,8 @@ test("another layer's overlay on top keeps a click off the area", async () => {
{
pick: () => pickResult,
// Unfiltered: the topmost entry of any source.
// As the host does: drone-airspace cards are not interactive, so only
// another layer's card painted on top is ever hit.
cardHit: (_x, _y, options) =>
foreignOnTop && !options?.sourceId
? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }
@@ -171,13 +178,20 @@ test("another layer's overlay on top keeps a click off the area", async () => {
h.overlay.entries.get('drone-airspace')[0].id,
'drone-airspace-card:310',
);
// An overlay on top never clears an existing selection either.
// An overlay on top covers the selected area's card.
foreignOnTop = true;
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(
h.overlay.entries.get('drone-airspace')[0].id,
'drone-airspace-card:310',
);
pickResult = null;
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(
h.overlay.entries.get('drone-airspace')[0].id,
'drone-airspace-card:310',
'the foreground overlay preserves selection over bare map too',
);
});
test('late refresh cannot publish after disable or destroy', async () => {
@@ -270,3 +284,21 @@ test('a boundary change alone redraws the zone; identical geometry does not', as
assert.notDeepEqual(redrawn.positions, first.positions);
assert.ok(h.layer.getAnalystRecords()[0].lon > -76.6);
});
// A card painted over the area may act there (a live CCTV card): the layer
// names its own drawn shapes, and only while it takes clicks.
test('enabled, the zone shapes register as card background', async () => {
const h = harness({ getSnapshot: async () => [row] });
await h.layer.update(h.viewer);
const isBackground = h.backgrounds.get('drone-airspace');
const own = {
set: h.fills().spec.id,
id: 'drone-airspace:310:0',
surface: false,
};
assert.equal(isBackground(own), true);
assert.equal(isBackground({ ...own, set: 'other:1:fills' }), false);
assert.equal(isBackground({ ...own, id: 'other-layer:x' }), false);
h.layer.disable(h.viewer);
assert.equal(h.backgrounds.has('drone-airspace'), false);
});
+26 -7
View File
@@ -60,7 +60,11 @@ let instances = 0;
* the card be clicked).
* @param {(viewer: object) => {onClick: Function}} [options.input] The
* viewer's click dispatcher.
* @param {{resolvePickId: Function, isOwnedByOtherLayer: Function}} [options.picking]
* @param {{resolvePickId: Function, isOwnedByOtherLayer: Function,
* isActedOnByOtherLayer?: Function, registerCardBackground?: Function,
* unregisterCardBackground?: Function}} [options.picking] The pick
* registry; with the card-background pair, a card painted over a disc
* (a CCTV card) may act on the click.
* @param {{registerEntityContext: Function, selectEntityContext: Function,
* clearSelectedEntityContextForLayer: Function,
* getContextStore: Function}} [options.context] Shared selection store.
@@ -319,6 +323,14 @@ export function createEarthquakesLayer({
clicks = null;
}
if (!clicks) return;
// Our discs stand aside for another layer's card painted over them
// (below), so that card's layer may act on the click; without a
// hit-test they cannot.
if (overlayHost?.hitTest)
picking.registerCardBackground?.(
EARTHQUAKES_LAYER_ID,
(hit) => pickedEvent(hit) !== null,
);
_clickHandler = clicks.onClick((click) => {
if (!_enabled || (pointer && !pointer.isPointerFree())) return;
const at = click.screenPosition;
@@ -331,14 +343,16 @@ export function createEarthquakesLayer({
topEntry.sourceId !== EARTHQUAKE_OVERLAY_SOURCE_ID
)
return;
// Another layer's pick (an aircraft, a camera) is not this layer's,
// even under this layer's card or a magnitude label: that layer acts
// on the click itself, and this card stays. Checked before the card
// and the labels, as the fire layer does.
// Another layer's pick that it acts on (an aircraft, a camera) is not
// this layer's, even under this layer's card or a magnitude label:
// that layer takes the click, and this card stays. A passive owner's
// pick (a flight trail, a directions route) acts for nobody, so the
// card or label over it keeps the click.
const hit = click.hit;
const pickId = picking.resolvePickId(hit);
if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
return;
const actedOn =
picking.isActedOnByOtherLayer ?? picking.isOwnedByOtherLayer;
if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId)) return;
const cardHit = overlayHost.hitTest?.(at?.x, at?.y, {
sourceId: EARTHQUAKE_CARD_SOURCE_ID,
});
@@ -355,6 +369,10 @@ export function createEarthquakesLayer({
selectAndFocus(labelHit.entryId);
return;
}
// A passive owner's pick with nothing of ours over it is still not
// empty space: leave the selection alone, as every layer does.
if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
return;
const event = pickedEvent(hit);
if (event) {
_selectedId = event.stableId;
@@ -383,6 +401,7 @@ export function createEarthquakesLayer({
function removeClickHandler() {
_clickHandler?.();
_clickHandler = null;
picking?.unregisterCardBackground?.(EARTHQUAKES_LAYER_ID);
}
const layer = {
+54 -1
View File
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import * as picking from '../../data/pickRegistry.js';
// Registers the shared `gev-trail:` owner as passive, as the app does.
import '../../data/trailRenderer.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { createDroneAirspaceLayer } from '../droneAirspace/index.js';
import {
@@ -250,12 +252,17 @@ test('a refresh keeps the selected quake while it is in the feed', async () => {
h.layer.destroy();
});
test('disable removes the click handler and the card', async () => {
test('disable removes the click handler, card background and the card', async () => {
const h = harness([quake('ak1')]);
h.layer.enable(h.viewer);
await h.layer.update(h.viewer);
h.clickDisc('ak1');
// A drawn disc is background to a card painted over it (a CCTV card).
const disc = { set: h.discs().spec.id, id: 'earthquake:ak1' };
assert.equal(picking.isCardBackground(disc), true);
assert.equal(picking.isCardBackground({ ...disc, set: 'other:1' }), false);
h.layer.disable(h.viewer);
assert.equal(picking.isCardBackground(disc), false);
assert.deepEqual(h.lastCard(), []);
assert.equal(
h.handlers.every((handler) => handler.destroyed),
@@ -878,3 +885,49 @@ test('quake card and label work over pickable items no layer acts on', async ()
h.layer.destroy();
}
});
// Flight trails and a directions route line are registered owners that act
// on no click. Under the quake card or a magnitude label they must not make
// the click dead; a layer that acts (an aircraft) still takes it.
test('quake card and label act over a flight trail and a directions route', async () => {
const h = harness([quake('ak1'), quake('ak2', { mag: 4 })]);
picking.registerPickOwner(
'test-directions',
(id) => String(id).startsWith('directions:'),
{ passive: (id) => !id.startsWith('directions:step:') },
);
picking.registerPickOwner('test-plane', (id) => id === 'plane-9');
try {
h.layer.enable(h.viewer);
await h.layer.update(h.viewer);
h.clickDisc('ak1');
const trail = { set: 'trail:1:lines', id: 'gev-trail:fl-a1b2c3:head' };
const route = { set: 'directions:1:route', id: 'directions:route' };
assert.equal(picking.findPickOwner(trail.id), 'trails');
h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', trail);
h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', route);
assert.equal(h.opened.length, 2, 'the card opens USGS over both');
h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', trail);
assert.equal(h.focused.at(-1)?.id, 'earthquake:ak2', 'the label flies');
// A route step acts for directions: it takes the click.
const focusedBefore = h.focused.length;
h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak1', {
set: 'directions:1:steps',
id: 'directions:step:2',
});
assert.equal(h.focused.length, focusedBefore, 'a step takes the click');
// So does an aircraft under the card.
h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak2', {
set: 'flights:1',
id: 'plane-9',
});
assert.equal(h.opened.length, 2);
// A plain click on a trail is still not empty space: the card stays.
h.click(trail);
assert.equal(h.lastCard()[0].id, 'earthquake-card:ak2');
} finally {
picking.unregisterPickOwner('test-directions');
picking.unregisterPickOwner('test-plane');
h.layer.destroy();
}
});
+77
View File
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createLifecycle } from './lifecycle.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
/** Any part method is a no-op unless the test supplies it. */
const stubs = (given = {}) =>
new Proxy(given, {
get: (target, key) => (key in target ? target[key] : () => undefined),
});
// Mission overlays are not interactive: an overlay entry under the pointer is
// another layer's card or label painted over the mission (a quake label), and
// that layer takes the click, so the mission is not also selected.
test('a card painted over a launch marker keeps its click; with none the mission selects', () => {
const viewer = {
scene: {
pick: () => null,
canvas: { clientWidth: 100, clientHeight: 100 },
},
};
const input = fakeInput(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
const selected = [];
const state = { _launches: [{ id: 'L1' }], _enabled: false };
const { methods: lifecycle } = createLifecycle({
state,
services: {
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
overlays: { hitTestWorldOverlay: () => top },
picking,
},
parts: {
panel: stubs(),
overlays: stubs(),
launchPad: stubs(),
orbitRendering: stubs(),
replay: stubs(),
ingestion: stubs(),
rendering: stubs({
missionsShown: () => true,
missionHitsAt: () => [{ id: 'mission:L1' }],
launchIdFromPicks: (hits) =>
hits.some((hit) => hit?.id === 'mission:L1') ? 'L1' : null,
}),
selection: stubs({ setSelectedMission: (id) => selected.push(id) }),
},
source: {},
});
try {
// init installs the click handler; enable would start a feed load.
lifecycle.init(viewer);
state._enabled = true;
input.click();
assert.deepEqual(selected, [], 'the mission stands aside');
top = null;
input.click();
assert.deepEqual(
selected,
['L1'],
'with no card on top, the mission selects',
);
// So a card on top (a live CCTV card) may act over the mission instead.
const mission = { set: 'launches:1:markers', id: 'mission:L1' };
assert.equal(picking.isCardBackground(mission), true);
assert.equal(picking.isCardBackground({ ...mission, id: 'x' }), false);
state._enabled = false;
assert.equal(picking.isCardBackground(mission), false);
state._inputSubscription();
state._enabled = true;
assert.equal(picking.isCardBackground(mission), false);
} finally {
state._inputSubscription?.();
input.destroy();
}
});
+24
View File
@@ -4,6 +4,8 @@ import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
const HOVER_PICK_INTERVAL_MS = 120;
/** Our id in the pick registry's card backgrounds. */
const CARD_BACKGROUND_ID = 'rocket-launches';
/**
* Bound hover picking independently of precise click selection. A move inside
@@ -200,8 +202,29 @@ export function createLifecycle({
layerState._orbitMatches = 0;
parts.overlays.clearMissionOverlaySources();
const input = inputFor(viewer);
// Our mission items stand aside for a card painted over them (below),
// so that card's layer may act on the click; without a hit-test they
// cannot.
if (services.overlays?.hitTestWorldOverlay)
services.picking?.registerCardBackground?.(
CARD_BACKGROUND_ID,
(hit) =>
layerState._enabled &&
parts.rendering.missionsShown() &&
parts.rendering.launchIdFromPicks([hit]) !== null,
);
const unsubscribeClick = input.onClick((event) => {
if (!layerState._enabled || !parts.rendering.missionsShown()) return;
// Mission overlays are not interactive, so any overlay entry hit
// here is another layer's card or label painted over the click: that
// layer's click, not a mission's.
if (
services.overlays?.hitTestWorldOverlay?.(
event.screenPosition?.x,
event.screenPosition?.y,
)
)
return;
// The click's pick position (CSS px), as the click picked it.
const launchId = parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
@@ -221,6 +244,7 @@ export function createLifecycle({
layerState._inputSubscription = () => {
unsubscribeClick();
unsubscribeHover();
services.picking?.unregisterCardBackground?.(CARD_BACKGROUND_ID);
};
// Apply horizon visibility before the renderer draws and picks.
// A postRender write is one frame late and can remain visibly stale when
+11 -10
View File
@@ -215,14 +215,23 @@ export function createFirePerimetersLayer({
// so claiming these large ground polygons would make FIRMS/vessel/CCTV
// cards inert anywhere over a perimeter. Unowned, our picks read as
// "empty space" to siblings — the pre-existing behavior for the globe.
// Our shapes stand aside for a card painted over them (below), so that
// card's layer may act on the click; without a hit-test they cannot.
if (overlayHost?.hitTest)
picking?.registerCardBackground?.(
layer.id,
(hit) => pickedIncidentId(hit) !== null,
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
// A click on the incident card itself opens its InciWeb page (when the
// incident has one) and never disturbs the selection.
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: PERIMETER_OVERLAY_SOURCE_ID },
);
// Only the top painted card owns the click; this area's shapes are
// background when another layer has painted a card or label over them.
if (cardHit && cardHit.sourceId !== PERIMETER_OVERLAY_SOURCE_ID) return;
if (cardHit && cardHit.entryId === _selectedCardId) {
if (_selectedLink && openExternal) openExternal(_selectedLink);
return;
@@ -230,15 +239,6 @@ export function createFirePerimetersLayer({
const picked = event.topHit;
const incidentId = picked ? pickedIncidentId(event.drawHit) : null;
if (incidentId) {
// Another layer's card or label painted over the perimeter (a
// quake's card or magnitude label, a fire card) is that layer's
// click: under it the perimeter is background, so it stays as is.
const top = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{},
);
if (top && top.sourceId !== PERIMETER_OVERLAY_SOURCE_ID) return;
abortLinkVerification();
_selectedId = incidentId;
publishSelectedCard();
@@ -261,6 +261,7 @@ export function createFirePerimetersLayer({
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
picking?.unregisterCardBackground?.(layer.id);
}
function clearSelection() {
+37 -4
View File
@@ -27,6 +27,7 @@ function harness(
) {
const overlay = { entries: new Map(), visible: null };
const owners = new Map();
const backgrounds = new Map();
const opened = [];
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
@@ -58,6 +59,9 @@ function harness(
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
registerCardBackground: (layerId, predicate) =>
backgrounds.set(layerId, predicate),
unregisterCardBackground: (layerId) => backgrounds.delete(layerId),
},
inciwebSource: inciwebIndex
? { getIndex: async () => inciwebIndex }
@@ -77,6 +81,7 @@ function harness(
overlay,
clicks,
owners,
backgrounds,
opened,
};
}
@@ -316,12 +321,16 @@ test('a matched incident card carries the InciWeb line and click-through', async
},
];
let cardHitResult = null;
let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => [{ ...row, name: 'Fixture' }] },
{
pick: () => null,
inciwebIndex,
cardHit: () => cardHitResult,
cardHit: (_x, _y, options) =>
foreignOnTop && !options?.sourceId
? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }
: cardHitResult,
},
);
await h.layer.update(h.viewer);
@@ -336,9 +345,15 @@ test('a matched incident card carries the InciWeb line and click-through', async
const entries = h.overlay.entries.get('fire-perimeters');
assert.equal(entries[0].details.at(-1), 'InciWeb ↗ · click card to open');
// Clicking the card itself opens the InciWeb page.
cardHitResult = { entryId: entries[0].id };
// A selected card covered by a quake card cannot open its hidden link.
cardHitResult = { sourceId: 'fire-perimeters', entryId: entries[0].id };
h.viewer.scene.pick = () => null;
foreignOnTop = true;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, []);
assert.equal(h.overlay.entries.get('fire-perimeters')[0].id, entries[0].id);
// Removing the foreground card makes the incident card actionable again.
foreignOnTop = false;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']);
assert.equal(
@@ -365,7 +380,7 @@ test('an unmatched incident renders no InciWeb line and card clicks stay inert',
entries[0].details.some((line) => line.includes('InciWeb')),
false,
);
cardHitResult = { entryId: entries[0].id };
cardHitResult = { sourceId: 'fire-perimeters', entryId: entries[0].id };
h.viewer.scene.pick = () => null;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, []);
@@ -679,3 +694,21 @@ test('a failed refresh after a stale snapshot reads as the failure, not stale',
assert.equal(h.layer.getStats().stale, false);
assert.equal(h.layer.getStats().error, 'WFIGS HTTP 502');
});
// A card painted over the area may act there (a live CCTV card): the layer
// names its own drawn shapes, and only while it takes clicks.
test('enabled, the perimeter shapes register as card background', async () => {
const h = harness({ getSnapshot: async () => [row] });
await h.layer.update(h.viewer);
const isBackground = h.backgrounds.get('fire-perimeters');
const own = {
set: h.fills().spec.id,
id: 'fire-perimeter:2026-NMGNF-000123:0',
surface: false,
};
assert.equal(isBackground(own), true);
assert.equal(isBackground({ ...own, set: 'other:1:fills' }), false);
assert.equal(isBackground({ ...own, id: 'other-layer:x' }), false);
h.layer.disable(h.viewer);
assert.equal(h.backgrounds.has('fire-perimeters'), false);
});
+3
View File
@@ -8,6 +8,7 @@ import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
export function createSubmarineCableLayer({
source,
overlayHost,
picking = null,
inputFor = defaultInputFor,
mapStackEventTarget = null,
sweepClock = defaultSweepClock,
@@ -23,6 +24,8 @@ export function createSubmarineCableLayer({
parts,
source,
inputFor,
overlayHost,
picking,
mapStackEventTarget,
};
parts.rendering = createRendering(context);
+27 -2
View File
@@ -1,15 +1,40 @@
import { toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createInteraction({ state, parts, inputFor }) {
const CARD_BACKGROUND_ID = 'submarine-cables';
export function createInteraction({
state,
parts,
inputFor,
overlayHost,
picking,
}) {
function beginInteraction(viewer) {
if (state._clickSubscription) return;
state._clickSubscription = inputFor(viewer).onClick((event) => {
// Our cables stand aside for a card painted over them (below), so that
// card's layer may act on the click; without a hit-test they cannot.
if (overlayHost?.hitTest)
picking?.registerCardBackground?.(
CARD_BACKGROUND_ID,
(hit) => state._enabled && Boolean(resolvePickRecord(hit)?.reference),
);
const unsubscribe = inputFor(viewer).onClick((event) => {
if (!state._enabled) return;
// Cable labels are not interactive, so any overlay entry hit here is
// another layer's card or label painted over the cable: its click.
if (
overlayHost?.hitTest?.(event.screenPosition?.x, event.screenPosition?.y)
)
return;
const record = resolvePickRecord(event.drawHit);
if (!record?.reference) return;
flyToReference(viewer, record.reference);
});
state._clickSubscription = () => {
unsubscribe();
picking?.unregisterCardBackground?.(CARD_BACKGROUND_ID);
};
}
/**
@@ -0,0 +1,89 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createInteraction } from './interaction.js';
import * as picking from '../../data/pickRegistry.js';
/** The cable click handler, with its click and overlay seams faked. */
function harness({ overlayTop = null } = {}) {
let onClick = null;
const picked = [];
let top = overlayTop;
const interaction = createInteraction({
state: { _enabled: true, _clickSubscription: null },
parts: {
rendering: {
pickInfo: (hit) => {
picked.push(hit);
return null;
},
},
},
inputFor: () => ({
onClick: (fn) => {
onClick = fn;
return () => (onClick = null);
},
}),
overlayHost: { hitTest: () => top },
});
interaction.beginInteraction({});
return {
picked,
setTop: (next) => {
top = next;
},
click: () =>
onClick({
screenPosition: { x: 5, y: 5 },
drawHit: { set: 'c', id: 'x' },
}),
};
}
// Cable labels are not interactive: an overlay entry under the pointer is
// another layer's card or label painted over the cable (a quake card), and
// that layer takes the click, so the cable does not also fly the camera.
test('a card painted over a cable keeps its click; with none the cable reads the pick', () => {
const h = harness({
overlayTop: { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' },
});
h.click();
assert.equal(h.picked.length, 0, 'the cable stands aside');
h.setTop(null);
h.click();
assert.equal(
h.picked.length,
1,
'with no card on top, the cable reads its pick',
);
});
// So a card on top (a live CCTV card) may act over the cable instead.
test('while it takes clicks, a drawn cable registers as card background', () => {
const state = { _enabled: true, _clickSubscription: null };
const interaction = createInteraction({
state,
parts: {
rendering: {
pickInfo: (hit) =>
hit?.set === 'cables:1' ? { reference: { lon: 1, lat: 2 } } : null,
},
},
inputFor: () => ({ onClick: () => () => {} }),
overlayHost: { hitTest: () => null },
picking,
});
interaction.beginInteraction({});
const cable = { set: 'cables:1', id: 'cable:0' };
try {
assert.equal(picking.isCardBackground(cable), true);
assert.equal(picking.isCardBackground({ set: 'other:1', id: 'x' }), false);
state._enabled = false;
assert.equal(picking.isCardBackground(cable), false);
state._enabled = true;
state._clickSubscription();
assert.equal(picking.isCardBackground(cable), false);
} finally {
state._clickSubscription?.();
}
});