fix(click): the card or label on top takes the click in every layer

Review fixes for #1781:

- One rule for cards: the world-overlay host hands its hit test to the
  pick registry, and every click handler reads the topmost interactive
  card or label once per click (`clickCard`, `isUnderOtherCard` in
  src/data/pickRegistry.js), so all handlers agree in any listener order.
  A layer whose own card or label is on top acts on it whatever is drawn
  under it; a layer under another layer's card neither acts nor treats
  the click as empty space (a tracked aircraft stays tracked, a selection
  stays selected); Context names nothing under a card. A selected news
  card over a vessel no longer opens the link and selects the vessel.
- With one rule, the per-owner arbitration options are no longer read
  and are removed: `passive`, `expanded` and `declinesClick` pick owners,
  `rememberClickPickActions`, `isActedOnByOtherLayer`, card backgrounds
  and `cardKeepsClick`. The dispatcher is unchanged from main.
- A drag that ends on a quake disc, label or card does nothing; opening
  the USGS page or clearing the selection needs a clean click.
- A click on the map under another layer's card opens no Street Level
  ground image.
- A CCTV card that is going away is still not the scene under it.
- Docs and changelog describe the new rule.
This commit is contained in:
Sameh Khamis committed 2026-11-18 18:23:41 -08:00
1 parent 7312280817
commit bb3bf9858b
87 files changed
+1398 -1775

No files matched your search

+64 -59
View File
@@ -32,7 +32,12 @@ import aisLiveVesselsLayer from './aisLiveVessels.js';
import { registerEntityContext, selectEntityContext } from './contextStore.js';
import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js';
import { ensureGeoidReady, geoidHeight } from './geoid.js';
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
import {
isUnderOtherCard,
registerPickOwner,
setClickCardHitTest,
unregisterPickOwner,
} from './pickRegistry.js';
import { applyVesselOverlayPolicy } from './vesselLabels.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { layerFeedState } from './manager.js';
@@ -490,7 +495,7 @@ test('first accepted position ends grace and warm data survives later open silen
const clock = makeFakeAisRuntime(7000);
const record = makeRecord();
_setAisRuntimeForTest(clock.runtime);
_setVesselOverlayHostForTest({
useVesselHost({
setEntries() {},
setVisible() {},
clearSource() {},
@@ -540,7 +545,7 @@ test('first accepted position ends grace and warm data survives later open silen
assert.equal(feed.error, 'awaiting usable AIS positions…');
} finally {
_setVesselStateForTest({ enabled: false });
_setVesselOverlayHostForTest();
useVesselHost();
_setAisRuntimeForTest();
}
});
@@ -1643,7 +1648,7 @@ test('vessel host publication preserves the shipped grid winner and separation s
},
},
});
_setVesselOverlayHostForTest({
useVesselHost({
setEntries(sourceId, entries, options) {
publications.push({ sourceId, entries, options });
},
@@ -1667,7 +1672,7 @@ test('vessel host publication preserves the shipped grid winner and separation s
} finally {
unbind();
_setVesselStateForTest({ enabled: false });
_setVesselOverlayHostForTest();
useVesselHost();
}
});
@@ -1694,7 +1699,7 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
globalThis.window.addEventListener('gev:world-request-focus', (event) => {
focusRequests.push(event.detail);
});
_setVesselOverlayHostForTest(host);
useVesselHost(host);
_setVesselStateForTest({
viewer: {
get canvas() {
@@ -1743,7 +1748,7 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
);
} finally {
_setVesselStateForTest({ enabled: false });
_setVesselOverlayHostForTest();
useVesselHost();
if (hadWindow) globalThis.window = priorWindow;
else delete globalThis.window;
globalThis.document = priorDocument;
@@ -1849,6 +1854,15 @@ test('vessel interaction wire: a vessel with an id and no MMSI is selected by cl
}
});
/**
* Hand the vessel layer an overlay host, and answer the pick registry's
* card-on-top question from the same host, as the application does.
*/
function useVesselHost(host) {
_setVesselOverlayHostForTest(host);
setClickCardHitTest(host ? (x, y) => host.hitTest(x, y) : null);
}
/**
* Overlay-host recorder whose hitTest answers with one card id. The real host
* only publishes rects for `interactive` entries, so a stub returning a hit is
@@ -1880,9 +1894,7 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
hostWithCardHit(`vessel:${harness.record.mmsi}`),
);
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -1893,7 +1905,7 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s
assert.equal(requests[0].kind, 'vessel');
assert.equal(requests[0].id, harness.record.mmsi);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
});
@@ -1908,9 +1920,7 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
hostWithCardHit(`vessel:${harness.record.mmsi}`),
);
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -1921,29 +1931,31 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact
assert.equal(requests[0].id, harness.record.mmsi);
assert.equal(harness.trail.clearCalls, 0);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
});
test('vessel interaction wire: a covered card yields while a real vessel pick still focuses', () => {
// Another layer's card on top takes the click from the vessel card under it
// and from a vessel icon under it alike.
test('vessel interaction wire: a covered card and a covered vessel pick both yield', () => {
for (const ownPick of [false, true]) {
const harness = installWireHarness(ownPick ? { id: makeRecord().mmsi } : null);
const requests = [];
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
useVesselHost(
hostWithCardHit(`vessel:${harness.record.mmsi}`, {
sourceId: 'earthquakes', entryId: 'quake:cover',
}),
);
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(requests.length, ownPick ? 1 : 0);
assert.equal(requests.length, 0, `own pick: ${ownPick}`);
assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
}
@@ -1960,7 +1972,7 @@ test('vessel interaction wire: an unknown card id preserves selection and never
requests.push(event.detail),
);
// An evicted vessel's card id resolves to no live record.
_setVesselOverlayHostForTest(hostWithCardHit('vessel:999999999'));
useVesselHost(hostWithCardHit('vessel:999999999'));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -1969,52 +1981,47 @@ test('vessel interaction wire: an unknown card id preserves selection and never
);
assert.equal(requests.length, 0);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
});
test('vessel interaction wire: a sibling-owned pick wins without selection mutation', () => {
// Another layer is already acting on this click; two camera commands is the
// worse failure, so the card is not consulted.
test('vessel interaction wire: the vessel card on top wins over a sibling-owned pick', () => {
// The card painted on top takes the click; the sibling (an aircraft)
// stands aside under it, so there is one camera command, not two.
registerPickOwner('flights', (pickedId) => pickedId === 'a1b2c3');
const harness = installWireHarness({ id: 'a1b2c3' });
const requests = [];
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
hostWithCardHit(`vessel:${harness.record.mmsi}`),
);
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
harness.record.mmsi,
);
assert.equal(requests.length, 0);
assert.equal(requests.length, 1);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
unregisterPickOwner('flights');
}
});
// The aircraft layer runs first and starts tracking the plane under the
// vessel's card, making it passive. The card reads the owners that acted
// when the click resolved, so it still yields: one action.
test('vessel interaction wire: a card yields to an aircraft that starts tracking in the same click', (t) => {
// The aircraft layer runs first. Under the vessel's card it stands aside, so
// the card takes the click: one action.
test('vessel interaction wire: a card over an aircraft takes the click; the aircraft does not track', (t) => {
let tracked = null;
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9', {
expanded: true,
passive: (pickedId) => pickedId === tracked,
});
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9');
t.after(() => unregisterPickOwner('test-planes'));
const harness = installWireHarness(
{ id: 'plane:9' },
{ selectedRecord: null },
{},
(event) => {
if (isUnderOtherCard(event)) return;
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
},
);
@@ -2022,16 +2029,17 @@ test('vessel interaction wire: a card yields to an aircraft that starts tracking
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
hostWithCardHit(`vessel:${harness.record.mmsi}`),
);
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(tracked, 'plane:9', 'the aircraft starts tracking');
assert.equal(requests.length, 0, 'the vessel card yields');
assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi ?? null, null);
assert.equal(tracked, null, 'the aircraft does not track');
assert.equal(requests.length, 1, 'the vessel card acts');
assert.equal(
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
harness.record.mmsi,
);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
});
@@ -2048,7 +2056,7 @@ test('vessel interaction wire: a card over a trail selects; a bare trail is a no
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
useVesselHost(
hostWithCardHit(carded ? `vessel:${harness.record.mmsi}` : null),
);
try {
@@ -2059,16 +2067,15 @@ test('vessel interaction wire: a card over a trail selects; a bare trail is a no
carded ? harness.record.mmsi : null,
);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
}
});
// A coarse tap on the vessel's card finds a fire nearby through the shared
// touch contact. The fire layer acts only on exact hits, so the card keeps the
// tap; an exact fire pick under the card still belongs to the fire.
test('vessel interaction wire: a coarse near miss of an exact-only item keeps the card tap', (t) => {
// A coarse tap on the vessel's card over a fire, nearby or exact: the card on
// top keeps the tap.
test('vessel interaction wire: the card keeps a tap over a nearby or exact fire', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
@@ -2088,18 +2095,16 @@ test('vessel interaction wire: a coarse near miss of an exact-only item keeps th
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
_setVesselOverlayHostForTest(
hostWithCardHit(`vessel:${harness.record.mmsi}`),
);
useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(requests.length, exact ? 0 : 1, `exact fire: ${exact}`);
assert.equal(requests.length, 1, `exact fire: ${exact}`);
assert.equal(
aisLiveVesselsLayer.getSelectedInfo()?.mmsi ?? null,
exact ? null : harness.record.mmsi,
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
harness.record.mmsi,
);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
}
}
@@ -2130,7 +2135,7 @@ for (const card of ['live', 'stale', 'absent', 'covered']) {
);
return { sourceId: 'cctv', entryId: 'vessel:999999999' };
};
_setVesselOverlayHostForTest(host);
useVesselHost(host);
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -2139,7 +2144,7 @@ for (const card of ['live', 'stale', 'absent', 'covered']) {
);
assert.equal(requests.length, card === 'live' ? 1 : 0);
} finally {
_setVesselOverlayHostForTest(null);
useVesselHost(null);
harness.cleanup();
unregisterPickOwner('weather-cyclones');
}
+6 -5
View File
@@ -2959,11 +2959,12 @@ export function createBhoteKoshiEventLayer({
: Number.isFinite(clientY) && bounds
? clientY - bounds.top
: Number.NaN;
const hit = overlayHost.hitTest?.(x, y, {
sourceId: BHOTE_KOSHI_OVERLAY_SOURCE_ID,
filter: (entry) => String(entry?.id || '').startsWith('evidence-card-'),
});
if (typeof hit?.entry?.activate !== 'function') return;
// Only the card painted on top acts: an evidence card covered by
// another layer's card or label leaves the click to that card.
const hit = overlayHost.hitTest?.(x, y);
if (hit?.sourceId !== BHOTE_KOSHI_OVERLAY_SOURCE_ID) return;
if (!String(hit.entry?.id || '').startsWith('evidence-card-')) return;
if (typeof hit.entry.activate !== 'function') return;
hit.entry.activate();
}
+9 -1
View File
@@ -2114,6 +2114,7 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
};
const viewer = eventViewer();
let activeCard = null;
let coveredBy = null;
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
@@ -2131,9 +2132,11 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
},
setVisible() {},
clearSource() {},
// As the host does: unfiltered, the topmost entry.
hitTest(_x, _y, options) {
if (coveredBy && !options?.sourceId) return coveredBy;
if (!activeCard || options?.filter?.(activeCard) === false) return null;
return { entry: activeCard };
return { sourceId: 'bhote-koshi-witnesses', entry: activeCard };
},
},
renderHost: { request() {}, hold() {}, release() {} },
@@ -2160,6 +2163,11 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
} finally {
releasePointer(lease);
}
// Another layer's card painted over the evidence card takes the click.
coveredBy = { sourceId: 'earthquake-card', entryId: 'earthquake-card:q' };
viewer._test.canvas.dispatch('click', { offsetX: 640, offsetY: 420 });
assert.equal(opened.length, 0, 'a covered evidence card does not open');
coveredBy = null;
viewer._test.canvas.dispatch('click', { offsetX: 640, offsetY: 420 });
assert.deepEqual(opened, [[
event.evidenceSpine[1].media.sourceUrl,
+5 -25
View File
@@ -1,10 +1,9 @@
import {
clearOverlaySource,
hitTestWorldOverlay,
setOverlayEntries,
} from '../overlays/worldOverlay.js';
import { inputFor } from '../input/dispatcher.js';
import { isActedOnByOtherLayer, resolvePickId } from './pickRegistry.js';
import { clickCard } from './pickRegistry.js';
import { isTrackingSelectionGesture } from './trackingClickGesture.js';
import { governorRequestRender } from '../renderGovernor.js';
import { drawOf, findCamera } from '../render/rendererOf.js';
@@ -284,7 +283,6 @@ export function createBhoteKoshiLocatorLayer({
scheduleDelay = (callback, delayMs) => setTimeout(callback, delayMs),
cancelDelay = (handle) => clearTimeout(handle),
input = inputFor,
hitTest = hitTestWorldOverlay,
} = {}) {
let _viewer = null;
// The globe click that opens an actionable callout of ours on top.
@@ -1153,9 +1151,8 @@ export function createBhoteKoshiLocatorLayer({
/**
* An actionable callout of ours (the trigger record's) is a card painted
* over the globe: a click on it opens its source, as its keyboard action
* does. Like the other cards, it leaves a drag alone and yields to a layer
* that acts on what is under it (an aircraft, a vessel): its exact pick, or
* a coarse tap's touch contact whose layer acts on nearby contacts.
* does. Like the other cards, it leaves a drag alone and, on top, takes the
* click over whatever is drawn under it.
*/
function installCalloutClick(viewer) {
if (_removeClick) return;
@@ -1168,26 +1165,9 @@ export function createBhoteKoshiLocatorLayer({
_removeClick =
clicks?.onClick?.((event) => {
if (!_enabled || !isTrackingSelectionGesture(event.gesture)) return;
const top = hitTest?.(event.screenPosition?.x, event.screenPosition?.y);
// The card painted on top, read once per click so every layer agrees.
const top = clickCard(event);
if (top?.sourceId !== BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID) return;
const exactId = resolvePickId(event.topHit ?? null);
if (
exactId &&
isActedOnByOtherLayer(BHOTE_KOSHI_LOCATOR_LAYER_ID, exactId, {
click: event,
})
)
return;
const contactId = resolvePickId(event.hit ?? null);
if (
contactId &&
contactId !== exactId &&
isActedOnByOtherLayer(BHOTE_KOSHI_LOCATOR_LAYER_ID, contactId, {
expanded: true,
click: event,
})
)
return;
if (typeof top.entry?.activate === 'function') top.entry.activate();
}) ?? null;
}
+14 -24
View File
@@ -11,7 +11,11 @@ import {
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
import * as Cesium from 'cesium';
import { setLocale } from '../i18n/index.js';
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
import {
registerPickOwner,
setClickCardHitTest,
unregisterPickOwner,
} from './pickRegistry.js';
import { SceneDirector } from '../scenes/director.js';
import { createPlaybackClock } from '../director/clock.js';
import { createDefaultScenePacks } from '../scenes/packs/defaults.js';
@@ -1071,8 +1075,9 @@ test('a click on the locator callout runs its action', async () => {
};
},
}),
hitTest: () => top,
});
// The card on top at a click, as the host answers the pick registry.
setClickCardHitTest(() => top);
await layer.init(viewer);
await layer.enable(viewer);
const click = (extra = {}) =>
@@ -1103,34 +1108,19 @@ test('a click on the locator callout runs its action', async () => {
};
click({ gesture: { travelPx: 30, durationMs: 80 } });
assert.deepEqual(activated, ['trigger'], 'a drag does not open it');
// An aircraft under it is that layer's click, exact or a touch contact.
registerPickOwner('test-planes', (id) => id === 'plane:1', {
expanded: true,
});
// On top, it takes the click over an aircraft or a camera under it, exact
// or a touch contact: those layers stand aside under a card.
registerPickOwner('test-planes', (id) => id === 'plane:1');
try {
const plane = { set: 'planes:1', id: 'plane:1' };
const cam = { set: 'cams:1', id: 'cam:1' };
click({ topHit: plane, hit: plane });
click({ topHit: null, hit: plane });
assert.deepEqual(activated, ['trigger'], 'the aircraft takes it');
click({ topHit: cam, hit: cam });
assert.equal(activated.length, 4, 'the callout on top acts each time');
} finally {
unregisterPickOwner('test-planes');
}
// A layer that acts only on exact hits does not take a touch contact, and
// one that ignores this click (a long press on a camera) takes nothing: the
// callout keeps both.
registerPickOwner('test-cameras', (id) => id === 'cam:1', {
declinesClick: (event) => (event?.gesture?.durationMs ?? 0) > 400,
});
try {
const cam = { set: 'cams:1', id: 'cam:1' };
click({ topHit: null, hit: cam });
assert.equal(activated.length, 2, 'a near miss of an exact-only camera');
click({ topHit: cam, hit: cam, gesture: { travelPx: 0, durationMs: 900 } });
assert.equal(activated.length, 3, 'a long press the camera ignores');
click({ topHit: cam, hit: cam });
assert.equal(activated.length, 3, 'a clean click on the camera is its own');
} finally {
unregisterPickOwner('test-cameras');
setClickCardHitTest(null);
}
await layer.disable();
assert.equal(onClick, null, 'disable removes the click handler');
+2 -2
View File
@@ -1020,7 +1020,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
);
assert.match(
componentFunctionSource(cctvLayer.init),
/_cctvOverlayHost\.hitTest/,
/clickCard\?\.\(event\)/,
);
assert.match(
componentFunctionSource(cctvLayer.init),
@@ -1028,7 +1028,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
);
assert.match(
componentFunctionSource(cctvLayer.init),
/activateCctvCameraFromWorldClick\(cardId, setActiveCamera\)/,
/activateCctvCameraFromWorldClick\(\s*top\.entryId,/,
);
});
+37 -17
View File
@@ -28,7 +28,7 @@ import {
createApplicationDirectionsLayer,
} from './directions.js';
import { GROUND_FLOOR_LIFT_M } from './groundFloor.js';
import { isActedOnByOtherLayer, isOwnedByOtherLayer } from './pickRegistry.js';
import { isOwnedByOtherLayer, setClickCardHitTest } from './pickRegistry.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { instructionFor } from './routeSteps.js';
import { setLocale } from '../i18n/index.js';
@@ -467,10 +467,9 @@ 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) => {
// Directions owns its route, markers and steps while enabled: none of them
// is empty space to other layers.
test('enabled, directions owns its picks', (t) => {
ownershipFixture(t);
const viewer = {
scene: {
@@ -488,24 +487,45 @@ test('enabled, directions owns its picks and acts only on its steps', (t) => {
'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);
});
// The card or label painted on top takes the click: directions does not even
// pick under another layer's card, so no step is selected or cleared there.
test("another layer's card over directions keeps the click", (t) => {
ownershipFixture(t);
let picks = 0;
const viewer = {
scene: {
pick: () => {
picks++;
return null;
},
canvas: { clientWidth: 100, clientHeight: 100 },
},
};
const input = fakeInput(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => {
setClickCardHitTest(null);
input.destroy();
});
directionsLayer.enable(viewer);
try {
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
} finally {
directionsLayer.disable(viewer);
}
});
test('placing an endpoint takes the pointer, and every exit path gives it back', (t) => {
ownershipFixture(t);
+45 -46
View File
@@ -11,7 +11,12 @@ import {
buildCellCard,
} from './firmsHeatmap.js';
import { fireDetectionKey } from './firmsLabels.js';
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
import {
isUnderOtherCard,
registerPickOwner,
setClickCardHitTest,
unregisterPickOwner,
} from './pickRegistry.js';
import { getSelectedEntityContext } from './contextStore.js';
import { setLocale } from '../i18n/index.js';
import { shownEntityLabel } from '../voice/speech.js';
@@ -80,21 +85,24 @@ function harness({
};
const published = [];
const overlayHost = {
setEntries: (sourceId, entries) => published.push(...entries),
setVisible() {},
clearSource() {},
hitTest: (_x, _y, { sourceId } = {}) =>
!sourceId && topCard
? topCard
: cardHit
? { sourceId: 'firms', entryId: cardHit }
: null,
};
// The card on top at a click, as the host answers the pick registry.
setClickCardHitTest((x, y) => overlayHost.hitTest(x, y));
const layer = createFirmsHeatmapLayer({
...(feed ? { feed } : {}),
id: 'firms-test',
name: 'Fires',
overlayHost: {
setEntries: (sourceId, entries) => published.push(...entries),
setVisible() {},
clearSource() {},
hitTest: (_x, _y, { sourceId } = {}) =>
!sourceId && topCard
? topCard
: cardHit
? { sourceId: 'firms', entryId: cardHit }
: null,
},
overlayHost,
});
const draw = fakeDrawPort();
@@ -171,6 +179,7 @@ function harness({
picked = next;
},
cleanup() {
setClickCardHitTest(null);
Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection;
if (hadWindow) globalThis.window = priorWindow;
else delete globalThis.window;
@@ -331,6 +340,10 @@ test('clicking a fire sprite selects it and requests the camera transfer', () =>
topCard: { sourceId: 'earthquakes', entryId: 'quake:cover' },
});
try {
// Under another layer's card the sprite is that card's click.
h.click();
assert.equal(h.requests.length, 0, 'covered: the card takes it');
h.cover(null);
h.click();
assert.equal(h.requests.length, 1);
assert.equal(h.requests[0].kind, 'fire');
@@ -435,9 +448,9 @@ test('a click on neither sprite nor card clears without moving the camera', () =
}
});
// Sibling layers surface heterogeneous pick shapes. Reading `picked.id`
// directly recognized only bare strings, so an AIS sprite (or satellite, or
// entity) under a fire card let BOTH layers issue a camera command.
// Sibling layers surface heterogeneous pick shapes. Whatever is drawn under
// it, the fire card painted on top takes the click (those layers stand aside
// under another layer's card, so one click does one thing).
const SIBLING_PICKS = [
['flights', 'a1b2c3', { id: 'a1b2c3' }],
['flights', 'a1b2c3', { primitive: { id: 'a1b2c3' } }],
@@ -447,7 +460,7 @@ const SIBLING_PICKS = [
];
for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
test(`a ${layerId} pick shaped ${JSON.stringify(picked)} wins over a card hit`, () => {
test(`a fire card wins over a ${layerId} pick shaped ${JSON.stringify(picked)}`, () => {
const fire = makeFire();
registerPickOwner(layerId, (pickedId) => pickedId === ownedId);
const h = harness({
@@ -457,11 +470,7 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
});
try {
h.click();
assert.equal(
h.requests.length,
0,
`the ${layerId} layer is already acting on this click`,
);
assert.equal(h.requests.length, 1, 'the card on top acts');
} finally {
h.cleanup();
unregisterPickOwner(layerId);
@@ -474,9 +483,7 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
// still not empty space, so the selection stays.
test('a fire card acts over a passive pick; the bare pick leaves the selection', () => {
const fire = makeFire();
registerPickOwner('test-route', (pickedId) => pickedId === 'route:line', {
passive: true,
});
registerPickOwner('test-route', (pickedId) => pickedId === 'route:line');
const carded = harness({
fires: [fire],
picked: { id: 'route:line' },
@@ -505,9 +512,8 @@ test('a fire card acts over a passive pick; the bare pick leaves the selection',
});
// A coarse tap on a fire card finds an aircraft nearby through the shared
// touch contact. The flights layer acts on that contact, so the card yields:
// one action, not two.
test('a fire card yields to a touch contact its layer acts on', (t) => {
// touch contact. The card on top takes it; the aircraft layer stands aside.
test('a fire card takes a tap over a touch contact its layer acts on', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
@@ -515,9 +521,7 @@ test('a fire card yields to a touch contact its layer acts on', (t) => {
else delete globalThis.matchMedia;
});
const fire = makeFire();
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1', {
expanded: true,
});
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1');
t.after(() => unregisterPickOwner('test-planes'));
const h = harness({
fires: [fire],
@@ -526,8 +530,8 @@ test('a fire card yields to a touch contact its layer acts on', (t) => {
});
try {
h.click();
assert.equal(h.requests.length, 0, 'the aircraft takes the tap');
assert.equal(h.layer.getSelectedInfo(), null);
assert.equal(h.requests.length, 1, 'the card takes the tap');
assert.ok(h.layer.getSelectedInfo());
} finally {
h.cleanup();
}
@@ -544,9 +548,7 @@ test('a fire card keeps a tap whose contact does not act; bare taps still clear'
});
const fire = makeFire();
registerPickOwner('test-cameras', (pickedId) => pickedId === 'cam:1');
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1', {
expanded: true,
});
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1');
t.after(() => {
unregisterPickOwner('test-cameras');
unregisterPickOwner('test-planes');
@@ -579,30 +581,27 @@ test('a fire card keeps a tap whose contact does not act; bare taps still clear'
}
});
// The aircraft layer runs first and starts tracking the plane it was clicked
// on, which makes that plane passive. The fire card painted over it reads
// the owners that acted when the click resolved, so it still yields.
test('a fire card yields to an aircraft that starts tracking in the same click', (t) => {
// The aircraft layer runs first. Under the fire card painted over its plane
// it stands aside, so the card takes the click: one action, in either order.
test('a fire card over an aircraft takes the click; the aircraft does not track', (t) => {
const fire = makeFire();
let tracked = null;
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9', {
expanded: true,
passive: (pickedId) => pickedId === tracked,
});
registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9');
t.after(() => unregisterPickOwner('test-planes'));
const h = harness({
fires: [fire],
picked: { id: 'plane:9' },
cardHit: `fire:${fireDetectionKey(fire)}`,
firstClick: (event) => {
if (isUnderOtherCard(event)) return;
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
},
});
try {
h.click();
assert.equal(tracked, 'plane:9', 'the aircraft starts tracking');
assert.equal(h.requests.length, 0, 'the fire card yields');
assert.equal(h.layer.getSelectedInfo(), null);
assert.equal(tracked, null, 'the aircraft does not track');
assert.equal(h.requests.length, 1, 'the fire card acts');
assert.ok(h.layer.getSelectedInfo());
} finally {
h.cleanup();
}
+4
View File
@@ -22,6 +22,7 @@ import {
import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js';
import { createGeojsonPins } from './geojsonPins.js';
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
import { isUnderOtherCard } from './pickRegistry.js';
import {
selectInfraLod,
applyInfraEvictionGrace,
@@ -1114,6 +1115,9 @@ export function createLocalGeoJsonLayer(
const input = inputFor(viewer);
_clickSubscription = input.onClick((event) => {
if (!_enabled || !_drawn) return;
// Another layer's card or label on top takes the click: the
// item under it neither acts nor reads as empty space.
if (isUnderOtherCard(event)) return;
const hit = event.drawHit;
if (!hit || !hit.set.startsWith(`${setPrefix}:`)) return;
const part = _drawn.parts.get(hit.id);
+19
View File
@@ -6,6 +6,7 @@ import {
} from './localGeojsonCore.js';
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import { getContextStore } from './contextStore.js';
import { setClickCardHitTest } from './pickRegistry.js';
import { readEntityRecord } from './entityRecords.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
const feature = (id, geometry, properties = { name: `Feature ${id}` }) => ({
@@ -161,6 +162,24 @@ test('polygons fill the ground, lines drape, points stand on pins, all shown', a
assert.equal(record?.label, 'Feature p');
});
// The card or label painted on top takes the click: a feature under another
// layer's card is not selected.
test("another layer's card over a drawn part keeps the click", async (t) => {
const env = await enabledLayer(t, [
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
]);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const fills = env.fake.set('fills');
const at = { x: 5, y: 5 };
env.click({ screenPosition: at, drawHit: { set: fills.spec.id, id: 'p' } });
assert.equal(env.fake.flights.length, 0, 'covered: not selected');
top = null;
env.click({ screenPosition: at, drawHit: { set: fills.spec.id, id: 'p' } });
assert.equal(env.fake.flights.length, 1);
});
test('a click on a drawn part selects its feature and flies above it', async (t) => {
const env = await enabledLayer(t, [
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
-180
View File
@@ -1,180 +0,0 @@
/**
* Which pick owners select nearby contacts. A coarse tap's shared contact
* hit (`pickContact`) can land on a contact near an exact miss; only owners
* whose click handlers act on such a hit, or on their own pick window,
* register `expanded`, so a quake card or label yields to them and not to
* exact-only owners (FIRMS, CCTV). Each case runs the layer's own
* registration code (its enable or install step) with stand-in services.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle as createFlightLifecycle } from '../layers/flights/lifecycle.js';
import { createLifecycle as createMilitaryLifecycle } from '../layers/military/lifecycle.js';
import { createLifecycle as createVesselLifecycle } from '../layers/vessels/lifecycle.js';
import { createInteraction as createRadioInteraction } from '../layers/radio/interaction.js';
import { createSelection as createStreetSelection } from '../layers/streetLevel/selection.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { STREET_LEVEL_LAYER_ID } from '../layers/streetLevel/policy.js';
import * as picking from './pickRegistry.js';
/**
* A stand-in for any collaborator: every property is another stand-in and
* every call returns one, except the keys `given` names. Not a thenable.
*/
function stub(given = {}) {
return new Proxy(function stand() {}, {
get(target, key) {
if (key in given) return given[key];
if (key === 'then' || typeof key === 'symbol') return undefined;
return stub();
},
set(target, key, value) {
given[key] = value;
return true;
},
apply: () => stub(),
});
}
/** Picking services that record each registration's options. */
function recordingPicking() {
const registered = new Map();
return {
registered,
services: {
...picking,
registerPickOwner(layerId, predicate, options) {
registered.set(layerId, options ?? {});
picking.registerPickOwner(layerId, predicate, options);
},
},
};
}
function withDocument(t, { cockpit = () => false } = {}) {
const previous = globalThis.document;
globalThis.document = {
body: {
classList: { contains: (name) => name === 'cockpit-mode' && cockpit() },
},
addEventListener() {},
removeEventListener() {},
};
t.after(() => {
if (previous === undefined) delete globalThis.document;
else globalThis.document = previous;
});
}
/** A quake card over `pickedId` reached as a nearby touch contact. */
const actsOnNearbyHit = (pickedId) =>
picking.isActedOnByOtherLayer('earthquakes', pickedId, { expanded: true });
for (const [name, layerId, create] of [
['flights', 'flights', createFlightLifecycle],
['military', 'military', createMilitaryLifecycle],
]) {
test(`${name} registers its aircraft as acting on nearby touch hits`, (t) => {
let cockpit = false;
withDocument(t, { cockpit: () => cockpit });
const { registered, services } = recordingPicking();
const flightState = stub({
_icons: { show: false, has: (id) => id === `${name}-1` },
records: { geoidReady: true },
timeline: null,
_trackedIcao: null,
});
const { methods: lifecycle } = create({
flightState,
services: stub({ picking: services }),
parts: stub(),
layer: stub(),
resolveAsset: () => '',
});
t.after(() => picking.unregisterPickOwner(layerId));
lifecycle.enable({});
assert.equal(registered.get(layerId)?.expanded, true);
assert.equal(actsOnNearbyHit(`${name}-1`), true);
// The handler ignores a dragged tap and any tap in cockpit mode, so the
// aircraft acts on neither click.
const nearby = (gesture) =>
picking.isActedOnByOtherLayer('earthquakes', `${name}-1`, {
expanded: true,
click: { gesture },
});
assert.equal(nearby({ travelPx: 0, durationMs: 80 }), true, 'a tap');
assert.equal(nearby({ travelPx: 12, durationMs: 80 }), false, 'a drag');
cockpit = true;
assert.equal(nearby({ travelPx: 0, durationMs: 80 }), false, 'cockpit');
cockpit = false;
// A click on the aircraft already tracked is ignored, so it is passive.
flightState._trackedIcao = `${name}-1`;
assert.equal(actsOnNearbyHit(`${name}-1`), false);
});
}
test('vessels register their icons as acting on nearby touch hits', (t) => {
withDocument(t);
const { registered, services } = recordingPicking();
const state = {
feed: { enabled: true, sessionId: 1 },
records: { byId: new Map([['vessel-1', {}]]) },
viewer: {},
};
const created = createVesselLifecycle({
vesselState: stub({ state, _geoidReady: true }),
services: stub({ picking: services }),
parts: stub(),
});
const lifecycle = created.methods ?? created;
t.after(() => picking.unregisterPickOwner('ais-live-vessels'));
lifecycle.enable({});
assert.equal(registered.get('ais-live-vessels')?.expanded, true);
assert.equal(actsOnNearbyHit('vessel-1'), true);
});
test('radio registers its stations as acting on nearby touch hits', (t) => {
const { registered, services } = recordingPicking();
const viewer = { scene: { canvas: new EventTarget(), pick: () => null } };
const input = fakeInput(viewer);
const state = { _viewer: viewer, _clickSubscription: null };
const interaction = createRadioInteraction({
state,
services: { picking: services, overlays: stub() },
parts: stub(),
});
t.after(() => {
interaction.removeInteraction();
input.destroy();
});
interaction.installInteraction();
assert.equal(registered.get('radio')?.expanded, true);
assert.equal(actsOnNearbyHit('radio:kexp'), true);
interaction.removeInteraction();
assert.equal(actsOnNearbyHit('radio:kexp'), false);
});
test('Street Level registers its picks as acting on nearby touch hits', (t) => {
withDocument(t);
const { registered, services } = recordingPicking();
const viewer = { scene: { canvas: new EventTarget(), pick: () => null } };
const input = fakeInput(viewer);
const state = { services: { picking: services }, clickSubscription: null };
const selection = createStreetSelection({
state,
parts: stub({
router: {
ownsPick: (id) => id === 'mly:seq-1',
resolve: (id) => (id === 'mly:seq-1' ? { id, instance: {} } : null),
},
}),
});
t.after(() => {
state.clickSubscription?.();
picking.unregisterPickOwner(STREET_LEVEL_LAYER_ID);
input.destroy();
});
selection.install(viewer);
assert.equal(registered.get(STREET_LEVEL_LAYER_ID)?.expanded, true);
assert.equal(actsOnNearbyHit('mly:seq-1'), true);
});
+43 -133
View File
@@ -26,29 +26,6 @@ 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();
/** Owners whose click handlers also select nearby contacts. */
const _expanded = new Set();
/**
* Owners whose click handlers act on none of their picks for some clicks
* (aircraft layers ignore a dragged tap, or any tap in cockpit mode).
* @type {Map<string, (click: object) => boolean>}
*/
const _declines = new Map();
/** @type {WeakMap<object, Map<string, [string, boolean][]>>} */
const clickActions = new WeakMap();
/**
* 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'
@@ -70,30 +47,11 @@ export function resolvePickId(hit) {
* @param {string} layerId - Owning layer id (e.g. 'flights').
* @param {(pickedId: string) => boolean} predicate - Returns true when the
* picked primitive/entity id belongs to this layer.
* @param {{passive?: boolean | ((pickedId: string) => boolean), expanded?: boolean, declinesClick?: (click: object) => boolean}} [options]
* `passive`: the layer never acts on a click on these picks (all of them,
* or those the predicate names). See {@link isActedOnByOtherLayer}.
* `expanded`: preserve precedence for handlers that select nearby contacts,
* through the shared contact hit or their own pick window.
* `declinesClick`: true for a click the layer's handler ignores whatever it
* picked (a dragged tap); for that click its picks act for nobody.
* @returns {void}
*/
export function registerPickOwner(
layerId,
predicate,
{ passive, expanded = false, declinesClick } = {},
) {
export function registerPickOwner(layerId, predicate) {
if (!layerId || typeof predicate !== 'function') return;
_owners.set(layerId, predicate);
if (typeof declinesClick === 'function')
_declines.set(layerId, declinesClick);
else _declines.delete(layerId);
if (expanded) _expanded.add(layerId);
else _expanded.delete(layerId);
if (passive === true || typeof passive === 'function')
_passive.set(layerId, passive);
else _passive.delete(layerId);
}
/**
@@ -103,9 +61,6 @@ export function registerPickOwner(
*/
export function unregisterPickOwner(layerId) {
_owners.delete(layerId);
_expanded.delete(layerId);
_declines.delete(layerId);
_passive.delete(layerId);
}
/**
@@ -144,67 +99,6 @@ export function isOwnedByOtherLayer(layerId, pickedId) {
return false;
}
/**
* @param {string} pickedId
* @param {object} [click] The click being arbitrated, if any.
* @returns {Generator<[string, boolean]>}
*/
function* actingPickOwners(pickedId, click) {
for (const [ownerId, predicate] of _owners) {
try {
if (!predicate(pickedId)) continue;
if (click && _declines.get(ownerId)?.(click)) continue;
const passive = _passive.get(ownerId);
if (passive === true) continue;
if (typeof passive === 'function' && passive(pickedId)) continue;
yield [ownerId, _expanded.has(ownerId)];
} catch {
// a broken predicate must never break click handling
}
}
}
/**
* Hold the acting owners as soon as a click resolves a hit. A handler can
* start tracking the hit and make it passive before later handlers run.
* @param {object} click The shared dispatcher event.
* @param {import('../render/contract/query').Hit|null} hit The resolved hit.
*/
export function rememberClickPickActions(click, hit) {
const pickedId = resolvePickId(hit);
if (!pickedId) return;
let actions = clickActions.get(click);
if (!actions) clickActions.set(click, (actions = new Map()));
if (!actions.has(pickedId)) {
actions.set(pickedId, [...actingPickOwners(pickedId, click)]);
}
}
/**
* 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.
* @param {{expanded?: boolean, click?: object}} [options] For a nearby hit,
* only expanded owners take precedence. Pass the shared click to use the
* acting owners from when it first resolved this hit.
* @returns {boolean}
*/
export function isActedOnByOtherLayer(
layerId,
pickedId,
{ expanded = false, click } = {},
) {
if (!pickedId) return false;
const owners =
clickActions.get(click)?.get(pickedId) ?? actingPickOwners(pickedId, click);
for (const [ownerId, selectsNearby] of owners) {
if (ownerId !== layerId && (!expanded || selectsNearby)) return true;
}
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
@@ -253,41 +147,57 @@ export function pickContact(query, position, options = {}) {
}
/**
* 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.
* The world overlay's hit test: the topmost interactive card or label painted
* at CSS-pixel coordinates, or null. Set by the overlay host while it runs.
* @type {((x: number, y: number) => {sourceId: string, entryId: string}|null)|null}
*/
let _overlayHitTest = null;
/** @type {WeakMap<object, {sourceId: string, entryId: string}|null>} */
const clickCards = new WeakMap();
/**
* Sets (or with null, clears) the hit test that names the card or label
* painted at a click. The world-overlay host sets it while it runs.
* @param {((x: number, y: number) => object|null)|null} hitTest
* @returns {void}
*/
export function registerCardBackground(layerId, predicate) {
if (!layerId || typeof predicate !== 'function') return;
_cardBackgrounds.set(layerId, predicate);
export function setClickCardHitTest(hitTest) {
_overlayHitTest = typeof hitTest === 'function' ? hitTest : null;
}
/**
* Removes a layer's card-background predicate (call when its clicks stop).
* @param {string} layerId - Registering layer id.
* @returns {void}
* The topmost interactive card or label painted at a click, read once per
* click so every handler of it sees the same one whatever ran first.
* @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
* @returns {{sourceId: string, entryId: string}|null}
*/
export function unregisterCardBackground(layerId) {
_cardBackgrounds.delete(layerId);
export function clickCard(click) {
if (!click || typeof click !== 'object') return null;
if (clickCards.has(click)) return clickCards.get(click);
const at = click.screenPosition;
let card = null;
try {
card = _overlayHitTest?.(at?.x, at?.y) ?? null;
} catch {
// a broken hit test must never break click handling
}
clickCards.set(click, card);
return card;
}
/**
* True when 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
* True when another layer's card or label is painted on top at a click. The
* card on top takes the click: a scene item under it does not act, and is
* not empty space either, so the layer leaves its selection alone.
* @param {object} click The shared dispatcher event.
* @param {Iterable<string>} [ownSourceIds] The asking layer's overlay
* sources: its own card on top is its click.
* @returns {boolean}
*/
export function 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;
export function isUnderOtherCard(click, ownSourceIds = []) {
const card = clickCard(click);
if (!card) return false;
for (const sourceId of ownSourceIds)
if (card.sourceId === sourceId) return false;
return true;
}
+44 -127
View File
@@ -15,13 +15,11 @@ import {
registerPickOwner,
unregisterPickOwner,
isOwnedByOtherLayer,
isActedOnByOtherLayer,
resolvePickId,
pickContact,
findPickOwner,
registerCardBackground,
unregisterCardBackground,
isCardBackground,
clickCard,
isUnderOtherCard,
setClickCardHitTest,
} from './pickRegistry.js';
// ---------------------------------------------------------------------------
@@ -54,11 +52,8 @@ 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);
@@ -66,15 +61,9 @@ 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
@@ -87,9 +76,7 @@ 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);
@@ -137,83 +124,6 @@ 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('cards', 'plane:1', { expanded: true }),
false,
);
registerPickOwner('test-plane', (id) => id === 'plane:1', {
expanded: true,
});
assert.equal(
isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }),
true,
);
registerPickOwner('test-plane', (id) => id === 'plane:1', {
expanded: true,
passive: true,
});
assert.equal(
isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }),
false,
);
registerPickOwner('test-plane', (id) => id === 'plane:1');
assert.equal(
isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }),
false,
);
registerPickOwner('test-plane', (id) => id === 'plane:1', {
expanded: true,
});
unregisterPickOwner('test-plane');
registerPickOwner('test-plane', (id) => id === 'plane:1');
assert.equal(
isActedOnByOtherLayer('cards', 'plane:1', { expanded: true }),
false,
);
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);
@@ -234,14 +144,10 @@ 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]]);
});
@@ -274,13 +180,7 @@ 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) => {
@@ -301,22 +201,39 @@ 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');
test("the card on top is read once per click, and only another layer's card counts", () => {
let top = { sourceId: 'quake-card', entryId: 'q1' };
let reads = 0;
setClickCardHitTest((x, y) => {
reads++;
assert.deepEqual([x, y], [4, 5]);
return top;
});
try {
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');
const click = { screenPosition: { x: 4, y: 5 } };
assert.equal(isUnderOtherCard(click, ['vessel-card']), true);
assert.equal(isUnderOtherCard(click, ['quake-card']), false, 'own card');
// A card published later in the same click does not change it.
top = { sourceId: 'vessel-card', entryId: 'v1' };
assert.equal(clickCard(click).sourceId, 'quake-card');
assert.equal(reads, 1);
assert.equal(isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }), true);
top = null;
assert.equal(isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }), false);
} finally {
unregisterCardBackground('test-zones');
unregisterCardBackground('test-broken');
setClickCardHitTest(null);
}
assert.equal(
isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }),
false,
'no host',
);
setClickCardHitTest(() => {
throw new Error('broken');
});
try {
assert.equal(clickCard({ screenPosition: { x: 1, y: 1 } }), null);
} finally {
setClickCardHitTest(null);
}
assert.equal(isCardBackground(shape), false);
});
+1 -27
View File
@@ -1,10 +1,6 @@
import { getContextStore, isContextRecordActive } from './contextStore.js';
import { readEntityRecord } from './entityRecords.js';
import {
findPickOwner,
isActedOnByOtherLayer,
resolvePickId,
} from './pickRegistry.js';
import { findPickOwner, resolvePickId } from './pickRegistry.js';
/**
* Resolve a pick (the contract's `Hit`, as `pickAt` in
@@ -127,25 +123,3 @@ export function resolvePickedContext(picked, { dataManager = null } = {}) {
altitudeM: finite(found?.altitudeM),
};
}
/**
* Whether a world-overlay card or label under a click keeps it from the item
* the click names, because that item's owner does not act on this hit: a
* passive owner (a directions route) acts on none, and an owner that acts
* only on exact hits (a fire, a camera) does not act on a coarse pointer's
* nearby contact (`hit` is not the exact `topHit`). The card's layer takes
* such a click (quake, fire, camera, vessel, news and wildlife cards act over
* it; an inert card, such as a selected drone-zone card, does nothing), so
* Context leaves the item; owners that act on it (an aircraft, a vessel, a
* directions step) still name it.
* @param {{hit?: object|null, topHit?: object|null}} click
* @param {boolean} underCard Whether a world-overlay entry is under it.
* @returns {boolean}
*/
export function cardKeepsClick(click, underCard) {
if (!underCard || !click?.hit) return false;
const pickId = resolvePickId(click.hit);
if (!pickId) return false;
const expanded = pickId !== resolvePickId(click.topHit ?? null);
return !isActedOnByOtherLayer('', pickId, { expanded, click });
}
+2 -72
View File
@@ -11,8 +11,8 @@ globalThis.CustomEvent ||= class CustomEvent {
globalThis.dispatchEvent ||= () => true;
const { registerEntityContext } = await import('./contextStore.js');
const { registerPickOwner, unregisterPickOwner, findPickOwner, rememberClickPickActions } = await import('./pickRegistry.js');
const { resolvePickedContext, pickedKindForLayer, cardKeepsClick } = await import('./pickedContext.js');
const { registerPickOwner, unregisterPickOwner, findPickOwner } = await import('./pickRegistry.js');
const { resolvePickedContext, pickedKindForLayer } = await import('./pickedContext.js');
function manager({ enabled = new Set(['flights', 'local-datacenters']), modules = {} } = {}) {
return {
@@ -97,73 +97,3 @@ test('disabled layers, trails and empty picks never resolve', () => {
assert.equal(resolvePickedContext(hit('unknown'), { dataManager: manager() }), null);
assert.equal(pickedKindForLayer('ais-live-vessels'), 'vessel');
});
test('a card keeps a click from items whose layer does not act on that hit', (t) => {
registerPickOwner('test-fires', (id) => id === 'fire:1');
registerPickOwner('test-planes', (id) => id === 'plane:1', {
expanded: true,
});
registerPickOwner('test-route', (id) => id.startsWith('route:'), {
passive: (id) => !id.startsWith('route:step:'),
});
t.after(() => {
unregisterPickOwner('test-fires');
unregisterPickOwner('test-planes');
unregisterPickOwner('test-route');
});
const fire = { set: 'fires:1', id: 'fire:1' };
const plane = { set: 'planes:1', id: 'plane:1' };
const exact = (hit) => ({ topHit: { ...hit }, hit });
// A coarse tap: nothing exact, the contact found nearby.
const near = (hit) => ({ topHit: null, hit });
assert.equal(
cardKeepsClick(near(fire), true),
true,
'fires act only on exact hits',
);
assert.equal(cardKeepsClick(near(plane), true), false, 'aircraft act nearby');
assert.equal(
cardKeepsClick(near(fire), false),
false,
'open map: Context names it',
);
assert.equal(
cardKeepsClick(exact(fire), true),
false,
"an exact fire is the fire's",
);
const line = { set: 'route:1', id: 'route:line' };
const step = { set: 'route:1', id: 'route:step:2' };
// Every card layer acts over a passive route, so the card keeps the click.
assert.equal(
cardKeepsClick(exact(line), true),
true,
'a route acts for nobody',
);
assert.equal(
cardKeepsClick(exact(step), true),
false,
"a step is directions' own",
);
assert.equal(cardKeepsClick({ topHit: null, hit: null }, true), false);
});
// An aircraft layer can start tracking the plane it was clicked on before
// Context runs, making that plane passive. Context reads the owners that
// acted when the click resolved, so the card over it does not keep the click.
test('a card keeps a click by the owners that acted when it resolved', (t) => {
let tracked = null;
registerPickOwner('test-planes', (id) => id === 'plane:9', {
expanded: true,
passive: (id) => id === tracked,
});
t.after(() => unregisterPickOwner('test-planes'));
const plane = { set: 'planes:1', id: 'plane:9' };
const click = { topHit: plane, hit: plane };
rememberClickPickActions(click, plane);
tracked = 'plane:9';
assert.equal(cardKeepsClick(click, true), false, 'the aircraft acted');
// A click that resolves now sees the tracked plane as passive.
const later = { topHit: { ...plane }, hit: { ...plane } };
assert.equal(cardKeepsClick(later, true), true);
});
+2 -6
View File
@@ -36,12 +36,8 @@ 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.
// 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 },
registerPickOwner('trails', (pickedId) =>
String(pickedId).startsWith('gev-trail:'),
);
/** @type {number} Uniquifier for trail set and line ids. */