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

+1 -2
View File
@@ -1,6 +1,5 @@
import { createEarthquakesLayer } from '../../layers/earthquakes/index.js';
import { overlayHost } from './overlayHost.js';
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import { inputFor } from '../../input/dispatcher.js';
import * as picking from '../../data/pickRegistry.js';
import * as context from '../../data/contextStore.js';
@@ -33,7 +32,7 @@ export const earthquakeCardText = Object.freeze({
*/
export function createApplicationEarthquakes(options) {
return createEarthquakesLayer({
overlayHost: { ...overlayHost, hitTest: hitTestWorldOverlay },
overlayHost,
input: (viewer) => inputFor(viewer),
picking,
context,
+1 -3
View File
@@ -6,7 +6,6 @@ import { createPanoramaxProvider } from '../../layers/streetLevel/providers/pano
import * as picking from '../../data/pickRegistry.js';
import * as scenePick from '../../data/scenePick.js';
import * as render from '../../renderGovernor.js';
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
/** The browser Maps key the scene was started with (src/app/scene.js). */
const googleApiKey = () => globalThis.window?.__GOOGLE_MAPS_API_KEY__ || null;
@@ -36,7 +35,6 @@ export function createApplicationStreetLevel({
}) {
return createStreetLevelLayer({
providers,
// Hit-testing lets a card painted over a near miss keep its click.
services: { picking, scenePick, render, overlayHit: hitTestWorldOverlay },
services: { picking, scenePick, render },
});
}
+1 -3
View File
@@ -1,12 +1,10 @@
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({
// Hit-testing lets a card painted over a cable keep its click.
overlayHost: { ...overlayHost, hitTest: hitTestWorldOverlay },
overlayHost,
picking,
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
+7 -5
View File
@@ -403,10 +403,11 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
'vessel click',
);
ordered(vesselClick, [
'clickCard?.(event)',
'selectAndFocusVessel(carded)',
"isOwnedByOtherLayer('ais-live-vessels', pickedId)",
'_vesselOverlayHost.hitTest?.(',
'selectAndFocusVessel(record)',
], 'vessel sibling ownership');
], 'vessel card on top, then sibling ownership');
const vesselFocus = body(
vessels,
/function selectAndFocusVessel\(record\) \{([\s\S]*?)\n \}/,
@@ -419,8 +420,9 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
'fire click',
);
ordered(fireClick, [
'isOwnedByOtherLayer(id, pickedId)',
'overlayHost.hitTest?.(',
'clickCard?.(event)',
'selectAndFocusFire(carded)',
], 'fire sibling ownership');
'isOwnedByOtherLayer(id, pickedId)',
'clearFireSelection()',
], 'fire card on top, then sibling ownership');
});
+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. */
+2 -7
View File
@@ -51,7 +51,6 @@ import {
import {
findPickOwner,
pickContact,
rememberClickPickActions,
resolvePickId,
} from '../data/pickRegistry.js';
import { isPickedWorldPosition } from '../data/scenePick.js';
@@ -457,9 +456,7 @@ function createClickEvent(viewer, queryOf, at, gesture) {
// The adapter's own pick of this click is the renderer's pass, held
// now: read later, it would be another, of a scene drawn since.
void native()?.native.pick;
const top = topHitOf(hit, () => native()?.foreign() ?? null);
rememberClickPickActions(this, top);
return top;
return topHitOf(hit, () => native()?.foreign() ?? null);
});
},
get drawHit() {
@@ -470,7 +467,7 @@ function createClickEvent(viewer, queryOf, at, gesture) {
return once('hit', () => {
const q = query();
if (!q) return this.topHit;
const hit = pickContact(q, position, {
return pickContact(q, position, {
picked: this.topHit,
// Everything drawn there, as the adapter sees it, so a contact
// search stops at what is drawn over a contact outside the draw
@@ -483,8 +480,6 @@ function createClickEvent(viewer, queryOf, at, gesture) {
: this.drill(limit, width, height);
},
});
rememberClickPickActions(this, hit);
return hit;
});
},
get id() {
+4
View File
@@ -1,5 +1,6 @@
import { isFollowing } from '../../data/followed.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import {
LAYER_ID,
@@ -581,6 +582,9 @@ export function createAlprPresentation({ state, services, source }) {
if (state.clickSubscription) return;
state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// The painted overlay answers first; the scene is picked only if not.
const hit = event.drawHit;
const id =
+57
View File
@@ -0,0 +1,57 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAlprPresentation } from './presentation.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
// The card or label painted on top takes the click: ALPR does not even pick
// under another layer's card, so no camera is selected or released there.
test("another layer's card over an ALPR camera keeps the click", (t) => {
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const noop = () => {};
const state = {
enabled: true,
viewer,
clickSubscription: null,
markers: { icons: null },
recordById: new Map(),
selectedId: null,
};
const presentation = createAlprPresentation({
state,
services: {
render: { governorRequestRender: noop },
context: {
clearSelectedEntityContextForLayer: noop,
getSelectedEntityContext: () => null,
registerEntityContext: noop,
removeEntityContextsForLayer: noop,
selectEntityContext: noop,
},
groundFloor: { cachedGroundFloor: () => null },
},
});
presentation.installInteraction(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => {
setClickCardHitTest(null);
state.clickSubscription?.();
input.destroy();
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
+4
View File
@@ -1,5 +1,6 @@
import { t } from '../../i18n/index.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
@@ -143,6 +144,9 @@ export function createSelection({
if (layerState._clickSubscription) return;
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
const hit = event.drawHit;
if (hit) {
+68
View File
@@ -0,0 +1,68 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
/** A station layer's selection on a viewer whose pick is scripted. */
function harness(t) {
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
let picked = null;
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
const input = fakeInput(viewer);
const noop = () => {};
const state = {
_selectedKey: null,
_clickSubscription: null,
_stationRenderMap: new Map([['nyc:1', { position: { x: 1, y: 0, z: 0 } }]]),
_stationSet: { id: 'bikeshare:stations', upsert: noop },
_selectedSet: {
id: 'bikeshare:selected',
set: noop,
size: () => 0,
clear: noop,
},
_overlayHost: { setEntries: noop, clearSource: noop },
};
const selection = createSelection({
state,
services: {},
parts: { rendering: { stationItem: () => ({}) } },
});
selection._installClickHandler(viewer);
t.after(() => {
state._clickSubscription?.();
input.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
return {
state,
click(hit) {
picked = hit ? { id: hit } : null;
input.tap({ x: 10, y: 10 });
},
};
}
// The card or label painted on top takes the click: a station under another
// layer's card is neither selected nor let go.
test("another layer's card over a station keeps the click", (t) => {
const h = harness(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const station = { set: 'bikeshare:stations', id: 'nyc:1' };
h.click(station);
assert.equal(h.state._selectedKey, null, 'covered: not selected');
top = null;
h.click(station);
assert.equal(h.state._selectedKey, 'nyc:1');
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
h.click(null);
assert.equal(h.state._selectedKey, 'nyc:1', 'covered: kept');
top = null;
h.click(null);
assert.equal(h.state._selectedKey, null, 'open map lets it go');
});
+34 -83
View File
@@ -5,7 +5,6 @@ import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
import { inputFor } from '../../input/dispatcher.js';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
import {
GROUND_PRIOR_INIT_WAIT_MS,
CALIBRATION_RANGE_FLOOR_M,
@@ -24,14 +23,8 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const {
resolvePickId,
registerPickOwner,
unregisterPickOwner,
isOwnedByOtherLayer,
isActedOnByOtherLayer,
isCardBackground,
} = services.picking;
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -398,6 +391,20 @@ export function createLifecycle({
(event) => {
if (!layerState._enabled) return;
const picked = event.topHit;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: a live card of ours acts whatever
// is drawn under it; another layer's is that layer's click.
const top = clickCard?.(event) ?? null;
if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
if (top) {
// A card of ours that is going away is still not the scene.
if (layerState._recordById.has(top.entryId))
activateCctvCameraFromWorldClick(
top.entryId,
parts.selection.setActiveCamera,
);
return;
}
const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
@@ -408,60 +415,11 @@ export function createLifecycle({
);
return;
}
// 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,
{},
);
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));
// A passive owner's pick (a flight trail, a directions route) acts
// for nobody, so a live top CCTV card over it keeps the click.
const passiveUnderCard =
cardId &&
typeof pickedId === 'string' &&
Boolean(isActedOnByOtherLayer) &&
isOwnedByOtherLayer?.('cctv', pickedId) &&
!isActedOnByOtherLayer('cctv', pickedId, { click: event });
if (pickedId !== null && !cardBackground && !passiveUnderCard) return;
// A coarse tap's touch contact (not the exact pick) that its layer
// acts on (an aircraft, a vessel, a radio station) is that layer's
// click, even under a card of ours.
const contactId = resolvePickId(event.hit ?? null);
if (
cardId &&
contactId &&
contactId !== pickedId &&
isActedOnByOtherLayer?.('cctv', contactId, {
expanded: true,
click: event,
})
)
return;
if (cardHit && cardHit.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
if (cardId) {
activateCctvCameraFromWorldClick(
cardId,
parts.selection.setActiveCamera,
);
return;
}
// Any identified scene object owns this click even if its layer
// does not register a shared pick predicate. This keeps selectable
// siblings ahead of the CCTV selection while ID-less globe, terrain
// and tile surfaces remain eligible for empty-space deselection.
if (resolvePickId(picked) !== null) return;
if (
parts.selection.cctvEmptyClickDeselects(picked, {
activeCameraId: layerState._activeCameraId,
@@ -510,26 +468,19 @@ export function createLifecycle({
layerState._lastUpdate = Date.now();
// Pick-ownership (H2): camera icons use the camera id directly;
// coverage polyline entities use `cctv-<cameraId>-<role>` entity ids.
registerPickOwner(
'cctv',
(pickedId) => {
if (layerState._recordById.has(pickedId)) return true;
if (
typeof pickedId === 'string' &&
pickedId.startsWith(GIZMO_ID_PREFIX)
)
return true;
const coverage =
/^cctv-(.+)-(?:ray-tl|ray-tr|ray-br|ray-bl|cap|plane|plane-label)$/.exec(
pickedId,
);
return Boolean(coverage && layerState._recordById.has(coverage[1]));
},
// The world click handler takes only clean clicks (see
// `bindCctvWorldClickGesture`), so a card over a camera keeps any
// other tap.
{ declinesClick: (click) => !isTrackingClickGesture(click?.gesture) },
);
registerPickOwner('cctv', (pickedId) => {
if (layerState._recordById.has(pickedId)) return true;
if (
typeof pickedId === 'string' &&
pickedId.startsWith(GIZMO_ID_PREFIX)
)
return true;
const coverage =
/^cctv-(.+)-(?:ray-tl|ray-tr|ray-br|ray-bl|cap|plane|plane-label)$/.exec(
pickedId,
);
return Boolean(coverage && layerState._recordById.has(coverage[1]));
});
if (!layerState._activeCameraId && layerState._records.length) {
layerState._activeCameraId = parts.navigation.openingCameraId();
layerState._autoHopSuspended = false;
+37 -60
View File
@@ -77,7 +77,7 @@ test('the view listeners follow the camera port and let go on teardown', () => {
assert.equal(state._viewListenerCamera, null);
});
test('world clicks respect the painted top card and registered card backgrounds', async (t) => {
test('the card painted on top takes world clicks, whatever is drawn under it', async (t) => {
const noop = () => {};
const { viewer } = viewerWithCamera();
let picked = null;
@@ -88,10 +88,11 @@ test('world clicks respect the painted top card and registered card backgrounds'
};
let drilled = [];
const input = fakeInput(viewer);
// An aircraft layer that runs before ours and starts tracking the plane
// it was clicked on, which makes that plane passive mid-click.
// An aircraft layer that runs before ours and tracks the plane it was
// clicked on, standing aside under another layer's card.
let tracked = null;
input.input.onClick((event) => {
if (picking.isUnderOtherCard(event)) return;
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
});
const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
@@ -101,6 +102,8 @@ test('world clicks respect the painted top card and registered card backgrounds'
};
let painted = [];
const actions = [];
// The card on top at a click, as the host answers the pick registry.
picking.setClickCardHitTest(() => painted[0] ?? null);
const state = {
_cctvOverlayHost: {
hitTest: (_x, _y, options = {}) =>
@@ -148,12 +151,12 @@ test('world clicks respect the painted top card and registered card backgrounds'
state._clickSubscription?.();
lifecycle.detachViewListeners();
input.destroy();
picking.setClickCardHitTest(null);
picking.unregisterPickOwner('area-control');
picking.unregisterPickOwner('test-trails');
picking.unregisterPickOwner('test-planes');
picking.unregisterPickOwner('test-tracking');
picking.unregisterPickOwner('test-exact');
picking.unregisterCardBackground('area-fixture');
});
await lifecycle.methods.init(viewer);
state._enabled = true;
@@ -184,36 +187,32 @@ test('world clicks respect the painted top card and registered card backgrounds'
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], []);
}
// The live top card acts over anything drawn under it; with no card an
// identified object is not empty map.
for (const hit of [
{ set: 'flights:1', id: 'aircraft', surface: false },
{ set: '', id: 'unregistered-local-entity', surface: false },
{ set: '', id: '', surface: false },
{ ...drone, set: 'unrelated:1:fills' },
{ ...drone, id: 'unregistered-local-entity' },
])
click(hit, [ownCard], []);
// A passive owner's pick (a trail, a route) acts for nobody: the live top
// card keeps the click, and with no card the pick is not empty map.
]) {
click(hit, [ownCard], ['cam-1']);
click(hit, [], []);
}
// A trail under the live top card: the card keeps the click, and with no
// card the owned pick is not empty map.
const trail = { set: 'trails:1', id: 'gev-trail:fl-1:head', surface: false };
picking.registerPickOwner('test-trails', (id) => id === trail.id, {
passive: true,
});
picking.registerPickOwner('test-trails', (id) => id === trail.id);
click(trail, [ownCard], ['cam-1']);
click(trail, [], []);
click(trail, [foreignCard, ownCard], []);
picking.unregisterPickOwner('test-trails');
// A coarse tap whose touch contact is an aircraft (a layer that acts on
// nearby contacts) is the aircraft's, even under a live CCTV card.
// nearby contacts) under a live CCTV card is the card's.
const previousMatch = globalThis.matchMedia;
const restoreMatch = () => {
if (previousMatch) globalThis.matchMedia = previousMatch;
@@ -223,11 +222,9 @@ test('world clicks respect the painted top card and registered card backgrounds'
// failing assertion cannot leave the coarse pointer for later tests.
t.after(restoreMatch);
globalThis.matchMedia = () => ({ matches: true });
picking.registerPickOwner('test-planes', (id) => id === 'plane:1', {
expanded: true,
});
picking.registerPickOwner('test-planes', (id) => id === 'plane:1');
drilled = ['plane:1'];
click(null, [ownCard], []);
click(null, [ownCard], ['cam-1']);
// With no card, the bare tap near the aircraft still deselects.
click(null, [], ['clear']);
// A contact whose layer acts only on exact hits leaves the card its tap.
@@ -239,49 +236,29 @@ test('world clicks respect the painted top card and registered card backgrounds'
click(null, [ownCard], ['cam-1']);
picking.unregisterPickOwner('test-planes');
restoreMatch();
// The live card reads the owners that acted when the click resolved, so it
// yields to the aircraft even though tracking made it passive meanwhile.
picking.registerPickOwner('test-tracking', (id) => id === 'plane:9', {
expanded: true,
passive: (id) => id === tracked,
});
click({ set: 'flights:1', id: 'plane:9', surface: false }, [ownCard], []);
assert.equal(tracked, 'plane:9', 'the aircraft started tracking');
// The live card over an aircraft takes the click; the aircraft layer,
// run first, stands aside and does not track.
picking.registerPickOwner('test-tracking', (id) => id === 'plane:9');
click(
{ set: 'flights:1', id: 'plane:9', surface: false },
[ownCard],
['cam-1'],
);
assert.equal(tracked, null, 'the aircraft did not track');
picking.unregisterPickOwner('test-tracking');
picking.registerPickOwner('area-control', (id) => id === drone.id);
click(drone, [ownCard], []);
click(drone, [ownCard], ['cam-1']);
picking.unregisterPickOwner('area-control');
click(null, [foreignCard, ownCard], []);
click(null, [ownCard], ['cam-1']);
click(null, [], ['clear']);
click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
click(
{ set: 'cctv:fixture', id: 'cam-1' },
[foreignCard, ownCard],
['cam-1'],
);
// CCTV takes only clean clicks, so for a long press or a drag its cameras
// act for nobody: a card painted over one keeps that tap.
// Enable's own work is beside the point here: only its registration.
Object.assign(parts.cards, {
refreshAmbientCards: noop,
startCardFrameLoop: noop,
});
parts.frames = { refreshProjectionImage: noop };
Object.assign(parts.geometryQueue, { startGeometryLoadQueue: noop });
parts.navigation = { openingCameraId: () => 'cam-1' };
Object.assign(parts.projection, {
ensureProjectionRuntime: noop,
startProjectionLoop: noop,
});
state._cctvOverlayHost.setVisible ??= noop;
lifecycle.methods.enable();
t.after(() => picking.unregisterPickOwner('cctv'));
const acted = (gesture) =>
picking.isActedOnByOtherLayer('earthquakes', 'cam-1', {
click: { gesture },
});
assert.equal(acted({ travelPx: 0, durationMs: 80 }), true, 'a clean click');
assert.equal(acted({ travelPx: 0, durationMs: 900 }), false, 'a long press');
assert.equal(acted({ travelPx: 20, durationMs: 80 }), false, 'a drag');
// A card of ours that is going away is still not the scene under it: no
// camera beneath it activates, and nothing clears.
const staleCard = { ...ownCard, entryId: 'stale-camera' };
click({ set: 'cctv:fixture', id: 'cam-1' }, [staleCard], []);
click(null, [staleCard], []);
// A camera icon under another layer's card is that card's click.
click({ set: 'cctv:fixture', id: 'cam-1' }, [foreignCard, ownCard], []);
click({ set: 'cctv:fixture', id: 'cam-1' }, [], ['cam-1']);
});
+10 -62
View File
@@ -1,7 +1,6 @@
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { inputFor } from '../../input/dispatcher.js';
import {
clickCard,
registerPickOwner,
unregisterPickOwner,
} from '../../data/pickRegistry.js';
@@ -79,7 +78,6 @@ const intensityText = (storm) => {
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
export function createCyclonesLayer({
feed,
hitTestOverlay = hitTestWorldOverlay,
overlayHost,
context = null,
createRendering = createCycloneRendering,
@@ -97,8 +95,7 @@ export function createCyclonesLayer({
selectionIntent = 'auto',
navigationGeneration = 0,
selectionOwner = null,
selectedContextStormId = null,
removeClickCapture = null;
selectedContextStormId = null;
let enabled = false,
loading = false,
error = null,
@@ -169,75 +166,28 @@ export function createCyclonesLayer({
rendering?.setSelection(id);
}
function installSelection() {
const canvas = canvasOf(viewer);
if (selectionOwner || !canvas) return;
if (selectionOwner || !canvasOf(viewer)) return;
const owner = {};
selectionOwner = owner;
// Snapshot before sibling bubble listeners can rebuild the overlay hit
// rectangles. A vessel selection does that synchronously in the same click.
let capturedHit = null;
const overlayHit = (x, y) => {
const hit = hitTestOverlay(x, y);
return { sourceId: hit?.sourceId, entryId: hit?.entryId };
};
const capture = (event) => {
capturedHit = null;
const point = event.changedTouches?.[0] || event;
if (!Number.isFinite(point.clientX) || !Number.isFinite(point.clientY))
return;
const rect = canvas.getBoundingClientRect();
const x = point.clientX - rect.left,
y = point.clientY - rect.top;
capturedHit = { x, y, ...overlayHit(x, y) };
};
const resetCapture = () => {
capturedHit = null;
};
const resetEvents = [
'pointerdown',
'mousedown',
'touchstart',
'pointercancel',
'touchcancel',
];
for (const type of resetEvents)
canvas.addEventListener?.(type, resetCapture, { capture: true });
const events = ['pointerup', 'mouseup', 'touchend'];
for (const type of events)
canvas.addEventListener?.(type, capture, { capture: true });
removeClickCapture = () => {
for (const type of events)
canvas.removeEventListener?.(type, capture, { capture: true });
for (const type of resetEvents)
canvas.removeEventListener?.(type, resetCapture, { capture: true });
capturedHit = null;
};
const unsubscribe = inputFor(viewer).onClick((event) => {
const nativeHit = capturedHit;
capturedHit = null;
// Ambient selection yields to draw tools and Director (the dispatcher
// skips a held pointer); it never claims the pointer, camera, or
// tracking state.
const position = event.screenPosition;
if (!enabled || destroyed || selectionOwner !== owner || !position)
return;
// AIS cards paint above the globe on a pointer-events:none canvas. The
// vessel handler resolves this same topmost hit before cyclone geometry.
const captureMatches =
nativeHit &&
Math.abs(nativeHit.x - position.x) < 1 &&
Math.abs(nativeHit.y - position.y) < 1;
const hit = captureMatches
? nativeHit
: overlayHit(position.x, position.y);
if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
// The card or label painted on top, as it was when the click landed.
const card = clickCard(event);
// Storm cards and lead-hour labels paint on the same canvas; a click on
// one selects its storm. An id from a superseded advisory changes nothing.
if (hit.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
const id = cycloneStormIdFromEntryId(hit.entryId);
if (card?.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
const id = cycloneStormIdFromEntryId(card.entryId);
if (id) layer.setParams({ stormId: id });
return;
}
// Another layer's card on top takes the click: the storm under it does
// not act, and the click is not empty map either.
if (card) return;
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
// clears the selection.
const id = rendering?.pickStorm(event.drawHit);
@@ -249,8 +199,6 @@ export function createCyclonesLayer({
function removeSelection() {
const owner = selectionOwner;
selectionOwner = null;
removeClickCapture?.();
removeClickCapture = null;
owner?.unsubscribe?.();
}
const layer = {
+19 -45
View File
@@ -6,7 +6,10 @@ import {
releasePointer,
isPointerFree,
} from '../../data/inputOwnership.js';
import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
import {
isOwnedByOtherLayer,
setClickCardHitTest,
} from '../../data/pickRegistry.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
@@ -77,7 +80,7 @@ const deferred = () => {
return { promise, resolve };
};
test('map selection yields to pointer owners and owns only its enabled handler', async () => {
test('map selection yields to pointer owners and owns only its enabled handler', async (t) => {
const handlers = [],
// A pick of an item in one of the layer's draw sets, and one of another
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
@@ -109,11 +112,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
createRendering: () => rendering,
hitTestOverlay: () => {
overlayTests++;
return overlayHit;
},
});
setClickCardHitTest(() => {
overlayTests++;
return overlayHit;
});
t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
const viewer = {
@@ -180,41 +184,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
'foreground AIS card wins before scene picking',
);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
// A native capture runs before an earlier sibling handler clears hit rects.
const up = new Event('pointerup');
Object.assign(up, { clientX: 110, clientY: 220 });
canvas.dispatchEvent(up);
overlayHit = null;
// Any other layer's card on top takes the click, not only a vessel's.
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
handlers[0].click(click);
assert.equal(
layer.getDiagnostics().selectedId,
'ep152026',
'captured AIS hit survives synchronous sibling overlay rebuild',
'a camera card over the storm keeps the click',
);
// A captured background hit remains background even if a sibling adds a card.
canvas.dispatchEvent(up);
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
layer.setParams({ stormId: 'ep152026' });
// A new gesture clears an unconsumed release snapshot.
canvas.dispatchEvent(up);
canvas.dispatchEvent(new Event('pointerdown'));
overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
layer.setParams({ stormId: 'ep152026' });
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
canvas.dispatchEvent(up);
overlayHit = null;
handlers[0].click({ position: { x: 15, y: 25 } });
assert.equal(
layer.getDiagnostics().selectedId,
'ep162026',
'a different click cannot reuse the captured card',
);
layer.setParams({ stormId: 'ep152026' });
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
const before = notices;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
@@ -264,13 +242,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
assert.equal(layer.getDiagnostics().selectionActive, false);
const afterDisable = picks;
const afterDisableOverlay = overlayTests;
canvas.dispatchEvent(up);
handlers[0].click(click);
assert.equal(
overlayTests,
afterDisableOverlay,
'disable removes native capture listeners',
'a disabled layer reads no card',
);
handlers[0].click(click);
assert.equal(picks, afterDisable, 'queued disabled callback is inert');
layer.enable();
await layer.update();
@@ -289,7 +266,7 @@ test('map selection yields to pointer owners and owns only its enabled handler',
);
assert.equal(handlers[1].destroyed, true);
});
test('a click on a storm card or lead-hour label selects that storm without picking', async () => {
test('a click on a storm card or lead-hour label selects that storm without picking', async (t) => {
const handlers = [];
let picks = 0,
overlayHit = null,
@@ -309,8 +286,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
getDiagnostics: () => ({}),
};
},
hitTestOverlay: () => overlayHit,
});
setClickCardHitTest(() => overlayHit);
t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
const viewer = {
@@ -343,15 +321,11 @@ test('a click on a storm card or lead-hour label selects that storm without pick
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:al019999' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
// The native release snapshot carries the card identity too.
const up = new Event('pointerup');
Object.assign(up, { clientX: 10, clientY: 20 });
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:ep162026' };
canvas.dispatchEvent(up);
overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
assert.equal(picks, 0, 'card clicks never fall through to the scene');
overlayHit = null;
handlers[0].click(click);
assert.equal(picks, 1);
assert.equal(layer.getDiagnostics().selectedId, null, 'empty map clears');
+3 -3
View File
@@ -1584,6 +1584,9 @@ export function createDirectionsLayer({ services, source }) {
// yields the moment a tool (this one included) owns the click.
const offSelect = input.onClick((event) => {
if (!_enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (services.picking?.isUnderOtherCard?.(event)) return;
let hit = null;
try {
hit = event.drawHit;
@@ -1672,13 +1675,10 @@ 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();
},
+5 -17
View File
@@ -129,23 +129,12 @@ 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,
);
// 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;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: this area's shapes are background to
// another layer's card or label painted over them, and a click on our
// own card leaves the selection as it is.
if (picking.clickCard?.(event)) return;
const picked = event.topHit;
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
if (zoneId) {
@@ -167,7 +156,6 @@ export function createDroneAirspaceLayer({
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
picking?.unregisterCardBackground?.(layer.id);
}
function clearSelection() {
+3 -23
View File
@@ -17,7 +17,6 @@ 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);
@@ -48,9 +47,9 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
registerCardBackground: (layerId, predicate) =>
backgrounds.set(layerId, predicate),
unregisterCardBackground: (layerId) => backgrounds.delete(layerId),
// The card on top at a click, as the registry answers from the host.
clickCard: (click) =>
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
});
layer.init(viewer);
@@ -65,7 +64,6 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
overlay,
clicks,
owners,
backgrounds,
};
}
@@ -284,21 +282,3 @@ 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);
});
+31 -54
View File
@@ -1,6 +1,10 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
isTrackingClickGesture,
isTrackingSelectionGesture,
} from '../../data/trackingClickGesture.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
@@ -58,15 +62,13 @@ let instances = 0;
* without `input` and `picking` the discs are drawn but take no clicks.
* @param {object} options
* @param {object} options.source Snapshot source.
* @param {object} options.overlayHost World-overlay host (`hitTest` lets
* the card be clicked).
* @param {object} options.overlayHost World-overlay host.
* @param {(viewer: object) => {onClick: Function}} [options.input] The
* viewer's click dispatcher.
* @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.
* clickCard?: Function}} [options.picking] The pick
* registry; `clickCard` names the card or label painted on top of a
* click, which takes it (the quake card and labels need it to act).
* @param {{registerEntityContext: Function, selectEntityContext: Function,
* clearSelectedEntityContextForLayer: Function,
* getContextStore: Function}} [options.context] Shared selection store.
@@ -351,63 +353,39 @@ 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;
// Another layer's card or label painted on top (a fire's card over a
// quake disc) is that layer's click: the disc under it is background.
const topEntry = overlayHost.hitTest?.(at?.x, at?.y);
if (
topEntry &&
topEntry.sourceId !== EARTHQUAKE_CARD_SOURCE_ID &&
topEntry.sourceId !== EARTHQUAKE_OVERLAY_SOURCE_ID
)
return;
// 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);
const actedOn =
picking.isActedOnByOtherLayer ?? picking.isOwnedByOtherLayer;
// Exact-only handlers cannot act on a nearby touch hit. Compare ids,
// since the dispatcher may expose distinct objects for the same pick.
const expanded =
'topHit' in click && picking.resolvePickId(click.topHit) !== pickId;
if (pickId && actedOn(EARTHQUAKES_LAYER_ID, pickId, { expanded, click }))
return;
const cardHit = overlayHost.hitTest?.(at?.x, at?.y, {
sourceId: EARTHQUAKE_CARD_SOURCE_ID,
});
if (cardHit && cardHit.entryId === _selectedCardId) {
// A pan that ends near where it began still raises a click. As for the
// tracking layers and Context, a press that travelled is a drag, not a
// pick; opening the source and clearing also need a short press.
if (!isTrackingSelectionGesture(click.gesture)) return;
const clean = isTrackingClickGesture(click.gesture);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: another layer's is that layer's click
// (the disc under it is background), and ours acts whatever is drawn
// under it.
const top = picking.clickCard?.(click) ?? null;
if (top?.sourceId === EARTHQUAKE_CARD_SOURCE_ID) {
// The card's action, as its keyboard action: open the source, or
// with none, fly to the quake.
if (_selectedLink) openExternal(_selectedLink);
else if (focus?.requestWorldFocus && _selectedId)
if (top.entryId !== _selectedCardId) return;
if (_selectedLink) {
if (clean) openExternal(_selectedLink);
} else if (focus?.requestWorldFocus && _selectedId)
selectAndFocus(_selectedId);
return;
}
// A magnitude label is what a far view (the whole globe) can click:
// it selects the quake and flies to it.
const labelHit = overlayHost.hitTest?.(at?.x, at?.y, {
sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID,
});
if (labelHit && _eventById.has(labelHit.entryId)) {
selectAndFocus(labelHit.entryId);
if (top?.sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) {
if (_eventById.has(top.entryId)) selectAndFocus(top.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 (top) return;
// Another layer's pick (an aircraft, a camera, a flight trail) is not
// empty space and not this layer's: leave the selection alone.
const hit = click.hit;
const pickId = picking.resolvePickId(hit);
if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
return;
const event = pickedEvent(hit);
@@ -416,7 +394,7 @@ export function createEarthquakesLayer({
publishCard({ user: true });
return;
}
clearSelection();
if (clean) clearSelection();
});
}
@@ -443,7 +421,6 @@ export function createEarthquakesLayer({
function removeClickHandler() {
_clickHandler?.();
_clickHandler = null;
picking?.unregisterCardBackground?.(EARTHQUAKES_LAYER_ID);
}
const layer = {
+97 -59
View File
@@ -83,6 +83,8 @@ function harness(
return hit && entry?.interactive === true ? hit : null;
},
};
// The card on top at a click, as the host answers the pick registry.
picking.setClickCardHitTest((x, y) => overlayHost.hitTest(x, y));
const layer = createEarthquakesLayer({
source: { getSnapshot: async () => snapshot },
overlayHost,
@@ -128,13 +130,14 @@ function harness(
snapshot = next;
},
/** Click a quake's disc (by stable id), something else, or the map. */
click(hit, resolvedHit = hit) {
click(hit, resolvedHit = hit, gesture = { travelPx: 0, durationMs: 0 }) {
for (const { callback } of live())
callback({
screenPosition: { x: 10, y: 10 },
topHit: hit,
hit: resolvedHit,
drawHit: hit && !hit.surface ? hit : null,
gesture,
});
},
clickDisc(id) {
@@ -276,17 +279,12 @@ test('a refresh keeps the selected quake while it is in the feed', async () => {
h.layer.destroy();
});
test('disable removes the click handler, card background and the card', async () => {
test('disable removes the click handler 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),
@@ -673,7 +671,8 @@ test('a feed refresh neither retakes the selection nor restarts the contours', a
h.layer.destroy();
});
test("another layer's object over a magnitude label takes the click", async () => {
// The label painted on top takes the click: the object drawn under it does not.
test("a magnitude label takes the click over another layer's object", async () => {
const h = harness([quake('ak1')]);
h.layer.enable(h.viewer);
await h.layer.update(h.viewer);
@@ -684,12 +683,11 @@ test("another layer's object over a magnitude label takes the click", async () =
set: 'flights:1',
id: 'plane-9',
});
assert.equal(h.cards.length, 0, 'the quake is not selected');
assert.equal(h.focused.length, 0, 'and the camera stays');
// The label alone still selects and flies.
h.clickLabel('ak1');
assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1');
assert.equal(h.focused.length, 1);
assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1', 'selected');
assert.equal(h.focused.length, 1, 'and the camera flies');
// The plane alone, with no label over it, is not empty space.
h.click({ set: 'flights:1', id: 'plane-9' });
assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1', 'kept');
} finally {
picking.unregisterPickOwner('test-plane');
h.layer.destroy();
@@ -709,21 +707,19 @@ test('a touch-expanded quake hit selects its disc without flying', async () => {
}
});
test('a touch-expanded sibling hit takes precedence over a quake label', async () => {
test('a quake label takes the click over a touch-expanded sibling hit', async () => {
const h = harness([quake('ak1'), quake('ak2')]);
try {
h.layer.enable(h.viewer);
await h.layer.update(h.viewer);
h.clickDisc('ak1');
picking.registerPickOwner('test-plane', (id) => id === 'plane-9', {
expanded: true,
});
picking.registerPickOwner('test-plane', (id) => id === 'plane-9');
h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', null, {
set: 'flights:1',
id: 'plane-9',
});
assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1');
assert.equal(h.focused.length, 0);
assert.equal(h.lastCard()[0].id, 'earthquake-card:ak2');
assert.equal(h.focused.length, 1);
} finally {
picking.unregisterPickOwner('test-plane');
h.layer.destroy();
@@ -751,7 +747,7 @@ test("another layer's card over a quake disc takes the click, and the disc yield
});
for (const coarse of [false, true]) {
test(`a quake card yields while an aircraft starts tracking (${coarse ? 'coarse' : 'exact'} hit)`, async (t) => {
test(`a quake card takes the click over an aircraft, which does not track (${coarse ? 'coarse' : 'exact'} hit)`, async (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: coarse });
t.after(() => {
@@ -771,9 +767,10 @@ for (const coarse of [false, true]) {
drillPick: () => (nearby ? [{ id: nearby }] : []),
};
input = fakeInput(viewer);
// The aircraft layer runs first and changes its passive predicate
// synchronously after reading the dispatched hit.
// The aircraft layer runs first; like every layer, it leaves a
// click under another layer's card to that card.
input.input.onClick((event) => {
if (picking.isUnderOtherCard(event)) return;
const id = event.hit?.id;
if (id !== plane.id || tracked === id) return;
tracked = id;
@@ -782,10 +779,7 @@ for (const coarse of [false, true]) {
return input.input;
},
});
picking.registerPickOwner('test-plane', (id) => id === plane.id, {
expanded: true,
passive: (id) => id === tracked,
});
picking.registerPickOwner('test-plane', (id) => id === plane.id);
t.after(() => {
picking.unregisterPickOwner('test-plane');
h.layer.destroy();
@@ -804,15 +798,18 @@ for (const coarse of [false, true]) {
nearby = coarse ? plane : null;
input.click();
assert.equal(tracks, 1, 'the aircraft starts tracking');
assert.deepEqual(h.opened, [], 'the quake card yields for the whole click');
assert.equal(h.lastCard()[0].id, card.id, 'the card stays');
input.click();
assert.equal(tracks, 1, 'already tracking the aircraft');
assert.equal(tracks, 0, 'the aircraft under the card does not track');
assert.deepEqual(h.opened, [
'https://earthquake.usgs.gov/earthquakes/eventpage/ak1',
]);
assert.equal(h.lastCard()[0].id, card.id, 'the card stays');
// Without the card the aircraft takes it, and the quake stays selected.
h.overlayHits.clear();
input.click();
assert.equal(tracks, 1, 'the bare aircraft tracks');
assert.equal(h.opened.length, 1);
assert.equal(h.lastCard()[0].id, card.id);
});
}
@@ -853,6 +850,7 @@ for (const kind of ['card', 'label']) {
paint();
input.click();
};
picking.setClickCardHitTest((x, y) => host.hitTest(x, y));
const q = createEarthquakesLayer({
source: { getSnapshot: async () => [quake('ak1')] },
overlayHost: host,
@@ -983,15 +981,12 @@ test('quake card and label work over pickable items no layer acts on', async ()
}
});
// 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 () => {
// The quake card or a magnitude label on top takes the click over whatever is
// drawn under it: a flight trail, a route, a route step or an aircraft.
test('quake card and label act over trails, routes, steps and aircraft', 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-directions', (id) =>
String(id).startsWith('directions:'),
);
picking.registerPickOwner('test-plane', (id) => id === 'plane-9');
try {
@@ -1006,19 +1001,19 @@ test('quake card and label act over a flight trail and a directions route', asyn
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;
// A route step under the label: the label still takes it.
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.
assert.equal(h.focused.at(-1)?.id, 'earthquake:ak1', 'over a step');
// So does the card over an aircraft.
h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', null);
h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak2', {
set: 'flights:1',
id: 'plane-9',
});
assert.equal(h.opened.length, 2);
assert.equal(h.opened.length, 3, 'over an aircraft');
// 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');
@@ -1029,7 +1024,7 @@ test('quake card and label act over a flight trail and a directions route', asyn
}
});
test('coarse FIRMS near-misses leave quake overlays actionable; exact fire hits act once', async (t) => {
test('quake overlays take the click over a nearby or exact fire; a bare fire acts once', async (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
@@ -1094,8 +1089,12 @@ test('coarse FIRMS near-misses leave quake overlays actionable; exact fire hits
assert.equal(fireFocus.length, 0);
sceneHit = fireHit;
input.click();
assert.equal(fireFocus.length, 1, 'exact fire hit acts');
assert.equal(h.opened.length, 1, 'card yields to the exact fire');
assert.equal(fireFocus.length, 0, 'an exact fire under the card does not');
assert.equal(h.opened.length, 2, 'the card on top acts');
h.overlayHits.clear();
input.click();
assert.equal(fireFocus.length, 1, 'the bare fire acts');
assert.equal(h.opened.length, 2);
} finally {
selection.removeClickHandler();
picking.unregisterPickOwner('firms');
@@ -1104,9 +1103,9 @@ test('coarse FIRMS near-misses leave quake overlays actionable; exact fire hits
}
});
// A tap that drifts more than the tracking click travel is ignored by the
// aircraft layers, so a quake card painted beside an aircraft keeps it.
test('a quake card keeps a dragged tap beside an aircraft that declines it', async (t) => {
// A tap that drifts more than the tracking click travel is a drag: the quake
// card ignores it, as the aircraft layers do.
test('a quake card takes a still tap beside an aircraft but not a dragged one', async (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
@@ -1127,10 +1126,7 @@ test('a quake card keeps a dragged tap beside an aircraft that declines it', asy
return input.input;
},
});
picking.registerPickOwner('test-plane', (id) => id === plane.id, {
expanded: true,
declinesClick: (click) => (click?.gesture?.travelPx ?? 0) > 6,
});
picking.registerPickOwner('test-plane', (id) => id === plane.id);
t.after(() => {
picking.unregisterPickOwner('test-plane');
h.layer.destroy();
@@ -1147,15 +1143,57 @@ test('a quake card keeps a dragged tap beside an aircraft that declines it', asy
});
sceneHit = null;
nearby = plane;
// A still tap: the aircraft acts on its contact, so the card yields.
// A still tap: the card on top takes it over the aircraft's contact.
input.tap({ x: 10, y: 10 });
assert.deepEqual(h.opened, []);
assert.equal(h.opened.length, 1);
// A tap that drifts 10 px: the aircraft ignores it, so the card opens.
input.down({ x: 10, y: 10 });
input.move({ x: 20, y: 10 }, { x: 10, y: 10 });
input.up({ x: 20, y: 10 });
input.click({ x: 20, y: 10 });
assert.equal(h.opened.length, 1, 'the card keeps the dragged tap');
assert.equal(h.opened.length, 1, 'a drag opens nothing');
});
// A pan that ends near where it began still raises a click: it must not
// select a quake, fly to one, open its source or clear the selection.
test('a drag that ends on a quake does nothing; a long press selects but neither opens nor clears', async () => {
const drag = { travelPx: 12, durationMs: 120 };
const hold = { travelPx: 0, durationMs: 900 };
const h = harness([quake('ak1'), quake('ak2')]);
h.layer.enable(h.viewer);
await h.layer.update(h.viewer);
const disc = (id) => ({ set: h.discs().spec.id, id: `earthquake:${id}` });
h.click(disc('ak1'), disc('ak1'), drag);
assert.equal(h.cards.length, 0, 'a drag over a disc selects nothing');
h.overlayHits.set(EARTHQUAKE_OVERLAY_SOURCE_ID, {
sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID,
entryId: 'ak2',
});
h.click(null, null, drag);
h.overlayHits.clear();
assert.equal(h.focused.length, 0, 'a drag over a label does not fly');
h.click(disc('ak1'), disc('ak1'), hold);
const card = h.lastCard()[0];
assert.ok(card, 'a long press on a disc selects it');
h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, {
sourceId: EARTHQUAKE_CARD_SOURCE_ID,
entryId: card.id,
});
h.click(null, null, hold);
h.overlayHits.clear();
assert.deepEqual(h.opened, [], 'a long press does not open the source');
const cardsBefore = h.cards.length;
h.click(null, null, drag);
h.click(null, null, hold);
assert.equal(
h.cards.length,
cardsBefore,
'a drag or hold on the map keeps it',
);
assert.ok(h.lastCard().length, 'still selected');
h.click(null);
assert.deepEqual(h.lastCard(), [], 'a clean click on the map clears it');
h.layer.destroy();
});
// A refresh that no longer carries the selected quake evicts it, as other
+16 -40
View File
@@ -13,8 +13,7 @@ export function createSelection({
config,
feed,
}) {
const { resolvePickId, isOwnedByOtherLayer, isActedOnByOtherLayer } =
services.picking;
const { resolvePickId, isOwnedByOtherLayer, clickCard } = services.picking;
const { requestWorldFocus } = services.focus;
const {
selectEntityContext,
@@ -22,7 +21,7 @@ export function createSelection({
getContextStore,
registerEntityContext,
} = services.context;
const { id, name, overlayHost } = config;
const { id, name } = config;
/**
* Install the LEFT_CLICK handler for fire selection (enable-time only,
@@ -35,48 +34,25 @@ export function createSelection({
if (layerState._clickSubscription || !layerState._viewer) return;
const input = inputFor(layerState._viewer);
layerState._clickSubscription = input.onClick((event) => {
const picked = event.topHit;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: ours acts whatever is drawn under it;
// another layer's is that layer's click.
const top = clickCard?.(event) ?? null;
if (top) {
if (top.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return;
const carded = layerState._fireByCardId.get(top.entryId);
if (carded) selectAndFocusFire(carded);
return;
}
const fire = pickedFire(event.drawHit);
if (fire) {
selectAndFocusFire(fire);
return;
}
// A pick that belongs to a sibling layer (e.g. an aircraft) is not
// "empty space" — leave the selection alone and let that layer handle it.
// A passive owner's pick (a flight trail, a directions route) acts for
// nobody, so a card of ours painted over it still takes the click.
let passivePick = false;
if (picked) {
const pickedId = resolvePickId(picked);
if (pickedId && isOwnedByOtherLayer(id, pickedId)) {
passivePick =
Boolean(isActedOnByOtherLayer) &&
!isActedOnByOtherLayer(id, pickedId, { click: event });
if (!passivePick) return;
}
}
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
);
if (passivePick && cardHit?.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return;
// A coarse tap's touch contact (not the exact pick) that its layer acts
// on (an aircraft, a vessel, a radio station) is that layer's click,
// even under a card of ours.
const contactId = resolvePickId(event.hit ?? null);
if (
cardHit &&
contactId &&
contactId !== resolvePickId(picked ?? null) &&
isActedOnByOtherLayer?.(id, contactId, { expanded: true, click: event })
)
return;
if (cardHit) {
if (cardHit.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return;
const carded = layerState._fireByCardId.get(cardHit.entryId);
if (carded) selectAndFocusFire(carded);
return;
}
// A pick that belongs to a sibling layer (an aircraft, a flight trail)
// is not "empty space": leave the selection alone.
const pickedId = resolvePickId(event.topHit ?? null);
if (pickedId && isOwnedByOtherLayer(id, pickedId)) return;
clearFireSelection();
});
}
-14
View File
@@ -1,4 +1,3 @@
import { isTrackingSelectionGesture } from '../../data/trackingClickGesture.js';
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { loadFleetModelSet } from '../../data/fleetModels.js';
import { forgetPlacedAircraft } from './placed.js';
@@ -135,19 +134,6 @@ export function createLifecycle({
registerPickOwner(
'flights',
(pickedId) => flightState._icons?.has(pickedId) === true,
{
expanded: true,
// A click on the aircraft already tracked is ignored: for that one
// plane the layer acts on nothing, so a card over it keeps the tap.
passive: (pickedId) =>
Boolean(flightState._trackedIcao) &&
pickedId === flightState._trackedIcao,
// The click handler ignores a dragged tap and any tap in cockpit
// mode, so a card over the aircraft keeps that tap.
declinesClick: (click) =>
!isTrackingSelectionGesture(click?.gesture) ||
Boolean(document.body?.classList.contains('cockpit-mode')),
},
);
const frame = findFrame(viewer);
if (!flightState._preRenderRemove && frame) {
+46
View File
@@ -4,6 +4,8 @@ import { createCivilFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createEnrichment } from './enrichment.js';
import { createTracking } from './tracking.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
import { LiveSourceError } from '../../sources/live/contract.js';
function services() {
@@ -608,3 +610,47 @@ test('a route answer for a callsign the plane no longer flies is dropped', async
assert.equal(meta.routeCallsign, 'UAL10');
flightState.lifetime.abort();
});
// The card or label painted on top takes the click: an aircraft under another
// layer's card is not even picked, so it is neither tracked nor released.
test("another layer's card over an aircraft keeps the click", (t) => {
const previousDocument = globalThis.document;
globalThis.document = Object.assign(new EventTarget(), {
body: { classList: { contains: () => false } },
});
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const flightState = createFlightState({ services: services() });
flightState._trackedEntityChangedRemove = () => {};
const tracking = createTracking({
flightState,
services: { ...services(), picking },
parts: {},
layer: {},
});
tracking._installClickHandler(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
picking.setClickCardHitTest(() => top);
t.after(() => {
picking.setClickCardHitTest(null);
flightState._clickSubscription?.();
input.destroy();
flightState.lifetime.abort();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
+5 -1
View File
@@ -86,7 +86,8 @@ export function createTracking({
const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout;
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
services.camera;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
services.picking;
const flightsLayer = layer;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
@@ -1272,6 +1273,9 @@ export function createTracking({
// first-person reference. A globe click must not fall through to the
// normal empty-space deselection path; cockpit has explicit exit controls.
if (document.body.classList.contains('cockpit-mode')) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard?.(event)) return;
const picked = event.hit;
if (picked) {
+13 -13
View File
@@ -707,15 +707,19 @@ export function createGhostMapsLayer({
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
);
if (
cardHit?.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId
) {
if (_selectedLink && openExternal) openExternal(_selectedLink);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: ours opens its source whatever is drawn
// under it; another layer's is that layer's click, so the maps under
// it do not act and the selection stays.
const cardHit = picking.clickCard?.(event) ?? null;
if (cardHit) {
if (
cardHit.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId &&
_selectedLink &&
openExternal
)
openExternal(_selectedLink);
return;
}
const picked = event.topHit;
@@ -731,10 +735,6 @@ export function createGhostMapsLayer({
if (pickId && picking.isOwnedByOtherLayer(GHOSTMAPS_LAYER_ID, pickId))
return;
}
// A covered card must neither open its source nor clear the selection.
// A marker of ours under that card was already selected by the pick
// check before this one.
if (cardHit) return;
if (_selectedKey) {
clearSelection();
render();
+10 -6
View File
@@ -664,7 +664,11 @@ test('a covered selected card yields while genuine GhostMaps markers still selec
hitTest: (_x, _y, { sourceId } = {}) =>
painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null,
},
picking: { resolvePickId: (picked) => picked },
picking: {
resolvePickId: (picked) => picked,
// The card on top at a click, as the registry answers from the host.
clickCard: () => painted[0] ?? null,
},
openExternal: (url) => opened.push(url),
},
});
@@ -679,13 +683,13 @@ test('a covered selected card yields while genuine GhostMaps markers still selec
click(null);
assert.deepEqual(opened, []);
assert.equal(cards.at(-1)[0].id, first.id);
// A marker under another layer's card is that card's click too.
click('ghostmaps:cip:1:0');
assert.equal(cards.at(-1)[0].id, first.id, 'a covered marker yields');
painted = [];
click('ghostmaps:cip:1:0');
const second = cards.at(-1)[0];
assert.notEqual(
second.id,
first.id,
'an actual marker still selects beneath the foreign card',
);
assert.notEqual(second.id, first.id, 'a bare marker selects');
painted = [{ sourceId: 's2-ghostmaps', entryId: second.id }];
click(null);
assert.deepEqual(opened, ['https://example.com/second']);
+4
View File
@@ -1,4 +1,5 @@
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
export function createSelection({
@@ -52,6 +53,9 @@ export function createSelection({
const input = inputFor(viewer);
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
const hit = event.drawHit;
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -186,6 +187,30 @@ test('a click on a named marker point selects its site; again releases it', (t)
h.assertSelected(false);
});
// The card or label painted on top takes the click: a site under another
// layer's card neither selects nor releases.
test("another layer's card over a site keeps the click", (t) => {
const h = harness(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const setId = h.parts.namedMarkers.setId;
const item = h.draw.set(setId).items.get(namedPointId('base'));
const pointPick = { id: { set: setId, id: item.id, meta: item.meta } };
h.click(pointPick);
h.assertSelected(true);
h.click(undefined);
h.assertSelected(true);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.parts.rendering.renderRecords();
h.click(pointPick);
h.assertSelected(false);
top = null;
h.click(pointPick);
h.assertSelected(true);
});
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
const h = harness(t);
h.state.selectedId = null;
+2 -11
View File
@@ -28,8 +28,8 @@ test('a card painted over a launch marker keeps its click; with none the mission
state,
services: {
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
overlays: { hitTestWorldOverlay: () => top },
picking,
// The card on top at a click, as the registry answers from the host.
picking: { ...picking, clickCard: () => top },
},
parts: {
panel: stubs(),
@@ -61,15 +61,6 @@ test('a card painted over a launch marker keeps its click; with none the mission
['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();
+1 -21
View File
@@ -4,8 +4,6 @@ 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
@@ -206,29 +204,12 @@ 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;
if (services.picking?.clickCard?.(event)) return;
// The click's pick position (CSS px), as the click picked it.
const launchId = parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
@@ -248,7 +229,6 @@ 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
+3
View File
@@ -684,6 +684,9 @@ export function createLocalAdsbLayer({
if (clickSubscription || !viewer) return;
clickSubscription = inputFor(viewer).onClick((event) => {
if (!enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (services.picking.isUnderOtherCard?.(event)) return;
const target = clickTarget(event);
// Clicking a local aircraft always (re)selects it and republishes its
// card, including the one already selected: its card may have been
+40 -1
View File
@@ -14,7 +14,11 @@ import {
} from './index.js';
import { createLocalAdsbModels } from './models.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import {
isUnderOtherCard,
resolvePickId,
setClickCardHitTest,
} from '../../data/pickRegistry.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js';
@@ -1172,6 +1176,41 @@ test('clicking the selected aircraft keeps it selected and republishes its card'
assert.deepEqual(calls.cleared, []);
});
// The card or label painted on top takes the click: a local aircraft under
// another layer's card is neither selected nor released.
test("another layer's card over a local aircraft keeps the click", async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const harness = clickHarness();
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer,
services: {
picking: {
registerPickOwner() {},
unregisterPickOwner() {},
resolvePickId,
isUnderOtherCard,
},
},
});
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
harness.click();
assert.deepEqual(calls.selected, [], 'covered: not selected');
top = null;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
harness.scene.pickResult = null;
harness.click();
assert.deepEqual(calls.cleared, [], 'covered: the selection stays');
});
test('a click on a local aircraft under an unowned or trail pick still selects it', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
-14
View File
@@ -1,4 +1,3 @@
import { isTrackingSelectionGesture } from '../../data/trackingClickGesture.js';
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { loadFleetModelSet } from '../../data/fleetModels.js';
import { forgetPlacedAircraft } from '../flights/placed.js';
@@ -116,19 +115,6 @@ export function createLifecycle({
registerPickOwner(
'military',
(pickedId) => flightState._icons?.has(pickedId) === true,
{
expanded: true,
// A click on the aircraft already tracked is ignored: for that one
// plane the layer acts on nothing, so a card over it keeps the tap.
passive: (pickedId) =>
Boolean(flightState._trackedIcao) &&
pickedId === flightState._trackedIcao,
// The click handler ignores a dragged tap and any tap in cockpit
// mode, so a card over the aircraft keeps that tap.
declinesClick: (click) =>
!isTrackingSelectionGesture(click?.gesture) ||
Boolean(document.body?.classList.contains('cockpit-mode')),
},
);
// The flights layer suppresses its military duplicates while we render them
setMilitaryLayerActive(true);
+46
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import { createMilitaryFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
function services() {
const names = [
@@ -294,3 +296,47 @@ test('a military layer without an icon set declines contact refreshes', () => {
assert.equal(layer.refreshTr3b('abc123'), false);
assert.equal(layer.trackById('abc123'), false);
});
// The card or label painted on top takes the click: an aircraft under another
// layer's card is not even picked, so it is neither tracked nor released.
test("another layer's card over an aircraft keeps the click", (t) => {
const previousDocument = globalThis.document;
globalThis.document = Object.assign(new EventTarget(), {
body: { classList: { contains: () => false } },
});
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const flightState = createFlightState({ services: services() });
flightState._trackedEntityChangedRemove = () => {};
const tracking = createTracking({
flightState,
services: { ...services(), picking },
parts: {},
layer: {},
});
tracking._installClickHandler(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
picking.setClickCardHitTest(() => top);
t.after(() => {
picking.setClickCardHitTest(null);
flightState._clickSubscription?.();
input.destroy();
flightState.lifetime.abort();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
+5 -1
View File
@@ -87,7 +87,8 @@ export function createTracking({
const { clearFocusTarget } = services.focus;
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
services.camera;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
services.picking;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
viewer: () => flightState._viewer,
@@ -1191,6 +1192,9 @@ export function createTracking({
// first-person reference. Empty globe clicks are inert until the user
// exits with C, Escape, or the dedicated button.
if (document.body.classList.contains('cockpit-mode')) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard?.(event)) return;
const picked = event.hit;
if (picked) {
+8 -9
View File
@@ -8,8 +8,8 @@ import {
findFrame,
rendererOf,
} from '../../render/rendererOf.js';
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import {
clickCard,
isOwnedByOtherLayer,
registerPickOwner,
resolvePickId,
@@ -203,7 +203,6 @@ export function createNewsLayer({
inputFor = defaultInputFor,
matchMedia = globalThis.matchMedia?.bind(globalThis),
now = () => Date.now(),
hitTestOverlay = hitTestWorldOverlay,
openUrl = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
getViewCentre = viewCentre,
registerCredit = registerDynamicCredit,
@@ -1348,11 +1347,13 @@ export function createNewsLayer({
clickOff = inputFor(viewer).onClick((event) => {
const at = event?.screenPosition;
if (!enabled || destroyed || !isPointerFree() || !at) return;
// The topmost painted entry decides: our own card acts; one covered by
// another layer's card does not.
const card = hitTestOverlay(at.x, at.y);
if (card?.sourceId === NEWS_OVERLAY_SOURCE_ID && card.entry?.activate) {
card.entry.activate();
// The card or label painted on top takes the click, read once per
// click so every layer agrees: our own card acts whatever is drawn
// under it; another layer's is that layer's click, so the pins under
// it do not act and the selection stays.
const card = clickCard(event);
if (card) {
if (card.sourceId === NEWS_OVERLAY_SOURCE_ID) card.entry?.activate?.();
return;
}
// What is on top under the click: a draw-set item, or null for the
@@ -1408,8 +1409,6 @@ export function createNewsLayer({
return;
}
if (id && isOwnedByOtherLayer(NEWS_LAYER_ID, id)) return;
// Another layer's card on top is that layer's click, not empty map.
if (card) return;
if (selectedId && !picked?.id) layer.setParams({ clear: true });
});
}
+24 -4
View File
@@ -5,7 +5,12 @@ import { fromDegrees } from '../../geo/ellipsoid.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { NEWS_KEY_PROVIDERS, createNewsLayer } from './index.js';
import { findPickOwner } from '../../data/pickRegistry.js';
import {
findPickOwner,
registerPickOwner,
setClickCardHitTest,
unregisterPickOwner,
} from '../../data/pickRegistry.js';
// Registers the shared `gev-trail:` no-op owner, as the app does.
import '../../data/trailRenderer.js';
import { getSelectedEntityContext } from '../../data/contextStore.js';
@@ -141,11 +146,12 @@ function fixture(
for (const fn of [...clickHandlers])
fn({ screenPosition: { x: 10, y: 10 }, topHit });
};
// The card on top at a click, as the host answers the pick registry.
setClickCardHitTest((x, y) => hitTestOverlay(x, y));
const layer = createNewsLayer({
source,
overlayHost,
inputFor: () => input,
hitTestOverlay,
now,
matchMedia: () => ({ matches: reduced }),
getViewCentre: () => centre(),
@@ -162,6 +168,7 @@ function fixture(
layer.attachShellServices({ runNavigation: (navigate) => navigate() });
t.after(() => {
layer.destroy();
setClickCardHitTest(null);
unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
@@ -1289,7 +1296,7 @@ test('a click on a marker selects its report, on a beacon chooses its hotspot, o
assert.equal(clickHandlers.size, 0);
});
test('a covered news card yields; the top news card acts over a flight trail', async (t) => {
test('a covered news card and pin yield; the top news card acts over a trail or a vessel', async (t) => {
let hits = [];
const { layer, items, entries, click, flights } = fixture(t, {
height: 500_000,
@@ -1322,10 +1329,14 @@ test('a covered news card yields; the top news card acts over a flight trail', a
assert.equal(layer.getRowControls().feed.selected.id, 'major');
assert.deepEqual(layer.getRowControls().feed.filters, before.filters);
assert.equal(flights.length, flightCount);
// A news pin under another layer's card is that card's click too.
layer.setParams({ clear: true });
click({ set: 'news:1:points', id: marker.id, surface: false });
assert.equal(layer.getRowControls().feed.selected, null, 'covered pin');
hits = [];
click({ set: 'news:1:points', id: marker.id, surface: false });
assert.equal(layer.getRowControls().feed.selected.id, 'major');
hits.shift();
hits = [{ sourceId: 'news', entry: card }];
click(null);
assert.equal(activations, 1, 'the unobscured news card acts once');
// A flight trail is registered so every layer reads a click on it as a
@@ -1338,6 +1349,15 @@ test('a covered news card yields; the top news card acts over a flight trail', a
surface: false,
});
assert.equal(activations, 2, 'the news card acts over a flight trail');
// Over a vessel (a layer that acts on its pick) the card on top acts too;
// the vessel layer stands aside under it, so one click does one thing.
registerPickOwner('test-vessels', (id) => id === '353136000');
try {
click({ set: 'vessels:1', id: '353136000', surface: false });
assert.equal(activations, 3, 'the news card acts over a vessel');
} finally {
unregisterPickOwner('test-vessels');
}
});
test('zoomed out, a hotspot is one beacon; off, nothing draws; destroyed, the sets go', async (t) => {
+12 -17
View File
@@ -215,25 +215,21 @@ 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,
);
// 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);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: this area's shapes are background to
// another layer's card or label painted over them.
const cardHit = picking.clickCard?.(event) ?? null;
if (cardHit) {
if (
cardHit.sourceId === PERIMETER_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId &&
_selectedLink &&
openExternal
)
openExternal(_selectedLink);
return;
}
const picked = event.topHit;
@@ -261,7 +257,6 @@ export function createFirePerimetersLayer({
function removeClickHandler() {
_clickSubscription?.();
_clickSubscription = null;
picking?.unregisterCardBackground?.(layer.id);
}
function clearSelection() {
+3 -23
View File
@@ -27,7 +27,6 @@ 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);
@@ -59,9 +58,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),
// The card on top at a click, as the registry answers from the host.
clickCard: (click) =>
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
inciwebSource: inciwebIndex
? { getIndex: async () => inciwebIndex }
@@ -81,7 +80,6 @@ function harness(
overlay,
clicks,
owners,
backgrounds,
opened,
};
}
@@ -694,21 +692,3 @@ 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);
});
+6 -21
View File
@@ -15,6 +15,7 @@ export function createInteraction({
const {
resolvePickId,
isOwnedByOtherLayer,
isUnderOtherCard,
registerPickOwner,
unregisterPickOwner,
} = services.picking;
@@ -29,6 +30,9 @@ export function createInteraction({
*/
function pickedRadioStationAt(event) {
if (!event) return null;
// Another layer's card or label painted on top is that layer's click,
// read once per click so every layer agrees: no station under it acts.
if (isUnderOtherCard?.(event, [RADIO_OVERLAY_SOURCE_ID])) return null;
const stationFromPick = (picked) => {
const stationId = parts.rendering.radioStationIdFromPick(picked);
@@ -48,28 +52,11 @@ export function createInteraction({
RADIO_PICK_WINDOW_PX,
)) {
const stationId = stationFromPick(picked);
if (!stationId) continue;
// Found only through our wider window, not as the tap's touch contact:
// another layer's card or label painted here is that layer's click,
// since its handler never sees this window. A station of ours that is
// the contact is still ours: that card yields to it.
const contactStationId = stationFromPick(event.hit);
if (contactStationId !== stationId && foreignCardAt(event))
return contactStationId;
return stationId;
if (stationId) return stationId;
}
return null;
}
/** Whether another layer's world-overlay card or label is under a click. */
function foreignCardAt(event) {
const top = services.overlays?.hitTestWorldOverlay?.(
event.screenPosition?.x,
event.screenPosition?.y,
);
return Boolean(top) && top.sourceId !== RADIO_OVERLAY_SOURCE_ID;
}
function radioPresentationAllowed() {
if (!layerState._managerLifecyclePresentation) return layerState._enabled;
return (
@@ -97,9 +84,7 @@ export function createInteraction({
function installInteraction() {
if (!layerState._viewer || layerState._clickSubscription) return;
registerPickOwner('radio', (id) => id.startsWith(RADIO_PREFIX), {
expanded: true,
});
registerPickOwner('radio', (id) => id.startsWith(RADIO_PREFIX));
const viewer = layerState._viewer;
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
if (!radioPresentationAllowed()) return;
+24 -49
View File
@@ -63,73 +63,48 @@ test('a direct hit needs no drill, and another layer’s contact keeps its click
assert.equal(pickedRadioStationAt(other), null);
});
// A station found only through radio's wider window, not as the tap's own
// pick or its touch contact, sits under another layer's card or label: that
// layer acts and never sees this window, so radio leaves the click.
test('a window-only station yields to a card painted over it', () => {
// Another layer's card or label painted on top takes the click: no station
// under it acts, whether radio found it through its window, as the tap's touch
// contact or as the exact pick. Radio's own card on top is radio's click.
test("a station under another layer's card does not act", () => {
let top = null;
const radio = createInteraction({
state: { _stationById: new Map([['kexp', {}]]) },
state: {
_stationById: new Map([
['kexp', {}],
['kuow', {}],
]),
},
services: {
picking: {
resolvePickId: (picked) => picked?.id ?? null,
isOwnedByOtherLayer: () => false,
// The card on top at a click, as the registry answers from the host.
isUnderOtherCard: (_click, own = []) =>
Boolean(top) && !own.includes(top.sourceId),
registerPickOwner() {},
unregisterPickOwner() {},
},
overlays: {
setOverlaySourceVisible() {},
hitTestWorldOverlay: () => top,
},
overlays: { setOverlaySourceVisible() {} },
},
parts: { rendering: { radioStationIdFromPick } },
});
const station = hit('radio:kexp');
const near = (contact = null) => ({
...clickEvent({ windowHits: [station] }),
const tap = (contact = null, pick = null) => ({
...clickEvent({ pick, windowHits: [station] }),
hit: contact,
screenPosition: { x: 5, y: 5 },
});
assert.equal(radio.pickedRadioStationAt(near()), 'kexp', 'open map');
assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'open map');
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
assert.equal(radio.pickedRadioStationAt(near()), null, 'under a quake card');
assert.equal(radio.pickedRadioStationAt(tap()), null, 'window only');
assert.equal(radio.pickedRadioStationAt(tap(station)), null, 'contact');
assert.equal(
radio.pickedRadioStationAt(near(station)),
'kexp',
'the touch contact: the card yielded to the station',
radio.pickedRadioStationAt(tap(hit('radio:kuow'))),
null,
'another contact station',
);
assert.equal(radio.pickedRadioStationAt(tap(null, station)), null, 'exact');
top = { sourceId: 'radio', entryId: 'radio:kexp' };
assert.equal(radio.pickedRadioStationAt(near()), 'kexp', 'our own card');
});
// Under another layer's card, radio's window can name a different station
// from the tap's touch contact. The card yields to that contact, a station of
// ours, so radio acts on it instead of leaving the click dead.
test('under a card, the touch contact station is ours even when the window names another', () => {
const radio = createInteraction({
state: { _stationById: new Map([['kexp', {}], ['kuow', {}]]) },
services: {
picking: {
resolvePickId: (picked) => picked?.id ?? null,
isOwnedByOtherLayer: () => false,
registerPickOwner() {},
unregisterPickOwner() {},
},
overlays: {
setOverlaySourceVisible() {},
hitTestWorldOverlay: () => ({
sourceId: 'earthquake-card',
entryId: 'earthquake-card:ak1',
}),
},
},
parts: { rendering: { radioStationIdFromPick } },
});
const tap = (contact) => ({
...clickEvent({ windowHits: [hit('radio:kexp')] }),
hit: contact,
screenPosition: { x: 5, y: 5 },
});
assert.equal(radio.pickedRadioStationAt(tap(hit('radio:kuow'))), 'kuow');
assert.equal(radio.pickedRadioStationAt(tap(null)), null, 'no contact');
assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'our own card');
});
+20
View File
@@ -10,6 +10,7 @@ import {
SELECTION_FOLLOW_TRANSITION_S,
} from '../../data/trackedCamera.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { distance } from '../../geo/vector.js';
import {
ACTIVATION_EXIT_ALTITUDE_M,
@@ -203,6 +204,25 @@ test('a click on a train selects it; a click on the map lets it go', async (t) =
assert.equal(app.state()._selectedKey, key);
});
// The card or label painted on top takes the click: a train under another
// layer's card is neither selected nor let go.
test("another layer's card over a train keeps the click", async (t) => {
const app = harness(t);
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
const icons = app.drawn('icons');
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
app.click({ set: icons.spec.id, id: key, surface: false });
assert.equal(app.state()._selectedKey ?? null, null, 'covered: not selected');
top = null;
app.click({ set: icons.spec.id, id: key, surface: false });
assert.equal(app.state()._selectedKey, key);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
app.click(null);
assert.equal(app.state()._selectedKey, key, 'covered: kept');
});
test('a parked train, or one known from a single report, is flown to once', async (t) => {
const app = harness(t);
await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
+4
View File
@@ -7,6 +7,7 @@ import {
} from './policy.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { t } from '../../i18n/index.js';
/**
@@ -173,6 +174,9 @@ export function createSelection({ state, services, parts }) {
if (!state._enabled) return;
// A held train keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
const key = trainKeyOf(event.drawHit);
if (key) selectAndFocusTrain(key);
else if (state._selectedKey) clearSelection();
+5 -1
View File
@@ -7,7 +7,8 @@ export function createInteraction({
parts,
source,
}) {
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
services.picking;
function _onKeyDown(e) {
// The Cockpit owns Escape while it rides the tracked satellite.
@@ -50,6 +51,9 @@ export function createInteraction({
// The Cockpit camera rides the tracked satellite: a click on the
// picture below must not untrack it or switch satellites.
if (parts.cockpit?._cockpitHeld()) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard?.(event)) return;
const picked = event.topHit;
const hit = event.drawHit;
@@ -0,0 +1,65 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createInteraction } from './interaction.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
// The card or label painted on top takes the click: a satellite under another
// layer's card is neither tracked nor let go.
test("another layer's card over a satellite keeps the click", (t) => {
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
let picked = null;
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
const input = fakeInput(viewer);
const calls = [];
const state = {
_enabled: true,
_trackedNorad: null,
_clickSubscription: null,
_trackedEntityChangedRemove: () => {},
_catalog: new Map([[25544, {}]]),
};
const interaction = createInteraction({
state,
services: { picking },
parts: {
rendering: {
_hitIsTracked: () => false,
_hitPointId: (hit) =>
hit?.set === 'satellites:dots' ? Number(hit.id) : null,
},
tracking: {
_cancelPendingTrackingRestore() {},
_trackSatellite: (id) => calls.push(['track', id]),
_clearTracking: () => calls.push(['clear']),
},
},
});
interaction._installClickHandler(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
picking.setClickCardHitTest(() => top);
t.after(() => {
picking.setClickCardHitTest(null);
state._clickSubscription?.();
input.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
const click = (hit) => {
picked = hit ? { id: hit } : null;
input.tap({ x: 10, y: 10 });
};
const dot = { set: 'satellites:dots', id: '25544' };
click(dot);
assert.deepEqual(calls, [], 'covered: not tracked');
state._trackedNorad = 1;
click(null);
assert.deepEqual(calls, [], 'covered: tracking kept');
top = null;
click(null);
assert.deepEqual(calls, [['clear']], 'open map lets it go');
state._trackedNorad = null;
click(dot);
assert.deepEqual(calls.at(-1), ['track', 25544]);
});
+12 -11
View File
@@ -277,13 +277,18 @@ export function createShipwrecksLayer({
if (!clicks) return;
_clickHandler = clicks.onClick((click) => {
if (pointer && !pointer.isPointerFree()) return;
const at = click.screenPosition;
const cardHit = overlayHost.hitTest?.(at?.x, at?.y);
if (
cardHit?.sourceId === SHIPWRECKS_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId
) {
if (_selectedLink) openExternal(_selectedLink);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: ours opens its source whatever is drawn
// under it; another layer's is that layer's click, so the markers
// under it do not act and the selection stays.
const cardHit = picking.clickCard?.(click) ?? null;
if (cardHit) {
if (
cardHit.sourceId === SHIPWRECKS_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId &&
_selectedLink
)
openExternal(_selectedLink);
return;
}
// A marker's item id is its pick id, `shipwreck:<id>`. Read from what is
@@ -300,10 +305,6 @@ export function createShipwrecksLayer({
}
if (pickId && picking.isOwnedByOtherLayer(SHIPWRECKS_LAYER_ID, pickId))
return;
// A covered card must neither open its source nor clear the selection.
// A marker of ours under that card was already selected by the pick
// check before this one.
if (cardHit) return;
if (_selectedId) {
clearSelection();
render();
+7 -1
View File
@@ -47,6 +47,8 @@ function harness({ snapshots, now = () => 1, cardHit = () => null } = {}) {
const { draw } = bindFakeDraw(viewer);
const queue = [...(snapshots || [])];
const requests = [];
// The card on top at a click, as the host answers the pick registry.
picking.setClickCardHitTest((x, y) => cardHit(x, y));
const layer = createShipwrecksLayer({
source: {
getSnapshot({ signal }) {
@@ -394,7 +396,7 @@ test('the page deadline subtracts the newest available source age from the limit
assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults');
});
test('a covered selected card yields while genuine wreck markers still select', async () => {
test('a covered selected card and covered markers yield; bare markers select', async () => {
let painted = [];
const h = harness({
snapshots: [
@@ -421,8 +423,12 @@ test('a covered selected card yields while genuine wreck markers still select',
click();
assert.deepEqual(h.opened, []);
assert.equal(h.lastCard()[0].id, first.id);
// A marker under another layer's card is that card's click too.
h.pick('b');
click();
assert.equal(h.lastCard()[0].id, first.id, 'a covered marker yields');
painted = [];
click();
assert.equal(h.lastCard()[0].id, 'shipwreck-card:b');
painted = [{ sourceId: 'shipwrecks', entryId: 'shipwreck-card:b' }];
h.pick(null);
+9 -21
View File
@@ -23,29 +23,22 @@ export function createSelection({ state, parts }) {
/** The id carries a provider's prefix: that provider handles the pick. */
function onClick(event) {
if (!state.viewer || !state.enabled) return;
// Another layer's card or label painted on top takes the click, read once
// per click so every layer agrees: no image, sequence or ground under it
// opens. Street Level paints no cards of its own.
if (picking?.isUnderOtherCard?.(event)) return;
const hit = event.windowHit(CLICK_PICK_WINDOW_PX, CLICK_PICK_WINDOW_PX);
const windowId = pickIdOf(hit);
// A coarse tap's touch contact (event.hit) reaches farther than this
// window; a card or label over it yields to our item there, so it is ours.
// window: an item of ours there is still ours.
const contact = event.hit;
const contactId =
contact && !contact.surface
? pickIdOf({ drawHit: contact.set ? contact : null, id: event.id })
: null;
let route = parts.router.resolve(windowId);
// Found only through our window, not as the contact (which is the exact
// hit whenever there is one): another layer's card or label painted here
// is that layer's click, since its handler never sees this window.
// An item of ours that is the contact is still ours: that card yields
// to it.
if (route && windowId !== contactId) {
const at = event.screenPosition;
if (state.services.overlayHit?.(at?.x, at?.y)) {
route = contactId ? parts.router.resolve(contactId) : null;
if (!route) return;
}
}
if (!route && contactId) route = parts.router.resolve(contactId);
const route =
parts.router.resolve(windowId) ??
(contactId ? parts.router.resolve(contactId) : null);
// Not ours: the ground handler decides whether it is the map itself.
if (!route) {
parts.openAtGround?.({ surface: hit.surface, ground: groundOf(event) });
@@ -92,12 +85,7 @@ export function createSelection({ state, parts }) {
if (state.clickSubscription) return;
state.clickSubscription = inputFor(viewer).onClick(onClick);
document.addEventListener('keydown', onKeyDown);
picking?.registerPickOwner?.(STREET_LEVEL_LAYER_ID, parts.router.ownsPick, {
expanded: true,
// The core's position marker is ours but selects nothing: a card over
// it keeps the tap.
passive: (id) => !parts.router.resolve(id)?.instance,
});
picking?.registerPickOwner?.(STREET_LEVEL_LAYER_ID, parts.router.ownsPick);
}
function uninstall() {
+57 -42
View File
@@ -48,11 +48,13 @@ function harness({
...sceneExtras,
},
};
// The card on top at a click, as the host answers the pick registry.
pickRegistry.setClickCardHitTest(services.overlayHit ?? null);
const state = {
viewer,
enabled: true,
clickSubscription: null,
services: { picking: null, input: null, ...services },
services: { picking: pickRegistry, input: null, ...services },
providers: new Map([
[
'mapillary',
@@ -106,6 +108,7 @@ function harness({
return event;
},
restore() {
pickRegistry.setClickCardHitTest(null);
selection.uninstall();
globalThis.document = saved;
},
@@ -315,26 +318,48 @@ test('an item found only in our window yields to a card painted over it', () =>
}
});
// A coarse tap's touch contact reaches farther than this window. A quake card
// or label over that contact yields to it, so Street Level takes it here.
test('a coarse touch contact beyond our window is ours to open', (t) => {
// The map itself under another layer's card or label is that card's click:
// a ground click there must not also open the nearest street image.
test("a click on the map under another layer's card opens no ground image", () => {
let top = null;
const h = harness({ services: { overlayHit: () => top } });
try {
h.click();
assert.equal(
h.groundClicks.length,
1,
'open map: the ground handler decides',
);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
h.click();
assert.equal(h.groundClicks.length, 1, 'under a card: the card keeps it');
assert.deepEqual(h.opened, []);
} finally {
h.restore();
}
});
// A coarse tap's touch contact reaches farther than this window: on open map
// Street Level takes it; under another layer's card the card does.
test('a coarse touch contact beyond our window is ours to open, unless a card is on top', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
if (previous) globalThis.matchMedia = previous;
else delete globalThis.matchMedia;
});
let top = { sourceId: 'earthquake-card', entryId: 'q' };
const h = harness({
services: {
picking: pickRegistry,
overlayHit: () => ({ sourceId: 'earthquake-card', entryId: 'q' }),
},
services: { picking: pickRegistry, overlayHit: () => top },
sceneExtras: {
pick: () => null,
drillPick: () => [{ id: 'mly:img:contact' }],
},
});
try {
h.click();
assert.deepEqual(h.opened, [], 'under a card: the card keeps it');
top = null;
h.click();
assert.deepEqual(h.opened, ['contact']);
assert.equal(h.groundClicks.length, 0);
@@ -343,22 +368,27 @@ test('a coarse touch contact beyond our window is ours to open', (t) => {
}
});
// The exact hit or the touch contact is ours under a card too: a quake card
// or label yields to a Street Level owner's pick, so yielding back would
// leave the click dead. Line parts compare by the sequence they pick as.
test('an exact or contact hit on our line part acts under a card', (t) => {
// The exact hit or the touch contact on our line part under another layer's
// card is that card's click; on open map it selects the sequence its part
// picks as.
test('an exact or contact hit on our line part acts only with no card on top', (t) => {
const part = {
set: 'street-level:mapillary-coverage:1',
id: 'mly:seq:abc#2',
meta: { pick: 'mly:seq:abc' },
};
const card = () => ({ sourceId: 'earthquake-card', entryId: 'q' });
let top = { sourceId: 'earthquake-card', entryId: 'q' };
const card = () => top;
const exact = harness({ services: { overlayHit: card } });
try {
exact.scene.under = part;
exact.click();
assert.deepEqual(exact.sequences.selects, [], 'under a card');
top = null;
exact.click();
assert.deepEqual(exact.sequences.selects, ['abc'], 'mouse, exact part');
} finally {
top = { sourceId: 'earthquake-card', entryId: 'q' };
exact.restore();
}
const previous = globalThis.matchMedia;
@@ -375,6 +405,9 @@ test('an exact or contact hit on our line part acts under a card', (t) => {
},
});
try {
contact.click();
assert.deepEqual(contact.sequences.selects, [], 'coarse, under a card');
top = null;
contact.click();
assert.deepEqual(contact.sequences.selects, ['abc'], 'coarse contact');
} finally {
@@ -383,7 +416,7 @@ test('an exact or contact hit on our line part acts under a card', (t) => {
});
// Our window catching another layer's item says nothing about our own touch
// contact beyond it: that contact is still ours under a card.
// contact beyond it: that contact is still ours.
test('a contact of ours acts even when our window finds another item', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
@@ -392,10 +425,7 @@ test('a contact of ours acts even when our window finds another item', (t) => {
else delete globalThis.matchMedia;
});
const h = harness({
services: {
picking: pickRegistry,
overlayHit: () => ({ sourceId: 'earthquake-card', entryId: 'q' }),
},
services: { picking: pickRegistry },
sceneExtras: {
pick: (_position, width = 3) =>
width >= 9 ? { id: { set: 'flights:1', id: 'flight:9' } } : null,
@@ -410,36 +440,18 @@ test('a contact of ours acts even when our window finds another item', (t) => {
}
});
// The core's position marker is ours but selects nothing, so it is a passive
// pick: a card painted over it keeps the tap. Our images and lines act.
test('the position marker is a passive pick; our items act', () => {
const h = harness({ services: { picking: pickRegistry } });
try {
const acted = (id) =>
pickRegistry.isActedOnByOtherLayer('test-card', id, { expanded: true });
assert.equal(pickRegistry.findPickOwner('sl:pos'), 'street-level');
assert.equal(acted('sl:pos'), false, 'the marker acts for nobody');
assert.equal(acted('mly:img:abc'), true, 'an image opens');
} finally {
h.restore();
}
});
// Under another layer's card, our window can name a different item from the
// tap's touch contact. The card yields to that contact, an item of ours, so
// Street Level opens it instead of leaving the click dead.
test('under a card, the touch contact item is ours even when the window names another', (t) => {
// Under another layer's card nothing of ours opens, whatever our window or the
// tap's touch contact names; on open map our window's item opens.
test('under a card, neither our window item nor our touch contact opens', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
if (previous) globalThis.matchMedia = previous;
else delete globalThis.matchMedia;
});
let top = { sourceId: 'earthquake-card', entryId: 'q' };
const h = harness({
services: {
picking: pickRegistry,
overlayHit: () => ({ sourceId: 'earthquake-card', entryId: 'q' }),
},
services: { picking: pickRegistry, overlayHit: () => top },
sceneExtras: {
pick: (_position, width = 3) =>
width >= 9 ? { id: 'mly:img:window' } : null,
@@ -448,8 +460,11 @@ test('under a card, the touch contact item is ours even when the window names an
});
try {
h.click();
assert.deepEqual(h.opened, ['contact']);
assert.deepEqual(h.opened, []);
assert.equal(h.groundClicks.length, 0);
top = null;
h.click();
assert.deepEqual(h.opened, ['window']);
} finally {
h.restore();
}
-1
View File
@@ -24,7 +24,6 @@ export function createSubmarineCableLayer({
parts,
source,
inputFor,
overlayHost,
picking,
mapStackEventTarget,
};
+5 -27
View File
@@ -1,40 +1,18 @@
import { toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
const CARD_BACKGROUND_ID = 'submarine-cables';
export function createInteraction({
state,
parts,
inputFor,
overlayHost,
picking,
}) {
export function createInteraction({ state, parts, inputFor, picking }) {
function beginInteraction(viewer) {
if (state._clickSubscription) return;
// 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) => {
state._clickSubscription = 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;
// Cable labels are not interactive, so any card or label painted on
// top is another layer's, painted over the cable: its click.
if (picking?.clickCard?.(event)) return;
const record = resolvePickRecord(event.drawHit);
if (!record?.reference) return;
flyToReference(viewer, record.reference);
});
state._clickSubscription = () => {
unsubscribe();
picking?.unregisterCardBackground?.(CARD_BACKGROUND_ID);
};
}
/**
@@ -25,6 +25,8 @@ function harness({ overlayTop = null } = {}) {
},
}),
overlayHost: { hitTest: () => top },
// The card on top at a click, as the registry answers from the host.
picking: { clickCard: () => top },
});
interaction.beginInteraction({});
return {
@@ -57,33 +59,3 @@ test('a card painted over a cable keeps its click; with none the cable reads the
'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?.();
}
});
+25
View File
@@ -44,6 +44,7 @@ import {
uninstallRenderGovernor,
} from '../../renderGovernor.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindRenderer, rendererOf } from '../../render/rendererOf.js';
@@ -3696,6 +3697,30 @@ test('click handler selects a migrated scripted billboard and prepares its drape
assert.equal(entry.marker.show, true);
});
// The card or label painted on top takes the click: a vehicle under another
// layer's card is neither selected nor released.
test("another layer's card over a vehicle keeps the click", async (t) => {
const app = harness(t, { floorAt: () => undefined });
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
app.layer.enable(app.viewer);
app.layer._loadTransitFleetForTest(4, BOSTON, 70);
const [first, second] = app.vehicles();
app.viewer.scene.pick = () => app.pickOf(first);
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, null, 'covered: not selected');
top = null;
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, first.key);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
app.viewer.scene.pick = () => app.pickOf(second);
app.input.click(new Cesium.Cartesian2(500, 400));
app.viewer.scene.pick = () => undefined;
app.input.click(new Cesium.Cartesian2(500, 400));
assert.equal(app.state()._selectedKey, first.key, 'covered: kept');
});
test('intercepted scripted reports resolve their explicit floor and wake without a preRender bootstrap', async (t) => {
const app = harness(t, { floorAt: () => undefined });
app.layer._setTransitFixtureFloorsForTest(['mbta:sim-straight'], 20);
+4
View File
@@ -7,6 +7,7 @@ import {
} from './policy.js';
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { t } from '../../i18n/index.js';
/**
@@ -151,6 +152,9 @@ export function createSelection({ state, services, parts }) {
collection:
set === 'moving' ? 'animated' : set === 'still' ? 'stationary' : null,
};
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
if (key) {
selectVehicle(key, { byUser: true });
return;
+2 -4
View File
@@ -192,10 +192,8 @@ export function createLifecycle({
});
}
// Pick-ownership (H2): a vessel icon's pick id is its row id, the record's id.
registerPickOwner(
'ais-live-vessels',
(pickedId) => state.records.byId.has(pickedId),
{ expanded: true },
registerPickOwner('ais-live-vessels', (pickedId) =>
state.records.byId.has(pickedId),
);
// Vessels are asked for by view, so ask again when the view moves away.
removeViewListener();
+25 -69
View File
@@ -10,8 +10,7 @@ export function createSelection({
options,
}) {
const { state } = vesselState;
const { isOwnedByOtherLayer, isActedOnByOtherLayer, resolvePickId } =
services.picking;
const { isOwnedByOtherLayer } = services.picking;
const { requestWorldFocus } = services.worldFocus;
const {
selectEntityContext,
@@ -31,8 +30,23 @@ export function createSelection({
// The bridge view owns the selection: a click on open water must not
// deselect the vessel the camera is riding.
if (state.cockpitSubjectId) return;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: a card of ours acts whatever is drawn
// under it; another layer's is that layer's click.
const top = services.picking.clickCard?.(event) ?? null;
if (top) {
if (top.sourceId !== VESSEL_OVERLAY_SOURCE_ID) return;
const id = String(top.entryId || '').startsWith('vessel:')
? top.entryId.slice('vessel:'.length)
: null;
const carded = id ? state.records.byId.get(id) || null : null;
// A stale card id is not empty terrain and must not clear a newer
// selection. The next paint will evict its hit rectangle.
if (carded) selectAndFocusVessel(carded);
return;
}
const pickedId = event.id;
let record = pickedId ? state.records.byId.get(pickedId) : null;
const record = pickedId ? state.records.byId.get(pickedId) : null;
// A vessel icon's pick is an item of the layer's icon set, whose id is
// its row id: the record's id, or an unkeyed row's. Removing a row
// removes its item, so an evicted vessel cannot be picked at all; a
@@ -45,76 +59,18 @@ export function createSelection({
// An own-layer row without a live map key is a strict no-op (FB-1
// residual). Trails carry no layer identity and hug their contacts, so any
// `gev-trail:*` pick is also a no-op. Every other non-vessel pick — sibling
// unowned scene picks dismiss the current vessel inspection.
// `gev-trail:*` pick is also a no-op. A pick a sibling layer owns (an
// aircraft, a route, a cyclone) is that layer's: preserve the current
// vessel selection and do not compete with its camera command. Every
// other non-vessel pick dismisses the current vessel inspection.
if (ownRecordPick && (!pickedId || !record)) return;
/** Whether this layer's own card is painted under the click. */
const ownCardUnder = () =>
vesselState._vesselOverlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
)?.sourceId === VESSEL_OVERLAY_SOURCE_ID;
// A passive owner's pick (a trail, a directions route) acts for nobody:
// a card of ours painted over it keeps the click; otherwise a no-op.
const passivePick =
Boolean(pickedId) &&
!record &&
(String(pickedId).startsWith('gev-trail:') ||
(Boolean(isActedOnByOtherLayer) &&
isOwnedByOtherLayer('ais-live-vessels', pickedId) &&
!isActedOnByOtherLayer('ais-live-vessels', pickedId, {
click: event,
})));
if (passivePick && !ownCardUnder()) return;
// A sibling layer already owns this click. Preserve the current vessel
// selection and do not compete with its camera command.
const siblingOwned =
!passivePick &&
pickedId &&
isOwnedByOtherLayer('ais-live-vessels', pickedId);
// Cyclone geometry is ambient context behind painted cards. Its handler
// yields to the same foreground AIS hit. Keep moving-contact precedence
// unchanged: those handlers may issue their own camera command.
const cycloneBackground =
siblingOwned && !isOwnedByOtherLayer('weather-cyclones', pickedId);
if (siblingOwned && !cycloneBackground) {
// A coarse tap's nearby contact (not the exact pick) whose layer acts
// only on exact hits (a fire, a camera) does not take a tap on this
// layer's own card: that card keeps it.
const nearMissOfExactOnly =
isActedOnByOtherLayer &&
resolvePickId?.(event.topHit ?? null) !== pickedId &&
!isActedOnByOtherLayer('ais-live-vessels', pickedId, {
expanded: true,
click: event,
});
if (!nearMissOfExactOnly || !ownCardUnder()) return;
}
// Cards are painted on a pointer-events:none canvas, so the scene pick is
// usually terrain behind the card. Resolve against the host's current
// actionable hit rectangles before treating the click as empty space.
const cardHit = !record
? vesselState._vesselOverlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
)
: null;
if (
(cardHit && cardHit.sourceId !== VESSEL_OVERLAY_SOURCE_ID) ||
(cycloneBackground && !cardHit)
!record &&
pickedId &&
(String(pickedId).startsWith('gev-trail:') ||
isOwnedByOtherLayer('ais-live-vessels', pickedId))
)
return;
if (!record && cardHit) {
const id = String(cardHit.entryId || '').startsWith('vessel:')
? cardHit.entryId.slice('vessel:'.length)
: null;
record = id ? state.records.byId.get(id) || null : null;
// A stale card id is not empty terrain and must not clear a newer
// selection. The next paint will evict its hit rectangle.
if (!record) return;
}
if (record) {
// A valid sprite or card click always transfers the camera exactly once,
@@ -221,6 +221,8 @@ function harness(
unregisterPickOwner: (id) => owners.delete(id),
resolvePickId: (pick) => pick?.id ?? pick?.primitive?.id,
isOwnedByOtherLayer: (_layerId, id) => id?.startsWith('other:'),
// The card on top at a click, as the registry answers from the host.
clickCard: () => cardHit,
},
sprites: { spriteDrawOrder: () => -9 },
render: { governorRequestRender: (reason) => renders.push(reason) },
+7 -8
View File
@@ -482,12 +482,13 @@ export function createSelection({ state, services, parts }) {
state.clickHandler = input.onClick((click) => {
if (!state.enabled || services.pointer?.isPointerFree?.() === false)
return;
const at = click.screenPosition;
// The topmost painted entry decides: our own card or label acts; one
// covered by another layer's card does not.
const hit = overlay?.hitTest?.(at?.x, at?.y);
if (hit && sourceIds.includes(hit.sourceId)) {
hit.entry?.activate?.();
// The card or label painted on top takes the click, read once per
// click so every layer agrees: ours acts whatever is drawn under it;
// another layer's is that layer's click, so the sightings under it do
// not act and the selection stays.
const hit = services.picking?.clickCard?.(click) ?? null;
if (hit) {
if (sourceIds.includes(hit.sourceId)) hit.entry?.activate?.();
return;
}
// A sighting icon's item id is its pick id, `wildlife:<stableId>`.
@@ -509,8 +510,6 @@ export function createSelection({ state, services, parts }) {
services.picking?.isOwnedByOtherLayer?.('wildlife-sightings', id)
)
return;
// Another layer's card on top is that layer's click, not empty map.
if (hit) return;
clearAndRebuild();
});
}
+20 -16
View File
@@ -43,20 +43,17 @@ function fixture(sighting = row, extraServices = {}) {
},
};
bindWildlifeViewer(state.viewer);
const overlayHost = {
setEntries: (id, value) => entries.set(id, value),
clearSource: (id) => entries.delete(id),
setVisible() {},
hitTest: (_x, _y, { sourceId } = {}) =>
sourceId ? (hit?.sourceId === sourceId ? hit : null) : coveringHit || hit,
};
const selection = createSelection({
state,
services: {
overlayHost: {
setEntries: (id, value) => entries.set(id, value),
clearSource: (id) => entries.delete(id),
setVisible() {},
hitTest: (_x, _y, { sourceId } = {}) =>
sourceId
? hit?.sourceId === sourceId
? hit
: null
: coveringHit || hit,
},
overlayHost,
now: () => row.observedAt + 60_000,
project: (_scene, anchor) => {
projections++;
@@ -71,6 +68,12 @@ function fixture(sighting = row, extraServices = {}) {
}),
eventTarget: new EventTarget(),
...extraServices,
// The card on top at a click, as the registry answers from the host.
picking: {
clickCard: (c) =>
overlayHost.hitTest(c.screenPosition?.x, c.screenPosition?.y),
...extraServices.picking,
},
},
parts: {
rendering: {
@@ -187,7 +190,7 @@ test('selected photo and name cards use the selected lane, select on click and n
}
});
test('a covered sighting label yields; the top label acts over trails and other scene items', () => {
test('a covered sighting label and icon yield; the top label acts over trails and other scene items', () => {
const f = fixture(row, {
// Registered owners, as the app has them: an aircraft, and the flight
// trails every layer reads as a no-op (src/data/trailRenderer.js).
@@ -205,15 +208,16 @@ test('a covered sighting label yields; the top label acts over trails and other
f.click(null);
assert.equal(f.flights.length, 1);
assert.equal(f.state.selectedRow, row);
// A sighting icon under another layer's card is that card's click too.
f.click();
assert.equal(f.flights.length, 2, 'an actual sighting remains selectable');
assert.equal(f.flights.length, 1, 'a covered sighting does not act');
f.cover(null);
// The top label acts over a flight trail: never a dead click.
f.click('gev-trail:fl-a1b2c3:head');
assert.equal(f.flights.length, 3, 'the label acts over a flight trail');
// And over another layer's scene item, as on main.
assert.equal(f.flights.length, 2, 'the label acts over a flight trail');
// And over another layer's scene item.
f.click('other:aircraft');
assert.equal(f.flights.length, 4, 'the top label acts');
assert.equal(f.flights.length, 3, 'the top label acts');
assert.equal(f.state.selectedRow, row);
f.selection.remove();
});
+4
View File
@@ -1,4 +1,5 @@
import { WORLD_OVERLAY_OCCLUDER_SELECTORS } from './worldOverlayChrome.js';
import { setClickCardHitTest } from '../data/pickRegistry.js';
export { WORLD_OVERLAY_OCCLUDER_SELECTORS } from './worldOverlayChrome.js';
import {
createCyberSonarSampler,
@@ -2869,6 +2870,8 @@ export function initWorldOverlay(viewer) {
};
window.addEventListener('gev:cockpit-mode-changed', _cockpitModeHandler);
_removePostRender = frame.on('postRender', () => drawWorldOverlay());
// Click handlers read the card painted on top through the pick registry.
setClickCardHitTest(hitTestWorldOverlay);
_removeMoveEnd = camera.on('moveEnd', () => invalidateHost());
installUiOccluderObservers();
// The backing store and the occluder inventory are both deferred to the
@@ -2954,6 +2957,7 @@ export function destroyWorldOverlay() {
_paintCount = 0;
_paintRectCount = 0;
_hitRectCount = 0;
setClickCardHitTest(null);
_uiOcclusionRects.length = 0;
_uiOcclusionRectPool.length = 0;
_destroyed = hadHost || _destroyed;
+4
View File
@@ -1,6 +1,7 @@
import { nextTick } from 'vue';
import { isPointerFree } from '../data/inputOwnership.js';
import { inputFor } from '../input/dispatcher.js';
import { isUnderOtherCard } from '../data/pickRegistry.js';
import { createInteractionSession } from '../director/interactions/session.js';
import { t } from '../i18n/index.js';
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
@@ -119,6 +120,9 @@ export function createSceneInteractions(
session.activate(items);
unsubscribeClick = inputFor(viewer).onClick((event) => {
if (panel?.owner !== owner || !shown() || !available()) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// A pack feature is its draw set's item (see dataPacks/presentation.js).
const hit = event.drawHit;
if (!hit) return;
+38
View File
@@ -10,6 +10,8 @@ import { createPinia } from 'pinia';
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
import SceneInteractions from '../ui/views/panels/SceneInteractions.vue';
import { createSceneInteractions } from './interactions.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { setClickCardHitTest } from '../data/pickRegistry.js';
const target = (featureId) => ({ packId: 'qa', featureId });
const key = (featureId) => JSON.stringify(['qa', featureId]);
@@ -192,3 +194,39 @@ test("an earlier owner leaves a later owner's panel alone", async (t) => {
await settle();
assert.equal(later.getState().selected, 'fly');
});
// The card or label painted on top takes the click: a pack feature under
// another layer's card is not selected for its actions.
test("another layer's card over a pack feature keeps the click", async (t) => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const canvas = container.appendChild(document.createElement('canvas'));
const pinia = createPinia();
const app = createApp(SceneInteractions).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
let picked = null;
const viewer = { container, scene: { canvas, pick: () => picked } };
const input = fakeInput(viewer);
const store = useSceneInteractionsStore(pinia);
const interactions = createSceneInteractions(viewer, {
execute: async () => true,
store,
});
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => {
setClickCardHitTest(null);
interactions.destroy();
input.destroy();
app.unmount();
});
const feature = { set: 'qa:points', id: 'point' };
interactions.activate(SHOT, new Map([[key('point'), feature]]));
await nextTick();
picked = { id: feature, primitive: {} };
input.tap({ x: 10, y: 10 });
assert.deepEqual(store.panel?.outlined ?? [], [], 'covered: not selected');
top = null;
input.tap({ x: 10, y: 10 });
assert.deepEqual(store.panel.outlined, ['card', 'fly']);
});
-1
View File
@@ -199,7 +199,6 @@ export class StyleManager extends ShellFacade {
pinia: applicationPinia(),
pickWorld: services.pickWorldFromScreen,
regionalBrief: services.fetchRegionalBrief,
overlayHit: services.hitTestWorldOverlay,
});
this.mapStackController = mapStackController;
this.placeSearch = placeSearch;
+7 -1
View File
@@ -10,6 +10,7 @@
*/
import { fromDegrees } from '../geo/ellipsoid.js';
import { inputFor } from '../input/dispatcher.js';
import { isUnderOtherCard } from '../data/pickRegistry.js';
import { findQuery } from '../render/rendererOf.js';
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
@@ -286,7 +287,12 @@ export function routeSceneClick() {
// A viewer with no input (headless tools, partial stubs) has no clicks.
return () => {};
}
return input.onClick((event) => this.onOrbitalClick(event?.position));
return input.onClick((event) => {
// Another layer's card or label painted on top takes the click: the site
// under it does not focus, and the click does not end a held focus.
if (isUnderOtherCard(event)) return;
this.onOrbitalClick(event?.position);
});
}
/**
+18
View File
@@ -30,6 +30,7 @@ import CockpitView from './views/CockpitView.vue';
import ContextView from './views/ContextView.vue';
import IntelHudView from './views/IntelHudView.vue';
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
import { setClickCardHitTest } from '../data/pickRegistry.js';
import { ORBITAL_FOCUS_EASE_TAU_MS } from '../cockpitOrbitalFocus.js';
import { ORBITAL_HOP_MS } from '../cockpitOrbitalSatellites.js';
@@ -635,6 +636,23 @@ test('a click a tool owns is left alone', async (t) => {
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'kept while drawing');
});
// The card or label painted on top takes the click: a site under another
// layer's card does not focus, and a click there does not end a held focus.
test('another layer\'s card over the orbital view keeps the click', async (t) => {
const scene = await inOrbit(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
scene.click(SITES.alpha.at);
assert.equal(scene.cockpit.orbital.focus ?? null, null, 'covered: no focus');
top = null;
scene.click(SITES.alpha.at);
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
scene.click(EMPTY_GROUND);
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'covered: kept');
});
test('a double-click on a site focuses it and keeps the orbital view', async (t) => {
const scene = await inOrbit(t);
const { cockpit, viewer, handler } = scene;
+8 -18
View File
@@ -1,4 +1,5 @@
import { cardKeepsClick, resolvePickedContext } from '../data/pickedContext.js';
import { resolvePickedContext } from '../data/pickedContext.js';
import { clickCard } from '../data/pickRegistry.js';
import { followedOf, onFollowChanged } from '../data/followed.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
import { inputFor } from '../input/dispatcher.js';
@@ -45,8 +46,6 @@ const FOLLOWABLE = new Set(['flights', 'military', 'satellites']);
* to the point under the camera without it.
* @param {(lat: number, lon: number) => Promise<object>} [options.regionalBrief]
* The app's regional brief service, for the weather and news Context shows.
* @param {(x: number, y: number) => object|null} [options.overlayHit]
* The overlay card under a screen point, if any (a vessel's, a fire's).
* @returns {() => void} disconnects
*/
export function installEntityContext({
@@ -55,7 +54,6 @@ export function installEntityContext({
pinia,
pickWorld,
regionalBrief,
overlayHit,
}) {
const store = useEntityCardStore(pinia);
const omnibar = useOmnibarStore(pinia);
@@ -311,16 +309,14 @@ export function installEntityContext({
// Cockpit has its own picks, and Context is hidden while it runs. A
// camera drag never selects, even if it ends over something.
if (inCockpit() || !isTrackingSelectionGesture(event.gesture)) return;
// A card or label painted on top is its layer's click, read once per
// click so every layer agrees: Context names nothing under it and keeps
// its own card as it is.
if (clickCard(event)) return;
const identity = resolvePickedContext(event.hit, {
dataManager: getDataManager(),
});
if (identity) {
// A card or label painted over an item its layer does not act on here
// (a quake card beside a fire, or over a route) is the card's click.
const underCard = Boolean(
overlayHit?.(event.screenPosition?.x, event.screenPosition?.y),
);
if (cardKeepsClick(event, underCard)) return;
// These layers start following on their own click; following again
// from here would fight them (the flights layer reads a second track
// of the same plane as a click on empty map and lets go).
@@ -330,14 +326,8 @@ export function installEntityContext({
// A click on open ground, sea or sky lets go of what was selected. A
// click on something else Context cannot describe (a label, a trail)
// leaves the card as it is.
// Only a clean click lets go, as the layers' own clicks do; a card
// painted on the overlay (a vessel's, a fire's) is not open map.
if (
event.surface &&
isTrackingClickGesture(event.gesture) &&
!overlayHit?.(event.screenPosition?.x, event.screenPosition?.y)
)
store.clear();
// Only a clean click lets go, as the layers' own clicks do.
if (event.surface && isTrackingClickGesture(event.gesture)) store.clear();
});
// Layers that select through the context store (GeoJSON sites, fires,
+38 -54
View File
@@ -6,14 +6,14 @@ import { useEntityCardStore } from './stores/entityCard.js';
import { fakeInput } from '../input/testDoubles.mjs';
import {
registerPickOwner,
setClickCardHitTest,
unregisterPickOwner,
} from '../data/pickRegistry.js';
// A coarse tap that misses everything exactly finds a fire within the shared
// touch window. On open map Context names it; under a quake card or label the
// card takes the tap, since the fire layer acts only on exact hits; an exact
// hit on the fire is the fire's, under a card or not.
test('Context leaves a near-missed exact-only item to a card painted over it', (t) => {
// The card or label painted on top takes the click: Context names nothing
// under it, exact or nearby, an acting owner's item or a passive one, and
// keeps its own card. On open map it names what the click found.
test('Context names nothing under a card painted on top, and keeps its card', (t) => {
const previous = globalThis.matchMedia;
globalThis.matchMedia = () => ({ matches: true });
t.after(() => {
@@ -21,17 +21,31 @@ test('Context leaves a near-missed exact-only item to a card painted over it', (
else delete globalThis.matchMedia;
});
const fire = { set: 'test-fires:1', id: 'fire:1' };
const plane = { set: 'test-planes:1', id: 'plane:1' };
const route = { set: 'test-route:1', id: 'route:line' };
registerPickOwner('test-fires', (id) => id === fire.id);
t.after(() => unregisterPickOwner('test-fires'));
let exact = false;
registerPickOwner('test-planes', (id) => id === plane.id);
registerPickOwner('test-route', (id) => id.startsWith('route:'));
let cardOnTop = false;
// The card on top at a click, as the host answers the pick registry.
setClickCardHitTest(() =>
cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
);
t.after(() => {
setClickCardHitTest(null);
unregisterPickOwner('test-fires');
unregisterPickOwner('test-planes');
unregisterPickOwner('test-route');
});
let exact = null;
let near = null;
const viewer = {
scene: {
pick: () => (exact ? { id: fire } : null),
drillPick: () => [{ id: fire }],
pick: () => (exact ? { id: exact } : null),
drillPick: () => (near ? [{ id: near }] : []),
},
};
const input = fakeInput(viewer);
let cardOnTop = false;
const pinia = createPinia();
const disconnect = installEntityContext({
viewer,
@@ -41,8 +55,6 @@ test('Context leaves a near-missed exact-only item to a card painted over it', (
getAll: () => [],
}),
pinia,
overlayHit: () =>
cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
});
t.after(() => {
disconnect();
@@ -50,52 +62,24 @@ test('Context leaves a near-missed exact-only item to a card painted over it', (
});
const store = useEntityCardStore(pinia);
const named = [];
let clears = 0;
store.select = (identity) => named.push(identity.id);
const tap = () => {
store.clear = () => clears++;
const tap = (hitExact, hitNear) => {
exact = hitExact;
near = hitNear;
named.length = 0;
input.click();
return [...named];
};
assert.deepEqual(tap(), ['fire:1'], 'open map: Context names the fire');
assert.deepEqual(tap(null, fire), ['fire:1'], 'open map: a near fire');
assert.deepEqual(tap(route, null), ['route:line'], 'open map: a route');
cardOnTop = true;
assert.deepEqual(tap(), [], 'under a card: the card keeps the tap');
exact = true;
assert.deepEqual(tap(), ['fire:1'], 'an exact hit is the fire’s');
});
// Every card layer acts over a passive owner's pick (a directions route), so
// Context leaves an exact route hit under a card to that card, and names it on
// open map as before.
test('Context leaves an exact passive route under a card to the card', (t) => {
const route = { set: 'test-route:1', id: 'route:line' };
registerPickOwner('test-route', (id) => id.startsWith('route:'), {
passive: true,
});
t.after(() => unregisterPickOwner('test-route'));
const viewer = { scene: { pick: () => ({ id: route }) } };
const input = fakeInput(viewer);
let cardOnTop = false;
const pinia = createPinia();
const disconnect = installEntityContext({
viewer,
getDataManager: () => ({
isEnabled: () => true,
layers: new Map(),
getAll: () => [],
}),
pinia,
overlayHit: () =>
cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
});
t.after(() => {
disconnect();
input.destroy();
});
const named = [];
useEntityCardStore(pinia).select = (identity) => named.push(identity.id);
input.click();
assert.deepEqual(named, ['route:line'], 'open map: Context names the route');
cardOnTop = true;
input.click();
assert.deepEqual(named, ['route:line'], 'under a card: the card keeps it');
assert.deepEqual(tap(null, fire), [], 'under a card: a near fire');
assert.deepEqual(tap(fire, fire), [], 'under a card: an exact fire');
assert.deepEqual(tap(plane, plane), [], 'under a card: an aircraft');
assert.deepEqual(tap(route, null), [], 'under a card: a route');
const cleared = clears;
tap(null, null);
assert.equal(clears, cleared, 'a card over open map is not open map');
});
+2
View File
@@ -140,6 +140,8 @@ function fixture(
},
}),
focus: { requestWorldFocus: (value) => flights.push(value) },
// The card on top at a click, as the registry answers from the host.
picking: { clickCard: () => hit },
},
parts: {
rendering: { refreshSelection() {}, requestRender() {} },
-1
View File
@@ -194,7 +194,6 @@ test('cyclones flatten the storm position and stay empty while off', async () =>
ownsPickId: () => false,
getDiagnostics: () => ({}),
}),
hitTestOverlay: () => null,
});
const viewer = {
scene: { canvas: new EventTarget(), pick: () => null },