fix(input): no double-click follow or zoom on the map

The globe viewer's own double-click tracked a picked entity with a
position or zoomed to one without. Layers moving onto the draw port had it
re-created one by one (data/stockFollow.js); following is a click in GEV,
so the viewer's handler is removed where the viewer is made and every
re-creation goes: earthquakes, cyclones, air quality, news, perimeters,
drone airspace, ghost maps, places, radio, cables, CCTV, ALPR, launches,
bikeshare, Local ADS-B, installations, directions, trails, data packs,
annotations, the library's view and local GeoJSON. The Cockpit's own
double-click and the draw tool's finishing double-click stay.
This commit is contained in:
Sameh Khamis committed 2026-11-14 09:10:14 -08:00
1 parent bb2d22dbce
commit b86014244d
69 files changed
+94 -2797

No files matched your search

+2 -39
View File
@@ -1,11 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { cssColor } from '../../render/color.js';
import { drawOf, findCamera, findInput } from '../../render/rendererOf.js';
import {
drawnItemTarget,
followOnDoubleClick,
} from '../../data/stockFollow.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
import { drawOf, findCamera } from '../../render/rendererOf.js';
import { msg, t, tn } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
@@ -39,11 +34,7 @@ function withAlpha(css, alpha) {
}
/** Own one air-quality display, its refresh lifecycle, and its readout card. */
export function createAirQualityLayer({
source,
overlayHost,
inputFor = defaultInputFor,
} = {}) {
export function createAirQualityLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Air quality requires a snapshot source');
if (!overlayHost) throw new TypeError('Air quality requires an overlay host');
@@ -55,9 +46,6 @@ export function createAirQualityLayer({
let _lastUpdate = null;
let _lastError = null;
let _enabled = false;
// Each drawn station by id, and the follow a double-click on one started.
let _drawn = new Map();
let _stockFollow = null;
let rowControlsListener = null;
const notify = () => rowControlsListener?.();
@@ -80,22 +68,6 @@ export function createAirQualityLayer({
show: false,
});
_viewer = viewer;
// A double-click follows a station, framed to fit its disc, as the
// default renderer followed its entity (a scene that takes no input
// has none).
_stockFollow =
inputFor && findInput(viewer)
? followOnDoubleClick({
viewer,
inputFor,
name: 'air-quality',
enabled: () => _enabled,
targetFor: (hit) =>
hit.set === _markers?.id
? drawnItemTarget(hit.set, _drawn.get(hit.id))
: null,
})
: null;
_readings = [];
_count = 0;
_lastUpdate = null;
@@ -116,7 +88,6 @@ export function createAirQualityLayer({
_request?.abort();
_request = null;
_enabled = false;
_stockFollow?.stop();
if (_markers) _markers.show = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
@@ -199,11 +170,6 @@ export function createAirQualityLayer({
);
}
_markers.set(markers);
_drawn = new Map(markers.map((item) => [item.id, item]));
// A station no longer reported takes its follow with it.
_stockFollow?.retain((key) =>
_drawn.has(key.slice(_markers.id.length + 1)),
);
if (_enabled) {
overlayHost.setEntries(
AIR_QUALITY_OVERLAY_SOURCE_ID,
@@ -221,9 +187,6 @@ export function createAirQualityLayer({
_request?.abort();
_request = null;
_enabled = false;
_stockFollow?.destroy();
_stockFollow = null;
_drawn = new Map();
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
_markers?.dispose();
-32
View File
@@ -322,35 +322,3 @@ test('a failed refresh over good readings reports degraded, not nominal', async
'showing old data after a failure is degraded',
);
});
test('a double-click follows a station until it is no longer reported, as its entity was', async (t) => {
const { bindRenderer } = await import('../../render/rendererOf.js');
const { createStubRenderer } = await import('../../render/stub/index.js');
const renderer = createStubRenderer();
const viewer = { isDestroyed: () => false };
const unbind = bindRenderer(viewer, renderer);
let rows = [reading('a', 12)];
const layer = createAirQualityLayer({
source: { getSnapshot: async () => rows },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
t.after(() => {
layer.destroy();
unbind();
renderer.destroy();
});
layer.init(viewer);
layer.enable();
await layer.update();
const set = renderer.testing
.sets()
.find((id) => id.startsWith('air-quality'));
renderer.testing.scriptPicks(() => [
{ set, id: 'air-quality:eccc:a', surface: false },
]);
renderer.testing.pointer('dblclick', 10, 10);
assert.ok(renderer.camera.followed, 'the station is followed');
rows = [reading('b', 12)];
await layer.update();
assert.equal(renderer.camera.followed, null, 'gone: not followed');
});
-4
View File
@@ -70,8 +70,6 @@ export function createAlprCamerasLayer({ source, services } = {}) {
postRenderRemove: null,
lastAnchorSampleAt: 0,
clickSubscription: null,
/** The follow a double-click on a camera started, while installed. */
stockFollow: null,
debounceTimer: null,
/** Snapped box of the last successful query; a view still inside it reuses its records. */
lastQueryBox: null,
@@ -346,8 +344,6 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.postRenderRemove = null;
state.clickSubscription?.();
state.clickSubscription = null;
state.stockFollow?.destroy();
state.stockFollow = null;
clearRendered();
state.markers.dispose();
state.credit = null;
-24
View File
@@ -1,6 +1,5 @@
import { isFollowing } from '../../data/followed.js';
import { inputFor } from '../../input/dispatcher.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import {
LAYER_ID,
@@ -323,7 +322,6 @@ export function createAlprPresentation({ state, services, source }) {
visibleRecords = [];
clampedMarkers.clear();
markers.clear();
state.stockFollow?.stop();
removeEntityContextsForLayer(LAYER_ID);
}
@@ -378,8 +376,6 @@ export function createAlprPresentation({ state, services, source }) {
if (!visibleIds.has(carrier.id)) gone.push(carrier.id);
if (gone.length) {
markers.remove(gone);
// A camera no longer shown takes its follow with it.
state.stockFollow?.retain((key) => Boolean(markers.get(key)));
for (const id of gone) clampedMarkers.delete(id);
changed = true;
}
@@ -598,26 +594,6 @@ export function createAlprPresentation({ state, services, source }) {
selectRecord(id);
else if (state.selectedId) clearSelection();
});
// A double-click follows a camera, its card shown, as the default
// renderer followed its entity.
state.stockFollow = followOnDoubleClick({
viewer,
inputFor,
name: LAYER_ID,
enabled: () => state.enabled,
targetFor: (hit) => {
const carrier = hit.set === markers.icons?.id && markers.get(hit.id);
if (!carrier) return null;
return {
key: carrier.id,
position: () => {
const at = alprIconPosition(carrier);
return at ? { ...at } : null;
},
entity: carrier,
};
},
});
}
return {
initOverlay: () => overlay.init(),
+1 -24
View File
@@ -1,6 +1,5 @@
import { t } from '../../i18n/index.js';
import { inputFor } from '../../input/dispatcher.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
@@ -102,8 +101,6 @@ export function createSelection({
if (record?.position)
layerState._stationSet?.upsert([parts.rendering.stationItem(record)]);
if (layerState._selectedSet?.size()) layerState._selectedSet.clear();
// Removing the highlight entity ended the default renderer's follow of it.
layerState._stockFollow?.stop();
layerState._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID);
}
@@ -145,7 +142,7 @@ export function createSelection({
function _installClickHandler(viewer) {
if (layerState._clickSubscription) return;
const clickOff = inputFor(viewer).onClick((event) => {
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
const hit = event.drawHit;
if (hit) {
@@ -165,26 +162,6 @@ export function createSelection({
// Clicked anything else — deselect.
if (layerState._selectedKey) _clearSelection();
});
// A double-click follows the selected station's highlight, as the
// default renderer followed the point entity it was (the station dots
// were point primitives, which it never followed).
layerState._stockFollow = followOnDoubleClick({
viewer,
inputFor,
name: 'bikeshare',
enabled: () => layerState._enabled,
targetFor: (hit) => {
const key = layerState._selectedKey;
const position = layerState._stationRenderMap.get(key)?.position;
if (hit.set !== layerState._selectedSet?.id || !position) return null;
return { key, position: () => ({ ...position }) };
},
});
layerState._clickSubscription = () => {
clickOff?.();
layerState._stockFollow?.destroy();
layerState._stockFollow = null;
};
document.addEventListener('keydown', _onKeyDown);
}
-72
View File
@@ -1,72 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
import { bindFakeGroundRenderer } from '../../testSupport/fakeGroundRenderer.mjs';
import { fromDegrees } from '../../geo/ellipsoid.js';
test('a double-click follows the selected station, as its highlight entity was; deselecting ends it', (t) => {
const viewer = {};
const fake = bindFakeGroundRenderer(viewer);
t.after(fake.unbind);
const listeners = {};
fake.renderer.input = {
on(type, fn) {
listeners[type] = fn;
return () => delete listeners[type];
},
behaviours: { dblclickFollow: { enabled: true } },
};
const press = (type) =>
listeners[type]({
button: 0,
modifiers: { shift: false, ctrl: false, alt: false, meta: false },
position: { x: 5, y: 5 },
});
const position = fromDegrees(2, 41, 20);
const state = {
_enabled: true,
_selectedKey: null,
_stationRenderMap: new Map([['bcn:1', { position, stationId: '1' }]]),
_stationSet: fake.renderer.draw.points({ id: 'bikeshare:stations' }),
_selectedSet: fake.renderer.draw.points({ id: 'bikeshare:selected' }),
_overlayHost: { setEntries() {}, clearSource() {} },
_clickSubscription: null,
};
const selection = createSelection({
state,
services: {},
parts: {
rendering: { stationItem: (r) => ({ id: 'bcn:1', pos: r.position }) },
},
source: {},
});
const priorDocument = globalThis.document;
globalThis.document = { addEventListener() {}, removeEventListener() {} };
t.after(() => {
if (priorDocument === undefined) delete globalThis.document;
else globalThis.document = priorDocument;
});
selection._installClickHandler(viewer);
// A station dot itself (a point primitive before) is never followed.
fake.setPick(() => ({ set: 'bikeshare:stations', id: 'bcn:1' }));
press('dblclick');
assert.equal(fake.follows.length, 0);
// Its first click selects it; the double-click lands on the highlight.
press('click');
assert.equal(state._selectedKey, 'bcn:1');
fake.setPick(() => ({ set: 'bikeshare:selected', id: 'selected' }));
press('dblclick');
assert.equal(fake.follows.length, 1);
assert.deepEqual(fake.renderer.camera.followed.position(), { ...position });
selection._clearSelection();
assert.equal(fake.renderer.camera.followed, null, 'the highlight went');
// Disabled: a double-click on it follows nothing.
state._clickSubscription();
selection._selectStation('bcn:1');
press('dblclick');
assert.equal(fake.follows.length, 2, 'only the stop since');
});
+2 -55
View File
@@ -17,8 +17,6 @@
* Meshes and quads are capabilities: on a renderer without them there are
* no viewshed volumes or monitor plane, and the lines still draw.
*/
import { positionToEcef } from '../../geo/ellipsoid.js';
import { drawnItemTarget } from '../../data/stockFollow.js';
import { drawOf } from '../../render/rendererOf.js';
/** Layer instances, for set ids unique to each. */
@@ -93,9 +91,6 @@ export function createDrawSets({ state: layerState }) {
plane: draw.quads?.({ id: `cctv:${n}:plane` }) ?? null,
// What each line item was last written as, by id.
lineKeys: new Map(),
// Each line and plane item as last written, by id.
lineItems: new Map(),
planeItems: new Map(),
};
return current;
}
@@ -107,7 +102,6 @@ export function createDrawSets({ state: layerState }) {
/** Let the sets go (the layer leaves its viewer, or moves to another). */
function dispose() {
if (!current) return;
layerState._stockFollow?.stop();
for (const set of [current.coverage, current.viewshed, current.plane])
try {
set?.dispose();
@@ -145,7 +139,6 @@ export function createDrawSets({ state: layerState }) {
const key = lineKey(item);
if (s.lineKeys.get(item.id) === key) continue;
s.lineKeys.set(item.id, key);
s.lineItems.set(item.id, item);
changed.push(item);
}
if (changed.length) s.coverage.upsert(changed);
@@ -157,62 +150,17 @@ export function createDrawSets({ state: layerState }) {
if (!s) return;
s.coverage.clear();
s.lineKeys.clear();
s.lineItems.clear();
}
/** Write the plane handle as it is now. */
function writePlane(plane) {
if (!plane?.id) return;
const s = sets();
if (!s?.plane) return;
const item = quadItemOf(plane);
s.planeItems.set(item.id, item);
s.plane.upsert([item]);
sets()?.plane?.upsert([quadItemOf(plane)]);
}
/** Take a plane out. */
function removePlane(plane) {
const s = live();
if (!plane?.id || !s?.plane) return;
s.planeItems.delete(plane.id);
s.plane.remove([plane.id]);
// Removing the plane entity ended the default renderer's follow of it.
layerState._stockFollow?.retain(
(key) => key !== `${s.plane.id}:${plane.id}`,
);
}
/**
* What a double-click on a hit follows or zooms to, as the default
* renderer did for the entities these were: a coverage line (a polyline
* entity) is zoomed to and the monitor plane (a plane entity with a
* position) followed, framed to fit it. Null for anything else.
* @param {{set: string, id: string}} hit
*/
function followTargetFor(hit) {
const s = live();
if (!s) return null;
if (hit.set === s.coverage.id) {
const item = s.lineItems.get(hit.id);
return item && item.show !== false
? drawnItemTarget(hit.set, item)
: null;
}
if (!s.plane || hit.set !== s.plane.id) return null;
const item = s.planeItems.get(hit.id);
if (!item?.center) return null;
const planes = s.planeItems;
const at = positionToEcef(item.center);
const [width, height] = item.size ?? [0, 0];
return {
key: `${hit.set}:${hit.id}`,
// Where the plane is drawn now, as the entity's position was read.
position: () => {
const now = planes.get(hit.id)?.center;
return now ? positionToEcef(now) : null;
},
sphere: { center: at, radius: Math.hypot(width, height) / 2 || 0 },
};
if (plane?.id) live()?.plane?.remove([plane.id]);
}
/** Write a viewshed volume. */
@@ -242,7 +190,6 @@ export function createDrawSets({ state: layerState }) {
removePlane,
writeVolume,
removeVolume,
followTargetFor,
volumeWritesForTest,
};
}
-54
View File
@@ -133,57 +133,3 @@ test('a renderer without meshes or quads still draws the lines', () => {
unbind();
}
});
test('a double-click zooms to a coverage line and follows the plane, as their entities were', () => {
const viewer = {};
const { unbind } = bindFakeDraw(viewer);
const retained = [];
const state = {
_viewer: viewer,
_stockFollow: { retain: (drawn) => retained.push(drawn), stop() {} },
};
const drawSets = createDrawSets({ state });
try {
const a = line('cctv-cam-ray-tl');
drawSets.writeLines([a]);
const plane = {
id: 'cctv-cam-plane',
cameraId: 'cam',
center: { x: 10, y: 0, z: 0 },
orientation: { x: 0, y: 0, z: 0, w: 1 },
size: [6, 8],
show: true,
};
drawSets.writePlane(plane);
const [coverage, planes] = drawSets.pickableSetIds();
const zoom = drawSets.followTargetFor({ set: coverage, id: a.id });
assert.deepEqual(zoom.zoomTo.center, { x: 2.5, y: 3.5, z: 4.5 });
const follow = drawSets.followTargetFor({ set: planes, id: plane.id });
assert.equal(follow.key, `${planes}:${plane.id}`);
assert.deepEqual(follow.position(), { x: 10, y: 0, z: 0 });
assert.equal(follow.sphere.radius, 5, 'framed to fit the plane');
plane.center = { x: 20, y: 0, z: 0 };
drawSets.writePlane(plane);
assert.deepEqual(follow.position(), { x: 20, y: 0, z: 0 }, 'as drawn now');
assert.equal(drawSets.followTargetFor({ set: 'other', id: a.id }), null);
a.show = false;
drawSets.writeLines([a]);
assert.equal(
drawSets.followTargetFor({ set: coverage, id: a.id }),
null,
'a hidden line takes no part',
);
// Taking the plane out ends a follow of it, and only of it.
drawSets.removePlane(plane);
assert.equal(retained.length, 1);
assert.equal(retained[0](follow.key), false);
assert.equal(retained[0]('other:key'), true);
} finally {
drawSets.dispose();
unbind();
}
});
-13
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 { followOnDoubleClick } from '../../data/stockFollow.js';
import {
GROUND_PRIOR_INIT_WAIT_MS,
CALIBRATION_RANGE_FLOOR_M,
@@ -439,21 +438,9 @@ export function createLifecycle({
const unsubscribeHover = input.onPointer('move', (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
);
// A double-click zooms to a coverage line and follows the monitor
// plane, as the default renderer did for their entities (the camera
// icons were billboards, which it never followed).
layerState._stockFollow = followOnDoubleClick({
viewer: layerState._viewer,
inputFor: () => input,
name: 'cctv',
enabled: () => layerState._enabled,
targetFor: (hit) => parts.drawSets.followTargetFor(hit),
});
layerState._clickSubscription = () => {
unsubscribeClick();
unsubscribeHover();
layerState._stockFollow?.destroy();
layerState._stockFollow = null;
};
await parts.health.syncHealthState(true);
+1 -19
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 { followOnDoubleClick } from '../../data/stockFollow.js';
import {
registerPickOwner,
unregisterPickOwner,
@@ -231,20 +230,7 @@ export function createCyclonesLayer({
if (id) layer.setParams({ stormId: id });
else if (!event.topHit) layer.setParams({ clear: true });
});
// A double-click follows a storm's point or zooms to its track or cone,
// as the default renderer did for their entities.
const follow = followOnDoubleClick({
viewer,
inputFor,
name: 'weather-cyclones',
enabled: () => enabled && !destroyed && selectionOwner === owner,
targetFor: (hit) => rendering?.followTargetFor?.(hit) ?? null,
});
owner.follow = follow;
owner.unsubscribe = () => {
unsubscribe();
follow.destroy();
};
owner.unsubscribe = unsubscribe;
}
function removeSelection() {
const owner = selectionOwner;
@@ -313,7 +299,6 @@ export function createCyclonesLayer({
if (next.unavailable) {
// An expired advisory must not remain presented as current hazard context.
rendering.clear();
selectionOwner?.follow?.stop();
snapshot = next;
selectedId = null;
++navigationGeneration;
@@ -333,8 +318,6 @@ export function createCyclonesLayer({
return false;
snapshot = next;
error = null;
// A storm point no longer in the advisory takes its follow with it.
selectionOwner?.follow?.retain((key) => rendering.drawsFollowKey(key));
if (!snapshot.storms.some((storm) => storm.id === selectedId))
select(
selectionIntent === 'cleared'
@@ -352,7 +335,6 @@ export function createCyclonesLayer({
error = cause?.message || ADVISORIES_UNAVAILABLE;
// Failed acquisition has no bounded last-good age guarantee at this layer.
rendering?.clear();
selectionOwner?.follow?.stop();
snapshot = null;
selectedId = null;
++navigationGeneration;
+2 -44
View File
@@ -63,10 +63,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
let centers = new Map(),
forecasts = [],
spheres = new Map(),
itemStorms = new Map(),
// Per drawn item, where a double-click follows it (a point) or what it
// zooms to (a track, cone or outline).
itemPlaces = new Map();
itemStorms = new Map();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
let itemCount = 0;
@@ -102,8 +99,7 @@ export function createCycloneRendering({ viewer, overlayHost }) {
if (destroyed) return false;
const nextCenters = new Map(),
nextSpheres = new Map(),
nextItemStorms = new Map(),
nextItemPlaces = new Map();
nextItemStorms = new Map();
const nextForecasts = [],
nextLines = [],
nextCones = [],
@@ -126,7 +122,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
const center = ecef(at);
const extent = [center];
own(`cyclone:${storm.id}:center`);
nextItemPlaces.set(`cyclone:${storm.id}:center`, { at: center });
nextCenters.set(storm.id, { id: storm.id, at });
const label = {
id: storm.id,
@@ -147,9 +142,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
// Lines take ECEF (draw.d.ts `LineItem`).
const positions = line.map((c) => ecef(pair(c)));
extent.push(...positions);
nextItemPlaces.set(`cyclone:${storm.id}:track:${index}`, {
extent: positions,
});
nextLines.push({
id: own(`cyclone:${storm.id}:track:${index}`),
positions,
@@ -169,9 +161,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextItemPlaces.set(`cyclone:${storm.id}:cone:${index}`, {
extent: ecefRings[0],
});
nextCones.push({
id: own(`cyclone:${storm.id}:cone:${index}`),
geometry: { kind: 'polygon', rings: all },
@@ -179,10 +168,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
height: 'clampGround',
});
ecefRings.forEach((ring, ringIndex) => {
nextItemPlaces.set(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
{ extent: ring },
);
nextLines.push({
id: own(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
@@ -203,9 +188,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
const pos = lonLat(point.position);
const p = ecef(pos);
extent.push(p);
nextItemPlaces.set(`cyclone:${storm.id}:forecast:${index}`, {
at: p,
});
nextForecasts.push({
id: own(`cyclone:${storm.id}:forecast:${index}`),
pos,
@@ -230,7 +212,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
forecasts = nextForecasts;
spheres = nextSpheres;
itemStorms = nextItemStorms;
itemPlaces = nextItemPlaces;
counts = nextCounts;
itemCount = nextItemStorms.size;
committed = true;
@@ -254,28 +235,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
if (!setIds.has(hit.set)) return null;
return itemStorms.get(hit.id) ?? null;
},
/**
* What a double-click on a hit follows or zooms to (`followOnDoubleClick`
* in `data/stockFollow.js`), as the default renderer did for the
* advisory's entities: a center or forecast point is followed, a track,
* cone or outline zoomed to.
*/
followTargetFor(hit) {
if (!committed || !hit || hit.surface || !setIds.has(hit.set))
return null;
const place = itemPlaces.get(hit.id);
if (!place) return null;
if (place.extent) return { zoomTo: sphereFromPoints(place.extent) };
const at = place.at;
return { key: `${hit.set}:${hit.id}`, position: () => ({ ...at }) };
},
/** Whether the item a follow's key (`<set>:<item>`) names is drawn now. */
drawsFollowKey(key) {
for (const set of setIds)
if (key.startsWith(`${set}:`))
return committed && itemPlaces.has(key.slice(set.length + 1));
return false;
},
getFocusSphere(id) {
return spheres.get(id) || null;
},
@@ -291,7 +250,6 @@ export function createCycloneRendering({ viewer, overlayHost }) {
forecasts = [];
spheres = new Map();
itemStorms = new Map();
itemPlaces = new Map();
itemCount = 0;
selected = null;
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
-40
View File
@@ -451,43 +451,3 @@ test('labels publish committed anchors to the shared overlay and follow selectio
h.rendering.destroy();
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
});
test('a double-click follows a storm’s points and zooms to its tracks and cones, as their entities did', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
for (const id of h.sets.points.items.keys()) {
const target = h.rendering.followTargetFor(h.hit('points', id));
assert.ok(target?.position, `${id} is followed`);
assert.equal(target.key, `${h.sets.points.spec.id}:${id}`);
}
const center = h.rendering
.followTargetFor(h.hit('points', 'cyclone:ep152026:center'))
.position();
const want = fromDegrees(179, 15, 0);
assert.ok(
Math.hypot(center.x - want.x, center.y - want.y, center.z - want.z) < 1e-6,
);
for (const kind of ['lines', 'cones'])
for (const id of h.sets[kind].items.keys()) {
const target = h.rendering.followTargetFor(h.hit(kind, id));
assert.ok(target?.zoomTo?.radius > 0, `${id} is zoomed to`);
}
assert.equal(
h.rendering.followTargetFor({
set: 'other:points',
id: 'cyclone:ep152026:center',
surface: false,
}),
null,
);
const key = `${h.sets.points.spec.id}:cyclone:ep152026:center`;
assert.equal(h.rendering.drawsFollowKey(key), true);
assert.equal(h.rendering.drawsFollowKey(`other:points:x`), false);
h.rendering.clear();
assert.equal(h.rendering.drawsFollowKey(key), false, 'cleared: not drawn');
assert.equal(
h.rendering.followTargetFor(h.hit('points', 'cyclone:ep152026:center')),
null,
);
h.rendering.destroy();
});
-43
View File
@@ -18,8 +18,6 @@
import { roadLabel } from '../../data/routeSteps.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import { hexColor } from '../../render/color.js';
import { drawOf } from '../../render/rendererOf.js';
import {
@@ -1639,31 +1637,6 @@ export function createDirectionsLayer({ services, source }) {
}
}
/** What a double-click on a marker or the route follows or zooms to. */
function followTargetFor(hit) {
if (!_sets) return null;
if (hit.set === _sets.markers.id) {
const point =
hit.id === 'directions:marker:A'
? _a
: hit.id === 'directions:marker:B'
? _b
: null;
if (!point) return null;
return {
key: hit.id,
position: () => fromDegrees(point.lon, point.lat, 0),
};
}
if (hit.set === _sets.route.id && _route?.geometry?.length)
return {
zoomTo: sphereFromPoints(
_route.geometry.map(([lon, lat]) => fromDegrees(lon, lat, 0)),
),
};
return null;
}
function _installClickHandler(viewer) {
if (_clickSubscription) return;
const input = inputFor(viewer);
@@ -1697,25 +1670,9 @@ export function createDirectionsLayer({ services, source }) {
}
if (_selectedStep !== null) _clearStepSelection();
});
// A double-click follows an A or B marker and zooms to the route, as the
// default renderer's double-click did with their entities.
let follow = null;
try {
follow = followOnDoubleClick({
viewer,
inputFor: () => input,
name: 'directions',
enabled: () => _enabled,
targetFor: followTargetFor,
});
} catch {
// A renderer that takes no input has no double-click to follow on.
follow = null;
}
_clickSubscription = () => {
offPlace();
offSelect();
follow?.destroy();
};
if (typeof document !== 'undefined')
document.addEventListener('keydown', _onKeyDown);
+1 -26
View File
@@ -1,9 +1,5 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf, findInput } from '../../render/rendererOf.js';
import {
drawnItemTarget,
followOnDoubleClick,
} from '../../data/stockFollow.js';
import { drawOf } from '../../render/rendererOf.js';
import { cssColor } from '../../render/color.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
import { msg, t } from '../../i18n/index.js';
@@ -81,9 +77,6 @@ export function createDroneAirspaceLayer({
let _lastError = null;
let _stale = false;
let _enabled = false;
// Each drawn area by id, for a double-click to zoom to.
let _areaById = new Map();
let _stockFollow = null;
let _clickSubscription = null;
let _selectedId = null;
let _selectedCardId = null;
@@ -212,19 +205,6 @@ export function createDroneAirspaceLayer({
if (_fills) _fills.show = _lines.show = true;
overlayHost?.setVisible?.(DRONE_AIRSPACE_OVERLAY_SOURCE_ID, true);
installClickHandler();
// A double-click zooms to an area, as the default renderer zoomed to
// its entity (a scene that takes no input has none).
if (!_stockFollow && inputFor && findInput(_viewer))
_stockFollow = followOnDoubleClick({
viewer: _viewer,
inputFor,
name: layer.id,
enabled: () => _enabled,
targetFor: (hit) =>
_setIds?.has(hit.set)
? drawnItemTarget(hit.set, _areaById.get(hit.id))
: null,
});
},
disable() {
@@ -233,8 +213,6 @@ export function createDroneAirspaceLayer({
_enabled = false;
if (_fills) _fills.show = _lines.show = false;
removeClickHandler();
_stockFollow?.destroy();
_stockFollow = null;
clearSelection();
},
@@ -309,7 +287,6 @@ export function createDroneAirspaceLayer({
_fills.set(nextFills);
_lines.set(nextLines);
_areaById = new Map(nextFills.map((item) => [item.id, item]));
_snapshotSignature = signature;
if (_selectedId) publishSelectedCard();
_count = rows.length;
@@ -337,8 +314,6 @@ export function createDroneAirspaceLayer({
_request?.abort();
_request = null;
removeClickHandler();
_stockFollow?.destroy();
_stockFollow = null;
clearSelection();
_rowById.clear();
_snapshotSignature = null;
+2 -45
View File
@@ -1,7 +1,5 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
import { drawOf, findInput } from '../../render/rendererOf.js';
import { drawOf } from '../../render/rendererOf.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
@@ -34,20 +32,13 @@ let instances = 0;
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
*/
export function createEarthquakesLayer({
source,
overlayHost,
inputFor = defaultInputFor,
} = {}) {
export function createEarthquakesLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Earthquakes require a snapshot source');
if (!overlayHost) throw new TypeError('Earthquakes require an overlay host');
let _viewer = null;
let _request = null;
let _discs = null;
// Each drawn disc's centre and radius, for a double-click to follow.
let _discsById = new Map();
let _stockFollow = null;
// What the discs were drawn from, so analyst reads come from the app, not the drawing.
let _events = [];
let _count = 0;
@@ -69,26 +60,6 @@ export function createEarthquakesLayer({
show: false,
});
_viewer = viewer;
// A double-click follows a disc, framed to fit it, as the default
// renderer followed the discs' entities (a scene that takes no input
// has no double-click).
_stockFollow =
findInput(viewer) &&
followOnDoubleClick({
viewer,
inputFor,
name: 'earthquakes',
enabled: () => _enabled,
targetFor: (hit) => {
const disc = hit.set === _discs?.id && _discsById.get(hit.id);
if (!disc) return null;
return {
key: `${hit.set}:${hit.id}`,
position: () => ({ ...disc.center }),
sphere: { center: disc.center, radius: disc.radius },
};
},
});
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -109,7 +80,6 @@ export function createEarthquakesLayer({
_request?.abort();
_request = null;
_enabled = false;
_stockFollow?.stop();
if (_discs) _discs.show = false;
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
@@ -126,7 +96,6 @@ export function createEarthquakesLayer({
return false;
const nextDiscs = [];
const nextById = new Map();
const nextEvents = [];
let count = 0;
const overlayEntries = [];
@@ -150,10 +119,6 @@ export function createEarthquakesLayer({
const position = fromDegrees(lon, lat);
nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat });
nextById.set(`earthquake:${stableId}`, {
center: position,
radius: baseRadius,
});
// A filled disc on the ground, with static axes: re-tessellating
// clamped ground geometry every frame is what once cost 30 fps.
// No outline: clamped to the ground, Cesium never drew one.
@@ -180,11 +145,6 @@ export function createEarthquakesLayer({
}
_discs.set(nextDiscs);
_discsById = nextById;
// A disc no longer reported takes its follow with it.
_stockFollow?.retain((key) =>
_discsById.has(key.slice(_discs.id.length + 1)),
);
_events = nextEvents;
if (_enabled) {
overlayHost.setEntries(
@@ -221,11 +181,8 @@ export function createEarthquakesLayer({
_enabled = false;
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
_stockFollow?.destroy();
_stockFollow = null;
_discs?.dispose();
_discs = null;
_discsById = new Map();
_events = [];
_count = 0;
_lastUpdate = null;
-52
View File
@@ -168,55 +168,3 @@ test('a viewer with nothing to draw with is refused at init, and init can be ret
layer.destroy();
unbind();
});
test('a double-click follows a disc, framed to fit it, as its entity was', async (t) => {
const { bindRenderer } = await import('../../render/rendererOf.js');
const { createStubRenderer } = await import('../../render/stub/index.js');
const { resetPointerOwnership } = await import('../../input/dispatcher.js');
resetPointerOwnership?.();
const renderer = createStubRenderer();
const viewer = { isDestroyed: () => false };
const unbind = bindRenderer(viewer, renderer);
const layer = createEarthquakesLayer({
source: { getSnapshot: async () => rows },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
let rows = [row];
t.after(() => {
layer.destroy(viewer);
unbind();
renderer.destroy();
resetPointerOwnership?.();
});
layer.init(viewer);
layer.enable(viewer);
await layer.update(viewer);
const set = renderer.testing
.sets()
.find((id) => id.startsWith('earthquakes:'));
renderer.testing.scriptPicks(() => [
{ set, id: 'earthquake:event-a', surface: false },
]);
renderer.testing.pointer('dblclick', 10, 10);
const followed = renderer.camera.followed;
assert.ok(followed, 'the disc is followed');
assert.equal(followed.key, `${set}:earthquake:event-a`);
const p = followed.position(0);
const lon = (Math.atan2(p.y, p.x) * 180) / Math.PI;
assert.ok(Math.abs(lon - row.lon) < 1e-9, String(lon));
await layer.update(viewer);
assert.ok(renderer.camera.followed, 'still reported: still followed');
rows = [{ ...row, stableId: 'event-b', usgsId: 'event-b' }];
await layer.update(viewer);
assert.equal(
renderer.camera.followed,
null,
'gone from the feed: not followed',
);
rows = [row];
await layer.update(viewer);
renderer.testing.pointer('dblclick', 10, 10);
assert.ok(renderer.camera.followed);
layer.disable(viewer);
assert.equal(renderer.camera.followed, null, 'hiding the layer stops it');
});
+3 -58
View File
@@ -16,11 +16,7 @@ import {
import { createHorizonCull } from '../streetLevel/view.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { hexColor } from '../../render/color.js';
import { drawOf, findFrame, findInput } from '../../render/rendererOf.js';
import {
drawnItemTarget,
followOnDoubleClick,
} from '../../data/stockFollow.js';
import { drawOf, findFrame } from '../../render/rendererOf.js';
import { readGhostMapsKml } from './kml.js';
import {
fieldLabel,
@@ -201,8 +197,6 @@ export function createGhostMapsLayer({
let _stream = 'closed';
let _queue = Promise.resolve();
let _clickSubscription = null;
/** The follow a double-click on a placemark started, while installed. */
let _stockFollow = null;
let _rowListener = null;
let _selectedKey = null;
let _selectedCardId = null;
@@ -271,10 +265,7 @@ export function createGhostMapsLayer({
for (const [index, feature] of item.features) {
if (!isGhostMapsEventExpired(feature.dateMs, at, _ageDays)) continue;
for (const [kind, ids] of Object.entries(feature.itemIds))
if (ids.length) {
dropFollowOf(item.sets?.[kind], ids);
item.sets?.[kind]?.remove(ids);
}
if (ids.length) item.sets?.[kind]?.remove(ids);
item.features.delete(index);
if (_selectedKey === `${productId}:${index}`) clearSelection();
changed = true;
@@ -287,22 +278,9 @@ export function createGhostMapsLayer({
}
}
/**
* End a double-click's follow of an item that goes (any of `ids`, or the
* whole set), as removing its entity ended the default renderer's.
*/
function dropFollowOf(set, ids = null) {
const key = _stockFollow?.following?.key;
if (!set || !key?.startsWith(`${set.id}:`)) return;
if (!ids || ids.includes(key.slice(set.id.length + 1))) _stockFollow.stop();
}
function disposeSets(sets) {
if (!sets) return;
for (const set of Object.values(sets)) {
dropFollowOf(set);
set.dispose();
}
for (const set of Object.values(sets)) set.dispose();
}
/**
@@ -329,13 +307,6 @@ export function createGhostMapsLayer({
}
for (const pin of next.pins) pin.set = sets.icons;
next.sets = sets;
// Each set's items by id, for a double-click to follow or zoom to.
next.drawn = new Map(
Object.entries(sets).map(([kind, set]) => [
set.id,
new Map(next.items[kind].map((item) => [item.id, item])),
]),
);
}
/** The placemark a hit on one of this layer's items is, or null. */
@@ -765,32 +736,7 @@ export function createGhostMapsLayer({
});
}
/**
* A double-click follows a pin and zooms to a line or an area, as the
* default renderer did for their entities (a scene that takes no input
* has none).
*/
function installFollow() {
if (_stockFollow || !_viewer || !inputFor || !findInput(_viewer)) return;
_stockFollow = followOnDoubleClick({
viewer: _viewer,
inputFor,
name: GHOSTMAPS_LAYER_ID,
enabled: () => _enabled,
targetFor: (hit) => {
const key = hitKey(hit);
const loaded = key && _loaded.get(key.split(':')[0]);
return drawnItemTarget(
hit.set,
loaded?.drawn?.get(hit.set)?.get(hit.id),
);
},
});
}
function removeClickHandler() {
_stockFollow?.destroy();
_stockFollow = null;
_clickSubscription?.();
_clickSubscription = null;
picking?.unregisterPickOwner?.(GHOSTMAPS_LAYER_ID);
@@ -824,7 +770,6 @@ export function createGhostMapsLayer({
for (const item of _loaded.values())
for (const set of Object.values(item.sets ?? {})) set.show = true;
installClickHandler();
installFollow();
if (!_unsubscribe && typeof source.subscribe === 'function')
_unsubscribe = source.subscribe(
(catalog) => {
+3 -40
View File
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createGhostMapsLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
function element(localName, children = [], value = '', attributes = {}) {
@@ -122,26 +121,13 @@ function fixture(
const viewer = {};
// An input port and a query port: a click picks what `click(id)` names.
const listeners = new Set();
const doubleListeners = new Set();
let picked = null;
const camera = fakeCameraPort();
// What the camera follows, as the port's `follow` sets it.
camera.port.followed = null;
camera.port.follow = (target) => (camera.port.followed = target ?? null);
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
input: {
behaviours: { dblclickFollow: { enabled: true } },
on(type, cb) {
const into =
type === 'click'
? listeners
: type === 'dblclick'
? doubleListeners
: null;
if (!into) return () => {};
into.add(cb);
return () => into.delete(cb);
if (type !== 'click') return () => {};
listeners.add(cb);
return () => listeners.delete(cb);
},
},
query: { pick: () => picked },
@@ -165,17 +151,6 @@ function fixture(
modifiers: { shift: false, ctrl: false, alt: false },
});
};
const dblclick = (id) => {
const set = items().get(id);
picked = set ? { set, id, surface: false } : null;
for (const cb of [...doubleListeners])
cb({
type: 'dblclick',
position: { x: 0, y: 0 },
button: 0,
modifiers: { shift: false, ctrl: false, alt: false },
});
};
// The editions drawn: each draws in sets of its own.
const mounted = {
get size() {
@@ -216,8 +191,6 @@ function fixture(
items,
liveSets,
click,
dblclick,
camera: camera.port,
};
}
@@ -669,13 +642,3 @@ test('narrowing to a window the loaded data covers clears a failed wider reload'
assert.equal(layer.getStats().error, null);
assert.equal(layer.getStats().count, 1);
});
test('a double-click follows a pin until its edition goes, as its entity was', async (t) => {
const { layer, viewer, dblclick, camera } = fixture(t);
await layer.update(viewer);
dblclick('ghostmaps:cip:0:0');
assert.ok(camera.followed, 'the pin is followed');
assert.match(camera.followed.key, /:icons:ghostmaps:cip:0:0$/);
layer.disable();
assert.equal(camera.followed, null, 'its edition gone, so is the follow');
});
+4 -114
View File
@@ -1,18 +1,9 @@
import { installationClassLabel, installationTitle } from './classLabel.js';
import { t } from '../../i18n/index.js';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { entityFollowTarget } from '../../data/followed.js';
import { entityRecord } from '../../data/entityRecords.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { followOffsetFitting } from '../../geo/frames.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { heightsOf } from '../../queries/heights.js';
import {
drawOf,
findCamera,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { drawOf, findGlobe } from '../../render/rendererOf.js';
let instances = 0;
@@ -55,10 +46,7 @@ export function createRendering({
return [r, g, b, alpha ?? a];
}
/**
* Make the layer's draw sets, hidden until the layer is enabled, and
* follow a site on a double-click.
*/
/** Make the layer's draw sets, hidden until the layer is enabled. */
function attach(viewer) {
const draw = drawOf(viewer);
selectedDotKey = null;
@@ -72,7 +60,6 @@ export function createRendering({
}
function detach() {
stopFollow();
if (layerState.sets)
for (const set of Object.values(layerState.sets)) set.dispose();
layerState.sets = null;
@@ -82,7 +69,6 @@ export function createRendering({
function setShown(shown) {
if (!layerState.sets) return;
for (const set of Object.values(layerState.sets)) set.show = shown;
if (!shown) stopFollow();
}
/** Whether `setId` is one of this layer's sets. */
@@ -156,7 +142,6 @@ export function createRendering({
function clearRendered() {
clearSelectionFill();
stopFollow();
if (layerState.sets) {
layerState.sets.dots.clear();
layerState.sets.selected.clear();
@@ -252,13 +237,12 @@ export function createRendering({
else sets.selected.clear();
}
/** Stop drawing a record's dot and outlines, and following it. */
/** Stop drawing a record's dot and outlines. */
function removeRecordItems(id, dotIds, outlineIds) {
const rendered = layerState.renderedKeys.get(id);
if (!rendered) return;
dotIds.push(id);
outlineIds.push(...rendered.outlineIds);
if (follow?.recordId === id) stopFollow();
layerState.renderedKeys.delete(id);
}
@@ -444,98 +428,6 @@ export function createRendering({
syncSelectionFill();
}
/** The follow a double-click started, while the camera keeps it. */
let follow = null;
/**
* Follow the site whose dot is under `position`, as the default renderer
* followed the site's entity on a double-click: by the site's display
* position, framed as that renderer framed an entity it started
* following. A double-click on an outline or the selected fill, which had
* no position to follow, zooms to it at once instead.
* @param {{x: number, y: number}} position Canvas pixels.
*/
function followAt(position) {
const viewer = layerState.viewer;
if (!layerState.enabled || !layerState.sets) return;
const query = findQuery(viewer);
const hit = query?.pick(position.x, position.y);
if (!hit || !ownsSet(hit.set)) return;
const camera = findCamera(viewer);
if (!camera) return;
const recordId = hit.meta?.installationId;
const record = layerState.recordById.get(recordId);
if (!record) return;
try {
if (
hit.set !== layerState.sets.dots.id &&
hit.set !== layerState.sets.selected.id
) {
const points = partPoints(record, hit.id);
if (!points.length) return;
// Following nothing then, as that zoom stopped any follow first.
if (camera.followed) camera.follow(null);
camera.flyToBounds(sphereFromPoints(points), { durationS: 0 });
return;
}
const rendered = layerState.renderedKeys.get(recordId);
if (!rendered) return;
const { carrier } = rendered;
const shown = readEntityRecord(carrier)?.displayPosition?.();
if (!shown) return;
// Centred where the dot is drawn, on the surface under it when its
// height is loaded (the cached floor may not be yet), and held there
// as the stock follow held the dot's bounding sphere.
const surface = heightsOf(viewer).now({
lon: record.longitude,
lat: record.latitude,
});
const at = Number.isFinite(surface)
? fromDegrees(record.longitude, record.latitude, surface)
: shown;
const pose = camera.pose?.();
const target = entityFollowTarget(carrier, {
key: `installations:${record.id}`,
position: () => at,
frame: 'enu',
viewFrom: followOffsetFitting({ center: at, radius: 0 }, at, {
fovy: pose?.fovy,
aspectRatio: pose?.aspectRatio,
minDistance: camera.controls?.minDistance,
maxDistance: camera.controls?.maxDistance,
}),
});
camera.follow(target);
follow = { target, recordId };
} catch (error) {
// A camera that cannot follow leaves the view where it is, as a
// viewer without entity tracking did on a double-click.
console.warn(`${LAYER_ID}: cannot follow`, error);
}
}
/** The ground points of a record's outline or fill item `itemId`. */
function partPoints(record, itemId) {
const outline = /:outline:(\d+)$/.exec(itemId);
if (outline) {
const line = outlinesOf(record)[Number(outline[1])] || [];
return line.map(([lon, lat]) => fromDegrees(lon, lat));
}
const fill = /:selected-fill:(\d+)$/.exec(itemId);
if (fill) {
const rings = footprintsOf(record)[Number(fill[1])] || [];
return rings.flat().map(([lon, lat]) => fromDegrees(lon, lat));
}
return [];
}
/** Stop a follow this layer started, if the camera still keeps it. */
function stopFollow() {
const camera = follow && findCamera(layerState.viewer);
if (follow && camera?.followed === follow.target) camera.follow(null);
follow = null;
}
/**
* Second paint for floors that missed the bounded pre-render deadline.
*
@@ -579,8 +471,6 @@ export function createRendering({
detach,
setShown,
ownsSet,
followAt,
stopFollow,
installationSurfaceHeightM,
clearSelectionFill,
syncSelectionFill,
-12
View File
@@ -10,7 +10,6 @@ export function createSelection({
const { clearSelectedEntityContextForLayer } = services.context;
let removeContextListeners = null;
let removeDoubleClick = null;
function syncContextSelection(event) {
if (!layerState.enabled) return;
@@ -72,15 +71,6 @@ export function createSelection({
parts.rendering.renderRecords();
}
});
// Follow a site on a double-click, as the renderer's own double-click
// followed the site's entity.
removeDoubleClick =
input.onPointer?.('dblclick', (event) => {
// The renderer's own double-click follow, off while a tool holds it
// or on a renderer without one.
if (input.stockEnabled?.('dblclickFollow') !== true) return;
parts.rendering.followAt(event.position);
}) ?? null;
}
return {
selectRecord,
@@ -88,8 +78,6 @@ export function createSelection({
destroy() {
removeContextListeners?.();
removeContextListeners = null;
removeDoubleClick?.();
removeDoubleClick = null;
},
};
}
+1 -105
View File
@@ -7,7 +7,6 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { inputFor } from '../../input/dispatcher.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -40,16 +39,6 @@ function harness(t) {
renderedKeys: new Map(),
viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e6) },
// The viewer's stock double-click follow, which the site follow
// stands in for.
screenSpaceEventHandler: {
getInputAction: (type) =>
type === Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
? () => {}
: undefined,
setInputAction() {},
removeInputAction() {},
},
scene: {
globe: { show: false },
canvas: Object.assign(new EventTarget(), {
@@ -62,7 +51,7 @@ function harness(t) {
},
};
let picked;
const { draw, camera, query } = bindFakeCesiumScene(state.viewer);
const { draw } = bindFakeCesiumScene(state.viewer);
const input = fakeInput(state.viewer);
t.mock.method(
Cesium.SceneTransforms,
@@ -124,8 +113,6 @@ function harness(t) {
selection,
assertSelected,
draw,
camera,
query,
input,
parts,
/** Click on what `pick` names, as the scene would pick it. */
@@ -246,94 +233,3 @@ test('a click on a site dot or its outline selects the site; another set does no
h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), false);
});
test('a double-click follows a site dot where it is drawn and zooms to its outline', (t) => {
const h = harness(t);
h.state.records[0].namedArea = false;
h.state.records[0].outlineLines = [
[
[0, 0],
[0.01, 0],
],
];
h.parts.rendering.renderRecords({ claimSelection: true });
h.state.enabled = true;
const follows = [];
const flights = [];
let followed = null;
Object.assign(h.camera, {
follow(target) {
follows.push(target);
followed = target;
},
flyToBounds(sphere, options) {
flights.push({ sphere, options });
},
controls: { minDistance: 1, maxDistance: 1e9 },
});
Object.defineProperty(h.camera, 'followed', { get: () => followed });
let hit = null;
h.query.pick = () => hit;
const dots = h.state.sets.dots;
const dot = h.draw.set(dots.id).items.get('base');
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, 0, 'nothing of the layer under it');
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
const target = follows.at(-1);
assert.equal(target.key, 'installations:base');
assert.equal(target.frame, 'enu');
// The tracked card reads the site through the target's entity.
assert.equal(target.entity, dot.meta);
assert.equal(target.labelModel.title, 'Base');
const at = target.position(0);
assert.ok(Math.abs(at.x - 6378137) < 1e-6 && Math.abs(at.y) < 1e-6);
// 100 m from it, north up, pitched down 45 degrees.
const range = Math.hypot(
target.viewFrom.x,
target.viewFrom.y,
target.viewFrom.z,
);
assert.ok(Math.abs(range - 100) < 1e-6);
assert.ok(Math.abs(target.viewFrom.x) < 1e-9);
assert.ok(Math.abs(target.viewFrom.y + target.viewFrom.z) < 1e-6);
// On the surface under the dot once its height is loaded, before the
// cached floor has it, and held there.
h.query.sampleHeightNow = () => 2400;
h.input.dblclick({ x: 640, y: 400 });
const raised = follows.at(-1).position(0);
assert.ok(Math.abs(raised.x - 6380537) < 1e-6);
h.query.sampleHeightNow = () => null;
h.input.dblclick({ x: 640, y: 400 });
assert.ok(Math.abs(follows.at(-1).position(0).x - 6378137) < 1e-6);
const outlines = h.state.sets.outlines;
hit = {
set: outlines.id,
id: 'base:outline:0',
meta: { installationId: 'base' },
surface: false,
};
h.input.dblclick({ x: 640, y: 400 });
assert.equal(followed, null, 'a zoom stops the follow');
assert.equal(flights.length, 1);
assert.equal(flights[0].options.durationS, 0);
// The follow stops when the layer hides.
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
assert.equal(followed?.key, 'installations:base');
h.parts.rendering.setShown(false);
assert.equal(followed, null);
// Another layer's item under the cursor neither follows nor zooms.
h.parts.rendering.setShown(true);
const before = follows.length;
hit = { set: 'another:1', id: 'base', meta: dot.meta, surface: false };
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, before);
assert.equal(flights.length, 1);
// With the stock double-click follow turned off, nothing follows.
hit = { set: dots.id, id: 'base', meta: dot.meta, surface: false };
const release = inputFor(h.state.viewer).suppressStockClicks();
h.input.dblclick({ x: 640, y: 400 });
assert.equal(follows.length, before);
release();
});
-1
View File
@@ -180,7 +180,6 @@ async function fixture(t) {
addLaunchEntity: noop,
flushLaunchEntities: noop,
clearLaunchEntities: noop,
followTargetFor: () => null,
launchIdFromPicks: () => null,
launchMarkerAt: () => null,
missionHitsAt: () => [],
+2 -6
View File
@@ -137,7 +137,6 @@ async function fixture({ legacySource = false } = {}) {
},
launchIdFromPicks: () => null,
missionHitsAt: () => [],
followTargetFor: () => null,
launchMarkerAt: () => false,
addLaunchEntity(record) {
state._missionSets.items.push(record.id);
@@ -327,11 +326,8 @@ test('destroy followed by actual init starts a clean instance with owned handler
assert.equal(typeof f.state._inputSubscription, 'function');
await f.destroy();
assert.equal(f.state._inputSubscription, null);
assert.equal(
input.subscriberCount(),
before - 3,
'click, hover and double-click follow',
);
assert.equal(input.subscriberCount(), before - 2, 'click and hover');
assert.equal(f.attachedSets(), 0);
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
} finally {
-13
View File
@@ -1,7 +1,6 @@
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import { worldClock } from '../../time/worldClock.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -204,20 +203,9 @@ export function createLifecycle({
launchAt: parts.rendering.launchMarkerAt,
});
const unsubscribeHover = input.onPointer('move', hover.move);
// A double-click follows a mission point, as the default renderer
// followed the missions' entities.
layerState._stockFollow = followOnDoubleClick({
viewer,
inputFor: () => input,
name: 'rocket-launches',
enabled: () => layerState._enabled && parts.rendering.missionsShown(),
targetFor: parts.rendering.followTargetFor,
});
layerState._inputSubscription = () => {
unsubscribeClick();
unsubscribeHover();
layerState._stockFollow?.destroy();
layerState._stockFollow = null;
};
// Apply horizon visibility before the renderer draws and picks.
// A postRender write is one frame late and can remain visibly stale when
@@ -307,7 +295,6 @@ export function createLifecycle({
layerState._cameraReleased = true;
parts.selection.stopMissionZoomAnchor();
parts.rendering.showMissions(false);
layerState._stockFollow?.stop();
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
const canvas = canvasOf(layerState._viewer);
if (canvas) canvas.style.cursor = '';
+1 -40
View File
@@ -1,6 +1,5 @@
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { clamp } from '../../geo/vector.js';
import { hexColor } from '../../render/color.js';
import { drawOf, findCamera, findQuery } from '../../render/rendererOf.js';
@@ -42,18 +41,7 @@ export function createRendering({
let setIds = null;
/** Frames the mission sets have been walked in, the live cache's key. */
let frameNumber = 0;
// The follow reads its target before preRender (once a tick, and again
// in preUpdate while it first frames), so a follow read opens the live
// sample the next preRender keeps: the camera and the marker stand at
// the same instant, and every read until then shares it.
let followSampled = false;
/** Open the live sample a follow read and the next preRender share. */
function openFollowSample() {
if (followSampled) return;
followSampled = true;
frameNumber += 1;
}
/**
* Every drawn mission item by set and id, with what decides whether it
* shows: `isolated` (the mission's selection), and for points and icons
@@ -173,9 +161,6 @@ export function createRendering({
/** Remove every mission item, ahead of a rebuild. */
function clearLaunchEntities() {
// A followed item goes with them, as a removed entity stopped being
// followed.
layerState._stockFollow?.stop();
const sets = layerState._missionSets;
records.clear();
pending.clear();
@@ -194,28 +179,6 @@ export function createRendering({
);
}
/**
* What a double-click on a mission item follows: a point by where it is
* drawn (the payload as it moves), a line zoomed to by its bounds.
*/
function followTargetFor(hit) {
if (!missionHit(hit)) return null;
const name = Object.keys(setIds).find((key) => setIds[key] === hit.set);
const record = records.get(recordKey(name, hit.id));
if (!record) return null;
if (!record.position)
return { zoomTo: sphereFromPoints(record.item.positions) };
const at = record.position;
return {
key: `${setIds.sites}:${hit.id}`,
position: () => {
if (typeof at === 'function') openFollowSample();
const p = typeof at === 'function' ? at() : at;
return p ? copy(p) : null;
},
};
}
/** The launch of the first mission item among a click's drilled hits. */
function launchIdFromPicks(hits) {
for (const hit of hits) {
@@ -287,8 +250,7 @@ export function createRendering({
}
function updateMissionFrame() {
if (followSampled) followSampled = false;
else frameNumber += 1;
frameNumber += 1;
if (!layerState._enabled || !layerState._viewer || !missionsShown()) {
parts.overlays.hideReplayVehicleOverlay();
return;
@@ -841,7 +803,6 @@ export function createRendering({
showMissions,
clearLaunchEntities,
launchIdFromPicks,
followTargetFor,
missionHitsAt,
launchMarkerAt,
selectLaunchEntity,
-3
View File
@@ -35,9 +35,6 @@ export function createState({ services }) {
state._inputSubscription = null;
// The double-click follow of mission points, while initialised.
state._stockFollow = null;
state._viewer = null;
state._declutterHandler = null;
-28
View File
@@ -13,7 +13,6 @@ import {
findQuery,
} from '../../render/rendererOf.js';
import { inputFor } from '../../input/dispatcher.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { routePlausible } from '../../data/routePlausible.js';
import {
@@ -151,8 +150,6 @@ export function createLocalAdsbLayer({
let tickTimer = null;
let syncTimer = null;
let clickSubscription = null;
/** The follow a double-click on a marker started, while installed. */
let stockFollow = null;
let removePreRender = null;
let renderHeld = false;
let selectedId = null;
@@ -571,9 +568,6 @@ export function createLocalAdsbLayer({
if (ringsGone.length) sets.rings.remove(ringsGone);
// Expired aircraft take their 3D models (and pending loads) with them.
if (removed) models?.retain(markers);
// An aircraft that went took the follow a double-click gave it.
const followed = stockFollow?.following;
if (followed && !markers.has(followed.key)) stockFollow.stop();
if (selectedId && !live.has(selectedId))
clearSelection({ evicted: enabled });
removeEntityContextsForLayer(LAYER_ID, { retainIds: live });
@@ -688,26 +682,6 @@ export function createLocalAdsbLayer({
function installInteraction() {
if (clickSubscription || !viewer) return;
// A double-click follows a local aircraft, its card shown, as the
// default renderer followed its entity.
stockFollow = followOnDoubleClick({
viewer,
inputFor,
name: LAYER_ID,
enabled: () => enabled,
targetFor: (hit) => {
const marker =
!hit.surface &&
(hit.set === sets?.markers.id || hit.set === sets?.rings.id) &&
markers.get(hit.id);
if (!marker?.carrier) return null;
return {
key: marker.id,
position: () => (marker.position ? { ...marker.position } : null),
entity: marker.carrier,
};
},
});
clickSubscription = inputFor(viewer).onClick((event) => {
if (!enabled) return;
const target = clickTarget(event);
@@ -728,8 +702,6 @@ export function createLocalAdsbLayer({
}
function releaseInteraction() {
stockFollow?.destroy();
stockFollow = null;
clickSubscription?.();
clickSubscription = null;
}
-36
View File
@@ -1309,42 +1309,6 @@ test('a type change takes its belly offset with the new model, however soon it i
models.destroy();
});
test('a double-click follows a local aircraft with its card, until it goes, as its entity was', async (t) => {
const { bindRenderer } = await import('../../render/rendererOf.js');
const { createStubRenderer } = await import('../../render/stub/index.js');
const { followedOf } = await import('../../data/followed.js');
const renderer = createStubRenderer();
const viewer = { isDestroyed: () => false };
const unbind = bindRenderer(viewer, renderer);
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const { layer } = await enabledLayer(receiver, clock, null, {
viewer: { viewer, draw: renderer.draw },
});
t.after(() => {
layer.destroy();
unbind();
renderer.destroy();
});
receiver.set({ aircraft: [record()] });
await layer.update();
const set = renderer.testing.sets().find((id) => id.endsWith(':markers'));
renderer.testing.scriptPicks(() => [
{ set, id: 'local-adsb:abc123', surface: false },
]);
renderer.testing.pointer('dblclick', 10, 10);
const followed = followedOf(viewer);
assert.ok(followed, 'the aircraft is followed');
assert.equal(followed.key, 'local-adsb:abc123');
assert.ok(followed.entity, 'its entity record shows the tracked card');
assert.equal(typeof followed.displayPosition, 'function');
assert.ok(followed.labelModel?.title, 'with its card');
receiver.set({ aircraft: [] });
clock.now += 10 * 60_000;
await layer.update();
assert.equal(followedOf(viewer), null, 'gone, it is no longer followed');
});
test('a click on a UAT ring selects its aircraft, as the ring was a point on its entity', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const feeds = fakeFeeds();
-51
View File
@@ -1,9 +1,5 @@
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
import {
drawnItemTarget,
followOnDoubleClick,
} from '../../data/stockFollow.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { cssColor } from '../../render/color.js';
import {
@@ -222,15 +218,10 @@ export function createNewsLayer({
if (drawPictureCards !== null && typeof drawPictureCards !== 'function')
throw new TypeError('News picture cards must be a function');
const outlineItems = new Map();
let viewer = null,
// The layer's draw sets (`sets.icons` and the rest), made on init.
sets = null,
clickOff = null,
// The follow a double-click started, and what each set draws now (the
// markers by set, the outlines by id), for it to follow or zoom to.
stockFollow = null,
drawnMarkers = new Map(),
listener = null,
runNavigation = null,
request = null,
@@ -890,19 +881,6 @@ export function createNewsLayer({
horizon.update(cullTargets, { quiet: true });
for (const kind of ['halos', 'points', 'icons', 'boxes'])
sets[kind].set(list[kind]);
// Every marker was drawn anew as an entity: that ended a follow of one.
stockFollow?.retain(
(key) =>
!['halos', 'points', 'icons', 'boxes'].some((kind) =>
key.startsWith(`${sets[kind].id}:`),
),
);
drawnMarkers = new Map(
['halos', 'points', 'icons', 'boxes'].map((kind) => [
sets[kind].id,
new Map(list[kind].map((item) => [item.id, item])),
]),
);
updatePulse();
if (drawPictureCards)
// At every height: zoomed out, a hotspot's reports give way to its
@@ -1048,8 +1026,6 @@ export function createNewsLayer({
for (const [index, area] of disputed.entries())
for (const [k, points] of area.rings.entries())
line(`${pickId}~disputed${index}.${k}`, closed(points), 2, dotted);
for (const item of [...parts.fills, ...parts.borders])
outlineItems.set(item.id, item);
if (parts.fills.length) sets.outlineFills.upsert(parts.fills);
if (parts.borders.length) sets.outlineLines.upsert(parts.borders);
outlineDisputed.set(key, disputed);
@@ -1434,37 +1410,11 @@ export function createNewsLayer({
if (id && isOwnedByOtherLayer(NEWS_LAYER_ID, id)) return;
if (selectedId && !picked?.id) layer.setParams({ clear: true });
});
// A double-click follows a marker and zooms to an outline, as the
// default renderer did for their entities.
stockFollow = followOnDoubleClick({
viewer,
inputFor,
name: NEWS_LAYER_ID,
enabled: () => enabled && !destroyed,
targetFor: followTargetFor,
});
}
function removeSelection() {
clickOff?.();
clickOff = null;
stockFollow?.destroy();
stockFollow = null;
}
/**
* What a double-click on a hit follows or zooms to, as the default
* renderer did for the entity it was: a marker is followed, an outline or
* hotspot box zoomed to; an item not shown takes no part.
*/
function followTargetFor(hit) {
if (!sets || hit.surface) return null;
const item =
drawnMarkers.get(hit.set)?.get(hit.id) ??
(hit.set === sets.outlineFills.id || hit.set === sets.outlineLines.id
? outlineItems.get(hit.id)
: null);
return item && item.show !== false ? drawnItemTarget(hit.set, item) : null;
}
function feedView() {
@@ -1810,7 +1760,6 @@ export function createNewsLayer({
if (sets) for (const set of Object.values(sets)) set.dispose();
sets = null;
outlineParts.clear();
outlineItems.clear();
outlineDisputed.clear();
viewer = null;
listener = null;
-73
View File
@@ -103,10 +103,6 @@ function fixture(
});
cameraPort.port.flyTo = (destination, options = {}) =>
flights.push({ destination, ...options });
// What the camera follows, and where a double-click zooms.
cameraPort.port.followed = null;
cameraPort.port.follow = (target) =>
(cameraPort.port.followed = target ?? null);
const camera = {
setHeight: (next) =>
cameraPort.setPose({
@@ -116,10 +112,8 @@ function fixture(
moveEnd: () => cameraPort.emit('moveEnd'),
};
const viewer = {};
let picked = null;
const { draw, unbind } = bindFakeDraw(viewer, {
camera: cameraPort.port,
query: { pick: () => picked },
frame: { requestRender() {}, on: () => () => {} },
...(quality ? { quality } : {}),
});
@@ -133,23 +127,11 @@ function fixture(
];
// The scene's click dispatcher: `click(hit)` clicks over a drawn item.
const clickHandlers = new Set();
const doubleHandlers = new Set();
const input = {
onClick(fn) {
clickHandlers.add(fn);
return () => clickHandlers.delete(fn);
},
onPointer(type, fn) {
if (type !== 'dblclick') return () => {};
doubleHandlers.add(fn);
return () => doubleHandlers.delete(fn);
},
stockEnabled: (name) => name === 'dblclickFollow',
};
// `dblclick(hit)` double-clicks over a drawn item.
const dblclick = (hit) => {
picked = hit;
for (const fn of [...doubleHandlers]) fn({ position: { x: 10, y: 10 } });
};
const click = (topHit) => {
for (const fn of [...clickHandlers])
@@ -190,13 +172,6 @@ function fixture(
items,
click,
clickHandlers,
dblclick,
cameraPort: cameraPort.port,
/** The id of the layer's live draw set named `part`. */
setId: (part) =>
[...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(`:${part}`),
)?.spec.id,
};
}
@@ -1326,51 +1301,3 @@ test('zoomed out, a hotspot is one beacon; off, nothing draws; destroyed, the se
layer.destroy();
assert.deepEqual(items('points'), []);
});
test('a double-click follows a marker until the markers are drawn anew, and zooms to a hotspot outline', async (t) => {
const { layer, items, dblclick, cameraPort, setId } = fixture(t, {
height: 500_000,
source: {
getOutline: async () => ({
polygons: [
{
outer: [
[30, 45],
[40, 45],
[40, 52],
[30, 52],
],
holes: [],
},
],
borders: [],
disputed: [],
}),
},
});
const zooms = [];
cameraPort.flyToBounds = (sphere) => zooms.push(sphere);
layer.enable();
await layer.update();
await flush();
const marker = [...items('points'), ...items('icons')].find((item) =>
String(item.id).startsWith('news:report:major~'),
);
const set = setId(items('points').includes(marker) ? 'points' : 'icons');
dblclick({ set, id: marker.id, surface: false });
assert.ok(cameraPort.followed, 'the marker is followed');
assert.deepEqual(cameraPort.followed.position(), marker.pos);
// A render draws every marker anew, as the entities were.
await layer.update();
await flush();
assert.equal(cameraPort.followed, null, 'drawn anew: no longer followed');
// Each line a hotspot box or outline draws is zoomed to.
const line = [...items('boxes'), ...items('outline-lines')].find(
(item) => item.show !== false,
);
const part = items('boxes').includes(line) ? 'boxes' : 'outline-lines';
assert.ok(line, 'a box or outline is drawn');
dblclick({ set: setId(part), id: line.id, surface: false });
assert.ok(zooms.at(-1)?.radius > 0, 'it is zoomed to');
assert.equal(cameraPort.followed, null);
});
+1 -33
View File
@@ -1,7 +1,5 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf, findInput } from '../../render/rendererOf.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
import { drawOf } from '../../render/rendererOf.js';
import { msg } from '../../i18n/marker.js';
import { OSM_PLACES_LAYER_ID } from './model.js';
import { createNominatimStatus } from '../../sources/nominatimStatus.js';
@@ -30,7 +28,6 @@ export function createOsmPlacesLayer({
overlayHost,
// The same once-per-page capability probe as Nominatim's, on Overpass.
overpassConfigured = createNominatimStatus({ url: '/api/overpass/status' }),
inputFor = defaultInputFor,
} = {}) {
if (!overlayHost) throw new TypeError('OSM Places requires an overlay host');
let viewer = null;
@@ -42,17 +39,12 @@ export function createOsmPlacesLayer({
let lastUpdate = null;
/** true / false from the server's probe, null while unknown. */
let configured = null;
/** Each drawn place's position, for a double-click to follow. */
let placeAt = new Map();
let stockFollow = null;
function render() {
if (!points) return;
const items = [];
const nextAt = new Map();
const overlay = [];
for (const record of records) {
nextAt.set(`osm-place:${record.id}`, fromDegrees(record.lon, record.lat));
items.push({
id: `osm-place:${record.id}`,
pos: { lon: record.lon, lat: record.lat },
@@ -85,7 +77,6 @@ export function createOsmPlacesLayer({
});
}
points.set(items);
placeAt = nextAt;
if (enabled)
overlayHost.setEntries(OVERLAY_SOURCE_ID, overlay, {
cohortLimit: LABEL_LIMIT,
@@ -125,23 +116,6 @@ export function createOsmPlacesLayer({
show: false,
});
overlayHost.setVisible(OVERLAY_SOURCE_ID, false);
// A double-click follows a place, as the default renderer followed
// the places' entities (a scene that takes no input has none).
stockFollow?.destroy();
stockFollow =
findInput(viewer) &&
followOnDoubleClick({
viewer,
inputFor,
name: OSM_PLACES_LAYER_ID,
enabled: () => enabled,
targetFor: (hit) => {
const at = hit.set === points?.id && placeAt.get(hit.id);
return at
? { key: `${hit.set}:${hit.id}`, position: () => ({ ...at }) }
: null;
},
});
},
enable() {
@@ -154,7 +128,6 @@ export function createOsmPlacesLayer({
disable() {
enabled = false;
stockFollow?.stop();
if (points) points.show = false;
overlayHost.clearSource(OVERLAY_SOURCE_ID);
overlayHost.setVisible(OVERLAY_SOURCE_ID, false);
@@ -170,11 +143,8 @@ export function createOsmPlacesLayer({
enabled = false;
overlayHost.clearSource(OVERLAY_SOURCE_ID);
overlayHost.setVisible(OVERLAY_SOURCE_ID, false);
stockFollow?.destroy();
stockFollow = null;
points?.dispose();
points = null;
placeAt = new Map();
viewer = null;
records = [];
meta = null;
@@ -190,8 +160,6 @@ export function createOsmPlacesLayer({
records = Array.isArray(next) ? next.slice() : [];
meta = nextMeta ? { ...nextMeta } : null;
lastUpdate = Date.now();
// New results replace every place: one followed is gone with them.
stockFollow?.stop();
render();
},
-36
View File
@@ -150,39 +150,3 @@ test('places are depth-tested past close range, so they never show through the g
`depth test off only within ${distance} m`,
);
});
test('a double-click follows a place until new results replace it, as its entity was', async (t) => {
const { bindRenderer } = await import('../../render/rendererOf.js');
const { createStubRenderer } = await import('../../render/stub/index.js');
const renderer = createStubRenderer();
const viewer = { isDestroyed: () => false };
const unbind = bindRenderer(viewer, renderer);
const layer = createOsmPlacesLayer({
overlayHost: fakeOverlayHost(),
overpassConfigured: async () => true,
});
t.after(() => {
layer.destroy();
unbind();
renderer.destroy();
});
layer.init(viewer);
layer.enable();
layer.setResults(RECORDS, { kind: 'hospital', label: 'h', area: 'K' });
const set = renderer.testing.sets().find((id) => id.endsWith(':points'));
renderer.testing.scriptPicks(() => [
{ set, id: 'osm-place:node/1', surface: false },
]);
renderer.testing.pointer('dblclick', 10, 10);
const followed = renderer.camera.followed;
assert.ok(followed, 'the place is followed');
const p = followed.position(0);
const lat = (Math.asin(p.z / Math.hypot(p.x, p.y, p.z)) * 180) / Math.PI;
assert.ok(Math.abs(lat - 27.7) < 0.2, String(lat));
layer.setResults(RECORDS.slice(1), {
kind: 'hospital',
label: 'h',
area: 'K',
});
assert.equal(renderer.camera.followed, null, 'new results end it');
});
+1 -26
View File
@@ -1,9 +1,5 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf, findInput } from '../../render/rendererOf.js';
import {
drawnItemTarget,
followOnDoubleClick,
} from '../../data/stockFollow.js';
import { drawOf } from '../../render/rendererOf.js';
import { hexColor } from '../../render/color.js';
import {
PERIMETER_OVERLAY_SOURCE_ID,
@@ -85,9 +81,6 @@ export function createFirePerimetersLayer({
let _stale = false;
let _lastError = null;
let _enabled = false;
// Each drawn area by id, for a double-click to zoom to.
let _areaById = new Map();
let _stockFollow = null;
let _clickSubscription = null;
let _selectedId = null;
let _selectedLink = null;
@@ -309,19 +302,6 @@ export function createFirePerimetersLayer({
if (_fills) _fills.show = _lines.show = true;
overlayHost?.setVisible?.(PERIMETER_OVERLAY_SOURCE_ID, true);
installClickHandler();
// A double-click zooms to an area, as the default renderer zoomed to
// its entity (a scene that takes no input has none).
if (!_stockFollow && inputFor && findInput(_viewer))
_stockFollow = followOnDoubleClick({
viewer: _viewer,
inputFor,
name: layer.id,
enabled: () => _enabled,
targetFor: (hit) =>
_setIds?.has(hit.set)
? drawnItemTarget(hit.set, _areaById.get(hit.id))
: null,
});
},
disable() {
@@ -330,8 +310,6 @@ export function createFirePerimetersLayer({
_enabled = false;
if (_fills) _fills.show = _lines.show = false;
removeClickHandler();
_stockFollow?.destroy();
_stockFollow = null;
clearSelection();
},
@@ -407,7 +385,6 @@ export function createFirePerimetersLayer({
_fills.set(nextFills);
_lines.set(nextLines);
_areaById = new Map(nextFills.map((item) => [item.id, item]));
_snapshotSignature = signature;
// Refresh (or drop) the selected incident's card against the new feed.
if (_selectedId) publishSelectedCard();
@@ -435,8 +412,6 @@ export function createFirePerimetersLayer({
_request?.abort();
_request = null;
removeClickHandler();
_stockFollow?.destroy();
_stockFollow = null;
clearSelection();
_rowById.clear();
_snapshotSignature = null;
-35
View File
@@ -642,38 +642,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');
});
test('a double-click zooms to a perimeter, as the default renderer zoomed to its entity', async (t) => {
const { bindRenderer } = await import('../../render/rendererOf.js');
const { createStubRenderer } = await import('../../render/stub/index.js');
const renderer = createStubRenderer();
const viewer = { isDestroyed: () => false };
const unbind = bindRenderer(viewer, renderer);
const layer = createFirePerimetersLayer({
source: { getSnapshot: async () => [row] },
});
t.after(() => {
layer.destroy();
unbind();
renderer.destroy();
});
layer.init(viewer);
layer.enable();
await layer.update();
for (const suffix of [':fills', ':lines']) {
const set = renderer.testing.sets().find((id) => id.endsWith(suffix));
renderer.testing.scriptPicks(() => [
{ set, id: `fire-perimeter:${row.stableId}:0`, surface: false },
]);
renderer.camera.setView({
destination: { lon: 0, lat: 0, height: 20_000_000 },
});
renderer.testing.tick();
assert.ok(renderer.camera.pose().height > 1_000_000, 'starts far out');
renderer.testing.pointer('dblclick', 10, 10);
renderer.testing.tick();
const pose = renderer.camera.pose();
assert.equal(renderer.camera.followed, null, 'zoomed to, not followed');
assert.ok(pose.height < 1_000_000, `${suffix}: ${pose.height}`);
}
});
-12
View File
@@ -1,5 +1,4 @@
import { inputFor } from '../../input/dispatcher.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
import {
RADIO_PREFIX,
RADIO_PICK_WINDOW_PX,
@@ -99,15 +98,6 @@ export function createInteraction({
);
}
});
// A double-click follows a station, as the default renderer followed
// its entity.
layerState._stockFollow = followOnDoubleClick({
viewer,
inputFor,
name: 'radio',
enabled: () => radioPresentationAllowed(),
targetFor: (hit) => parts.rendering.followTargetFor(hit),
});
// Polling remains bounded during flights, but a stationary camera no longer
// rewrites every station's visibility four times per second while voice and
// audio processing share the main thread.
@@ -121,8 +111,6 @@ export function createInteraction({
unregisterPickOwner('radio');
layerState._clickSubscription?.();
layerState._clickSubscription = null;
layerState._stockFollow?.destroy();
layerState._stockFollow = null;
if (layerState._horizonTimer) clearInterval(layerState._horizonTimer);
layerState._horizonTimer = null;
}
-33
View File
@@ -529,10 +529,6 @@ export function createRendering({
layerState._selectedId = null;
}
// Every station was drawn anew as an entity: that ended a follow of one.
layerState._stockFollow?.retain(
(key) => !key.startsWith(`${sets?.stations.id}:`),
);
layerState._renderById.clear();
drawnShow.clear();
clusteredIds = new Set();
@@ -575,7 +571,6 @@ export function createRendering({
/** Stop clustering and let the stations' draw sets go. */
function removeDataSource() {
layerState._stockFollow?.stop();
offCameraChanged?.();
offCameraChanged = null;
if (sets) for (const set of Object.values(sets)) set.dispose();
@@ -603,10 +598,6 @@ export function createRendering({
/** Take the selected station's dot and bracket down, if it has them. */
function removeSelectionEntity() {
if (!selection) return;
// The selection's dot was an entity: taking it down ended its follow.
layerState._stockFollow?.retain(
(key) => !key.startsWith(`${sets?.selectedDot.id}:`),
);
selection = null;
sets?.selectedDot.clear();
sets?.selectedBracket.clear();
@@ -622,32 +613,8 @@ export function createRendering({
governorRequestRender('radio-recluster');
}
/**
* What a double-click on a hit follows (`followOnDoubleClick`), as the
* default renderer followed a station's entity or the selected one's: a
* cluster, never an entity, is followed by nothing.
*/
function followTargetFor(hit) {
if (!sets || hit.surface) return null;
let at = null;
let set = hit.set;
if (set === sets.stations.id && hit.id.startsWith(RADIO_PREFIX))
at = layerState._renderById.get(
hit.id.slice(RADIO_PREFIX.length),
)?.position;
else if (
(set === sets.selectedDot.id || set === sets.selectedBracket.id) &&
selection?.dot.id === hit.id
) {
at = selection.position;
set = sets.selectedDot.id;
}
return at ? { key: `${set}:${hit.id}`, position: () => ({ ...at }) } : null;
}
return {
radioStationIdFromPick,
followTargetFor,
installDataSource,
removeDataSource,
setStationsShown,
-23
View File
@@ -139,26 +139,3 @@ test('a filter that hides stations clusters them again at once', async () => {
},
);
});
test('a double-click follows a station, as its entity was', async () => {
const { createStubRenderer } = await import('../../render/stub/index.js');
const renderer = createStubRenderer();
const stations = [station(1, -97.0, 30.0), station(2, -90, 35)];
try {
await withRadioLayer({ stations, renderer }, async () => {
const set = renderer.testing
.sets()
.find((id) => id.endsWith(':stations'));
renderer.testing.scriptPicks(() => [
{ set, id: `radio:${stations[1].id}`, surface: false },
]);
renderer.testing.pointer('dblclick', 10, 10);
const followed = renderer.camera.followed;
assert.ok(followed, 'the station is followed');
const { lon, lat } = toLonLatH(followed.position(0), WGS84);
assert.ok(Math.abs(lon + 90) < 1e-6 && Math.abs(lat - 35) < 1e-6);
});
} finally {
renderer.destroy();
}
});
-2
View File
@@ -119,8 +119,6 @@ export function createState({ services }) {
layerState._playFallbackAttemptId = null;
layerState._clickSubscription = null;
/** The follow a double-click on a station started, while installed. */
layerState._stockFollow = null;
layerState._horizonTimer = null;
-10
View File
@@ -1,6 +1,5 @@
import { toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
import { followOnDoubleClick } from '../../data/stockFollow.js';
export function createInteraction({ state, parts, inputFor }) {
function beginInteraction(viewer) {
@@ -11,15 +10,6 @@ export function createInteraction({ state, parts, inputFor }) {
if (!record?.reference) return;
flyToReference(viewer, record.reference);
});
// A double-click follows a landing point or reference and zooms to a
// cable, as the default renderer did for their entities.
state._stockFollow = followOnDoubleClick({
viewer,
inputFor,
name: 'submarine-cables',
enabled: () => state._enabled,
targetFor: (hit) => parts.rendering.followTargetFor(hit),
});
}
/**
-2
View File
@@ -109,8 +109,6 @@ export function createLifecycle({ state, parts, source, mapStackEventTarget }) {
state._overlayPublisher.hide();
state._clickSubscription?.();
state._clickSubscription = null;
state._stockFollow?.destroy();
state._stockFollow = null;
if (state._preRenderRemover) {
state._preRenderRemover();
state._preRenderRemover = null;
-32
View File
@@ -4,7 +4,6 @@ import { densifyRhumb } from '../../geo/rhumb.js';
import { distance, toRadians } from '../../geo/vector.js';
import { cssColor } from '../../render/color.js';
import { cameraOf, canvasOf, drawOf } from '../../render/rendererOf.js';
import { drawnItemTarget } from '../../data/stockFollow.js';
import {
clampLabel,
createCableOverlayEntry,
@@ -181,9 +180,6 @@ export function createRendering({ state }) {
state._publishScratch.length = 0;
state._loaded = false;
state._referenceSweepGate.reset();
// The sources' entities went with them, and so did a follow of one.
state._stockFollow?.stop();
state._drawnItems = new Map();
if (!state._sets) return;
if (clearSets) for (const set of Object.values(state._sets)) set.clear();
for (const picks of state._picks.values()) picks.clear();
@@ -399,18 +395,6 @@ export function createRendering({ state }) {
map.clear();
for (const [id, info] of picks) map.set(id, info);
}
// Drawn anew, as new sources' entities were: a follow of one ends.
state._stockFollow?.stop();
state._drawnItems = new Map([
[sets.lines.id, new Map(out.lines.map((item) => [item.id, item]))],
[sets.fills.id, new Map(out.fills.map((item) => [item.id, item]))],
[sets.pins.id, new Map(out.pins.map((item) => [item.id, item]))],
// A reference's stem and point were one entity, placed at the tip.
...[sets.stems.id, sets.references.id].map((id) => [
id,
new Map(out.references.map((record) => [record.id, record.point])),
]),
]);
sets.lines.set(out.lines);
sets.fills.set(out.fills);
sets.pins.set(out.pins);
@@ -418,21 +402,6 @@ export function createRendering({ state }) {
sets.references.set(out.references.map((record) => record.point));
}
/**
* What a double-click on a hit follows or zooms to, as the default
* renderer did for the entity it was: a landing point or a reference is
* followed, a cable or area zoomed to.
*/
function followTargetFor(hit) {
if (!hit || hit.surface || !state._setIds.has(hit.set)) return null;
const item = state._drawnItems?.get(hit.set)?.get(hit.id);
if (!item) return null;
// A reference's stem and point follow as one.
const set =
hit.set === state._sets?.stems.id ? state._sets.references.id : hit.set;
return drawnItemTarget(set, item);
}
/** What a pick on one of the layer's sets names, or null. */
function pickInfo(hit) {
if (!hit || !state._setIds.has(hit.set)) return null;
@@ -533,7 +502,6 @@ export function createRendering({ state }) {
applyCableClassification,
drawFeatures,
pickInfo,
followTargetFor,
updateReferenceVisibility,
};
}
-3
View File
@@ -62,9 +62,6 @@ export function createState({ sweepClock, overlayHost }) {
state._referenceRecords = [];
state._clickSubscription = null;
/** The follow a double-click started, and each set's drawn items by id. */
state._stockFollow = null;
state._drawnItems = new Map();
state._preRenderRemover = null;