diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 38d838d0e2..789c158529 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -7495,7 +7495,7 @@ silently demoting every later lookup for the session. protected-card path. Disable tears the tier down completely. Coverage/viewshed semantics unchanged. - **Satellites**: every point moves every frame. Each satellite's SGP4 sample (position, velocity, gravity and its rate of change; `src/layers/satellites/motion.js`) is reckoned forward or back to the world time and turned into the Earth-fixed frame, so points glide at any play speed instead of stepping once a second. Core satellites take a fresh sample every second, or as soon as the world time is 30 s from their sample (fast play, a seek), which keeps every point within about 10 m of SGP4; Starlink extras are sampled round-robin, more per frame the faster time plays, and a point more than two minutes from its sample waits for the next one. Hidden points are not moved until shown. Orbit rings rotate about Earth's Z by ΔGMST every ~1s (exact inertial→ECEF compensation; no SGP4 re-runs); the tracked satellite propagates per frame with one shared epoch for dot/label/camera. Verified: ISS holds <1km perpendicular to its ring while tracked. Pass prediction (`src/data/satellitePass.js`; `getNextSatellitePass`, `getNextIssPass`) scans at 20s, bisects rise/set to ~0.2s, fits the peak with a parabola, and marks a pass visible when the satellite is outside a cylindrical Earth shadow while the observer's Sun is at or below −6°. `next_iss_pass` preserves its geometric-pass ordering and appends visibility metadata. General `next_satellite_pass` accepts a loaded NORAD ID or unambiguous name, searches 24 hours and optionally requires estimated visibility. These estimates do not account for weather or satellite brightness. -- **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer reveals its own right-rail button and roster and enables the required satellite layer; it does not touch Context. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from Data Layers hides its rail button and panel and restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. An explicit user or voice Satellites OFF requested after Space Missions ON exits Space Missions, including after returning from Stories; scene, story, preset and other programmatic Satellites changes do not. The controls under the Space Missions row cycle through available launches. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills the Space Missions panel with details, navigation, and replay controls, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable. Clicking the launch name on the globe selects and focuses the same mission as its dot; what is drawn beneath the name is not picked, and the other layers still hear the click as one on the name, so they close their cards or let go of their selection as for any other click. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, which skips the year check rather than rejecting the match. Speed is the magnitude of the SGP4 inertial velocity vector at the same propagation epoch as position, displayed in km/s with km/h available as hover detail. Unavailable operator, site, launch-time, orbit, current-altitude, and speed values omit their detail rows instead of reserving panel space with placeholders. Newly launched payloads absent from the core operational groups use CelesTrak's cached active TLE feed as a lookup-only fallback; weak constellation-name matches are rejected. The replay callout maps compressed animation progress onto Launch Library's mission-relative timeline, showing the historical UTC date/time at the marker's current path position; unavailable timelines remain explicit. Matched live satellite positions propagate at one-second cadence and use a distinct green dot/callout with the current UTC date/time. +- **Space Missions (30d)**: recent launches render as bounded shared-host, horizon-occluded mission markers using Launch Library 2 v2.3 detailed records. Enabling the layer reveals its own right-rail button and roster and enables the required satellite layer; it does not touch Context. Before applying its temporary dense/hidden Satellite mode, Space Missions snapshots the complete standalone Satellite parameter set and exact enabled-layer set. Disabling Space Missions from Data Layers hides its rail button and panel and restores those parameters and the exact prior enabled state, so a Satellite layer that was already on stays on while a mode-owned dependency returns off; enabling Satellites by itself remains independent. An explicit user or voice Satellites OFF requested after Space Missions ON exits Space Missions, including after returning from Stories; scene, story, preset and other programmatic Satellites changes do not. The controls under the Space Missions row cycle through available launches. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills the Space Missions panel with details, navigation, and replay controls, and animates a small phase-colored marker along the exact displayed Cartesian samples. Marker hit testing drill-picks through photorealistic tiles so the depth-test-free tactical dot remains reliably selectable. Clicking the launch name on the globe selects and focuses the same mission as its dot; what is drawn beneath the name is not picked, and the other layers still hear the click as one on the name, so they close their cards or let go of their selection as for any other click, but never select, turn on, focus or open the link of a contact, card or camera that lies under the name. The selected pad is the camera's zoom pivot: the overview remains centered on its launch site, wheel zoom approaches that site instead of drifting elsewhere, and camera pitch progressively changes from global nadir to an oblique close 3D view. Its protected shared-host callout remains visible and expands to include both mission and launch-site names. `FOCUS` flies directly to a 12 km oblique frame around the selected launch site and retains the same anchored zoom/orbit behavior. `REPLAY ASCENT` resets the selected marker at the pad, frames it from an oblique third-person angle, and follows it through the mission-specific compressed ascent directly into one orbital lap at the default `1×` rate. A live `0.25×`–`4×` slider changes ascent and orbit playback speed; adjusting it mid-replay preserves the current path position and historical mission timestamp. Re-entry/recovery cannot be inserted into replay. At orbit insertion the camera smoothly pulls back over the first fifth of the orbital replay and pitches to a globe-scale nadir view while continuing to target the moving replay point. Replay Cancel, mission navigation, deselection, layer disable, and data refresh all release camera ownership. Reconstructed paths are one continuous 128-sample geodetic curve: horizontal departure begins near zero while altitude rises quickly, then the climb progressively bends toward insertion without the former hard 120 km corner. Unmatched orbit fallbacks are smooth planar inclined rings rather than longitude/latitude ground-track curves. The panel lists disclosed payload names, types, operators/manufacturers, mass, multiplicity, and destination when supplied; an empty LL2 payload collection is shown as `CLASSIFIED / MULTI-PAYLOAD`. Launcher, spacecraft, and recoverable payload stages appear in a compact stage table with serial/flight/reuse details, recovery outcome/type, destination, and final coordinates when those records exist; an empty recovery collection omits the section. Stage recoveries with confirmed coordinates use those coordinates; return-to-launch-site records use the pad; downrange-only records receive an explicitly labeled estimated endpoint along the ascent azimuth. Available endpoints render as static 2 px dashed descent/recovery paths with a fixed final-position dot and an estimated atmospheric-interface segment when applicable. The ascent is geodetically densified above the ellipsoid toward the orbit's nearest insertion point, then rendered with `ArcType.NONE`, so it neither cuts through Earth nor separates from the marker. Because LL2 does not normally supply continuous ascent telemetry, pad-to-insertion paths without upstream trajectory samples are labeled `RECONSTRUCTED ESTIMATE` / `ASCENT ESTIMATE`; only supplied trajectory samples receive the replay wording. Selected-orbit framing fits the complete ring, rear-side linework uses normal scene depth occlusion, and current distance, speed, and callout data come only from a launch-year-validated satellite match. Both the loaded-catalog and active-TLE lookups read the launch year from the TLE international designator through one parser (`src/sources/tle.js`); a blank or malformed designator is an unknown year, which skips the year check rather than rejecting the match. Speed is the magnitude of the SGP4 inertial velocity vector at the same propagation epoch as position, displayed in km/s with km/h available as hover detail. Unavailable operator, site, launch-time, orbit, current-altitude, and speed values omit their detail rows instead of reserving panel space with placeholders. Newly launched payloads absent from the core operational groups use CelesTrak's cached active TLE feed as a lookup-only fallback; weak constellation-name matches are rejected. The replay callout maps compressed animation progress onto Launch Library's mission-relative timeline, showing the historical UTC date/time at the marker's current path position; unavailable timelines remain explicit. Matched live satellite positions propagate at one-second cadence and use a distinct green dot/callout with the current UTC date/time. When no mission is selected, the Space Missions panel presents a scrollable newest-first roster of every launch in the rolling window, including the smaller 5 px operator-colored marker, provider, and launch date. Hovering or keyboard-focusing a row shows four compact cyan corner brackets on both that roster row and its corresponding globe dot, rotates the globe at the current zoom to center it, and gives its label declutter priority without selecting it; the globe label remains unbracketed. Selecting a roster row invokes the same mission isolation and full-orbit framing as clicking its globe marker. The replay vehicle is one screen-space SVG/CSS HUD overlay rather than separate Cesium billboard, label, and reticle graphics. It is hidden during ordinary Focus and manual close views, where the standard selected launch-site label remains visible, and exists only while ascent replay is active. Its fixed pixel scale is shared by ascent and insertion, so camera range never resizes the rocket on screen before the phase boundary. Generic Launch Library pad names are reduced to their identifying suffix, and replay timestamps use a cyan state title over unprefixed white UTC date/time values. `REPLAY ASCENT` holds the unframed cyan/white rocket at the pad for a real-time `T−10` countdown, transitions through `LIFTOFF`, and attaches six tapered cyan/white ellipse waves directly below it from liftoff through insertion to convey thrust without adding scene geometry. While replay is active, the single start button is replaced by compact Play, Pause, and Cancel icon controls. Pause freezes countdown or mission time, vehicle/stage positions, camera target, labels, and thrust-wave animation; Play resumes from that exact frame, and Cancel releases replay camera ownership. The rocket and thrust group rotates from the path's live screen-space tangent, so its nose follows the visible ascent curve while the adjacent text remains upright. The camera begins as a close oblique launch chase, then smoothly widens between roughly 120 and 420 km vehicle altitude into a higher oblique context view that keeps the moving rocket targeted while exposing the ascent bend and orbit connection. At insertion the rocket/thrust glyph is replaced by the fixed-size cyan orbit dot, which the camera follows through the existing globe-scale orbit pullback. The chase camera limits per-frame yaw changes across heading wraps so it cannot abruptly cross in front of the vehicle and make ascent read in reverse; the replay-speed slider affects mission playback but not countdown duration. Mission world text has no native `LabelGraphics`: overview launch markers publish at most 48 ambient candidates for a 24-winner budget, while selecting a mission clears that overview source and publishes its launch-site callout, stage re-entry annotations, live/estimated payload-position readout, and orbit annotation as protected selected-lane entries. The source retains the exact former strings and colors. Static anchors reuse the Cartesian values used to build their mission geometry; the moving payload entry reads the layer's per-frame live-position cache; catalog-backed orbit annotation positions are cached in the same one-second matrix update that realigns the orbit primitive. Keyhole edge fade, horizon culling, final collision placement, and UI exclusion are owned by the shared host. Deselect restores the bounded overview, and refresh, disable, and destroy replace or clear both mission sources. A selected mission renders its orbit as four repeating tactical sectors, each containing one prominent cyan dot followed by one hundred thin translucent dashes. The bright dots act as orbit anchors while the subdued dash field remains depth-tested against the globe and is shown only for the selected mission. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 78f3edbf24..6b0b12a9a8 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1599,5 +1599,7 @@ "src/ui/omnibarRows.test.mjs", "src/ui/styles/omnibar-dock.css", "src/ui/styles/guide.css", - "src/ui/commandDock.test.mjs" + "src/ui/commandDock.test.mjs", + "src/layers/firms/selection.test.mjs", + "src/layers/vessels/selection.test.mjs" ] diff --git a/src/input/dispatcher.js b/src/input/dispatcher.js index 32ae401c47..9baea74c55 100644 --- a/src/input/dispatcher.js +++ b/src/input/dispatcher.js @@ -184,7 +184,9 @@ function topHitOf(hit, foreign) { * engine's pick objects that reads it here. * @property {boolean} overlay Whether a painted overlay target took the * click ({@link InputDispatcher.onOverlayClick}). Its hits then name only - * that target: something drawn outside the draw port, with no id. + * that target: something drawn outside the draw port, with no id. A + * subscriber with its own hit test (painted cards, a pick of its own) + * skips it then: what lies under the target is not clicked. * @property {(width: number, height: number) => unknown} pickWindow * `native.pickWindow`, the same. */ diff --git a/src/input/testDoubles.mjs b/src/input/testDoubles.mjs index 028e88e5fa..6812b2fbd3 100644 --- a/src/input/testDoubles.mjs +++ b/src/input/testDoubles.mjs @@ -140,3 +140,18 @@ export function fakeInput(viewer, { now } = {}) { destroy: () => input.destroy(), }; } + +/** + * `fakeInput` with a label painted over the map, as a Space Missions label + * is: while `label.over` is true the label takes each click, so every click + * subscriber hears it as an overlay click (`event.overlay`), and the + * geometry beneath it is not picked. + * @param {object} viewer + * @param {{now?: () => number}} [options] + */ +export function fakeInputUnderLabel(viewer, options) { + const fake = fakeInput(viewer, options); + const label = { over: false }; + fake.input.onOverlayClick(() => label.over); + return { ...fake, label }; +} diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index 72aa334c5c..4f9bb80193 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -582,9 +582,10 @@ export function createAlprPresentation({ state, services, source }) { state.clickSubscription = inputFor(viewer).onClick((event) => { if (!state.enabled) return; // The painted overlay answers first; the scene is picked only if not. + // A click a label painted over both took is on neither. const hit = event.drawHit; const id = - overlay.pick(event.screenPosition) || + (!event.overlay && overlay.pick(event.screenPosition)) || (hit && hit.set === markers.icons?.id ? hit.id : null); if ( id && diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 233a2b38e7..f6f8ca4c57 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -411,12 +411,15 @@ export function createLifecycle({ // painted ambient cards. The cards canvas is pointer-events:none (this // handler owns the events), so a click landing on a card's rect selects // its camera exactly like a click on the icon. Click positions - // and the recorded rects are both CSS px — direct comparison. - const cardId = layerState._cctvOverlayHost.hitTest( - event.screenPosition.x, - event.screenPosition.y, - { sourceId: CCTV_OVERLAY_SOURCE_ID }, - )?.entryId; + // and the recorded rects are both CSS px — direct comparison. A + // click a label painted over the cards took is not on a card. + const cardId = event.overlay + ? null + : layerState._cctvOverlayHost.hitTest( + event.screenPosition.x, + event.screenPosition.y, + { sourceId: CCTV_OVERLAY_SOURCE_ID }, + )?.entryId; if (cardId && layerState._recordById.has(cardId)) { activateCctvCameraFromWorldClick( cardId, diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index 205997721b..f2b5411e2e 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -3,6 +3,9 @@ import assert from 'node:assert/strict'; import { createLifecycle } from './lifecycle.js'; import { bindRenderer } from '../../render/rendererOf.js'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; +import { resolvePickId } from '../../data/pickRegistry.js'; +import { fakeInputUnderLabel } from '../../input/testDoubles.mjs'; function viewerWithCamera() { const camera = fakeCameraPort(); @@ -72,3 +75,81 @@ test('the view listeners follow the camera port and let go on teardown', () => { assert.deepEqual(counts(second.camera), [0, 0]); assert.equal(state._viewListenerCamera, null); }); + +/** A part whose members are `own`'s, and any other a function that does + * nothing. */ +const inert = (own = {}) => + new Proxy(own, { + get: (target, name) => (name in target ? target[name] : () => {}), + }); + +test("a click a label painted over a camera's card takes never turns that camera on, and lets go of the active one", async (t) => { + const { viewer } = viewerWithCamera(); + viewer.scene = { canvas: {}, pick: () => null }; + const fake = fakeInputUnderLabel(viewer); + t.after(() => fake.destroy()); + const activated = []; + const deactivated = []; + const state = {}; + const lifecycle = createLifecycle({ + state, + services: { + activation: { + activateCctvCameraFromWorldClick: (id) => activated.push(id), + }, + picking: { resolvePickId }, + focus: {}, + render: {}, + }, + parts: { + calibration: { loadCalibrationStore: () => new Map() }, + catalog: { + loadCameraSources: async () => [], + buildCatalogFromSources: () => [], + seedCatalog: () => [], + }, + ground: { + resolveGroundPriors: async () => [], + currentSurfaceRegime: () => null, + }, + rendering: inert({ refreshHorizonCulling: () => false }), + health: { syncHealthState: async () => {} }, + geometryQueue: inert(), + cards: inert(), + projection: inert(), + presentation: inert(), + navigation: inert(), + hover: inert(), + selection: { + // The camera's own gate takes only clean clicks; these are. + bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick), + extractPickedCameraId: () => null, + cctvEmptyClickDeselects: (picked, { activeCameraId }) => + Boolean(activeCameraId) && resolvePickId(picked) === null, + deactivateActiveCamera: () => deactivated.push(state._activeCameraId), + }, + }, + }); + // Init's bounded wait for ground heights never runs out here: they are in. + t.mock.timers.enable({ apis: ['setTimeout'] }); + await lifecycle.methods.init(viewer); + t.after(() => state._clickSubscription?.()); + state._enabled = true; + state._activeCameraId = 'cam-0'; + state._recordById.set('cam-1', {}); + // The card of camera `cam-1` lies under every click. + state._cctvOverlayHost = { + hitTest: (_x, _y, { sourceId }) => + sourceId === CCTV_OVERLAY_SOURCE_ID ? { entryId: 'cam-1' } : null, + }; + + fake.label.over = true; + fake.click(); + assert.deepEqual(activated, [], 'the camera under the label stays off'); + assert.deepEqual(deactivated, ['cam-0'], 'the active camera is let go'); + + // Off the label, a click on the card turns its camera on. + fake.label.over = false; + fake.click(); + assert.deepEqual(activated, ['cam-1']); +}); diff --git a/src/layers/droneAirspace/index.js b/src/layers/droneAirspace/index.js index 8bb8b72423..899a4c8b51 100644 --- a/src/layers/droneAirspace/index.js +++ b/src/layers/droneAirspace/index.js @@ -130,11 +130,14 @@ export function createDroneAirspaceLayer({ // cards inert anywhere over a zone. Unowned, our picks read as // "empty space" to siblings — the same contract as fire perimeters. _clickSubscription = inputFor(_viewer).onClick((event) => { - const cardHit = overlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - { sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID }, - ); + // A click a label painted over the cards took is not on a card. + const cardHit = event.overlay + ? null + : overlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + { sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID }, + ); if (cardHit && cardHit.entryId === _selectedCardId) return; const picked = event.topHit; const zoneId = picked ? pickedZoneId(event.drawHit) : null; diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index db80cef722..67f772361a 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -46,13 +46,16 @@ export function createSelection({ const pickedId = resolvePickId(picked); if (pickedId && isOwnedByOtherLayer(id, pickedId)) return; } - const cardHit = overlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - { - sourceId: FIRMS_OVERLAY_SOURCE_ID, - }, - ); + // A click a label painted over the cards took is not on a card. + const cardHit = event.overlay + ? null + : overlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + { + sourceId: FIRMS_OVERLAY_SOURCE_ID, + }, + ); if (cardHit) { const carded = layerState._fireByCardId.get(cardHit.entryId); if (carded) selectAndFocusFire(carded); diff --git a/src/layers/firms/selection.test.mjs b/src/layers/firms/selection.test.mjs new file mode 100644 index 0000000000..19dae5ffca --- /dev/null +++ b/src/layers/firms/selection.test.mjs @@ -0,0 +1,80 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js'; +import { resolvePickId } from '../../data/pickRegistry.js'; +import { fakeInputUnderLabel } from '../../input/testDoubles.mjs'; +import { createSelection } from './selection.js'; + +/** The fire selection over a viewer whose clicks a label may take, with a + * fire's card under every click. */ +function selectionHarness(t) { + const viewer = { scene: { canvas: {}, pick: () => null } }; + const fake = fakeInputUnderLabel(viewer); + t.after(() => fake.destroy()); + const fire = { lat: 1, lon: 2, acqMs: 3, frp: 40, satellite: 'N' }; + const focused = []; + const cleared = []; + const layerState = { + _viewer: viewer, + _icons: { id: 'firms:icons' }, + _pickIndexById: new Map(), + _fireByCardId: new Map([['firms-card:1', fire]]), + _selectedFire: null, + _contextIds: new Set(), + }; + const selection = createSelection({ + layerState, + services: { + picking: { resolvePickId, isOwnedByOtherLayer: () => false }, + focus: { requestWorldFocus: (request) => focused.push(request.kind) }, + context: { + selectEntityContext() {}, + clearSelectedEntityContextForLayer: (id) => cleared.push(id), + getContextStore() {}, + registerEntityContext() {}, + }, + }, + components: { + model: { + firePosition: () => ({ x: 0, y: 0, z: 0 }), + formatFrp: String, + confidenceBucket: String, + }, + cards: { rebuildAmbientLabels() {} }, + }, + config: { + id: 'firms', + name: 'Fires', + overlayHost: { + hitTest: (_x, _y, { sourceId }) => + sourceId === FIRMS_OVERLAY_SOURCE_ID + ? { entryId: 'firms-card:1' } + : null, + }, + }, + }); + selection.installClickHandler(); + t.after(() => selection.removeClickHandler()); + return { fake, layerState, fire, focused, cleared }; +} + +test("a click a label painted over a fire's card takes never selects or focuses the fire", (t) => { + const h = selectionHarness(t); + h.fake.label.over = true; + h.fake.click(); + assert.equal(h.layerState._selectedFire, null); + assert.deepEqual(h.focused, [], 'the camera is not sent to the fire'); +}); + +test('a click a label painted over the map takes lets go of the selected fire', (t) => { + const h = selectionHarness(t); + // Off the label, a click on the card selects and focuses its fire. + h.fake.click(); + assert.equal(h.layerState._selectedFire, h.fire); + assert.deepEqual(h.focused, ['fire']); + h.fake.label.over = true; + h.fake.click(); + assert.equal(h.layerState._selectedFire, null); + assert.deepEqual(h.cleared, ['firms']); + assert.deepEqual(h.focused, ['fire']); +}); diff --git a/src/layers/ghostMaps/index.js b/src/layers/ghostMaps/index.js index df94883845..4d218032ed 100644 --- a/src/layers/ghostMaps/index.js +++ b/src/layers/ghostMaps/index.js @@ -707,11 +707,14 @@ export function createGhostMapsLayer({ typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX), ); _clickSubscription = inputFor(_viewer).onClick((event) => { - const cardHit = overlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID }, - ); + // A click a label painted over the cards took is not on a card. + const cardHit = event.overlay + ? null + : overlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID }, + ); if (cardHit && cardHit.entryId === _selectedCardId) { if (_selectedLink && openExternal) openExternal(_selectedLink); return; diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js index 4d550bd08a..fcc83c9f72 100644 --- a/src/layers/localAdsb/index.js +++ b/src/layers/localAdsb/index.js @@ -8,12 +8,7 @@ import { } from '../../data/screenRotation.js'; import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js'; import { hexColor } from '../../render/color.js'; -import { - drawOf, - findCamera, - findFrame, - findQuery, -} from '../../render/rendererOf.js'; +import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js'; import { inputFor } from '../../input/dispatcher.js'; import { pickRenderAltitudeM } from '../../data/renderAltitude.js'; import { routePlausible } from '../../data/routePlausible.js'; @@ -682,10 +677,8 @@ export function createLocalAdsbLayer({ if (ownedElsewhere(topId) && !trail) return 'other'; let hits = []; try { - hits = - findQuery(viewer)?.drillPick(event.position.x, event.position.y, { - limit: CLICK_DRILL_LIMIT, - }) ?? []; + // The click's own drill: none under a label painted over the map. + hits = event.drill(CLICK_DRILL_LIMIT); } catch { hits = []; } diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 3e53c9bbeb..4bce75250a 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -17,6 +17,7 @@ import { createLocalAdsbModels } from './models.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; import { resolvePickId } from '../../data/pickRegistry.js'; import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { inputFor } from '../../input/dispatcher.js'; import { fakeInput } from '../../input/testDoubles.mjs'; import { hexColor } from '../../render/color.js'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; @@ -1174,7 +1175,8 @@ function iconPick(draw, id) { return { primitive: {}, id: { set: layerSet(draw, ':markers').spec.id, id } }; } -/** A viewer with a canvas and scripted picks, plus the layer's click action. */ +/** A viewer with a canvas and scripted picks, plus the layer's click action. + * A click drills through the viewer's `drillHits`. */ function clickHarness() { const scene = { canvas: {}, @@ -1182,6 +1184,8 @@ function clickHarness() { pick() { return scene.pickResult; }, + drillPick: () => + (base.viewer.drillHits ?? []).map((hit) => ({ primitive: {}, id: hit })), }; const base = fakeViewer({ scene }); return { @@ -1265,6 +1269,39 @@ test('a click on a local aircraft under an unowned or trail pick still selects i assert.equal(calls.selected.length, 2, 'the Flights contact is not taken'); }); +test('a click a label painted over a local aircraft takes never selects the aircraft, and lets go of the selection', async (t) => { + const receiver = fakeReceiver({ mode: 'adsb', connected: true }); + const clock = { now: 100_000 }; + const harness = clickHarness(); + const { layer, calls, draw } = await enabledLayer(receiver, clock, null, { + viewer: harness.viewer, + }); + t.after(() => layer.destroy()); + receiver.set({ aircraft: [record()] }); + await layer.update(); + const label = { over: true }; + inputFor(harness.viewer.viewer).onOverlayClick(() => label.over); + const model = { + set: layerSet(draw, ':models').spec.id, + id: 'local-adsb:abc123', + surface: false, + }; + // The aircraft is under the label, both exactly and in the drill. + harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123'); + harness.viewer.viewer.drillHits = [model]; + harness.click(); + assert.deepEqual(calls.selected, [], 'the aircraft beneath is not taken'); + + // Off the label the same click selects it; on the label it lets go. + label.over = false; + harness.click(); + assert.deepEqual(calls.selected, ['local-adsb:abc123']); + label.over = true; + harness.click(); + assert.deepEqual(calls.selected, ['local-adsb:abc123']); + assert.equal(calls.cleared.length, 1, 'the selection is released'); +}); + test('a grounded aircraft changing type keeps its drawn model on its own belly offset until the new one is ready', () => { const { draw, viewer, camera } = modelViewer(); const models = createLocalAdsbModels({ diff --git a/src/layers/news/index.js b/src/layers/news/index.js index 4ad5826c27..4e4afc9818 100644 --- a/src/layers/news/index.js +++ b/src/layers/news/index.js @@ -1348,9 +1348,12 @@ export function createNewsLayer({ clickOff = inputFor(viewer).onClick((event) => { const at = event?.screenPosition; if (!enabled || destroyed || !isPointerFree() || !at) return; - const card = hitTestOverlay(at.x, at.y, { - sourceId: NEWS_OVERLAY_SOURCE_ID, - }); + // A click a label painted over the cards took is not on a card. + const card = event.overlay + ? null + : hitTestOverlay(at.x, at.y, { + sourceId: NEWS_OVERLAY_SOURCE_ID, + }); if (card?.entry?.activate) { card.entry.activate(); return; diff --git a/src/layers/perimeters/index.js b/src/layers/perimeters/index.js index 3a5a180c48..460c7c534d 100644 --- a/src/layers/perimeters/index.js +++ b/src/layers/perimeters/index.js @@ -218,11 +218,14 @@ export function createFirePerimetersLayer({ _clickSubscription = inputFor(_viewer).onClick((event) => { // A click on the incident card itself opens its InciWeb page (when the // incident has one) and never disturbs the selection. - const cardHit = overlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - { sourceId: PERIMETER_OVERLAY_SOURCE_ID }, - ); + // A click a label painted over the cards took is not on a card. + const cardHit = event.overlay + ? null + : overlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + { sourceId: PERIMETER_OVERLAY_SOURCE_ID }, + ); if (cardHit && cardHit.entryId === _selectedCardId) { if (_selectedLink && openExternal) openExternal(_selectedLink); return; diff --git a/src/layers/shipwrecks/index.js b/src/layers/shipwrecks/index.js index c2c2db2814..c61a956a04 100644 --- a/src/layers/shipwrecks/index.js +++ b/src/layers/shipwrecks/index.js @@ -278,9 +278,12 @@ export function createShipwrecksLayer({ _clickHandler = clicks.onClick((click) => { if (pointer && !pointer.isPointerFree()) return; const at = click.screenPosition; - const cardHit = overlayHost.hitTest?.(at?.x, at?.y, { - sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID, - }); + // A click a label painted over the cards took is not on a card. + const cardHit = click.overlay + ? null + : overlayHost.hitTest?.(at?.x, at?.y, { + sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID, + }); if (cardHit && cardHit.entryId === _selectedCardId) { if (_selectedLink) openExternal(_selectedLink); return; diff --git a/src/layers/shipwrecks/index.test.mjs b/src/layers/shipwrecks/index.test.mjs index 7d69f2b457..b2e45a68a1 100644 --- a/src/layers/shipwrecks/index.test.mjs +++ b/src/layers/shipwrecks/index.test.mjs @@ -2,6 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; import * as picking from '../../data/pickRegistry.js'; +import { fakeInputUnderLabel } from '../../input/testDoubles.mjs'; import { createShipwrecksLayer, markerPixelSize, @@ -393,3 +394,51 @@ test('the page deadline subtracts the newest available source age from the limit ); assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults'); }); + +test("a click a label painted over the open card takes never opens the card's link, and closes the card", async (t) => { + let picked = null; + const viewer = { scene: { canvas: {}, pick: () => picked } }; + bindFakeDraw(viewer); + const fake = fakeInputUnderLabel(viewer); + t.after(() => fake.destroy()); + const cards = []; + const opened = []; + let cardUnder = null; + const layer = createShipwrecksLayer({ + source: { getSnapshot: () => Promise.resolve(snapshot([wreck('a')])) }, + overlayHost: { + setEntries: (_source, entries) => cards.push(entries), + setVisible() {}, + hitTest: () => (cardUnder ? { entryId: cardUnder } : null), + }, + input: () => fake.input, + picking, + pointer: { isPointerFree: () => true }, + openExternal: (url) => opened.push(url), + now: () => 1, + }); + layer.init(viewer); + t.after(() => layer.destroy()); + layer.enable(); + await layer.update(); + picked = { primitive: {}, id: { set: 'shipwrecks:', id: 'shipwreck:a' } }; + fake.click(); + const [card] = cards.at(-1); + assert.equal(card.id, 'shipwreck-card:a'); + + // The open card lies under the label: the click opens nothing. + picked = null; + cardUnder = card.id; + fake.label.over = true; + fake.click(); + assert.deepEqual(opened, [], 'the link beneath the label is not opened'); + assert.deepEqual(cards.at(-1), [], 'the card is closed'); + + // Off the label, a click on the open card opens its link. + fake.label.over = false; + picked = { primitive: {}, id: { set: 'shipwrecks:', id: 'shipwreck:a' } }; + fake.click(); + picked = null; + fake.click(); + assert.equal(opened.length, 1); +}); diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js index 7f8ddab832..e3009a1073 100644 --- a/src/layers/vessels/selection.js +++ b/src/layers/vessels/selection.js @@ -64,17 +64,19 @@ export function createSelection({ // Cards are painted on a pointer-events:none canvas, so the scene pick is // usually terrain behind the card. Resolve against the host's current // actionable hit rectangles before treating the click as empty space. - const cardHit = !record - ? vesselState._vesselOverlayHost.hitTest?.( - event.screenPosition?.x, - event.screenPosition?.y, - { - ...(cycloneBackground - ? {} - : { sourceId: VESSEL_OVERLAY_SOURCE_ID }), - }, - ) - : null; + // A click a label painted over the cards took is not on a card. + const cardHit = + !record && !event.overlay + ? vesselState._vesselOverlayHost.hitTest?.( + event.screenPosition?.x, + event.screenPosition?.y, + { + ...(cycloneBackground + ? {} + : { sourceId: VESSEL_OVERLAY_SOURCE_ID }), + }, + ) + : null; if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID) return; if (!record && cardHit) { diff --git a/src/layers/vessels/selection.test.mjs b/src/layers/vessels/selection.test.mjs new file mode 100644 index 0000000000..941b7118d9 --- /dev/null +++ b/src/layers/vessels/selection.test.mjs @@ -0,0 +1,89 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js'; +import { fakeInputUnderLabel } from '../../input/testDoubles.mjs'; +import { createSelection } from './selection.js'; + +/** Calls on any member are recorded by name and do nothing else. */ +function recorder(calls) { + return new Proxy( + {}, + { + get: + (_target, name) => + (...args) => + calls.push([name, ...args]), + }, + ); +} + +/** The vessel selection over a viewer whose clicks a label may take. */ +function selectionHarness(t) { + const viewer = { scene: { canvas: {}, pick: () => null } }; + const fake = fakeInputUnderLabel(viewer); + t.after(() => fake.destroy()); + const vessel = { id: 'v1', name: 'NORTHERN STAR', lat: 0, lon: 0 }; + const focused = []; + const calls = []; + const state = { + feed: { enabled: true }, + records: { byId: new Map([[vessel.id, vessel]]) }, + icons: { setId: 'vessels:icons', has: () => false }, + selectedRecord: null, + interactionKeyTarget: new EventTarget(), + }; + const vesselState = { + state, + // The vessel's card lies under the click. + _vesselOverlayHost: { + hitTest: (_x, _y, { sourceId } = {}) => + sourceId === VESSEL_OVERLAY_SOURCE_ID + ? { sourceId, entryId: `vessel:${vessel.id}` } + : null, + }, + }; + const selection = createSelection({ + vesselState, + services: { + picking: { isOwnedByOtherLayer: () => false }, + worldFocus: { requestWorldFocus: (request) => focused.push(request.id) }, + context: recorder(calls), + }, + parts: { + queries: { + reduceVesselSelection: ({ selectedId, pickedId }) => + pickedId + ? { action: pickedId === selectedId ? 'none' : 'select' } + : { action: selectedId ? 'deselect' : 'none' }, + }, + rendering: recorder(calls), + cards: recorder(calls), + photos: recorder(calls), + tracking: recorder(calls), + }, + layer: { source: 'AIS' }, + }); + selection.installInteraction(viewer); + t.after(() => selection.removeVesselInteraction()); + return { fake, state, vessel, focused }; +} + +test("a click a label painted over a vessel's card takes never selects or focuses the vessel", (t) => { + const h = selectionHarness(t); + h.fake.label.over = true; + h.fake.click(); + assert.equal(h.state.selectedRecord, null); + assert.deepEqual(h.focused, [], 'the camera is not sent to the vessel'); +}); + +test('a click a label painted over the map takes lets go of the selected vessel', (t) => { + const h = selectionHarness(t); + // Off the label, a click on the card selects and focuses its vessel. + h.fake.click(); + assert.equal(h.state.selectedRecord, h.vessel); + assert.deepEqual(h.focused, ['v1']); + h.fake.label.over = true; + h.fake.click(); + assert.equal(h.state.selectedRecord, null); + assert.deepEqual(h.focused, ['v1']); +}); diff --git a/src/layers/wildlifeSightings/selection.js b/src/layers/wildlifeSightings/selection.js index dc0b7c126c..7db90766aa 100644 --- a/src/layers/wildlifeSightings/selection.js +++ b/src/layers/wildlifeSightings/selection.js @@ -483,16 +483,18 @@ export function createSelection({ state, services, parts }) { if (!state.enabled || services.pointer?.isPointerFree?.() === false) return; const at = click.screenPosition; + // A click a label painted over the cards took is not on a card. const hit = - overlay?.hitTest?.(at?.x, at?.y, { + !click.overlay && + (overlay?.hitTest?.(at?.x, at?.y, { sourceId: WILDLIFE_SELECTED_SOURCE_ID, }) || - overlay?.hitTest?.(at?.x, at?.y, { - sourceId: WILDLIFE_OVERLAY_SOURCE_ID, - }) || - overlay?.hitTest?.(at?.x, at?.y, { - sourceId: WILDLIFE_LABEL_SOURCE_ID, - }); + overlay?.hitTest?.(at?.x, at?.y, { + sourceId: WILDLIFE_OVERLAY_SOURCE_ID, + }) || + overlay?.hitTest?.(at?.x, at?.y, { + sourceId: WILDLIFE_LABEL_SOURCE_ID, + })); if (hit) { hit.entry?.activate?.(); return; diff --git a/src/ui/cockpitController.js b/src/ui/cockpitController.js index 6bdd97f5f0..6139e51bf3 100644 --- a/src/ui/cockpitController.js +++ b/src/ui/cockpitController.js @@ -483,10 +483,12 @@ export class CockpitViewController { * A click on the orbital picture: on a mapped point in reach it keeps the * camera on that point; anywhere else it ends such a focus. * @param {{x: number, y: number}|null|undefined} position + * @param {{overlay?: boolean}} [options] `overlay`: a label painted over + * the map took the click, which then only ends a focus. * @returns {boolean} True when the click focused a point. */ - onOrbitalClick(position) { - return onOrbitalClick.call(this, position); + onOrbitalClick(position, options) { + return onOrbitalClick.call(this, position, options); } /** * A double-click on the orbital picture: on a mapped ground point it keeps diff --git a/src/ui/cockpitOrbitalFocus.js b/src/ui/cockpitOrbitalFocus.js index 5b97c34838..7452f47901 100644 --- a/src/ui/cockpitOrbitalFocus.js +++ b/src/ui/cockpitOrbitalFocus.js @@ -256,13 +256,16 @@ export function onOrbitalDoubleClick(position) { * focuses it; any other click ends a focus. A click a tool owns (drawing) * is left alone, as is every click outside orbit. * @param {{x: number, y: number}|null|undefined} position Canvas position. + * @param {{overlay?: boolean}} [options] `overlay`: a label painted over the + * map took the click, so it is on no site and only ends a focus. * @returns {boolean} True when the click focused a point. */ -export function onOrbitalClick(position) { +export function onOrbitalClick(position, { overlay = false } = {}) { if (!inOrbit(this) || !isPointerFree()) return false; if (!Number.isFinite(position?.x) || !Number.isFinite(position?.y)) return false; - const site = siteAt(this, position); + // A click a label painted over the map took is on no site. + const site = overlay ? null : siteAt(this, position); const state = this.orbital; if (site) { if (state.focus?.key === String(site.id)) return true; @@ -286,7 +289,9 @@ 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) => + this.onOrbitalClick(event?.position, { overlay: event?.overlay === true }), + ); } /**