diff --git a/changelog.d/1781-earthquake-click-details.md b/changelog.d/1781-earthquake-click-details.md
new file mode 100644
index 0000000000..595083a3f1
--- /dev/null
+++ b/changelog.d/1781-earthquake-click-details.md
@@ -0,0 +1,7 @@
+- Make earthquake discs and magnitude labels selectable, with magnitude, USGS
+ class, depth, location, time and source details. Labels also fly to the quake;
+ the selected disc shows a fading gradient and bounded contour animation. A
+ drag ending on a quake does nothing. The card or label painted on top now
+ takes a click in every layer: what is drawn under it neither acts nor loses
+ its selection, and the Context panel names nothing there
+ (Manjunath, @manjunath22466, #1781).
diff --git a/changelog.d/1827-three-step-welcome.md b/changelog.d/1827-three-step-welcome.md
new file mode 100644
index 0000000000..0889a08544
--- /dev/null
+++ b/changelog.d/1827-three-step-welcome.md
@@ -0,0 +1,5 @@
+- Replace the first-run launcher with a three-step welcome: an introduction to
+ the modes, where to start (Space Missions, Environmental or Explore
+ manually), then quick tips and links. The Live Contacts starting choice is
+ gone. GEV Stories opens in the app from the last step, and a light tint (no
+ blur) sits over the globe while the card is up (manjunath22466, samehkhamis, #1827).
diff --git a/changelog.d/1829-space-missions-fixes.md b/changelog.d/1829-space-missions-fixes.md
new file mode 100644
index 0000000000..626defeb94
--- /dev/null
+++ b/changelog.d/1829-space-missions-fixes.md
@@ -0,0 +1,9 @@
+- Space Missions going off no longer acts on a launch hovered, selected or
+ replayed meanwhile, and Satellites keeps the state it was saved with when
+ it is still busy (unless it was switched on or off by hand meanwhile); a
+ Satellites setting changed during a mission, such as a place search ending
+ tracking, is kept when the mission ends. A click on a mission label is a
+ click on the card on top, so no layer selects, turns on, flies to or opens
+ the link of what lies under it; in the cockpit a mission chosen by its
+ label, its dot or the row's arrows is selected without moving the camera
+ (manjunath22466, samehkhamis, #1829).
diff --git a/changelog.d/1830-place-privacy.md b/changelog.d/1830-place-privacy.md
new file mode 100644
index 0000000000..ebb9aea283
--- /dev/null
+++ b/changelog.d/1830-place-privacy.md
@@ -0,0 +1,7 @@
+- More private text typed into the Omnibar or Location search stays off the
+ place service: emails spelled out or spaced, IP addresses, wallet recovery
+ phrases, door, alarm and lockbox numbers, codes after their labels,
+ document and ID numbers, SSNs, more API token shapes and codes in links.
+ More real places get through: "Boise ID 83702", house numbers in the
+ order their country writes them, addresses of up to ten words, and long
+ questions for Ask GEV (manjunath22466, samehkhamis, #1830).
diff --git a/changelog.d/1832-firms-stand-in-focus-range.md b/changelog.d/1832-firms-stand-in-focus-range.md
new file mode 100644
index 0000000000..ad49cc01b3
--- /dev/null
+++ b/changelog.d/1832-firms-stand-in-focus-range.md
@@ -0,0 +1,3 @@
+- The fire layer's marker stand-in can set how far the camera stands from a
+ fire it draws (`focusRangeM`), and a world focus request may carry its own
+ range (samehkhamis, #1832).
diff --git a/changelog.d/1833-hud-credits-sonar-links.md b/changelog.d/1833-hud-credits-sonar-links.md
new file mode 100644
index 0000000000..c81dbc0590
--- /dev/null
+++ b/changelog.d/1833-hud-credits-sonar-links.md
@@ -0,0 +1,4 @@
+- Keep the HUD's bottom corners, the Omnibar dock and the corner row clear of
+ the map credits at every desktop width, also right to left and when the
+ credits wrap onto several lines; and carry Sonar with the Minimal HUD layout
+ in share links and scene shots (manjunath22466, samehkhamis, #1833).
diff --git a/changelog.d/1834-decoded-imagery.md b/changelog.d/1834-decoded-imagery.md
new file mode 100644
index 0000000000..5b3900d027
--- /dev/null
+++ b/changelog.d/1834-decoded-imagery.md
@@ -0,0 +1,5 @@
+- Renderer contract: a timed imagery source can be `decoded` (the
+ `imageryDecoded` capability), tiles the application makes itself and hands
+ over as finished images, slot by slot; the Cesium renderer draws each slot
+ as an imagery layer of its own, and the check `globe.imagery.decoded` covers
+ it (Sameh Khamis, #1834).
diff --git a/changelog.d/1835-icon-near-plane-flicker.md b/changelog.d/1835-icon-near-plane-flicker.md
new file mode 100644
index 0000000000..b6cf5c620c
--- /dev/null
+++ b/changelog.d/1835-icon-near-plane-flicker.md
@@ -0,0 +1,3 @@
+- Icons drawn over depth (aircraft, vessels) no longer vanish for a frame now
+ and then in dense far-away clusters: they sit just past the near plane instead
+ of exactly on it, where rounding could discard them (samehkhamis, #1835).
diff --git a/changelog.d/1836-delayed-clock-test.md b/changelog.d/1836-delayed-clock-test.md
new file mode 100644
index 0000000000..22456a2314
--- /dev/null
+++ b/changelog.d/1836-delayed-clock-test.md
@@ -0,0 +1,3 @@
+- The delayed-live aircraft icon test holds the clock still while it compares
+ drawn and read positions, so it no longer fails on a busy machine
+ (samehkhamis, #1836).
diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md
index 6f9231fba5..6b0cc95cdb 100644
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@ -1136,8 +1136,12 @@ opt-in visual style over Tactical or Minimal: Display > HUD > Sonar is OFF by
default, and ON reveals the Rings, Range, Power, Opacity and Sector sliders.
Share links, scenes and saved views that name Cyber keep its enum code and
open in Tactical with Sonar on. Links and scene shots record Tactical with
-Sonar on under that same code, and a restored state that names another layout
-turns Sonar off; Minimal has no such code, so its Sonar is not carried.
+Sonar on under that same code, so older builds still read it. Minimal with
+Sonar on is recorded as Minimal plus an explicit Sonar mark: flag bit 5
+(`hudSonar`) of a compact link, `hs=1` in the long form, and `hud.sonar: true`
+in a scene shot. A restored state turns Sonar on when it names Cyber or carries
+that mark, and off otherwise, so a link or shot made before the mark restores
+as it always did.
An explicit Sonar toggle or validated voice setting takes visual restore
authority, so a delayed share-link restore cannot undo the newer choice.
Choosing Reset Visual keeps the HUD layout and the Sonar setting.
@@ -1181,12 +1185,19 @@ corners, so it keeps to the bottom edge, the attribution row sits above it and
the coordinates clear the row's logo line. In the desktop Omnibar layout the
Omnibar's own rules (`src/ui/styles/omnibar-dock.css`) place the dock, the
World Timeline, the credits and the coordinates; its Tactical bottom-right
-readout also keeps 8px above the Power Up row. The left rail treats the
-centered World Timeline and voice control as obstacles only where they reach a
-laid-out panel, not the stack's transparent gutter. Known limit, unchanged
-from main: below 1200px with the World Timeline showing, the Tactical
-bottom-right readout does not rise with the bar and can touch the dock, and a
-credit line longer than the screen does not wrap.
+readout also keeps 8px above the Power Up row. There the credit line wraps at
+every width, right to left it takes the bottom right at every width, and
+`src/ui/creditLineHeight.js` keeps its height in `--credit-line-height`: the
+coordinates (and, right to left, the Tactical readout) stay 6px above it
+however many lines it wraps onto, and the dock and World Timeline rise when
+it is taller than their usual clearance. Narrower than 1120px the dock leaves
+no room between the corners, so the coordinates and the readout sit above
+the dock, and above the World Timeline while it shows. Outside that layout
+Cesium's credit box wraps from 1200px, as before; the phone shell, clean
+view, recording and scene playback lay the line out themselves.
+The left rail treats the centered World Timeline and voice control as
+obstacles only where they reach a laid-out panel, not the stack's
+transparent gutter.
Wind appears in the Weather group before Audio. The surface-weather prototype
uses keyless NOAA GFS or ECMWF IFS forecasts on an approximately 1° display grid.
@@ -2062,6 +2073,51 @@ feed's place, cut to 40 characters (`earthquakeMarkLabel` in
`src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon
Islands`, or `M6.4` with no place).
+Clicking a quake's disc selects it; clicking its magnitude label (what a far
+view can hit) also flies the camera there through the world-focus request
+(`earthquake` framing in `src/worldFocus.js`). The selected quake shows a card
+(`describeEarthquake`): magnitude and USGS class (`M5.5 · Moderate`), a
+six-step class meter with the depth band, place (cut to 48 characters; the
+card's accessible name carries all of it), UTC time and source; with a USGS
+event id the card opens that event's page, and without one a click or its
+keyboard action flies to the quake. The selection is also the
+shared context selection, so "what's selected" answers with it. Its disc is
+painted with a gradient fading to the outer circle and wavy contour lines
+(shaped by the quake's id, never crossing) under the labels, drawn at the
+ground height the disc is draped on (read again, at most twice a second, while
+they paint, as the ground loads under a label's fly-to). A label's
+fly-to frames the whole disc, scaling its range from the disc's radius above
+the M6 framing. The package takes clicks, picking, context, focus, the ground
+height, the opener, the painter and the translator by injection
+(`src/app/layers/earthquakes.js`); without input and picking it draws and takes
+no clicks, and its labels stay non-interactive.
+A press that travels past the tracking click limit is a drag, not a pick: the
+quake handler ignores it, and opening the source or clearing the selection
+also needs a short press (`src/data/trackingClickGesture.js`).
+Quake discs are deliberately not registered in the pick-ownership registry,
+like drone airspace and fire perimeters: sibling layers read a disc as empty
+space, so their near-miss taps and deselection work over a quake as before,
+and a disc yields to another layer's registered pick (an aircraft) under it.
+The card or label painted on top takes the click. The world-overlay host hands
+its hit test to the pick registry (`setClickCardHitTest`), and every click
+handler reads the topmost interactive card or label at the click through
+`clickCard(click)`, once per click, so all of them agree in any listener order
+(`src/data/pickRegistry.js`). A layer whose own card or label is on top acts
+on it, whatever is drawn under it: an aircraft, a vessel, a fire, a camera, a
+trail, a route. A layer under another layer's card or label
+(`isUnderOtherCard`) does nothing: it neither acts on its item there nor
+treats the click as empty space, so a tracked aircraft stays tracked and a
+selection stays selected. Context (`src/ui/entityContextBridge.js`) names
+nothing under a card. With no card on top, the scene rules are unchanged.
+World-overlay hit rectangles are what is painted on screen until the next
+paint: an overlay change (a click subscriber publishing its selection card)
+no longer clears them mid-click, and a paint that draws nothing clears them
+(`src/overlays/worldOverlay.js`). A click on the map under another layer's
+card opens no Street Level ground image. The Bhote Koshi trigger-record
+callout (`src/data/bhoteKoshiLocator.js`) opens its source on a click, as its
+keyboard action does, and ignores a drag; its evidence cards act only when
+they are the card on top.
+
Air quality (`./layers/air-quality`) draws its station discs as one renderer
draw set of ground-clamped fills and reads the view through the camera port; it
no longer reaches Cesium, so a caller handing it a Cesium viewer,
@@ -3392,6 +3448,9 @@ state or inert ancestry; ordinary visible enabled controls retain their order.
focus shared by the first-run launcher and Provider Settings. Each caller
activates it while open and deactivates it on dismissal; destruction releases
keyboard ownership without moving focus. Reopening captures the current opener.
+Tab from a control outside the surface moves into it unless the caller passes
+`claimOutsideFocus: false`, as the first-run launcher does; focus on the page
+body still moves in.
The launcher retains its hit-test/exclusive-surface arbitration and dismissal
preferences. Provider Settings retains its existing visibility and save policy.
Initial focus, transitions and DOM content remain with each screen. This
@@ -4106,10 +4165,34 @@ which embeds the MAP_KEY.
points to restrictions, quota, or connectivity. These hints do not expose keys.
> **2026-08-23 — first-run mission launcher** (`src/firstRunExperience.js`,
-> `#first-run-launcher`, styles at the tail of `style.css`). After startup
-> settles, a fresh session gets one card offering **Live Contacts · Space
-> Missions · Environmental · Explore manually**. No layer and no optional API
-> call happens until a tile is clicked. The right-hand DISPLAY rail
+> `#first-run-launcher`, styles in `src/ui/styles/first-run.css`). After startup
+> settles, a fresh session gets three steps: mode introduction, a starting
+> mission, then quick tips and links. God mode is available; Analyst is
+> marked coming soon. **Space Missions · Environmental · Explore
+> manually** are the starting choices, with Explore selected by default; Live
+> Contacts is no longer offered as a starting mission (its Context tab is
+> unchanged). The footer status line stays empty until a mission reports
+> progress or an error; the old voice tip is gone. While the card is up, a
+> click-through backdrop tints the globe behind it (`.first-run-backdrop`, a
+> 28% dark tint with no blur); it never takes input, so the card stays
+> non-modal. The last step links out to the GitHub repository and
+> its author's channels (YouTube, X, Instagram, LinkedIn, bilawal.ai) and
+> halfpixel.ai; each opens in a new tab with `rel="noopener noreferrer"`, and
+> the addresses live in `FIRST_RUN_LINKS` (`src/firstRunCopy.js`). The GEV
+> Stories card's BROWSE STORIES button closes the card (a session dismissal,
+> like Skip) and opens the in-app Stories Explore view, keeping the Stories
+> announcement hidden while Stories loads. Next and Back preserve that selection without starting
+> a mission. Only **Enter God mode** runs it; Back is inert while it is loading.
+> Step changes focus the main action, announce the new heading separately from
+> mission progress, and refresh the scrolling affordance after the transition. Repeated Enter keys,
+> double-clicks and activation during a step transition cannot launch a mission; a quick second
+> click on Next still moves to the next step. Tab cycles inside the card, and moves into it from
+> the page only when focus has nowhere else to be: Tab from the search bar or another control
+> follows the page's order.
+> No layer and no optional API call happens until the final action is clicked.
+> The Stories announcement waits, from startup until onboarding closes, without
+> marking it seen.
+> The right-hand DISPLAY rail
> (`pp-toggles`) now starts **collapsed** on a first run rather than expanded —
> a stored collapse state still wins, as before.
>
@@ -4157,26 +4240,28 @@ which embeds the MAP_KEY.
> `localStorage['gev:first-run-mission:v1'] === 'suppressed'`, written **only**
> by the "Don't show this again" checkbox → the per-session
> `sessionStorage['gev:first-run-mission-session:v1'] === 'dismissed'`, written
-> by **every** close path (mission, Explore, ESC, the footer dismiss button). So
+> by **every** close path (a mission or Explore from ENTER GOD MODE, ESC, the
+> header Skip button, BROWSE STORIES). So
> it returns each fresh browser session until the visitor ticks the box; clearing
> storage un-ticks it, which is accepted. Both stores fail open — an unreadable
> store still shows the launcher rather than silently swallowing first launch.
>
-> **The footer dismiss button is the keyboardless ESC.** Phones and tablets have
-> no ESC key, so the footer hint is a `data-first-run-dismiss` button that calls
+> **The header Skip button is the keyboardless ESC.** Phones and tablets have
+> no ESC key, so the header action is a `data-first-run-dismiss` button that calls
> the same `dismiss()` as ESC. It stays visible at every width (phones used to
-> hide it, leaving a mission as the only way out) and reads DISMISS on a
-> `(hover: none) and (pointer: coarse)` screen, "ESC to dismiss" otherwise. Its
-> 44px touch target is a `::before` outside the layout, so the footer row keeps
+> hide it, leaving a mission as the only way out) and reads SKIP on a
+> `(hover: none) and (pointer: coarse)` screen, "SKIP · ESC" otherwise. Its
+> 44px touch target is a `::before` outside the layout, so the header row keeps
> its one-line height.
>
> **What a mission may persist (do not "simplify" this).** Layer enablement is
> durable in this app (`gev:layer-state:v2`, written by
> `LayerStateCoordinator._commitExplicit` only for origin `user`/`voice`/`tool`).
> A mission enables **its own** layers at `origin: 'user'` — durable, exactly as
-> clicking those rows is, because picking the mission _is_ that choice. The two
-> Context missions also expand the Context panel, as the visible tabs do; the
-> globe missions open no panel. Everything else is off limits: detection
+> clicking those rows is, because picking the mission _is_ that choice. Space
+> Missions switches on its layer, which opens its own Space Missions panel; no
+> mission enters a Context mode or opens the Context panel, and the globe
+> missions open no panel. Everything else is off limits: detection
> mode/density, `gev:detection-allocation:v1`, 3D models, feather, and above all
> `_detectionUserOverridden` — setting that flag means "the operator hand-edited
> detection" and would silently disable the CRT/NVG/FLIR auto-preset contract for
@@ -5592,7 +5677,13 @@ activeCameraCardEnabled: true })` may publish it through the retained
> switching Space Missions off restores the pre-mission Satellite enabled
> state and presentation parameters, except that an explicit Satellites action
> taken while it ran is kept. Restored parameters never re-show primitives
-> while the Satellite layer is disabled.
+> while the Satellite layer is disabled. When Satellites is still busy after
+> the 30 s limit, the restore changes nothing and keeps the saved state, so
+> switching Space Missions off again finishes it; after an explicit
+> Satellites on/off action, which keeps its visibility, the parameters are
+> restored all the same and the saved state is let go. While Space Missions goes
+> off, its panel's roster and controls select, focus, preview and replay
+> nothing, so no camera move starts that nothing would end.
> - **Flights 3D/cockpit hardening:** the destination-direction cue is an
> inline SVG rather than a remotely loaded Material Icons ligature, so a
> blocked or late font can no longer expand the literal word `navigation`
@@ -7334,7 +7425,7 @@ silently demoting every later lookup for the session.
- Context is set for reading in every theme: mode, standby and action labels are 10 px, and the panel draws no glow halo. The two modes form one segmented control, the standby guidance is plain left-aligned text rather than a dashed placeholder, and the panel's section titles share the side panels' dock-label colour.
- The expanded desktop header omits the redundant `ON` label; the active mode button carries state. Expanded Contact results also omit the duplicate `GLOBAL CONTEXT` / `CONTEXT ONLY` status row and begin with the selected subject and its 250 km scope. Global Context does not fabricate a selected-entity model preview: the provisional hand-authored aircraft wireframe was removed because it was not geometry extracted from the selected entity's actual asset.
- Dependency ownership is reversible: disabling Global Context releases only dependencies it enabled, while user-enabled layers remain on. This also removes the Military-layer suppression handoff when Global Context owned Military, allowing an already-enabled civilian Flights layer to resume its normal mixed rendering. If OpenSky is unavailable and has no last-good cache, Flights requests a capped 250 nm adsb.lol point snapshot around the current view anchor and labels that provenance explicitly; it never relabels military-feed rows as civilian data. If both inputs fail, Flights remains `UNKNOWN`.
-- Space Missions is an ordinary layer, not a Context mode. It neither isolates the globe nor refuses other layers, opens no Context session, and runs beside Contacts. Turning it on enables its Satellites dependency in the temporary dense/hidden mode and turning it off restores Satellites' exact prior visibility and parameters; an explicit Satellites action taken while it runs (by the person or by voice) is kept through that restore, and such a Satellites OFF asked for after the newest Space Missions ON ends Space Missions (request order, not settle order, decides; `src/layers/launches/satelliteIntents.js`). A scene, story, preset or other programmatic Satellites change does neither (owner decision). Contacts leaves Satellites as it is. The first mission-index load is part of the enable: an HTTP error, timeout, network failure or malformed payload before any index has loaded fails the enable, the camera returns to its pre-entry view unless navigation took it, and a toast says the mission index could not load. A valid empty index still enables, and a refresh failure after an index loaded keeps its records. Turning the layer on by hand, choosing it at first run, asking for it by voice (`set_context_mode` still accepts `space-missions` and switches the layer), or picking a mission on the globe opens the Space Missions panel; on desktop, opening it closes Context and the other right-rail panels, and opening Context closes it. Voice `set_panel_open` refuses to open the panel while the layer is off and says to turn Space Missions on first.
+- Space Missions is an ordinary layer, not a Context mode. It neither isolates the globe nor refuses other layers, opens no Context session, and runs beside Contacts. Turning it on enables its Satellites dependency in the temporary dense/hidden mode and turning it off restores Satellites' exact prior visibility and parameters; an explicit Satellites action taken while it runs (by the person or by voice), a visibility switch or a changed setting (also a place search that stops tracking a satellite), is kept through that restore (also while a restore that found Satellites busy keeps the saved state, for the next Space Missions start, which switches Satellites on again), and such a Satellites OFF asked for after the newest Space Missions ON ends Space Missions (request order, not settle order, decides; `src/layers/launches/satelliteIntents.js`). A scene, story, preset or other programmatic Satellites change does neither (owner decision). Contacts leaves Satellites as it is. The first mission-index load is part of the enable: an HTTP error, timeout, network failure or malformed payload before any index has loaded fails the enable, the camera returns to its pre-entry view unless navigation took it, and a toast says the mission index could not load. A valid empty index still enables, and a refresh failure after an index loaded keeps its records. Turning the layer on by hand, choosing it at first run, asking for it by voice (`set_context_mode` still accepts `space-missions` and switches the layer), or picking a mission on the globe opens the Space Missions panel; on desktop, opening it closes Context and the other right-rail panels, and opening Context closes it. Voice `set_panel_open` refuses to open the panel while the layer is off and says to turn Space Missions on first.
- Enabled Data Layer controls report normalized feed health on the button (`LOADING`, `DEGRADED`, `STALE`, `FALLBACK`, or `UNAVAILABLE`) while the metadata line retains the source and reason. A partial CelesTrak group failure keeps the usable catalog and reports `DEGRADED`; a total outage keeps last-good catalog data visible but reports `UNAVAILABLE`.
- On activation it focuses the nearest currently observed aircraft across the civilian and military feeds, with military winning an exact distance tie; if none are available, it focuses an observed AIS vessel. The aircraft search is deliberately uncapped and one refresh-tick retry handles initially empty feeds. This is an attention-priority navigation shortcut, not a high-risk, affiliation, or threat classification.
- A selected aircraft, AIS vessel, or mapped installation gets a 250 km **context window** with nearby cohort counts, nearest examples, source labels, and stale/unavailable reasons. It emits `NEARBY` or `UNKNOWN`; no detection, engagement, affiliation, or sensor-activity conclusion is calculated.
@@ -7491,7 +7582,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. 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 (in the cockpit, which holds the camera, a mission chosen by its name, its dot or the layer row's arrows is selected without flying to it, also once its orbit arrives); what is drawn beneath the name is not picked, and the other layers still hear the click as one on the name. The name is an interactive world-overlay label, so it is the card on top for every click handler (`clickCard`, `isUnderOtherCard` in `src/data/pickRegistry.js`): no other layer selects, turns on, focuses or opens the link of a contact, card or camera that lies under the name, and their selections stay. 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.
@@ -8041,10 +8132,13 @@ while the tab is hidden.
A place search on its own runs through Location and shares its cancellation
and errors, keeping the separate Location draft intact.
-While typing, a short line (six words or fewer, no `?`, not a command,
+While typing, a short line (six words or fewer, ten with a number in it
+as an address has, no `?`, not a command,
coordinates, a hex code, a callsign such as UAL2110 or N123AB, and nothing
that may be private) is sent to
-Photon for place suggestions: at most one request every 500 ms per tab,
+Photon for place suggestions (the suggester itself never sends a line of
+more than eight words, or ten with a number): at most one request every
+500 ms per tab,
and none for a minute after a refusal. Photon is the keyless geocoder the
place search already uses; a submitted search is not part of this spacing.
A line that may be one name ("Satellite Beach") is looked up whole. While
@@ -8058,49 +8152,93 @@ digits and "@" count, and digits of any script count as digits. It is
any line with: an "@" with something right on both sides, ending a word,
starting a lowercase handle ("@jdoe"), or spaced before a domain ("john @
gmail.com") (an email address or a handle, also while it is typed; spaced, as in "Nanjampeta @
-Chandambylu", it is part of a name); seven digits or more with nothing but spaces,
+Chandambylu", it is part of a name); an email spelled around a filter
+("john(at)gmail.com", "john[at]gmail[dot]com", "john at gmail dot de",
+"john at gmail.com", "john at gmail (dot) com"); an IP address
+("10.0.0.1", "::1", "fe80::1", "https://[::1]/"); a wallet's recovery
+phrase (see below); seven digits or more with nothing but spaces,
punctuation, symbols or format characters between them (a phone, card,
SSN or account number or its start: "+1 415 555", "4111 1111", "123 45
6789", "123456789", "4111.1111.1111.1111", "123–45–6789"; a street address's house number
-and its postcode are read apart: five digits, or between the street and
+and its postcode are read apart (a house number never starts with 0, and
+a polite word such as "thanks" after the digits is not a city): five digits, or between the street and
the city "00-950", "111 21", "125009", "1100-053", or four digits after a
-comma ("Straße 120, 1070 Wien"); and so are a US ZIP+4 after a word,
-a Brazilian CEP, a Japanese postcode after "〒" or before the address, and
+comma ("Straße 120, 1070 Wien"); and so are a US ZIP+4 after a state's
+code or name ("Alice 12345-6789" and "Jo 12345-6789" stay private),
+a Brazilian CEP, a Japanese postcode after "〒" or next to the address in
+Japanese script ("東京都千代田区100-0001"; after a Latin name, as in
+"Shibuya 150-0002", it reads as a phone number), and
digits on either side of "#", so "Hauptstrasse 12 10115 Berlin", "DC
20500-0003", "〒100-0001 東京都千代田区" and "Calle 100 # 19-61" are places,
while a seven-digit postcode alone such as "Tel Aviv 6100000" still reads
as private); a phone number written with dots; two letters, two
digits and ten more letters or digits (an IBAN's shape); "password",
-"passcode", "passwd", "ssn", "pw", "pwd" or "bearer" followed by anything,
-"token", "secret", "api key", "key" or "pass" followed by ":" or "=", a
+"passcode", "passwd", "pw" or "pwd" followed by anything, "bearer"
+followed by anything but a short capitalised name or a place word such as
+island or lake ("Bearer Island", "bearer island" are places),
+"ssn" followed by a digit, also after "ending", "ends in" or "last four"
+("SSN Station" is a place), "token", "secret",
+"api key", "key" or "pass" followed by ":" or "=", a licence, plate,
+passport, membership, account, policy, ticket, booking, confirmation or
+reference number with a digit after its label ("license ABC1234",
+"passport no. 123456"), "ID" in capitals followed by a number ("ID
+AB123"), "otp", "2fa", "mfa", "cvv", "cvc" or a verification, one-time,
+security, auth or login code followed by a code (any value after a label
+in lower case, "verification code Abc", also before "thanks", ", thanks", "cheers" or "thanks a lot"; after a label
+written as a name, any value that is not one: "OTP Bank" and "Security
+Code Plaza" are places), a "pin" or door, access, gate, alarm or entry
+code followed by a value in mixed case ("PIN aBcD"), a
door, access, gate, alarm, entry or security code followed by a digit, "api
key", "access token" or "secret key" followed by a word of six characters
or more, the word for "password" in the interface's languages
(contraseña, Passwort, mot de passe, пароль…) followed by anything, or "pin"
(also "pin code", "pin number", "pin is") followed by a digit; a word
-starting `sk_`, `sk-`, `rk_`, `pk_live`, `ghp_` or a Slack token's `xoxb-` and the like (any case) or
-`AIza`, `eyJ` or `AKIA`; or a word that may be a password or key, with letters and digits mixed
+starting `sk_`, `sk-`, `rk_`, `pk_live`, `ghp_`, `github_pat_`, `glpat-`, `hf_`, a SendGrid
+`SG.` key or a Slack token's `xoxb-` and the like (any case) or
+`AIza` or `eyJ`, or an AWS key id (`AKIA` and twelve capitals or digits
+more; "Akiak" is a place); or a word that may be a password or key, with letters and digits mixed
within one run (a number beside a word, as in "Yanino-1", "2-chōme" or
"Route-66", is a name): eight characters or more, six or more with four
letters and a digit ("hunter22", "Area51"), or six or more with letters,
digits and a symbol ("Tr0ub4dor&3"). The password words match whole words
-only ("Sachsenhausen" is a place). Over the bundled names (139,502), five
-read as private: two with stray digits ("Maliga0N", "Jerónim67") and three
-with number lists or codes. When the text may be private the field says
+only ("Sachsenhausen" is a place). Over the bundled names (139,502), six
+read as private: two with stray digits ("Maliga0N", "Jerónim67"), two
+joined by "@" to a lower-case handle ("Pulipadu @Govardhanagiri") and two
+with number lists or dates. When the text may be private the field says
so ("Looks private, so nothing is searched or sent"), and a line whose
only private sign is an address-sized run of digits (no group over six
-digits, nine at most in all, counted as they fold, and no word such as
+digits, nine at most in all, counted as they fold, no three digits
+followed by four as a phone number writes them, and no word such as
card, code, key, phone or account beside them, in English and some other
European languages; compounds such as "Kreditkartennummer" and words in
other scripts are not read), with words beside it, gets a row
to search it as a place on purpose ("Search … as a place anyway"), which
runs the ordinary place search and its online services only when picked; a
bare number, an email or handle, a password, key, code or IBAN gets none.
+A suggested house is named by its number and its street (or, without a
+street, its locality, district or city) in the order its country writes them: "10 Downing
+Street", "Hauptstraße 12".
A nine-digit number or a short phone number written with no such word
still gets the row: only picking it sends anything. One-time and verification codes,
OTP, 2FA, MFA, CVV and CVC values, "card ending" digits, passphrases,
-recovery or seed phrases, "my secret is …" and an email spelled out ("john
-at example dot com") are private too. Text that parses as coordinates or a
+recovery or seed phrases (twelve words in a row on the BIP39 English list
+in `src/search/bip39Words.js`, also with commas, numbered, quoted, joined by
+dashes or slashes, or after "my seed is", so a long question or request
+still goes to Ask GEV; twelve with four words for places or for asking about
+them, such as "park", "airport", "near" or "today", are a list or a request,
+which lets about one phrase in a hundred through), "my secret is …", an email spelled
+out ("john at example dot com", "punto com", or letter by letter), a door,
+alarm or lockbox number ("code 4821"; "zip code 90210" and "area code 415"
+are places), "Authorization: Bearer …", a code in a link (`?code=…`), a
+spaced UK National Insurance number and "my id is …" are private too.
+"Boise ID 83702" names Idaho. Some private text is not caught: a
+passphrase run together as one word (a long place name is one word too),
+a lower-case word after "otp", "2fa" or "mfa" ("mfa boston" is a name;
+"otp ABCDEF" is caught) and a code of lower-case letters after "pin" or
+"gate code" ("PIN ABCD" is caught).
+A Japanese postcode after a Latin name is refused ("Shibuya 150-0002"), and
+so is a name in capitals after a code's label ("MFA BOSTON", which cannot
+be told from "OTP ABCDEF"). Text that parses as coordinates or a
grid reference is not private. A place's name is six words at most, or ten
when it has a number in it (an address: "1600 Pennsylvania Ave NW
Washington DC 20500"). The places picked from the Omnibar's rows and chips that carry a position
@@ -8785,6 +8923,16 @@ on it.
per frame, it holds NO continuous-render hold — the governor stays idle with
earthquakes on, and the manager's `layer-tick` / `layer-visibility` requests
carry new data to the screen. Pinned in `src/data/earthquakes.test.mjs`.
+ The one animation is the selected quake's contour lines
+ (`src/app/layers/earthquakeRipples.js`), painted on the world overlay, not
+ the ground set: they ask for frames for `RIPPLE_ACTIVE_CYCLES` (3) runs out
+ to the disc's edge after a selection (about 14 s), only while the disc is on
+ screen, then rest as still contours and ask for none. A parked camera with a
+ quake selected therefore returns to idle. A feed refresh updates the
+ selected quake in place: it neither runs the contours again nor takes back
+ a shared selection made since; only a click or a label's activation does.
+ Selecting fades that one disc's flat fill once (an `upsert`, not per frame)
+ under the painted gradient.
- **Geocode framing has an off-centre sanity gate.** A viewport that is both
bigger than any city (>300 km diagonal) and not centred on its own geocoded
location (anchor >15% of the diagonal from the centroid) is replaced by a
diff --git a/docs/RENDERER-CONTRACT.md b/docs/RENDERER-CONTRACT.md
index 76d547cb09..99f41b8c3c 100644
--- a/docs/RENDERER-CONTRACT.md
+++ b/docs/RENDERER-CONTRACT.md
@@ -361,6 +361,18 @@ names the nearest frame's time once every globe tile drawn shows that
frame's own imagery (`src/render/cesium/imageryFrames.js`). The checks
`globe.imagery.frames` and `globe.imagery.video` cover both.
+It also draws `decoded` sources (`imageryDecoded`): tiles the application
+makes itself and hands over as finished images. Their slots are times: the
+source's `slotAt` names the slot a time shows and `prefetch` the slots held
+ahead, of which the first `prefetch` (the option, 1 by default) load unseen.
+Each slot is a Cesium imagery layer in the layer's tiling whose tiles are the
+images the source's `tile` answers, asked as `shown` or `prefetch`; a
+deferred tile is asked again on a later frame, a missing one draws its
+parent's, and a slot let go aborts the tiles it still waits on and closes an
+image that arrives after. A time with no slot draws nothing and announces
+nothing; `frameReady` names the slot shown once it is drawn. The check
+`globe.imagery.decoded` covers it.
+
Every Cesium draw set takes `setColumns` (`columns`): icon sets on the GPU,
any other as the rows the columns make over the items it holds, each row the
item of that id with the columns' fields over it, replacing every item as
diff --git a/docs/SCENE-DOCUMENT.md b/docs/SCENE-DOCUMENT.md
index 6d4077d959..948062c8e0 100644
--- a/docs/SCENE-DOCUMENT.md
+++ b/docs/SCENE-DOCUMENT.md
@@ -54,8 +54,14 @@ fallback for zero; holds may be zero.
Visual fields are `style`, `mapStack`, `styleParams`, `bloom`, `sharpen`, `hud`, and
`detection`, and `scope`. Bloom has `enabled`, `intensity`, `version`; sharpen has `enabled`,
-`intensity`; HUD has `visible`, `variant`; detection has `mode`, `density`,
+`intensity`; HUD has `visible`, `variant` and an optional `sonar`; detection has `mode`, `density`,
`allocation`, `fadePct` and `outsideOpacityPct`. Scope has `enabled`, `featherPct`.
+HUD `sonar: true` is Sonar on beside a layout that cannot say it (Minimal); it
+is written only then, so Tactical with Sonar stays the variant `cyber` and a
+shot without Sonar has no `sonar`. A shot without it opens with Sonar on only
+when its variant is `cyber`. A build from before `sonar` refuses a project
+that has it, as it refuses any field it does not know; every other project
+still opens there.
The latter settings were written by Update Shot but previously lost during
normalization; they now survive import and capture.
Version-1/2 bloom without an explicit scale version uses the original inverted
diff --git a/docs/SHARE-LINK-FORMAT.md b/docs/SHARE-LINK-FORMAT.md
index 888c3a91e3..41e1b81abd 100644
--- a/docs/SHARE-LINK-FORMAT.md
+++ b/docs/SHARE-LINK-FORMAT.md
@@ -176,7 +176,11 @@ Opacity slider (the long form's `sco`). It is written only below 100, so a
link made before it, which opens at full opacity, keeps its code.
Flag bits (field 9): 0 `bloom`, 1 `sharpen`, 2 `hudVisible`, 3
-`celestialRing` (each defaulting by style), 4 `scopeEnabled` (default on).
+`celestialRing` (each defaulting by style), 4 `scopeEnabled` (default on), 5
+`hudSonar` (default off). `hudSonar` is Sonar on beside a HUD layout whose code
+cannot say so, Minimal (the long form's `hs=1`); Tactical with Sonar stays the
+`cyber` layout code alone. A link made before the bit has it off, and opens
+with Sonar on only when it names `cyber`, as before.
### Style defaults
diff --git a/scripts/format-scope.json b/scripts/format-scope.json
index 78f3edbf24..080febd46b 100644
--- a/scripts/format-scope.json
+++ b/scripts/format-scope.json
@@ -441,6 +441,12 @@
"src/layers/earthquakes/model.js",
"src/layers/earthquakes/source.js",
"src/layers/earthquakes/ownership.test.mjs",
+ "src/layers/earthquakes/selection.test.mjs",
+ "src/layers/submarineCables/interaction.test.mjs",
+ "src/ui/entityContextBridge.test.mjs",
+ "src/layers/launches/clickYield.test.mjs",
+ "src/app/layers/earthquakeRipples.js",
+ "src/app/layers/earthquakeRipples.test.mjs",
"src/layers/perimeters/index.js",
"src/layers/perimeters/records.js",
"src/layers/perimeters/source.js",
@@ -660,6 +666,7 @@
"src/layers/alpr/model.js",
"src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js",
+ "src/layers/alpr/presentation.test.mjs",
"src/layers/alpr/visuals.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/overlay.test.mjs",
@@ -1558,6 +1565,8 @@
"dev/stub-app/main.js",
"scripts/qa-stub-boot.mjs",
"src/ui/creditsView.js",
+ "src/ui/creditLineHeight.js",
+ "src/ui/creditLineHeight.test.mjs",
"src/ui/creditsView.test.mjs",
"src/cockpitSubjectProviders.js",
"src/cockpitSubjectProviders.test.mjs",
@@ -1592,6 +1601,7 @@
"src/data/wikidataCities.js",
"src/data/wikidataCities.test.mjs",
"scripts/build-wikidata-cities.mjs",
+ "src/search/bip39Words.js",
"src/search/placeSuggestions.test.mjs",
"scripts/wikidataPlaceTiles.mjs",
"src/tooling/wikidataPlaceTiles.test.mjs",
@@ -1599,5 +1609,9 @@
"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",
+ "src/layers/bikeshare/selection.test.mjs",
+ "src/layers/satellites/interaction.test.mjs"
]
diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json
index 8910282ebc..dbbfdf35bd 100644
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@ -307,7 +307,8 @@
"src/ui/omnibarRows.js",
"src/search/gridReference.js",
"src/search/coordinateParser.js",
- "src/search/placeSuggestions.js"
+ "src/search/placeSuggestions.js",
+ "src/search/bip39Words.js"
],
"external": ["vue", "pinia", "vue-i18n"]
},
@@ -2590,7 +2591,8 @@
"src/layers/earthquakes/model.js",
"src/layers/earthquakes/source.js",
"src/layers/earthquakes/records.js",
- "src/time/worldClock.js"
+ "src/time/worldClock.js",
+ "src/data/trackingClickGesture.js"
],
"external": ["cesium"]
},
@@ -4189,6 +4191,7 @@
"src/app/layers/bikeshare.js",
"src/app/layers/cctv.js",
"src/app/layers/cyclones.js",
+ "src/app/layers/earthquakeRipples.js",
"src/app/layers/earthquakes.js",
"src/app/layers/firms.js",
"src/app/layers/flights.js",
@@ -5475,6 +5478,7 @@
"src/render/applicationHooks.js",
"src/maps/globeEngine.js",
"src/render/cesium/viewers.js",
+ "src/ui/creditLineHeight.js",
"src/ui/creditsView.js",
"src/data/planespottersPhoto.js",
"src/maps/keylessTerrain.js",
@@ -5604,6 +5608,7 @@
"src/app/layers/bikeshare.js",
"src/app/layers/cctv.js",
"src/app/layers/cyclones.js",
+ "src/app/layers/earthquakeRipples.js",
"src/app/layers/earthquakes.js",
"src/app/layers/firms.js",
"src/app/layers/flights.js",
diff --git a/scripts/qa-firstrun-mutations.mjs b/scripts/qa-firstrun-mutations.mjs
index 91e303885a..2c622598fd 100644
--- a/scripts/qa-firstrun-mutations.mjs
+++ b/scripts/qa-firstrun-mutations.mjs
@@ -276,21 +276,21 @@ const MUTATIONS = [
},
{
defect: 'the tile stops promising the fires it actually turns on',
- file: 'html',
+ file: 'module',
from: " 'Live earthquakes and active fires, from USGS and NASA',",
to: " 'Live earthquakes worldwide, straight from USGS',",
},
{
- defect: 'the owner-authored first-run line is quietly rewritten',
+ defect: 'the maintainer-authored first-run line is quietly rewritten',
file: 'html',
from: 'It feels like a forbidden cockpit—then you realize the sources are public and the data is real.',
- to: "It feels like a forbidden cockpit. It isn't — every feed is public, and every contact is live.",
+ to: 'A live 3D globe of public data. Pick a view to begin.',
},
{
defect: 'the ledgered global-chip defect loses its pointer to the real fix',
file: 'module',
- from: ' // means a KEY REQUIRED terminal state in src/loadingFeedback.js, a state',
- to: ' // (note removed)',
+ from: ' // ends KEY REQUIRED (src/loadingFeedback.js), and the quakes half of the',
+ to: ' // ends KEY REQUIRED, and the quakes half of the',
},
{
defect: 'the globe missions never pull the camera out',
@@ -314,7 +314,7 @@ const MUTATIONS = [
defect: 'Explore manually quietly runs a mission instead of nothing',
file: 'module',
from: "if (mission.kind === 'none') return { ok: true, choice };",
- to: "if (mission.kind === 'none') return { ok: true, choice, ran: await setContextMode('contacts') };",
+ to: "if (mission.kind === 'none') return { ok: true, choice, ran: await setLayerEnabled('rocket-launches') };",
},
{
defect: 'an unknown choice is treated as a success',
@@ -348,15 +348,14 @@ const MUTATIONS = [
{
defect: 'a mission persists a 3D-models choice nobody made',
file: 'module',
- from: ' const result = await styleManager.setContextMode(mode);',
- to: ' styleManager._setModels3dEnabled?.(true);\n const result = await styleManager.setContextMode(mode);',
+ from: " setLayerEnabled: (layerId) =>\n dataManager.setEnabled(layerId, true, { origin: 'user' }),",
+ to: " setLayerEnabled: (layerId) => {\n styleManager._setModels3dEnabled?.(true);\n return dataManager.setEnabled(layerId, true, { origin: 'user' });\n },",
},
{
- defect:
- 'the Context panel is left collapsed, hiding the mode that just started',
+ defect: 'a mission writes panel chrome nobody chose',
file: 'module',
- from: " styleManager.setPanelCollapsed?.('global-context-panel', false, {\n explicit: true,\n });",
- to: ' // panel reveal removed',
+ from: ' flyToGlobe: () => styleManager.resetToGlobeView(),',
+ to: " flyToGlobe: () => {\n styleManager.setPanelCollapsed?.('global-context-panel', false, { explicit: true });\n return styleManager.resetToGlobeView();\n },",
},
{
defect:
@@ -371,8 +370,8 @@ const MUTATIONS = [
defect:
'disabling the focused tile drops the keyboard to
mid-flight',
file: 'html',
- from: ':aria-disabled="launcher?.busy ?? undefined" @click="controls?.choose(\'contacts\')"',
- to: ':disabled="launcher?.busy === \'true\'" @click="controls?.choose(\'contacts\')"',
+ from: ':aria-disabled="String(settling || launcher?.busy === \'true\')" @click="onPrimary"',
+ to: ':disabled="launcher?.busy === \'true\'" @click="onPrimary"',
},
{
defect: 'Tab escapes into an app the visitor has not seen yet',
@@ -421,8 +420,8 @@ const MUTATIONS = [
defect:
'the card loses its viewport cap and clips on a short landscape phone',
file: 'css',
- from: ' max-height: calc(100dvh - 1.5rem);',
- to: ' /* cap removed */',
+ from: ' body.mobile-shell #first-run-launcher {\n bottom: 5.8rem;\n max-height: calc(100vh - 6.55rem);\n max-height: calc(100dvh - 6.55rem);\n }',
+ to: ' body.mobile-shell #first-run-launcher {\n bottom: 5.8rem;\n /* cap removed */\n }',
},
{
defect:
@@ -437,7 +436,7 @@ const MUTATIONS = [
// those instead and prove nothing about this feature.
defect: "the launcher's reduced-motion opt-out is dropped",
file: 'css',
- from: ' #first-run-launcher,\n .first-run-choices button,\n .first-run-arrow {\n transition: none;\n }\n /* Scrolling a tile into view must not animate either. */\n .first-run-choices {\n scroll-behavior: auto;\n }',
+ from: ' #first-run-launcher,\n .first-run-backdrop,\n .first-run-back,\n .first-run-missions button,\n .first-run-link-card,\n .first-run-link-button,\n .first-run-enter {\n transition: none;\n }\n /* Scrolling a tile into view must not animate either. */\n .first-run-choices {\n scroll-behavior: auto;\n }',
to: ' .first-run-nothing {\n transition: none;\n }',
},
@@ -445,14 +444,14 @@ const MUTATIONS = [
{
defect: 'a mission tile is dropped from the menu',
file: 'html',
- from: ' page.evaluate(() => {
const gev = window.__godsEyeView || {};
const sm = gev.styleManager;
const dm = gev.dataManager;
- const carto = sm?.viewer?.camera?.positionCartographic;
+ const carto = gev.viewer?.camera?.positionCartographic;
const layers = {};
const counts = {};
const all = dm?.getAll?.() || [];
@@ -170,8 +170,22 @@ async function watchLoadingChip(page) {
const readLoadingChip = (page) => page.evaluate(() => window.__chipSeen || []);
+async function nextStep(page, readySelector) {
+ await page.click('[data-first-run-next]');
+ await page.waitForSelector(readySelector, { visible: true });
+ await page.waitForFunction(() => {
+ const steps = [...document.querySelectorAll('#first-run-launcher .first-run-step')];
+ return steps.length === 1
+ && !/first-run-step-(forward|back)-(enter|leave)-/.test(steps[0].className)
+ && document.querySelector('[data-first-run-primary]')?.getAttribute('aria-disabled') !== 'true';
+ });
+}
+
async function pick(page, choice, { timeout = 40000, settle = [] } = {}) {
- await page.click(`[data-first-run-choice="${choice}"]`);
+ await nextStep(page, '[data-first-run-start]');
+ await page.click(`[data-first-run-start="${choice}"]`);
+ await nextStep(page, '[data-first-run-choice]');
+ await page.click('[data-first-run-choice]');
await page.waitForFunction(
(sel) => !document.querySelector(sel) || !document.querySelector(sel).classList.contains('visible'),
{ timeout },
@@ -190,8 +204,8 @@ async function pick(page, choice, { timeout = 40000, settle = [] } = {}) {
/** Every section the run is expected to reach; the teeth verdict requires all. */
const EXPECTED_SECTIONS = [
'show-policy', 'esc-arbitration',
- 'mission-environmental', 'mission-contacts', 'mission-space', 'mission-explore',
- 'viewports', 'console',
+ 'mission-environmental', 'mission-space', 'mission-explore',
+ 'stories-card', 'viewports', 'console',
];
/*
@@ -482,8 +496,8 @@ async function main() {
record('a fresh session gets the launcher', freshVisible);
if (freshVisible) shots.push(await shoot(page, 'launcher-desktop'));
- const focused = await page.evaluate(() => document.activeElement?.dataset?.firstRunChoice ?? null);
- record('focus lands on the first mission tile', focused === 'contacts', `activeElement=${focused}`);
+ const focused = await page.evaluate(() => document.activeElement?.hasAttribute('data-first-run-next') ?? false);
+ record('focus lands on Next', focused === true, `activeElement=${focused}`);
// The card is a flex column (so its list can scroll on short viewports),
// and an author `display` on this id outranks the UA's `[hidden]` rule.
@@ -500,10 +514,11 @@ async function main() {
record('the hidden attribute still hides the flex card', hiddenHonored === 'none',
`computed display while hidden = ${hiddenHonored}`);
- const tiles = await page.$$eval('[data-first-run-choice]', (nodes) => nodes.map((n) => n.dataset.firstRunChoice));
+ await nextStep(page, '[data-first-run-start]');
+ const tiles = await page.$$eval('[data-first-run-start]', (nodes) => nodes.map((n) => n.dataset.firstRunStart));
record(
- 'four tiles in the owner\'s order',
- JSON.stringify(tiles) === JSON.stringify(['contacts', 'space-missions', 'environmental', 'explore']),
+ 'three tiles in the owner\'s order',
+ JSON.stringify(tiles) === JSON.stringify(['space-missions', 'environmental', 'explore']),
tiles.join(' · '),
);
@@ -558,7 +573,7 @@ async function main() {
// ── Mission outcomes ────────────────────────────────────────────────────
// One section PER MISSION: a throw in one (a tile that never rendered under
- // --teeth, say) must not take the other four down with it, or the teeth
+ // --teeth, say) must not take the other two down with it, or the teeth
// tally reports "reached" for assertions that never ran.
let state;
let before;
@@ -642,22 +657,6 @@ async function main() {
shots.push(await shoot(page, 'mission-environmental'));
});
- await section('mission-contacts', async () => {
- await open(page, { query: "?welcome=1", errorSink: consoleErrors });
- await pick(page, 'contacts');
- state = await appState(page);
- record('LIVE CONTACTS activates the Contacts context mode', state.contextMode === 'flights',
- `contextMode=${state.contextMode}`);
- const panelOpen = await page.evaluate(() => {
- const panel = document.getElementById('global-context-panel');
- return !!panel && !panel.classList.contains('collapsed');
- });
- record('LIVE CONTACTS reveals the Context panel', panelOpen);
- record('LIVE CONTACTS still leaves the detection override untouched',
- state.detectionOverridden === false, `_detectionUserOverridden=${state.detectionOverridden}`);
- shots.push(await shoot(page, 'mission-contacts'));
- });
-
await section('mission-space', async () => {
await open(page, { query: "?welcome=1", errorSink: consoleErrors });
await pick(page, 'space-missions');
@@ -674,25 +673,77 @@ async function main() {
`layerOn=${missions.layerOn} contextMode=${state.contextMode}`);
record('SPACE MISSIONS opens its own panel', missions.panelOpen,
`panelOpen=${missions.panelOpen}`);
+ record('SPACE MISSIONS still leaves the detection override untouched',
+ state.detectionOverridden === false, `_detectionUserOverridden=${state.detectionOverridden}`);
shots.push(await shoot(page, 'mission-space-missions'));
});
await section('mission-explore', async () => {
await open(page, { query: "?welcome=1", errorSink: consoleErrors });
+ // Start below the mission overview so an accidental overview flight is observable.
+ await page.evaluate(() => {
+ const camera = window.__godsEyeView.viewer.camera;
+ camera.cancelFlight();
+ camera.setView({ destination: camera.position.constructor.fromDegrees(-97.7431, 30.2672, 100000) });
+ });
const beforeExplore = await appState(page);
await pick(page, 'explore');
state = await appState(page);
record('EXPLORE MANUALLY enables no layer and no context mode',
Object.values(state.layers).every((on) => !on) && state.contextMode === null,
Object.entries(state.layers).filter(([, on]) => on).map(([id]) => id).join(', ') || 'nothing enabled');
- // The real claim is that Explore issues no camera command of its own: the
- // arrival fly-in owns the camera and must still be heading down, not out.
record('EXPLORE MANUALLY never commandeers the camera',
- (state.heightKm ?? 0) < 12000 && (state.heightKm ?? 1e9) <= (beforeExplore.heightKm ?? 1e9),
- `${beforeExplore.heightKm} → ${state.heightKm} km (globe would be 18000)`);
+ beforeExplore.heightKm === 100 && state.heightKm === beforeExplore.heightKm,
+ `${beforeExplore.heightKm} → ${state.heightKm} km (expected 100 → 100 km)`);
shots.push(await shoot(page, 'mission-explore'));
});
+ await section('stories-card', async () => {
+ await open(page, { query: "?welcome=1", errorSink: consoleErrors });
+ const backdrop = await page.evaluate(() => {
+ const el = document.querySelector('.first-run-backdrop');
+ if (!el) return null;
+ const style = getComputedStyle(el);
+ return {
+ filter: style.backdropFilter || style.webkitBackdropFilter || 'none',
+ background: style.backgroundColor,
+ pointerEvents: style.pointerEvents,
+ };
+ });
+ record('the welcome backdrop tints the globe without blurring it',
+ !!backdrop && backdrop.filter === 'none' && backdrop.background !== 'rgba(0, 0, 0, 0)'
+ && backdrop.pointerEvents === 'none',
+ JSON.stringify(backdrop));
+ await nextStep(page, '[data-first-run-start]');
+ await nextStep(page, '[data-first-run-choice]');
+ const button = await page.evaluate(() => {
+ const el = document.querySelector('#first-run-launcher [data-first-run-stories]');
+ return el ? { tag: el.tagName, href: el.getAttribute('href'), target: el.getAttribute('target') } : null;
+ });
+ record('the GEV Stories card offers an in-app BROWSE STORIES button',
+ button?.tag === 'BUTTON' && button.href === null && button.target === null,
+ JSON.stringify(button));
+ const pagesBefore = (await browser.pages()).length;
+ await page.click('#first-run-launcher [data-first-run-stories]');
+ const opened = await page.waitForFunction(
+ () => document.body.classList.contains('stories-mode')
+ && !!document.querySelector('#gev-stories .app'),
+ { timeout: 30000 },
+ ).then(() => true, () => false);
+ const after = await page.evaluate((sel) => ({
+ launcherVisible: !!document.querySelector(sel)?.classList.contains('visible'),
+ session: sessionStorage.getItem('gev:first-run-mission-session:v1'),
+ query: location.search,
+ }), LAUNCHER);
+ record('BROWSE STORIES opens Stories Explore in this tab',
+ opened && (await browser.pages()).length === pagesBefore,
+ `stories-mode=${opened}, query=${after.query}`);
+ record('BROWSE STORIES closes the welcome card for the session',
+ !after.launcherVisible && after.session !== null,
+ `visible=${after.launcherVisible}, session=${after.session}`);
+ shots.push(await shoot(page, 'stories-card-explore'));
+ });
+
// ── Viewports ───────────────────────────────────────────────────────────
await section('viewports', async () => {
// Portrait phone, LANDSCAPE phone (the short viewport that clipped the card
@@ -705,6 +756,8 @@ async function main() {
for (const vp of VIEWPORTS) {
await page.setViewport({ width: vp.width, height: vp.height, deviceScaleFactor: vp.dpr });
await open(page, { query: "?welcome=1", errorSink: consoleErrors });
+ for (let step = 1; step <= 3; step++) {
+ if (step > 1) await nextStep(page, step === 2 ? '[data-first-run-start]' : '[data-first-run-choice]');
const box = await page.evaluate((sel) => {
const node = document.querySelector(sel);
if (!node) return null;
@@ -725,22 +778,23 @@ async function main() {
const fits = !!box && box.top >= 0 && box.bottom <= box.vh
&& box.left >= 0 && box.right <= box.vw;
record(
- `the launcher fits a ${vp.label} with no clipping`,
+ `step ${step} fits a ${vp.label} with no clipping`,
fits,
box ? `${box.left},${box.top} → ${box.right},${box.bottom} in ${box.vw}x${box.vh}${box.listScrolls ? ' (list scrolls)' : ''}` : 'absent',
);
- record(`"Don't show this again" stays on screen at ${vp.width}x${vp.height}`,
+ record(`step ${step} checkbox stays on screen at ${vp.width}x${vp.height}`,
!!box?.checkboxOnScreen);
// Discoverability: if the list scrolls, the LAST tile must still peek
// above the fold. A fold that lands exactly between tiles looks like a
- // complete list of four, and the fifth mission is simply never found.
+ // complete list, and the last mission is simply never found.
+ if (step === 2) {
const peek = await page.evaluate((sel) => {
const node = document.querySelector(sel);
const list = node?.querySelector('.first-run-choices');
if (!list) return null;
list.scrollTop = 0;
- const tiles = [...list.querySelectorAll('[data-first-run-choice]')];
+ const tiles = [...list.querySelectorAll('[data-first-run-start]')];
const last = tiles[tiles.length - 1];
if (!last) return null;
const listBox = list.getBoundingClientRect();
@@ -749,7 +803,7 @@ async function main() {
return {
scrolls: list.scrollHeight > list.clientHeight + 1,
fraction: lastBox.height ? visible / lastBox.height : 0,
- label: last.dataset.firstRunChoice,
+ label: last.dataset.firstRunStart,
};
}, LAUNCHER);
record(
@@ -765,7 +819,7 @@ async function main() {
const reach = await page.evaluate(async (sel) => {
const node = document.querySelector(sel);
if (!node) return null;
- const targets = [...node.querySelectorAll('[data-first-run-choice], [data-first-run-suppress]')];
+ const targets = [...node.querySelectorAll('[data-first-run-start], [data-first-run-suppress]')];
const offscreen = [];
for (const target of targets) {
target.focus();
@@ -774,7 +828,7 @@ async function main() {
const host = node.getBoundingClientRect();
if (document.activeElement !== target
|| rect.bottom <= host.top || rect.top >= host.bottom) {
- offscreen.push(target.dataset.firstRunChoice || 'suppress-checkbox');
+ offscreen.push(target.dataset.firstRunStart || 'suppress-checkbox');
}
}
return { count: targets.length, offscreen };
@@ -783,7 +837,7 @@ async function main() {
// A hardcoded count silently turns into a failure the day the menu
// changes, which is exactly what it did when a tile was removed.
const expectedFocusable = await page.$$eval(
- '[data-first-run-choice]', (nodes) => nodes.length,
+ '[data-first-run-start]', (nodes) => nodes.length,
) + 1;
record(
`every tile and the checkbox are keyboard-reachable at ${vp.width}x${vp.height}`,
@@ -792,6 +846,7 @@ async function main() {
? `${reach.count}/${expectedFocusable} focusable${reach.offscreen.length ? `, unreachable: ${reach.offscreen.join(', ')}` : ''}`
: 'absent',
);
+ }
// The reachability probe above tabs to the last tile and scrolls the list
// with it. Put it back to the top so the taste-pass shot shows what a
// visitor actually opens on.
@@ -801,7 +856,8 @@ async function main() {
document.activeElement?.blur?.();
}, LAUNCHER);
await sleep(250);
- shots.push(await shoot(page, `launcher-${vp.name}`));
+ shots.push(await shoot(page, `launcher-${vp.name}-step-${step}`));
+ }
}
await page.setViewport({ width: 1440, height: 900, deviceScaleFactor: 1 });
});
diff --git a/scripts/qa-floor-hold.mjs b/scripts/qa-floor-hold.mjs
index 0b67b39943..49a9c51a82 100644
--- a/scripts/qa-floor-hold.mjs
+++ b/scripts/qa-floor-hold.mjs
@@ -111,7 +111,7 @@ await page.waitForFunction(() => window.__godsEyeView?.viewer && window.__godsEy
{ timeout: 150000 });
await sleep(12000); // let the boot fly-to settle before pinning
await page.evaluate(() => {
- document.querySelector('#first-run-launcher:not([hidden]) [data-first-run-choice="explore"]')?.click();
+ document.querySelector('#first-run-launcher:not([hidden]) [data-first-run-dismiss]')?.click();
});
await sleep(600); // let the launcher dismissal finish before taking evidence
diff --git a/scripts/qa-street-level.mjs b/scripts/qa-street-level.mjs
index 3dd0a3aa5f..147ce35655 100644
--- a/scripts/qa-street-level.mjs
+++ b/scripts/qa-street-level.mjs
@@ -231,9 +231,6 @@ async function boot(page, url) {
await page.waitForFunction(() => Boolean(window.__godsEyeView?.dataManager), {
timeout: 150_000,
});
- await page.evaluate(() =>
- document.querySelector('.first-run-explore')?.click(),
- );
await page.keyboard.press('Escape');
await page.evaluate(() => {
for (const el of document.querySelectorAll(
diff --git a/scripts/track-regression.mjs b/scripts/track-regression.mjs
index fb745e48d6..d05fea2a01 100644
--- a/scripts/track-regression.mjs
+++ b/scripts/track-regression.mjs
@@ -1637,19 +1637,48 @@ async function main() {
// The fixture planes repeat one position, so the icon holds and draws no
// head. Fly the tracked one east for this check; the display runs 30 s
// behind, so give it time to reach the moving reports.
- await evalPage((icao) => {
+ await evalPage(async (icao) => {
+ const { rendererOf } = await import(`${window.__gevQaSourceBase || '/src'}/render/rendererOf.js`);
+ const app = window.__godsEyeView;
+ const fl = app.dataManager.layers.get('flights').module;
+ // Observe this selection's actual draw-port submissions: trails no
+ // longer live in viewer.entities. Disabling destroys the reused trail
+ // set, so this selection creates one the probe can identify.
+ await app.dataManager.setEnabled('flights', false);
+ const draw = rendererOf(app.viewer).draw;
+ const createLines = draw.lines;
+ let head = null;
+ let trail = null;
+ draw.lines = function (spec) {
+ const set = createLines.call(this, spec);
+ if (!spec.id.startsWith('trail:')) return set;
+ draw.lines = createLines;
+ trail = set;
+ const upsert = set.upsert;
+ set.upsert = function (items) {
+ const result = upsert.call(this, items);
+ for (const item of items)
+ if (/^gev-trail:\d+:head$/.test(item.id)) head = item;
+ return result;
+ };
+ const clear = set.clear;
+ set.clear = function () { head = null; return clear.call(this); };
+ const dispose = set.dispose;
+ set.dispose = function () { head = null; trail = null; return dispose.call(this); };
+ return set;
+ };
+ window.__qaTrailHead = () => trail?.show && head?.show !== false ? head?.positions : null;
+ window.__qaRestoreTrailProbe = () => { draw.lines = createLines; };
+ await app.dataManager.setEnabled('flights', true);
+ if (!fl.trackById(icao)) throw new Error('trail fixture could not reselect its aircraft');
const f = window.__SYNTH.flights.find((p) => p.icao === icao);
f.moveFromMs = Date.now();
}, trackedIcao);
await sleep(55_000);
const headSamples = await sampleFrames(page, 40, (icao) => {
- const viewer = window.__godsEyeView.viewer;
const fl = window.__godsEyeView.dataManager.layers.get('flights').module;
- const ent = viewer.trackedEntity;
- const time = viewer.clock.currentTime;
- const head = viewer.entities.values.find((e) => String(e.id).startsWith('gev-trail:fl-head-'));
- const line = head?.polyline?.positions?.getValue(time);
- const drawn = ent?.position?.getValue(time);
+ const line = window.__qaTrailHead();
+ const drawn = window.__qaFollowed()?.position?.();
if (!line?.length || !drawn) return null;
const end = line[line.length - 1];
const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
@@ -1695,10 +1724,8 @@ async function main() {
for (let i = 0; i < 8; i++) {
await sleep(600);
betweenFrames.push(await evalPage((icao) => {
- const viewer = window.__godsEyeView.viewer;
- const head = viewer.entities.values.find((e) => String(e.id).startsWith('gev-trail:fl-head-'));
- const line = head?.polyline?.positions?.getValue(viewer.clock.currentTime);
- const drawn = viewer.trackedEntity?.position?.getValue(viewer.clock.currentTime);
+ const line = window.__qaTrailHead();
+ const drawn = window.__qaFollowed()?.position?.();
if (!line?.length || !drawn) return null;
const end = line[line.length - 1];
return Math.hypot(end.x - drawn.x, end.y - drawn.y, end.z - drawn.z);
@@ -1712,10 +1739,11 @@ async function main() {
f.lon += (f.vel * (Date.now() - f.moveFromMs)) / 1000
/ (111320 * Math.cos((f.lat * Math.PI) / 180));
delete f.moveFromMs;
+ window.__qaRestoreTrailProbe();
}, trackedIcao);
const headUsable = headSamples.values.filter((v) => v != null);
if (headUsable.length < 10) {
- skip('trail head: ends at the drawn icon on every frame',
+ record('trail head: ends at the drawn icon on every frame', false,
`only ${headUsable.length} frames with a drawn head (timedOut=${headSamples.timedOut})`);
} else {
const worst = Math.max(...headUsable.map((v) => v.end));
@@ -3681,6 +3709,9 @@ async function main() {
} while (Date.now() < fleetClampDeadline
&& (!Number.isFinite(fleetH) || fleetH < seeded + 1));
if (!fl.trackById('aaa097')) return { error: 'trackById(aaa097) failed' };
+ // The tracked contact obeys the same 3D toggle as the fleet. Arm it
+ // before testing the cold-ground gate and the warm model handoff.
+ fl.setParams({ models3d: true });
await window.__dfSettle(1500);
// Read the tracked entity's rendered height plus the floor under it and
// the sensor value the data APIs report, at whatever regime the camera
@@ -3770,6 +3801,7 @@ async function main() {
};
const trackedEntity = window.__qaFollowed();
const trackedModel = findOwnModel();
+ if (!trackedModel) return { error: 'tracked model absent before exit' };
const achievedOut = await window.__dfZoomAbove(window.__dfRegime.exit + 5000);
const zoomedOut = await window.__dfObserveTrackedExit({
scene: v.scene, trackedEntity, trackedModel, getTrackedModel: findOwnModel,
@@ -3908,10 +3940,8 @@ async function main() {
// the tracked billboard becomes the visual again. Gating the clamp on
// model EXISTENCE put the burial straight back in exactly that state.
//
- // This scenario also pins the toggle contract itself. The DISPLAY-rail
- // "3D" toggle stays OFF for the whole block on purpose: it governs the
- // FLEET's draw-call budget only, and the tracked contact must still take
- // its model on zoom without the operator arming anything.
+ // The tracked contact obeys the shared 3D toggle. Keep it enabled
+ // while zoom alone hands the visual between model and billboard.
const dfRetained = await evalPage(async () => {
const v = window.__godsEyeView.viewer;
const Cesium = await import('/node_modules/cesium/Build/Cesium/index.js');
@@ -3924,13 +3954,13 @@ async function main() {
// and there would otherwise hand an open skin to the seeded scenarios
// that follow; closing an already-closed skin is inert.
try {
- // Toggle OFF throughout — the tracked model must not need it.
- fl.setParams({ models3d: false });
- const toggleOff = fl.getParams().models3d === false;
+ // Arm the shared toggle so the zoom regime can retain a hidden model.
+ fl.setParams({ models3d: true });
+ const toggleOn = fl.getParams().models3d === true;
if (!fl.trackById('aaa097')) return { error: 'trackById(aaa097) failed' };
await window.__dfSettle(600);
// Below the ENTER ceiling (trackById re-frames to the close follow
- // range): the tracked model arrives on zoom alone, toggle still off.
+ // range): the tracked model arrives on zoom alone, 3D enabled.
const belowH = await window.__dfZoomBelow(window.__dfRegime.enter - 20000);
const withModel = await window.__dfAwaitTrackedModel('aaa097', 20000);
// Same split as the regime scenario: a browser with no usable GLB
@@ -3980,7 +4010,7 @@ async function main() {
const ent2 = window.__qaFollowed()?.position?.();
const c2 = ent2 ? window.__dfCarto(ent2) : null;
const out = {
- toggleOff,
+ toggleOn,
enter: window.__dfRegime.enter,
exit: window.__dfRegime.exit,
belowH,
@@ -4015,23 +4045,19 @@ async function main() {
record('display-floor/T7: while the tracked MODEL is the visual, the clamp stands aside',
!dfRetained.error && dfRetained.modelsRenderingBelow > 0,
dfRetained.error
- || `${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering at ${(dfRetained.belowH / 1000).toFixed(0)} km with the 3D toggle OFF; entity at ${Number(dfRetained.withModelH).toFixed(1)} m (ground-snap owns it)`);
+ || `${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering at ${(dfRetained.belowH / 1000).toFixed(0)} km with the 3D toggle ON; entity at ${Number(dfRetained.withModelH).toFixed(1)} m (ground-snap owns it)`);
- // The toggle contract after auto-3D (2026-08-20): the DISPLAY-rail "3D"
- // switch owns the FLEET only. The tracked contact's model is default-on
- // and decided purely by camera distance, so with the toggle OFF it is
- // SHOWN below the enter ceiling and handed back above the exit ceiling —
- // and handed back by HIDING, not destroying, which is the retained state
- // the floor pin below depends on.
- record('display-floor/regime: the 3D toggle governs the FLEET only — the tracked model follows the zoom',
- !dfRetained.error && dfRetained.toggleOff === true
+ // With 3D enabled, zooming out hides rather than destroys the
+ // tracked model: the retained state the floor check depends on.
+ record('display-floor/regime: with 3D enabled the tracked model follows the zoom',
+ !dfRetained.error && dfRetained.toggleOn === true
&& dfRetained.modelsRenderingBelow > 0
&& dfRetained.belowH < dfRetained.enter
&& dfRetained.shownModelsAbove === 0
&& dfRetained.hiddenModelsAbove > 0
&& dfRetained.aboveH > dfRetained.exit,
dfRetained.error
- || `toggle OFF throughout: at ${(dfRetained.belowH / 1000).toFixed(0)} km (< ${(dfRetained.enter / 1000).toFixed(0)} km enter) ${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering; at ${(dfRetained.aboveH / 1000).toFixed(0)} km (> ${(dfRetained.exit / 1000).toFixed(1)} km exit) ${dfRetained.shownModelsAbove} shown / ${dfRetained.hiddenModelsAbove} retained-hidden`);
+ || `toggle ON throughout: at ${(dfRetained.belowH / 1000).toFixed(0)} km (< ${(dfRetained.enter / 1000).toFixed(0)} km enter) ${dfRetained.modelsRenderingBelow} aaa097 model(s) rendering; at ${(dfRetained.aboveH / 1000).toFixed(0)} km (> ${(dfRetained.exit / 1000).toFixed(1)} km exit) ${dfRetained.shownModelsAbove} shown / ${dfRetained.hiddenModelsAbove} retained-hidden`);
record('display-floor: a retained-but-hidden tracked model does NOT suppress the floor',
Number.isFinite(dfRetained.afterSeedH)
diff --git a/src/app/layers/earthquakeRipples.js b/src/app/layers/earthquakeRipples.js
new file mode 100644
index 0000000000..015a101189
--- /dev/null
+++ b/src/app/layers/earthquakeRipples.js
@@ -0,0 +1,428 @@
+import { registerWorldOverlayPaintLane } from '../../overlays/worldOverlay.js';
+import { fromDegrees } from '../../geo/ellipsoid.js';
+import {
+ earthquakeContourRings,
+ earthquakeContourScale,
+ earthquakeContourShape,
+ earthquakeRippleRings,
+ EARTHQUAKE_RIPPLE_PERIOD_MS,
+} from '../../layers/earthquakes/model.js';
+
+/** Points around each contour line: smooth at the largest disc on screen. */
+export const RIPPLE_RING_SEGMENTS = 96;
+/** An index contour's width, and every other line's. */
+const INDEX_WIDTH_PX = 2;
+const LINE_WIDTH_PX = 1.1;
+/**
+ * The overlay lane the lines paint in: the magnitude labels' own. A lane's
+ * custom painters run before its entries, so the lines sit under the labels
+ * and under the selected quake's card.
+ */
+export const RIPPLE_PAINT_LANE = 'ambient-label';
+/**
+ * The selected disc's fill, [offset, alpha] from the epicentre (0) to its
+ * outer circle (1): strongest in the middle, fading out to nothing at the
+ * edge.
+ */
+export const DISC_FADE = Object.freeze([
+ [0, 0.42],
+ [0.35, 0.26],
+ [0.75, 0.1],
+ [1, 0],
+]);
+/**
+ * Each contour wave's fill, out to its own line: clear inside, tinting
+ * toward the line; times the wave's own fade.
+ */
+export const WAVE_FADE = Object.freeze([
+ [0, 0],
+ [0.55, 0],
+ [1, 0.2],
+]);
+
+/**
+ * `rgb(r,g,b)` (or `rgba`) as a function of alpha, for gradient stops; any
+ * other colour keeps its own alpha.
+ */
+export function cssWithAlpha(color) {
+ const m = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(String(color));
+ if (!m) return () => color;
+ const rgb = `${m[1]},${m[2]},${m[3]}`;
+ return (alpha) => `rgba(${rgb},${Math.max(0, Math.min(1, alpha))})`;
+}
+
+/**
+ * How many times the lines run out to the edge after a quake is selected
+ * before they rest as still contours and stop asking for frames: earthquakes
+ * otherwise hold no render (docs/CURRENT-STATE.md, "Earthquake discs are
+ * STATIC geometry"), and a quake can stay selected for hours.
+ */
+export const RIPPLE_ACTIVE_CYCLES = 3;
+
+let reducedMotionQuery;
+/**
+ * The viewer's reduced-motion setting, live: the media query is kept, so a
+ * change mid-session is read at the next paint and tick.
+ */
+const reducedMotion = () => {
+ try {
+ reducedMotionQuery ??=
+ globalThis.matchMedia?.('(prefers-reduced-motion: reduce)') ?? null;
+ return reducedMotionQuery?.matches === true;
+ } catch {
+ return false;
+ }
+};
+
+/** How often the rings re-read the ground height under the quake. */
+const HEIGHT_READ_INTERVAL_MS = 500;
+/**
+ * A ground height the rings accept, in metres: the Dead Sea shore to above
+ * Everest. Anything else is a bad sample (a hit on something drawn above
+ * the ground, or a broken tile), and the rings stay where they are.
+ */
+const groundHeightOk = (h) => Number.isFinite(h) && h >= -500 && h <= 9000;
+
+/**
+ * The selected earthquake's contour lines, painted on the world overlay:
+ * wavy closed lines, shaped by the quake's id (earthquakeContourShape), run
+ * from the marker out to the disc's edge and fade there, one after another,
+ * for RIPPLE_ACTIVE_CYCLES runs after a quake is selected and only while it
+ * is on screen, then rest as still contours. They never cross, and every third is
+ * a heavier index contour, as on a topographic map. Nothing is drawn, and no
+ * frame is asked for, while no quake is selected. With reduced motion the
+ * lines hold still.
+ *
+ * A line is drawn in the tangent plane at the epicentre: at the largest
+ * disc (M6, 64 km) it sits about 320 m above the curved ground at its edge
+ * (64² / 2R), about 1.5 px off the drawn disc at the 220 km, -45° framing a
+ * label click flies to (900 px tall, 35° field of view); less for smaller
+ * quakes, as the offset grows with the square of the radius.
+ * @param {object} [deps]
+ * @param {Function} [deps.registerLane] `registerWorldOverlayPaintLane`.
+ * @param {() => number} [deps.now] Steady clock, ms.
+ * @param {(cb: Function) => number} [deps.requestFrame]
+ * @param {(handle: number) => void} [deps.cancelFrame]
+ * @param {() => boolean} [deps.prefersReducedMotion]
+ * @returns {{show: Function, hide: Function, dispose: Function}}
+ */
+export function createEarthquakeRipples({
+ registerLane = registerWorldOverlayPaintLane,
+ now = () => globalThis.performance?.now?.() ?? Date.now(),
+ requestFrame = (cb) => globalThis.requestAnimationFrame?.(cb) ?? null,
+ cancelFrame = (handle) => globalThis.cancelAnimationFrame?.(handle),
+ prefersReducedMotion = reducedMotion,
+} = {}) {
+ let lane = null;
+ let target = null;
+ let frameHandle = null;
+ // When the running lines settle into still contours (the selection's
+ // bound), and whether the last paint found the quake on screen.
+ let startedAt = 0;
+ let settlesAt = 0;
+ let onScreen = false;
+ /** Whether the lines run now: in the window, and motion allowed. */
+ const running = () => now() < settlesAt && !prefersReducedMotion();
+ // Unit offsets around the line in the epicentre's tangent plane, packed
+ // x, y, z per point: north·cos + east·sin.
+ const offsets = new Float64Array((RIPPLE_RING_SEGMENTS + 1) * 3);
+ const angles = new Float64Array(RIPPLE_RING_SEGMENTS + 1);
+ for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++)
+ angles[i] = (2 * Math.PI * i) / RIPPLE_RING_SEGMENTS;
+
+ // Screen points, reused every frame.
+ const at = { x: 0, y: 0 };
+ const centerAt = { x: 0, y: 0 };
+ const eastAt = { x: 0, y: 0 };
+ const northAt = { x: 0, y: 0 };
+
+ /** Project an ECEF point to CSS pixels; false when it is behind the eye. */
+ function project(frame, px, py, pz, out) {
+ const m = frame.viewProjectionMatrix;
+ const w = m[3] * px + m[7] * py + m[11] * pz + m[15];
+ if (w <= 0) return false;
+ out.x =
+ ((m[0] * px + m[4] * py + m[8] * pz + m[12]) / w / 2 + 0.5) * frame.width;
+ out.y =
+ (0.5 - (m[1] * px + m[5] * py + m[9] * pz + m[13]) / w / 2) *
+ frame.height;
+ return true;
+ }
+
+ /**
+ * Trace one closed line at `fraction` of the disc's radius (`shaped`:
+ * as a contour, else the disc's own circle). True when all of it is in
+ * front of the eye, so it can be filled.
+ */
+ function trace(frame, fraction, shaped) {
+ const { ctx } = frame;
+ const center = target.center;
+ const reach = fraction * target.radiusM;
+ ctx.beginPath();
+ let pen = false;
+ let whole = true;
+ for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) {
+ // The last point repeats the first angle, so the line closes.
+ const r = shaped
+ ? reach * earthquakeContourScale(target.shape, angles[i], fraction)
+ : reach;
+ const visible = project(
+ frame,
+ center.x + offsets[i * 3] * r,
+ center.y + offsets[i * 3 + 1] * r,
+ center.z + offsets[i * 3 + 2] * r,
+ at,
+ );
+ if (!visible) {
+ pen = false;
+ whole = false;
+ continue;
+ }
+ if (pen) ctx.lineTo(at.x, at.y);
+ else ctx.moveTo(at.x, at.y);
+ pen = true;
+ }
+ return whole;
+ }
+
+ /**
+ * Fill the traced path with a radial gradient laid on the ground: the
+ * canvas places a path when it is traced and a gradient when it fills, so
+ * under the disc's ground-to-screen transform the gradient's circle
+ * becomes the disc's ellipse on screen while the path stays exact.
+ * @param {Array<[number, number]>} stops [offset, alpha], out to `reach`.
+ */
+ function fillGround(ctx, reach, stops) {
+ ctx.save();
+ ctx.transform(
+ eastAt.x - centerAt.x,
+ eastAt.y - centerAt.y,
+ northAt.x - centerAt.x,
+ northAt.y - centerAt.y,
+ centerAt.x,
+ centerAt.y,
+ );
+ const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, reach);
+ for (const [offset, alpha] of stops)
+ gradient.addColorStop(offset, target.rgba(alpha));
+ ctx.fillStyle = gradient;
+ ctx.globalAlpha = 1;
+ ctx.fill();
+ ctx.restore();
+ }
+
+ /**
+ * Whether any of the disc is in the viewport: its centre's screen point,
+ * padded by its larger screen radius (or, seen edge-on, the centre alone).
+ */
+ function discOnScreen(frame, c, e, n) {
+ if (!Number.isFinite(c.x) || !Number.isFinite(c.y)) return false;
+ const pad = Math.max(
+ Math.hypot(e.x - c.x, e.y - c.y) || 0,
+ Math.hypot(n.x - c.x, n.y - c.y) || 0,
+ );
+ return (
+ c.x + pad >= 0 &&
+ c.x - pad <= frame.width &&
+ c.y + pad >= 0 &&
+ c.y - pad <= frame.height
+ );
+ }
+
+ /**
+ * Re-read the ground height under the quake, at most twice a second while
+ * painting: the ground loads and refines as the camera comes in, and the
+ * rings move onto it once it differs by more than a metre.
+ */
+ function settleHeight() {
+ if (!target.heightAt) return;
+ const at = now();
+ if (at - target.heightReadAt < HEIGHT_READ_INTERVAL_MS) return;
+ target.heightReadAt = at;
+ let height = null;
+ try {
+ height = target.heightAt();
+ } catch {
+ height = null;
+ }
+ if (!groundHeightOk(height) || Math.abs(height - target.heightM) <= 1)
+ return;
+ target.heightM = height;
+ target.center = fromDegrees(target.lon, target.lat, height);
+ }
+
+ function paint(frame) {
+ if (!target) return;
+ const { ctx } = frame;
+ settleHeight();
+ const center = target.center;
+ onScreen = false;
+ if (frame.occluder?.isPointVisible?.(center) === false) return;
+ const R = target.radiusM;
+ // The disc's ground frame on screen: its centre, and a radius east and
+ // north. Seen edge-on (or partly behind the eye) it is not filled.
+ const centerOk = project(frame, center.x, center.y, center.z, centerAt);
+ const eastOk = project(
+ frame,
+ center.x + target.east.x * R,
+ center.y + target.east.y * R,
+ center.z + target.east.z * R,
+ eastAt,
+ );
+ const northOk = project(
+ frame,
+ center.x + target.north.x * R,
+ center.y + target.north.y * R,
+ center.z + target.north.z * R,
+ northAt,
+ );
+ let fills = centerOk && eastOk && northOk;
+ if (fills) {
+ const area =
+ (eastAt.x - centerAt.x) * (northAt.y - centerAt.y) -
+ (eastAt.y - centerAt.y) * (northAt.x - centerAt.x);
+ fills = Math.abs(area) > 1;
+ }
+ onScreen =
+ centerOk &&
+ discOnScreen(
+ frame,
+ centerAt,
+ eastOk ? eastAt : centerAt,
+ northOk ? northAt : centerAt,
+ );
+ // The disc: strongest at the epicentre, fading out to its outer circle.
+ if (fills && trace(frame, 1, false)) fillGround(ctx, 1, DISC_FADE);
+ const animate = running();
+ const rings = animate
+ ? earthquakeRippleRings(now() - startedAt)
+ : earthquakeContourRings();
+ // Brought back into view while the window lasts: run again.
+ if (animate && onScreen && frameHandle === null && lane)
+ frameHandle = requestFrame(tick);
+ ctx.strokeStyle = target.color;
+ ctx.lineJoin = 'round';
+ for (const { fraction, alpha, index } of rings) {
+ if (!(alpha > 0.01)) continue;
+ const whole = trace(frame, fraction, true);
+ // Each wave: clear inside, tinting toward its own line, as it fades.
+ if (fills && whole)
+ fillGround(
+ ctx,
+ fraction,
+ WAVE_FADE.map(([offset, a]) => [offset, a * alpha]),
+ );
+ ctx.lineWidth = index ? INDEX_WIDTH_PX : LINE_WIDTH_PX;
+ ctx.globalAlpha = alpha;
+ ctx.stroke();
+ }
+ ctx.globalAlpha = 1;
+ }
+
+ /** Ask for one more frame while the lines run (one request at a time). */
+ function tick() {
+ frameHandle = null;
+ if (!target || !lane) return;
+ // Settled, or out of sight: one last paint draws the still contours
+ // (or nothing), and no more frames are asked for. A paint that finds it
+ // on screen again inside the window starts the frames again.
+ if (!running() || !onScreen) {
+ lane.requestPaint();
+ return;
+ }
+ lane.requestPaint();
+ frameHandle = requestFrame(tick);
+ }
+
+ function stopFrames() {
+ if (frameHandle !== null) cancelFrame(frameHandle);
+ frameHandle = null;
+ }
+
+ /**
+ * Run the contour lines around one quake, replacing any other.
+ * @param {{id: string, lon: number, lat: number, heightM?: number, heightAt?: () => number|null, radiusM: number, color: string}} next
+ * @param {{restart?: boolean}} [options] `restart: false` updates the
+ * same quake in place (a feed refresh) without running it again.
+ */
+ function show(next, { restart = true } = {}) {
+ if (
+ !next ||
+ !Number.isFinite(next.lon) ||
+ !Number.isFinite(next.lat) ||
+ !(next.radiusM > 0)
+ ) {
+ hide();
+ return;
+ }
+ const sameQuake = target?.id === next.id;
+ const lon = (next.lon * Math.PI) / 180;
+ const lat = (next.lat * Math.PI) / 180;
+ const [sinLon, cosLon] = [Math.sin(lon), Math.cos(lon)];
+ const [sinLat, cosLat] = [Math.sin(lat), Math.cos(lat)];
+ for (let i = 0; i <= RIPPLE_RING_SEGMENTS; i++) {
+ const [c, s] = [Math.cos(angles[i]), Math.sin(angles[i])];
+ offsets[i * 3] = c * -sinLat * cosLon + s * -sinLon;
+ offsets[i * 3 + 1] = c * -sinLat * sinLon + s * cosLon;
+ offsets[i * 3 + 2] = c * cosLat;
+ }
+ target = {
+ id: next.id,
+ // On the ground the disc is draped on: the height known now, then
+ // re-read while painting (see `settleHeight`), since a label's fly-to
+ // starts from far away, before that ground has loaded.
+ lon: next.lon,
+ lat: next.lat,
+ heightM: groundHeightOk(next.heightM) ? next.heightM : 0,
+ heightAt: typeof next.heightAt === 'function' ? next.heightAt : null,
+ heightReadAt: -Infinity,
+ center: fromDegrees(
+ next.lon,
+ next.lat,
+ groundHeightOk(next.heightM) ? next.heightM : 0,
+ ),
+ radiusM: next.radiusM,
+ color: next.color || 'rgb(255,165,0)',
+ shape: earthquakeContourShape(next.id),
+ rgba: cssWithAlpha(next.color || 'rgb(255,165,0)'),
+ // Angle 0 is north and a quarter turn is east (see `offsets`).
+ north: { x: offsets[0], y: offsets[1], z: offsets[2] },
+ east: {
+ x: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3],
+ y: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 1],
+ z: offsets[(RIPPLE_RING_SEGMENTS / 4) * 3 + 2],
+ },
+ };
+ if (restart || !sameQuake) {
+ startedAt = now();
+ settlesAt =
+ startedAt + RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS;
+ // Assume it is in view until a paint says otherwise.
+ onScreen = true;
+ }
+ lane ??= registerLane(RIPPLE_PAINT_LANE, paint, {
+ id: 'earthquake-ripples',
+ });
+ lane.setActive(true);
+ lane.requestPaint();
+ // A refresh while the disc is out of sight asks for no frame; a paint
+ // that finds it on screen again starts them (a restart sets onScreen).
+ if (running() && onScreen && frameHandle === null)
+ frameHandle = requestFrame(tick);
+ }
+
+ function hide() {
+ stopFrames();
+ if (!target) return;
+ target = null;
+ lane?.setActive(false);
+ }
+
+ function dispose() {
+ hide();
+ lane?.unregister();
+ lane = null;
+ }
+
+ return { show, hide, dispose };
+}
diff --git a/src/app/layers/earthquakeRipples.test.mjs b/src/app/layers/earthquakeRipples.test.mjs
new file mode 100644
index 0000000000..1a7e047276
--- /dev/null
+++ b/src/app/layers/earthquakeRipples.test.mjs
@@ -0,0 +1,452 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ DISC_FADE,
+ cssWithAlpha,
+ RIPPLE_ACTIVE_CYCLES,
+ RIPPLE_PAINT_LANE,
+ RIPPLE_RING_SEGMENTS,
+ createEarthquakeRipples,
+} from './earthquakeRipples.js';
+import {
+ EARTHQUAKE_RIPPLE_PERIOD_MS,
+ EARTHQUAKE_RIPPLE_RINGS,
+} from '../../layers/earthquakes/model.js';
+import { fromDegrees } from '../../geo/ellipsoid.js';
+
+/** A paint lane, frame clock and canvas the test steps by hand. */
+function harness({ reducedMotion = false } = {}) {
+ let motionReduced = reducedMotion;
+ const lanes = [];
+ const frames = new Map();
+ let nextFrame = 1;
+ let clock = 0;
+ const ripples = createEarthquakeRipples({
+ registerLane(laneId, painter, options) {
+ const lane = {
+ laneId,
+ painter,
+ options,
+ active: false,
+ paints: 0,
+ unregistered: false,
+ setActive(next) {
+ lane.active = next;
+ },
+ requestPaint() {
+ lane.paints++;
+ },
+ unregister() {
+ lane.unregistered = true;
+ },
+ };
+ lanes.push(lane);
+ return lane;
+ },
+ now: () => clock,
+ requestFrame(cb) {
+ const handle = nextFrame++;
+ frames.set(handle, cb);
+ return handle;
+ },
+ cancelFrame: (handle) => frames.delete(handle),
+ prefersReducedMotion: () => motionReduced,
+ });
+ const strokes = [];
+ const fills = [];
+ let path = null;
+ const ctx = {
+ globalAlpha: 1,
+ beginPath() {
+ path = { moves: 0, lines: 0 };
+ },
+ moveTo() {
+ path.moves++;
+ },
+ lineTo() {
+ path.lines++;
+ },
+ stroke() {
+ strokes.push({
+ ...path,
+ alpha: ctx.globalAlpha,
+ color: ctx.strokeStyle,
+ width: ctx.lineWidth,
+ });
+ },
+ // Fills record their path, gradient and the transform they fill under.
+ saved: 0,
+ transformed: null,
+ save() {
+ ctx.saved++;
+ },
+ restore() {
+ ctx.saved--;
+ ctx.transformed = null;
+ },
+ transform(...args) {
+ ctx.transformed = args;
+ },
+ createRadialGradient(...circles) {
+ const gradient = { circles, stops: [] };
+ gradient.addColorStop = (offset, color) =>
+ gradient.stops.push([offset, color]);
+ return gradient;
+ },
+ fill() {
+ fills.push({
+ ...path,
+ gradient: ctx.fillStyle,
+ transform: ctx.transformed,
+ });
+ },
+ };
+ // w = 1 everywhere: every point is in front of the eye.
+ const matrix = new Float64Array(16);
+ matrix[0] = 1e-7;
+ matrix[5] = 1e-7;
+ matrix[15] = 1;
+ const frame = (visible = true) => ({
+ ctx,
+ width: 800,
+ height: 600,
+ viewProjectionMatrix: matrix,
+ occluder: { isPointVisible: () => visible },
+ });
+ return {
+ ripples,
+ lanes,
+ frames,
+ strokes,
+ fills,
+ frame,
+ matrix,
+ setReducedMotion(next) {
+ motionReduced = next;
+ },
+ advance(ms) {
+ clock += ms;
+ },
+ /** Run the pending animation frames once. */
+ step() {
+ const pending = [...frames.entries()];
+ frames.clear();
+ for (const [, cb] of pending) cb();
+ },
+ };
+}
+
+const target = {
+ id: 'ak1',
+ lon: -153.3,
+ lat: 60,
+ radiusM: 32000,
+ color: 'rgb(255,0,0)',
+};
+
+test('nothing is registered or animated until a quake is selected', () => {
+ const h = harness();
+ assert.equal(h.lanes.length, 0);
+ assert.equal(h.frames.size, 0);
+ h.ripples.hide();
+ assert.equal(h.frames.size, 0);
+});
+
+test('a selected quake animates one ring set, one frame request at a time', () => {
+ const h = harness();
+ h.ripples.show(target);
+ const [lane] = h.lanes;
+ assert.equal(lane.laneId, RIPPLE_PAINT_LANE);
+ assert.equal(RIPPLE_PAINT_LANE, 'ambient-label', 'under the labels');
+ assert.equal(lane.active, true);
+ assert.equal(h.frames.size, 1);
+ h.ripples.show({ ...target, id: 'ak2' });
+ assert.equal(h.lanes.length, 1, 'the lane is reused');
+ assert.equal(h.frames.size, 1, 'still one frame loop');
+ const before = lane.paints;
+ h.step();
+ h.step();
+ assert.equal(lane.paints, before + 2, 'one repaint per frame');
+ assert.equal(h.frames.size, 1);
+
+ h.advance(600);
+ lane.painter(h.frame());
+ // At 600 ms every line is between the marker and the edge, so all draw.
+ assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
+ assert.deepEqual(
+ h.strokes.map((stroke) => stroke.width),
+ [2, 1.1, 1.1, 2, 1.1, 1.1],
+ 'every third line is an index contour',
+ );
+ for (const stroke of h.strokes) {
+ assert.equal(stroke.moves, 1, 'one unbroken ring');
+ assert.equal(stroke.lines, RIPPLE_RING_SEGMENTS);
+ assert.equal(stroke.color, 'rgb(255,0,0)');
+ assert.ok(stroke.alpha > 0 && stroke.alpha <= 1);
+ }
+
+ h.ripples.hide();
+ assert.equal(lane.active, false);
+ assert.equal(h.frames.size, 0, 'no frames asked for once hidden');
+ h.strokes.length = 0;
+ lane.painter(h.frame());
+ assert.equal(h.strokes.length, 0);
+});
+
+test('rings are skipped behind the globe and broken behind the eye', () => {
+ const h = harness();
+ h.ripples.show(target);
+ h.advance(600);
+ const [lane] = h.lanes;
+ lane.painter(h.frame(false));
+ assert.equal(h.strokes.length, 0, 'epicentre over the horizon');
+
+ // Points with negative x fall behind the eye: each ring breaks there.
+ const frame = h.frame();
+ frame.viewProjectionMatrix[3] = 1e-6;
+ const center = fromDegrees(target.lon, target.lat);
+ frame.viewProjectionMatrix[15] = -1e-6 * center.x;
+ lane.painter(frame);
+ assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
+ for (const stroke of h.strokes)
+ assert.ok(stroke.lines < RIPPLE_RING_SEGMENTS, 'part of each ring hidden');
+});
+
+test('reduced motion draws still contour rings and asks for no frames', () => {
+ const h = harness({ reducedMotion: true });
+ h.ripples.show(target);
+ assert.equal(h.frames.size, 0);
+ assert.equal(h.lanes[0].paints, 1, 'painted once');
+ h.lanes[0].painter(h.frame());
+ assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
+ assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7));
+});
+
+test('an unusable target hides the rings; dispose releases the lane', () => {
+ const h = harness();
+ h.ripples.show(target);
+ h.ripples.show({ ...target, radiusM: 0 });
+ assert.equal(h.lanes[0].active, false);
+ assert.equal(h.frames.size, 0);
+ h.ripples.dispose();
+ assert.equal(h.lanes[0].unregistered, true);
+ // Shown again after dispose, it registers a fresh lane.
+ h.ripples.show(target);
+ assert.equal(h.lanes.length, 2);
+ h.ripples.dispose();
+});
+
+test('contour lines are wavy, the same for a quake every time, and inside the disc', () => {
+ const h = harness();
+ h.ripples.show(target);
+ h.advance(600);
+ // An identity-like projection: screen x, y follow ECEF y, z, so the
+ // distance from the projected epicentre measures each point's radius.
+ const frame = h.frame();
+ const m = frame.viewProjectionMatrix;
+ m[0] = 0;
+ m[5] = 0;
+ m[4] = 1e-6;
+ m[9] = 1e-6;
+ const points = [];
+ const ctx = frame.ctx;
+ const record = (x, y) => points.at(-1).push([x, y]);
+ ctx.beginPath = () => points.push([]);
+ ctx.moveTo = record;
+ ctx.lineTo = record;
+ ctx.stroke = () => {};
+ h.lanes[0].painter(frame);
+ const center = fromDegrees(target.lon, target.lat);
+ const cx = (center.y * 1e-6 * 0.5 + 0.5) * 800;
+ const cy = (0.5 - center.z * 1e-6 * 0.5) * 600;
+ const spread = (line) => {
+ const radii = line.map(([x, y]) => Math.hypot(x - cx, y - cy));
+ return Math.max(...radii) / Math.min(...radii);
+ };
+ // The disc's outer circle first (filled, not stroked), then each line.
+ assert.equal(points.length, EARTHQUAKE_RIPPLE_RINGS + 1);
+ points.shift();
+ assert.ok(
+ points.every((line) => spread(line) > 1.05),
+ 'not circles: each line dents in and out',
+ );
+ for (const line of points) {
+ const [first, last] = [line[0], line.at(-1)];
+ assert.ok(
+ Math.hypot(first[0] - last[0], first[1] - last[1]) < 1e-6,
+ 'closed',
+ );
+ }
+});
+
+test('the disc fades out to its outer circle; each wave fills with a fade', () => {
+ const h = harness();
+ h.ripples.show(target);
+ h.advance(600);
+ // A projection where east and north span the screen: the disc is seen
+ // from above, so its ground frame can be filled.
+ const frame = h.frame();
+ const m = frame.viewProjectionMatrix;
+ m[0] = 0;
+ m[5] = 0;
+ m[4] = 1e-6;
+ m[9] = 1e-6;
+ h.lanes[0].painter(frame);
+ assert.equal(h.fills.length, 1 + EARTHQUAKE_RIPPLE_RINGS);
+ const [disc, ...waves] = h.fills;
+ assert.equal(disc.lines, RIPPLE_RING_SEGMENTS, 'the whole outer circle');
+ assert.deepEqual(disc.gradient.circles, [0, 0, 0, 0, 0, 1]);
+ assert.deepEqual(
+ disc.gradient.stops,
+ DISC_FADE.map(([offset, alpha]) => [offset, `rgba(255,0,0,${alpha})`]),
+ );
+ assert.equal(disc.gradient.stops.at(-1)[1], 'rgba(255,0,0,0)', 'fades out');
+ assert.ok(disc.transform, 'filled under the ground-to-screen transform');
+ assert.equal(h.fills.length, waves.length + 1);
+ for (const wave of waves) {
+ const reach = wave.gradient.circles[5];
+ assert.ok(reach > 0 && reach < 1, 'out to its own line');
+ assert.equal(wave.gradient.stops[0][1], 'rgba(255,0,0,0)', 'clear inside');
+ }
+ // The transforms were undone: nothing leaks into the labels' painting.
+ assert.equal(frame.ctx.saved, 0);
+ // Seen edge-on, the ground frame has no area: lines only, no fills.
+ h.fills.length = 0;
+ m[9] = 0;
+ m[5] = 0;
+ h.lanes[0].painter(frame);
+ assert.equal(h.fills.length, 0);
+});
+
+test('cssWithAlpha turns rgb into rgba stops', () => {
+ assert.equal(cssWithAlpha('rgb(255,165,0)')(0.25), 'rgba(255,165,0,0.25)');
+ assert.equal(cssWithAlpha('rgba(1, 2, 3, 0.5)')(2), 'rgba(1,2,3,1)');
+ assert.equal(cssWithAlpha('red')(0.3), 'red');
+});
+
+test('the lines run a bounded time after a selection, then rest without frames', () => {
+ const h = harness();
+ h.ripples.show(target);
+ const [lane] = h.lanes;
+ const window = RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS;
+ assert.ok(window <= 15_000, 'about a quarter of a minute at most');
+ let frames = 0;
+ for (let t = 0; t < window * 3; t += 16) {
+ if (!h.frames.size) break;
+ lane.painter(h.frame());
+ h.advance(16);
+ h.step();
+ frames++;
+ }
+ assert.equal(h.frames.size, 0, 'no frame asked for once settled');
+ assert.ok(frames <= Math.ceil(window / 16) + 2, `bounded: ${frames} frames`);
+ // At rest the lines hold still as readable contours.
+ h.strokes.length = 0;
+ lane.painter(h.frame());
+ assert.equal(h.strokes.length, EARTHQUAKE_RIPPLE_RINGS);
+ assert.ok(h.strokes.every((stroke) => stroke.alpha === 0.7));
+ // A parked camera repainting the overlay does not start them again.
+ lane.painter(h.frame());
+ assert.equal(h.frames.size, 0);
+ // A new selection runs again.
+ h.ripples.show({ ...target, id: 'ak2' });
+ assert.equal(h.frames.size, 1);
+ h.ripples.dispose();
+});
+
+test('off screen the frames stop; back in view inside the window they resume', () => {
+ const h = harness();
+ h.ripples.show(target);
+ const [lane] = h.lanes;
+ // Behind the globe.
+ lane.painter(h.frame(false));
+ const paints = lane.paints;
+ h.step();
+ assert.equal(h.frames.size, 0, 'stopped while out of sight');
+ assert.equal(lane.paints, paints + 1, 'one last paint, then none');
+ h.step();
+ assert.equal(lane.paints, paints + 1);
+ // Panned away: the disc is far off the viewport.
+ h.ripples.show(target);
+ const away = h.frame();
+ away.viewProjectionMatrix[12] = 50;
+ lane.painter(away);
+ h.step();
+ assert.equal(h.frames.size, 0);
+ // The camera brings it back while the window lasts.
+ away.viewProjectionMatrix[12] = 0;
+ lane.painter(h.frame());
+ assert.equal(h.frames.size, 1, 'resumed');
+ h.ripples.dispose();
+});
+
+test('turning reduced motion on mid-run stills the lines and stops the frames', () => {
+ const h = harness();
+ h.ripples.show(target);
+ const [lane] = h.lanes;
+ lane.painter(h.frame());
+ h.setReducedMotion(true);
+ h.step();
+ assert.equal(h.frames.size, 0);
+ h.strokes.length = 0;
+ lane.painter(h.frame());
+ assert.ok(
+ h.strokes.every((stroke) => stroke.alpha === 0.7),
+ 'still',
+ );
+ // Turned off again within the window: the next paint runs them again.
+ h.setReducedMotion(false);
+ lane.painter(h.frame());
+ assert.equal(h.frames.size, 1);
+ h.ripples.dispose();
+});
+
+test('a refresh of the same quake does not run a settled selection again', () => {
+ const h = harness();
+ h.ripples.show(target);
+ const [lane] = h.lanes;
+ h.advance(RIPPLE_ACTIVE_CYCLES * EARTHQUAKE_RIPPLE_PERIOD_MS + 1);
+ lane.painter(h.frame());
+ h.step();
+ assert.equal(h.frames.size, 0, 'settled');
+ h.ripples.show({ ...target, radiusM: 40000 }, { restart: false });
+ assert.equal(h.frames.size, 0, 'a refresh keeps it at rest');
+ lane.painter(h.frame());
+ assert.equal(h.frames.size, 0);
+ // A different quake, or a user's restart, runs again.
+ h.ripples.show({ ...target, id: 'other' }, { restart: false });
+ assert.equal(h.frames.size, 1);
+ h.ripples.dispose();
+});
+
+// The rings sit on the ground the disc is draped on. A label's fly-to starts
+// far away, before that ground loads, so the painter reads the height again
+// while it paints and moves the rings onto it.
+test('the rings move onto the ground height once it loads', () => {
+ const h = harness();
+ let ground = null;
+ h.ripples.show({ ...target, heightM: 0, heightAt: () => ground });
+ h.advance(600);
+ const [lane] = h.lanes;
+ lane.painter(h.frame());
+ const atSea = h.fills.at(-1).transform;
+ h.fills.length = 0;
+ ground = 4000;
+ h.advance(600);
+ lane.painter(h.frame());
+ const onGround = h.fills.at(-1).transform;
+ assert.notDeepEqual(onGround, atSea, 'the centre moved up onto the ground');
+ // A change of a metre or less, or an impossible height, leaves them put.
+ for (const next of [4000.5, 25000, -2000]) {
+ ground = next;
+ h.advance(600);
+ lane.painter(h.frame());
+ assert.deepEqual(h.fills.at(-1).transform, onGround, String(next));
+ }
+ // Reads are bounded: a second paint within the interval does not ask again.
+ let reads = 0;
+ h.ripples.show({ ...target, id: 'ak2', heightAt: () => (reads++, 4000) });
+ lane.painter(h.frame());
+ lane.painter(h.frame());
+ assert.equal(reads, 1);
+});
diff --git a/src/app/layers/earthquakes.js b/src/app/layers/earthquakes.js
index ae6bc1b63a..87b79743d4 100644
--- a/src/app/layers/earthquakes.js
+++ b/src/app/layers/earthquakes.js
@@ -1,6 +1,49 @@
import { createEarthquakesLayer } from '../../layers/earthquakes/index.js';
import { overlayHost } from './overlayHost.js';
-/** Wire earthquake observations to the application overlay host. */
+import { inputFor } from '../../input/dispatcher.js';
+import * as picking from '../../data/pickRegistry.js';
+import * as context from '../../data/contextStore.js';
+import { isPointerFree } from '../../data/inputOwnership.js';
+import { requestWorldFocus } from '../../worldFocus.js';
+import { createEarthquakeRipples } from './earthquakeRipples.js';
+import { heightsOf } from '../../queries/heights.js';
+import { formatDate, formatNumber, t } from '../../i18n/index.js';
+
+const EVENT_TIME = Object.freeze({
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ timeZone: 'UTC',
+ timeZoneName: 'short',
+});
+
+/** The clicked quake's card text, in the page's language. */
+export const earthquakeCardText = Object.freeze({
+ t,
+ formatTime: (time) => formatDate(time, EVENT_TIME),
+ formatDepth: (km) => formatNumber(km, { maximumFractionDigits: 1 }),
+});
+
+/**
+ * Wire earthquake observations to the application overlay host, and its
+ * discs to the globe's clicks: a clicked quake shows its detail card.
+ */
export function createApplicationEarthquakes(options) {
- return createEarthquakesLayer({ overlayHost, ...options });
+ return createEarthquakesLayer({
+ overlayHost,
+ input: (viewer) => inputFor(viewer),
+ picking,
+ context,
+ pointer: { isPointerFree },
+ openExternal: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
+ focus: { requestWorldFocus },
+ ripples: createEarthquakeRipples(),
+ // The loaded ground (terrain or tiles) the clamped disc is draped on.
+ groundHeight: (viewer, lon, lat) =>
+ viewer ? heightsOf(viewer).now({ lon, lat }) : null,
+ text: earthquakeCardText,
+ ...options,
+ });
}
diff --git a/src/app/layers/rocketLaunches.js b/src/app/layers/rocketLaunches.js
index af60bd3b62..44ed64ead6 100644
--- a/src/app/layers/rocketLaunches.js
+++ b/src/app/layers/rocketLaunches.js
@@ -2,11 +2,12 @@ import { createRocketLaunchesLayer } from '../../layers/launches/index.js';
import * as geometry from '../../celestialRing.js';
import * as overlays from '../../overlays/worldOverlay.js';
import * as render from '../../renderGovernor.js';
+import * as picking from '../../data/pickRegistry.js';
/** Construct one layer using the application scene owners and a supplied source. */
export function createApplicationLaunches({ source, satellites }) {
return createRocketLaunchesLayer({
source,
- services: { satellites, geometry, overlays, render },
+ services: { satellites, geometry, overlays, render, picking },
});
}
diff --git a/src/app/layers/submarineCables.js b/src/app/layers/submarineCables.js
index 1f6dd7d817..7b9299fc3c 100644
--- a/src/app/layers/submarineCables.js
+++ b/src/app/layers/submarineCables.js
@@ -1,9 +1,11 @@
import { createSubmarineCableLayer } from '../../layers/submarineCables/index.js';
import { overlayHost } from './overlayHost.js';
+import * as picking from '../../data/pickRegistry.js';
/** Wire cable source geometry to the application overlay host. */
export function createApplicationCables(options) {
return createSubmarineCableLayer({
overlayHost,
+ picking,
mapStackEventTarget: typeof window !== 'undefined' ? window : null,
...options,
});
diff --git a/src/app/scene.js b/src/app/scene.js
index 63012fb663..9945fb2bbd 100644
--- a/src/app/scene.js
+++ b/src/app/scene.js
@@ -1,6 +1,7 @@
import { createApplicationOperations } from './operations.js';
import { registerDataCredits } from '../data/dataCredits.js';
import { mountCreditsView } from '../ui/creditsView.js';
+import { trackCreditLineHeight } from '../ui/creditLineHeight.js';
import { MapStackController } from '../mapStackController.js';
import { mapEngineFor } from '../maps/engine.js';
import { initLogoGaze } from '../logoGaze.js';
@@ -173,6 +174,8 @@ export async function createApplicationScene({
// The credits, in the application's own line, unless the renderer shows
// them in a display of its own.
if (!hooks.ownCreditDisplay) defer(mountCreditsView(viewer));
+ // The HUD corners above the line clear it when it wraps.
+ defer(trackCreditLineHeight(document));
loaderStatus.textContent =
googleApiKey || googleTokens || cesiumToken
? t('Loading Google 3D Tiles...')
diff --git a/src/cameraHandoff.test.mjs b/src/cameraHandoff.test.mjs
index 747a2f0a97..36b3380afa 100644
--- a/src/cameraHandoff.test.mjs
+++ b/src/cameraHandoff.test.mjs
@@ -403,10 +403,11 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
'vessel click',
);
ordered(vesselClick, [
+ 'clickCard?.(event)',
+ 'selectAndFocusVessel(carded)',
"isOwnedByOtherLayer('ais-live-vessels', pickedId)",
- '_vesselOverlayHost.hitTest?.(',
'selectAndFocusVessel(record)',
- ], 'vessel sibling ownership');
+ ], 'vessel card on top, then sibling ownership');
const vesselFocus = body(
vessels,
/function selectAndFocusVessel\(record\) \{([\s\S]*?)\n \}/,
@@ -419,8 +420,9 @@ test('vessel and fire layers announce valid clicks and never fly cameras', () =>
'fire click',
);
ordered(fireClick, [
- 'isOwnedByOtherLayer(id, pickedId)',
- 'overlayHost.hitTest?.(',
+ 'clickCard?.(event)',
'selectAndFocusFire(carded)',
- ], 'fire sibling ownership');
+ 'isOwnedByOtherLayer(id, pickedId)',
+ 'clearFireSelection()',
+ ], 'fire card on top, then sibling ownership');
});
diff --git a/src/creditAttribution.test.mjs b/src/creditAttribution.test.mjs
index 879f58d64e..958578689d 100644
--- a/src/creditAttribution.test.mjs
+++ b/src/creditAttribution.test.mjs
@@ -439,12 +439,21 @@ function resolve(candidates, prop, width, label) {
/** Evaluate a length. Anything the model cannot resolve exactly fails loudly. */
function toPx(value, viewportHeight, where) {
const trimmed = value.trim();
+ // The larger of its lengths, each resolved the same way.
+ if (/^max\(.*\)$/.test(trimmed))
+ return Math.max(
+ ...splitTopLevel(trimmed.slice(4, -1), ',').map((part) =>
+ toPx(part, viewportHeight, where),
+ ),
+ );
const inner = /^calc\(/.test(trimmed) ? trimmed.slice(5, -1) : trimmed;
- assert.doesNotMatch(
- inner,
- /\bcalc\(/,
- `nested calc() in ${where}: "${value}"`,
- );
+ // A calc() is a whole term of its own, resolved below; nowhere else.
+ for (const term of splitTopLevel(inner, '+'))
+ assert.doesNotMatch(
+ term.trim().replace(/^calc\(.*\)$/, ''),
+ /\bcalc\(/,
+ `nested calc() in ${where}: "${value}"`,
+ );
assert.doesNotMatch(
inner,
/\b(min|max|clamp|env|attr|round|mod)\(/,
@@ -465,6 +474,18 @@ function toPx(value, viewportHeight, where) {
const term = raw.trim();
if (!term) continue;
if (term === '100%') continue; // the tray's own panel height, added separately
+ // A calc() of its own, as a term ("calc(var(--omnibar-credits-clear) +
+ // 2px)" once substituted).
+ if (/^calc\(.*\)$/.test(term)) {
+ total += toPx(term, viewportHeight, where);
+ continue;
+ }
+ // The credit line's own height (src/ui/creditLineHeight.js), at the
+ // height this pin models it at.
+ if (/^var\(--credit-line-height\b/.test(term)) {
+ total += CREDIT_HEIGHT_PX;
+ continue;
+ }
if (term.startsWith('var(')) {
const name = term.slice(4, term.lastIndexOf(')')).split(',')[0].trim();
assert.ok(
@@ -859,16 +880,28 @@ function omnibarVar(name) {
const decls = RULES.filter((rule) => rule.parts.includes(OMNIBAR_SCOPE))
.flatMap((rule) => rule.decls)
.filter((decl) => decl.prop === name);
- assert.equal(decls.length, 1, `${name} is declared once in the Omnibar scope`);
+ assert.equal(
+ decls.length,
+ 1,
+ `${name} is declared once in the Omnibar scope`,
+ );
return decls[0].value;
}
/** A length in the Omnibar layout, with its scope's own custom properties. */
function omnibarPx(value, viewportHeight, where) {
- const substituted = value.replace(
- /var\((--omnibar-[\w-]+)\)/g,
- (_, name) => omnibarVar(name),
- );
+ // The scope's properties may name each other ("--omnibar-dock-bottom"
+ // clears "--omnibar-credits-clear"): substitute until none is left.
+ let substituted = value;
+ for (let pass = 0; /var\(--omnibar-/.test(substituted); pass += 1) {
+ assert.ok(
+ pass < 8,
+ `Omnibar properties name each other in a loop: ${value}`,
+ );
+ substituted = substituted.replace(/var\((--omnibar-[\w-]+)\)/g, (_, name) =>
+ omnibarVar(name),
+ );
+ }
return toPx(substituted, viewportHeight, where);
}
@@ -893,7 +926,11 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
width,
'Omnibar dock',
);
- assert.equal(dock.part, OMNIBAR.dock, `the Omnibar owns the dock at ${width}px`);
+ assert.equal(
+ dock.part,
+ OMNIBAR.dock,
+ `the Omnibar owns the dock at ${width}px`,
+ );
// Its top and height too: a legacy top or height winning here would
// move or stretch the dock the clearance below is measured from.
for (const [prop, value] of [
@@ -906,8 +943,16 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
width,
`Omnibar dock ${prop}`,
);
- assert.equal(own.part, OMNIBAR.dock, `the Omnibar owns the dock ${prop} at ${width}px`);
- assert.equal(own.decl.value, value, `Omnibar dock ${prop} at ${width}px`);
+ assert.equal(
+ own.part,
+ OMNIBAR.dock,
+ `the Omnibar owns the dock ${prop} at ${width}px`,
+ );
+ assert.equal(
+ own.decl.value,
+ value,
+ `Omnibar dock ${prop} at ${width}px`,
+ );
}
const credit = resolve(
[
@@ -923,7 +968,11 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
credit.part.startsWith(OMNIBAR_SCOPE),
`the Omnibar owns the credit row at ${width}px`,
);
- const dockBottom = omnibarPx(dock.decl.value, height, 'Omnibar dock bottom');
+ const dockBottom = omnibarPx(
+ dock.decl.value,
+ height,
+ 'Omnibar dock bottom',
+ );
const creditTop =
omnibarPx(credit.decl.value, height, 'Omnibar credit bottom') +
CREDIT_HEIGHT_PX;
@@ -938,7 +987,10 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
// and no rule elsewhere forces them back.
const trays = RULES.find((rule) => rule.parts.includes(OMNIBAR.trays));
assert.ok(trays, 'the Omnibar layout hides the legacy trays');
- assert.equal(trays.decls.find((decl) => decl.prop === 'display')?.value, 'none');
+ assert.equal(
+ trays.decls.find((decl) => decl.prop === 'display')?.value,
+ 'none',
+ );
for (const rule of RULES) {
for (const part of rule.parts) {
if (!/#(location-bar|control-panel)$/.test(lastCompound(part))) continue;
@@ -951,8 +1003,13 @@ test('Omnibar reserves a non-overlapping desktop footer at native credit sizing'
// The minimal-HUD rail cap only shortens the rail, which is anchored at
// its top, so it can only add room above the credit.
const rail = RULES.find((rule) => rule.parts.includes(OMNIBAR.minimalRail));
- const cap = rail.decls.find((decl) => decl.prop === '--omnibar-minimal-rail-height');
- assert.match(cap?.value || '', /^min\(\s*var\(--right-stack-max-height, 70vh\),/);
+ const cap = rail.decls.find(
+ (decl) => decl.prop === '--omnibar-minimal-rail-height',
+ );
+ assert.match(
+ cap?.value || '',
+ /^min\(\s*var\(--right-stack-max-height, 70vh\),/,
+ );
assert.equal(
rail.decls.find((decl) => decl.prop === 'max-height')?.value,
'var(--omnibar-minimal-rail-height)',
diff --git a/src/data/aisLiveVessels.test.mjs b/src/data/aisLiveVessels.test.mjs
index 0f94b7b86f..1bf364ddee 100644
--- a/src/data/aisLiveVessels.test.mjs
+++ b/src/data/aisLiveVessels.test.mjs
@@ -32,7 +32,12 @@ import aisLiveVesselsLayer from './aisLiveVessels.js';
import { registerEntityContext, selectEntityContext } from './contextStore.js';
import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js';
import { ensureGeoidReady, geoidHeight } from './geoid.js';
-import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
+import {
+ isUnderOtherCard,
+ registerPickOwner,
+ setClickCardHitTest,
+ unregisterPickOwner,
+} from './pickRegistry.js';
import { applyVesselOverlayPolicy } from './vesselLabels.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { layerFeedState } from './manager.js';
@@ -490,7 +495,7 @@ test('first accepted position ends grace and warm data survives later open silen
const clock = makeFakeAisRuntime(7000);
const record = makeRecord();
_setAisRuntimeForTest(clock.runtime);
- _setVesselOverlayHostForTest({
+ useVesselHost({
setEntries() {},
setVisible() {},
clearSource() {},
@@ -540,7 +545,7 @@ test('first accepted position ends grace and warm data survives later open silen
assert.equal(feed.error, 'awaiting usable AIS positions…');
} finally {
_setVesselStateForTest({ enabled: false });
- _setVesselOverlayHostForTest();
+ useVesselHost();
_setAisRuntimeForTest();
}
});
@@ -1012,7 +1017,12 @@ function makeCesiumEvent() {
};
}
-function installWireHarness(picked, stateOverrides = {}) {
+function installWireHarness(
+ picked,
+ stateOverrides = {},
+ sceneExtras = {},
+ firstClick = null,
+) {
const hadWindow = Object.hasOwn(globalThis, 'window');
const hadDocument = Object.hasOwn(globalThis, 'document');
const priorWindow = globalThis.window;
@@ -1038,9 +1048,11 @@ function installWireHarness(picked, stateOverrides = {}) {
},
};
const viewer = {
- scene: { pick: () => picked },
+ scene: { pick: () => picked, ...sceneExtras },
};
const input = fakeInput(viewer);
+ // A subscriber that runs before the layer's own (an aircraft layer).
+ if (firstClick) input.input.onClick(firstClick);
// The camera port other layers follow through, with no pose to read; its
// followChanged event counts who listens.
const followChanged = makeCesiumEvent();
@@ -1666,7 +1678,7 @@ test('vessel host publication preserves the shipped grid winner and separation s
},
},
});
- _setVesselOverlayHostForTest({
+ useVesselHost({
setEntries(sourceId, entries, options) {
publications.push({ sourceId, entries, options });
},
@@ -1690,7 +1702,7 @@ test('vessel host publication preserves the shipped grid winner and separation s
} finally {
unbind();
_setVesselStateForTest({ enabled: false });
- _setVesselOverlayHostForTest();
+ useVesselHost();
}
});
@@ -1717,7 +1729,7 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
globalThis.window.addEventListener('gev:world-request-focus', (event) => {
focusRequests.push(event.detail);
});
- _setVesselOverlayHostForTest(host);
+ useVesselHost(host);
_setVesselStateForTest({
viewer: {
get canvas() {
@@ -1766,7 +1778,7 @@ test('vessel real layer lifecycle publishes protected selection and leaves no st
);
} finally {
_setVesselStateForTest({ enabled: false });
- _setVesselOverlayHostForTest();
+ useVesselHost();
if (hadWindow) globalThis.window = priorWindow;
else delete globalThis.window;
globalThis.document = priorDocument;
@@ -1872,17 +1884,31 @@ test('vessel interaction wire: a vessel with an id and no MMSI is selected by cl
}
});
+/**
+ * Hand the vessel layer an overlay host, and answer the pick registry's
+ * card-on-top question from the same host, as the application does.
+ */
+function useVesselHost(host) {
+ _setVesselOverlayHostForTest(host);
+ setClickCardHitTest(host ? (x, y) => host.hitTest(x, y) : null);
+}
+
/**
* Overlay-host recorder whose hitTest answers with one card id. The real host
* only publishes rects for `interactive` entries, so a stub returning a hit is
* the same contract a painted, actionable card presents.
*/
-function hostWithCardHit(entryId) {
+function hostWithCardHit(entryId, topHit) {
return {
setEntries() {},
setVisible() {},
clearSource() {},
- hitTest: () => (entryId ? { sourceId: 'ais-live-vessels', entryId } : null),
+ hitTest: (_x, _y, { sourceId } = {}) =>
+ !sourceId && topHit
+ ? topHit
+ : entryId
+ ? { sourceId: 'ais-live-vessels', entryId }
+ : null,
};
}
@@ -1898,9 +1924,7 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
- _setVesselOverlayHostForTest(
- hostWithCardHit(`vessel:${harness.record.mmsi}`),
- );
+ useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -1911,7 +1935,7 @@ test('vessel interaction wire: clicking a card selects and transfers, like the s
assert.equal(requests[0].kind, 'vessel');
assert.equal(requests[0].id, harness.record.mmsi);
} finally {
- _setVesselOverlayHostForTest(null);
+ useVesselHost(null);
harness.cleanup();
}
});
@@ -1926,9 +1950,7 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
- _setVesselOverlayHostForTest(
- hostWithCardHit(`vessel:${harness.record.mmsi}`),
- );
+ useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -1939,11 +1961,36 @@ test('vessel interaction wire: clicking the selected vessel card refocuses exact
assert.equal(requests[0].id, harness.record.mmsi);
assert.equal(harness.trail.clearCalls, 0);
} finally {
- _setVesselOverlayHostForTest(null);
+ useVesselHost(null);
harness.cleanup();
}
});
+// Another layer's card on top takes the click from the vessel card under it
+// and from a vessel icon under it alike.
+test('vessel interaction wire: a covered card and a covered vessel pick both yield', () => {
+ for (const ownPick of [false, true]) {
+ const harness = installWireHarness(ownPick ? { id: makeRecord().mmsi } : null);
+ const requests = [];
+ harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
+ requests.push(event.detail),
+ );
+ useVesselHost(
+ hostWithCardHit(`vessel:${harness.record.mmsi}`, {
+ sourceId: 'earthquakes', entryId: 'quake:cover',
+ }),
+ );
+ try {
+ harness.handler.click({ position: { x: 10, y: 20 } });
+ assert.equal(requests.length, 0, `own pick: ${ownPick}`);
+ assert.equal(aisLiveVesselsLayer.getSelectedInfo()?.mmsi, harness.record.mmsi);
+ } finally {
+ useVesselHost(null);
+ harness.cleanup();
+ }
+ }
+});
+
test('vessel interaction wire: an unknown card id preserves selection and never flies', () => {
const harness = installWireHarness({
primitive: {},
@@ -1955,7 +2002,7 @@ test('vessel interaction wire: an unknown card id preserves selection and never
requests.push(event.detail),
);
// An evicted vessel's card id resolves to no live record.
- _setVesselOverlayHostForTest(hostWithCardHit('vessel:999999999'));
+ useVesselHost(hostWithCardHit('vessel:999999999'));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -1964,37 +2011,135 @@ test('vessel interaction wire: an unknown card id preserves selection and never
);
assert.equal(requests.length, 0);
} finally {
- _setVesselOverlayHostForTest(null);
+ useVesselHost(null);
harness.cleanup();
}
});
-test('vessel interaction wire: a sibling-owned pick wins without selection mutation', () => {
- // Another layer is already acting on this click; two camera commands is the
- // worse failure, so the card is not consulted.
+test('vessel interaction wire: the vessel card on top wins over a sibling-owned pick', () => {
+ // The card painted on top takes the click; the sibling (an aircraft)
+ // stands aside under it, so there is one camera command, not two.
registerPickOwner('flights', (pickedId) => pickedId === 'a1b2c3');
const harness = installWireHarness({ id: 'a1b2c3' });
const requests = [];
harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
- _setVesselOverlayHostForTest(
- hostWithCardHit(`vessel:${harness.record.mmsi}`),
- );
+ useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
harness.record.mmsi,
);
- assert.equal(requests.length, 0);
+ assert.equal(requests.length, 1);
} finally {
- _setVesselOverlayHostForTest(null);
+ useVesselHost(null);
harness.cleanup();
unregisterPickOwner('flights');
}
});
+// The aircraft layer runs first. Under the vessel's card it stands aside, so
+// the card takes the click: one action.
+test('vessel interaction wire: a card over an aircraft takes the click; the aircraft does not track', (t) => {
+ let tracked = null;
+ registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9');
+ t.after(() => unregisterPickOwner('test-planes'));
+ const harness = installWireHarness(
+ { id: 'plane:9' },
+ { selectedRecord: null },
+ {},
+ (event) => {
+ if (isUnderOtherCard(event)) return;
+ if (event.hit?.id === 'plane:9') tracked = 'plane:9';
+ },
+ );
+ const requests = [];
+ harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
+ requests.push(event.detail),
+ );
+ useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
+ try {
+ harness.handler.click({ position: { x: 10, y: 20 } });
+ assert.equal(tracked, null, 'the aircraft does not track');
+ assert.equal(requests.length, 1, 'the vessel card acts');
+ assert.equal(
+ aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
+ harness.record.mmsi,
+ );
+ } finally {
+ useVesselHost(null);
+ harness.cleanup();
+ }
+});
+
+// A trail acts for nobody: the vessel's card painted over it still selects,
+// and a bare trail pick stays a no-op that keeps the selection.
+test('vessel interaction wire: a card over a trail selects; a bare trail is a no-op', () => {
+ for (const carded of [true, false]) {
+ const harness = installWireHarness(
+ { id: 'gev-trail:fl-a1b2c3:head' },
+ { selectedRecord: null },
+ );
+ const requests = [];
+ harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
+ requests.push(event.detail),
+ );
+ useVesselHost(
+ hostWithCardHit(carded ? `vessel:${harness.record.mmsi}` : null),
+ );
+ try {
+ harness.handler.click({ position: { x: 10, y: 20 } });
+ assert.equal(requests.length, carded ? 1 : 0, `card: ${carded}`);
+ assert.equal(
+ aisLiveVesselsLayer.getSelectedInfo()?.mmsi ?? null,
+ carded ? harness.record.mmsi : null,
+ );
+ } finally {
+ useVesselHost(null);
+ harness.cleanup();
+ }
+ }
+});
+
+// A coarse tap on the vessel's card over a fire, nearby or exact: the card on
+// top keeps the tap.
+test('vessel interaction wire: the card keeps a tap over a nearby or exact fire', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const fire = 'fire:near-miss';
+ registerPickOwner('test-exact-fires', (pickedId) => pickedId === fire);
+ t.after(() => unregisterPickOwner('test-exact-fires'));
+ for (const exact of [false, true]) {
+ const harness = installWireHarness(
+ exact ? { id: fire } : null,
+ { selectedRecord: null },
+ { drillPick: () => [{ id: fire }] },
+ );
+ const requests = [];
+ harness.windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (event) =>
+ requests.push(event.detail),
+ );
+ useVesselHost(hostWithCardHit(`vessel:${harness.record.mmsi}`));
+ try {
+ harness.handler.click({ position: { x: 10, y: 20 } });
+ assert.equal(requests.length, 1, `exact fire: ${exact}`);
+ assert.equal(
+ aisLiveVesselsLayer.getSelectedInfo()?.mmsi,
+ harness.record.mmsi,
+ );
+ } finally {
+ useVesselHost(null);
+ harness.cleanup();
+ }
+ }
+});
+
for (const card of ['live', 'stale', 'absent', 'covered']) {
test(`vessel interaction wire: ${card} foreground card over registered cyclone`, () => {
const id = 'cyclone:fixture:cone:0';
@@ -2020,7 +2165,7 @@ for (const card of ['live', 'stale', 'absent', 'covered']) {
);
return { sourceId: 'cctv', entryId: 'vessel:999999999' };
};
- _setVesselOverlayHostForTest(host);
+ useVesselHost(host);
try {
harness.handler.click({ position: { x: 10, y: 20 } });
assert.equal(
@@ -2029,7 +2174,7 @@ for (const card of ['live', 'stale', 'absent', 'covered']) {
);
assert.equal(requests.length, card === 'live' ? 1 : 0);
} finally {
- _setVesselOverlayHostForTest(null);
+ useVesselHost(null);
harness.cleanup();
unregisterPickOwner('weather-cyclones');
}
diff --git a/src/data/bhoteKoshiEvent.js b/src/data/bhoteKoshiEvent.js
index b47dca8e2b..a2da738282 100644
--- a/src/data/bhoteKoshiEvent.js
+++ b/src/data/bhoteKoshiEvent.js
@@ -2959,11 +2959,12 @@ export function createBhoteKoshiEventLayer({
: Number.isFinite(clientY) && bounds
? clientY - bounds.top
: Number.NaN;
- const hit = overlayHost.hitTest?.(x, y, {
- sourceId: BHOTE_KOSHI_OVERLAY_SOURCE_ID,
- filter: (entry) => String(entry?.id || '').startsWith('evidence-card-'),
- });
- if (typeof hit?.entry?.activate !== 'function') return;
+ // Only the card painted on top acts: an evidence card covered by
+ // another layer's card or label leaves the click to that card.
+ const hit = overlayHost.hitTest?.(x, y);
+ if (hit?.sourceId !== BHOTE_KOSHI_OVERLAY_SOURCE_ID) return;
+ if (!String(hit.entry?.id || '').startsWith('evidence-card-')) return;
+ if (typeof hit.entry.activate !== 'function') return;
hit.entry.activate();
}
diff --git a/src/data/bhoteKoshiEvent.test.mjs b/src/data/bhoteKoshiEvent.test.mjs
index 5eb4b78634..d40bd9933f 100644
--- a/src/data/bhoteKoshiEvent.test.mjs
+++ b/src/data/bhoteKoshiEvent.test.mjs
@@ -2114,6 +2114,7 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
};
const viewer = eventViewer();
let activeCard = null;
+ let coveredBy = null;
const layer = createBhoteKoshiEventLayer({
eventLoader: async () => event,
imagerySpecFactory: async (url) => ({ url }),
@@ -2131,9 +2132,11 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
},
setVisible() {},
clearSource() {},
+ // As the host does: unfiltered, the topmost entry.
hitTest(_x, _y, options) {
+ if (coveredBy && !options?.sourceId) return coveredBy;
if (!activeCard || options?.filter?.(activeCard) === false) return null;
- return { entry: activeCard };
+ return { sourceId: 'bhote-koshi-witnesses', entry: activeCard };
},
},
renderHost: { request() {}, hold() {}, release() {} },
@@ -2160,6 +2163,11 @@ test('Debris-Dammed Lake card opens its source and is armed for approved local v
} finally {
releasePointer(lease);
}
+ // Another layer's card painted over the evidence card takes the click.
+ coveredBy = { sourceId: 'earthquake-card', entryId: 'earthquake-card:q' };
+ viewer._test.canvas.dispatch('click', { offsetX: 640, offsetY: 420 });
+ assert.equal(opened.length, 0, 'a covered evidence card does not open');
+ coveredBy = null;
viewer._test.canvas.dispatch('click', { offsetX: 640, offsetY: 420 });
assert.deepEqual(opened, [[
event.evidenceSpine[1].media.sourceUrl,
diff --git a/src/data/bhoteKoshiLocator.js b/src/data/bhoteKoshiLocator.js
index 81c3e3a196..d9aacfad4d 100644
--- a/src/data/bhoteKoshiLocator.js
+++ b/src/data/bhoteKoshiLocator.js
@@ -2,6 +2,9 @@ import {
clearOverlaySource,
setOverlayEntries,
} from '../overlays/worldOverlay.js';
+import { inputFor } from '../input/dispatcher.js';
+import { clickCard } from './pickRegistry.js';
+import { isTrackingSelectionGesture } from './trackingClickGesture.js';
import { governorRequestRender } from '../renderGovernor.js';
import { drawOf, findCamera } from '../render/rendererOf.js';
import { hexColor } from '../render/color.js';
@@ -279,8 +282,11 @@ export function createBhoteKoshiLocatorLayer({
cancelFrame = (handle) => cancelAnimationFrame(handle),
scheduleDelay = (callback, delayMs) => setTimeout(callback, delayMs),
cancelDelay = (handle) => clearTimeout(handle),
+ input = inputFor,
} = {}) {
let _viewer = null;
+ // The globe click that opens an actionable callout of ours on top.
+ let _removeClick = null;
const _serial = ++layerSerial;
// Whether the layer draws: from enable until it is let go.
let _drawing = false;
@@ -1107,6 +1113,7 @@ export function createBhoteKoshiLocatorLayer({
renderPresentation();
registerDynamicCredit(viewer, BHOTE_KOSHI_LOCATOR_CREDIT);
showOsmCredit(viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID);
+ installCalloutClick(viewer);
requestRender('bhote-koshi-locator-callout');
try {
@@ -1141,8 +1148,34 @@ export function createBhoteKoshiLocatorLayer({
}
}
+ /**
+ * An actionable callout of ours (the trigger record's) is a card painted
+ * over the globe: a click on it opens its source, as its keyboard action
+ * does. Like the other cards, it leaves a drag alone and, on top, takes the
+ * click over whatever is drawn under it.
+ */
+ function installCalloutClick(viewer) {
+ if (_removeClick) return;
+ let clicks = null;
+ try {
+ clicks = input?.(viewer) ?? null;
+ } catch {
+ clicks = null;
+ }
+ _removeClick =
+ clicks?.onClick?.((event) => {
+ if (!_enabled || !isTrackingSelectionGesture(event.gesture)) return;
+ // The card painted on top, read once per click so every layer agrees.
+ const top = clickCard(event);
+ if (top?.sourceId !== BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID) return;
+ if (typeof top.entry?.activate === 'function') top.entry.activate();
+ }) ?? null;
+ }
+
async function disable() {
hideOsmCredit(_viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID);
+ _removeClick?.();
+ _removeClick = null;
_enabled = false;
_boundaryReady = false;
_boundaryResolved = false;
diff --git a/src/data/bhoteKoshiLocator.test.mjs b/src/data/bhoteKoshiLocator.test.mjs
index a24afefee6..523e669cd1 100644
--- a/src/data/bhoteKoshiLocator.test.mjs
+++ b/src/data/bhoteKoshiLocator.test.mjs
@@ -11,6 +11,11 @@ import {
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
import * as Cesium from 'cesium';
import { setLocale } from '../i18n/index.js';
+import {
+ registerPickOwner,
+ setClickCardHitTest,
+ unregisterPickOwner,
+} from './pickRegistry.js';
import { SceneDirector } from '../scenes/director.js';
import { createPlaybackClock } from '../director/clock.js';
import { createDefaultScenePacks } from '../scenes/packs/defaults.js';
@@ -1049,3 +1054,74 @@ test('Bhote Koshi locator layers draw sets of their own, and halos only as they
assert.equal(await second.disable(), true);
assert.equal(viewer._test.live().length, 0);
});
+
+// The trigger record's callout is an actionable card: the layers under it
+// stand aside for it, so a click on it opens its source, as its keyboard
+// action does; anything else on top is left alone.
+test('a click on the locator callout runs its action', async () => {
+ const viewer = viewerFixture();
+ let onClick = null;
+ let top = null;
+ const activated = [];
+ const layer = createBhoteKoshiLocatorLayer({
+ overlayHost: overlayHostFixture(),
+ requestRender() {},
+ ...nonRunningAnimation(),
+ input: () => ({
+ onClick(callback) {
+ onClick = callback;
+ return () => {
+ onClick = null;
+ };
+ },
+ }),
+ });
+ // The card on top at a click, as the host answers the pick registry.
+ setClickCardHitTest(() => top);
+ await layer.init(viewer);
+ await layer.enable(viewer);
+ const click = (extra = {}) =>
+ onClick?.({
+ screenPosition: { x: 5, y: 5 },
+ gesture: { travelPx: 0, durationMs: 80 },
+ topHit: null,
+ hit: null,
+ ...extra,
+ });
+ top = {
+ sourceId: BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
+ entryId: 'bhote-koshi-trigger-record-callout',
+ entry: { activate: () => activated.push('trigger') },
+ };
+ click();
+ assert.deepEqual(activated, ['trigger']);
+ top = {
+ sourceId: 'earthquake-card',
+ entry: { activate: () => activated.push('other') },
+ };
+ click();
+ assert.deepEqual(activated, ['trigger'], 'another layer on top is its own');
+ // A drag that ends on it is not a click on it.
+ top = {
+ sourceId: BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
+ entry: { activate: () => activated.push('trigger') },
+ };
+ click({ gesture: { travelPx: 30, durationMs: 80 } });
+ assert.deepEqual(activated, ['trigger'], 'a drag does not open it');
+ // On top, it takes the click over an aircraft or a camera under it, exact
+ // or a touch contact: those layers stand aside under a card.
+ registerPickOwner('test-planes', (id) => id === 'plane:1');
+ try {
+ const plane = { set: 'planes:1', id: 'plane:1' };
+ const cam = { set: 'cams:1', id: 'cam:1' };
+ click({ topHit: plane, hit: plane });
+ click({ topHit: null, hit: plane });
+ click({ topHit: cam, hit: cam });
+ assert.equal(activated.length, 4, 'the callout on top acts each time');
+ } finally {
+ unregisterPickOwner('test-planes');
+ setClickCardHitTest(null);
+ }
+ await layer.disable();
+ assert.equal(onClick, null, 'disable removes the click handler');
+});
diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs
index 35a634c6cf..fadac2e1d0 100644
--- a/src/data/cctv.test.mjs
+++ b/src/data/cctv.test.mjs
@@ -1020,11 +1020,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
);
assert.match(
componentFunctionSource(cctvLayer.init),
- /_cctvOverlayHost\.hitTest/,
- );
- assert.match(
- componentFunctionSource(cctvLayer.init),
- /sourceId: CCTV_OVERLAY_SOURCE_ID/,
+ /clickCard\?\.\(event\)/,
);
assert.match(
componentFunctionSource(cctvLayer.init),
@@ -1032,7 +1028,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
);
assert.match(
componentFunctionSource(cctvLayer.init),
- /activateCctvCameraFromWorldClick\(cardId, setActiveCamera\)/,
+ /activateCctvCameraFromWorldClick\(\s*top\.entryId,/,
);
});
@@ -1157,11 +1153,8 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
const initSource = componentFunctionSource(cctvLayer.init);
- assert.ok(
- initSource.indexOf('if (pickedId !== null) return') <
- initSource.indexOf('_cctvOverlayHost.hitTest'),
- 'every identified sibling must win before an overlapping CCTV card hit test',
- );
+ // The real init-bound click route, including identified-object barriers,
+ // is exercised in layers/cctv/lifecycle.test.mjs.
assert.match(initSource, /activeCameraId: _activeCameraId/);
assert.match(initSource, /calibrationMode: _calibrationMode/);
});
diff --git a/src/data/directions.test.mjs b/src/data/directions.test.mjs
index ddd144e81f..1f004e1734 100644
--- a/src/data/directions.test.mjs
+++ b/src/data/directions.test.mjs
@@ -28,6 +28,8 @@ import {
createApplicationDirectionsLayer,
} from './directions.js';
import { GROUND_FLOOR_LIFT_M } from './groundFloor.js';
+import { isOwnedByOtherLayer, setClickCardHitTest } from './pickRegistry.js';
+import { fakeInput } from '../input/testDoubles.mjs';
import { instructionFor } from './routeSteps.js';
import { setLocale } from '../i18n/index.js';
import {
@@ -465,6 +467,65 @@ function ownershipFixture(t) {
});
}
+// Directions owns its route, markers and steps while enabled: none of them
+// is empty space to other layers.
+test('enabled, directions owns its picks', (t) => {
+ ownershipFixture(t);
+ const viewer = {
+ scene: {
+ pick: () => null,
+ canvas: { clientWidth: 100, clientHeight: 100 },
+ },
+ };
+ const input = fakeInput(viewer);
+ t.after(() => input.destroy());
+ directionsLayer.enable(viewer);
+ try {
+ for (const id of [
+ 'directions:route',
+ 'directions:marker:a',
+ 'directions:step:3',
+ ])
+ assert.equal(isOwnedByOtherLayer('earthquakes', id), true, id);
+ } finally {
+ directionsLayer.disable(viewer);
+ }
+ assert.equal(isOwnedByOtherLayer('earthquakes', 'directions:route'), false);
+});
+
+// The card or label painted on top takes the click: directions does not even
+// pick under another layer's card, so no step is selected or cleared there.
+test("another layer's card over directions keeps the click", (t) => {
+ ownershipFixture(t);
+ let picks = 0;
+ const viewer = {
+ scene: {
+ pick: () => {
+ picks++;
+ return null;
+ },
+ canvas: { clientWidth: 100, clientHeight: 100 },
+ },
+ };
+ const input = fakeInput(viewer);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => {
+ setClickCardHitTest(null);
+ input.destroy();
+ });
+ directionsLayer.enable(viewer);
+ try {
+ input.tap({ x: 10, y: 10 });
+ assert.equal(picks, 0, 'covered: the scene under the card is not picked');
+ top = null;
+ input.tap({ x: 10, y: 10 });
+ assert.ok(picks > 0, 'open map: the click reaches the scene');
+ } finally {
+ directionsLayer.disable(viewer);
+ }
+});
+
test('placing an endpoint takes the pointer, and every exit path gives it back', (t) => {
ownershipFixture(t);
diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs
index 483e4b00dc..f3741416aa 100644
--- a/src/data/firmsInteraction.test.mjs
+++ b/src/data/firmsInteraction.test.mjs
@@ -11,7 +11,12 @@ import {
buildCellCard,
} from './firmsHeatmap.js';
import { fireDetectionKey } from './firmsLabels.js';
-import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
+import {
+ isUnderOtherCard,
+ registerPickOwner,
+ setClickCardHitTest,
+ unregisterPickOwner,
+} from './pickRegistry.js';
import { getSelectedEntityContext } from './contextStore.js';
import { setLocale } from '../i18n/index.js';
import { shownEntityLabel } from '../voice/speech.js';
@@ -60,10 +65,13 @@ function harness({
fires = [makeFire()],
picked = null,
cardHit = null,
+ topCard = null,
cameraPosition = null,
withDataSource = false,
withGlobe = false,
feed = null,
+ drilled = null,
+ firstClick = null,
} = {}) {
const hadWindow = Object.hasOwn(globalThis, 'window');
const priorWindow = globalThis.window;
@@ -79,16 +87,24 @@ function harness({
};
const published = [];
+ const overlayHost = {
+ setEntries: (sourceId, entries) => published.push(...entries),
+ setVisible() {},
+ clearSource() {},
+ hitTest: (_x, _y, { sourceId } = {}) =>
+ !sourceId && topCard
+ ? topCard
+ : cardHit
+ ? { sourceId: 'firms', entryId: cardHit }
+ : null,
+ };
+ // The card on top at a click, as the host answers the pick registry.
+ setClickCardHitTest((x, y) => overlayHost.hitTest(x, y));
const layer = createFirmsHeatmapLayer({
...(feed ? { feed } : {}),
id: 'firms-test',
name: 'Fires',
- overlayHost: {
- setEntries: (sourceId, entries) => published.push(...entries),
- setVisible() {},
- clearSource() {},
- hitTest: () => (cardHit ? { sourceId: 'firms', entryId: cardHit } : null),
- },
+ overlayHost,
});
const draw = fakeDrawPort();
@@ -108,6 +124,7 @@ function harness({
const viewer = {
scene: {
pick,
+ ...(drilled ? { drillPick: () => drilled } : {}),
canvas: { clientWidth: 1280, clientHeight: 800 },
camera: cameraPosition ? { positionWC: cameraPosition } : undefined,
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
@@ -131,6 +148,8 @@ function harness({
if (!withGlobe)
layer.attachShellServices({ imageryHost: () => ({ kind: 'none' }) });
const input = fakeInput(viewer);
+ // A subscriber that runs before the layer's own (an aircraft layer).
+ if (firstClick) input.input.onClick(firstClick);
// The LOD rebuild (and with it the context-registration sweep) is inert
// without a data source, so tests that drive a real refresh need one.
if (withDataSource) layer.init(viewer);
@@ -155,7 +174,14 @@ function harness({
(record) => record.kind === 'icons' && !record.disposed,
),
click: () => input.click({ x: 400, y: 300 }),
+ cover: (hit) => {
+ topCard = hit;
+ },
+ setPicked: (next) => {
+ picked = next;
+ },
cleanup() {
+ setClickCardHitTest(null);
Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection;
if (hadWindow) globalThis.window = priorWindow;
else delete globalThis.window;
@@ -310,8 +336,16 @@ test('far-side detections cannot consume the bounded ambient-card cohort', () =>
test('clicking a fire sprite selects it and requests the camera transfer', () => {
const fire = makeFire();
- const h = harness({ fires: [fire], picked: glowPick('firms-7') });
+ const h = harness({
+ fires: [fire],
+ picked: glowPick('firms-7'),
+ topCard: { sourceId: 'earthquakes', entryId: 'quake:cover' },
+ });
try {
+ // Under another layer's card the sprite is that card's click.
+ h.click();
+ assert.equal(h.requests.length, 0, 'covered: the card takes it');
+ h.cover(null);
h.click();
assert.equal(h.requests.length, 1);
assert.equal(h.requests[0].kind, 'fire');
@@ -357,6 +391,34 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => {
}
});
+test('a covered fire card does not act, and keeps an existing selection', () => {
+ const fire = makeFire();
+ const h = harness({
+ fires: [fire],
+ cardHit: `fire:${fireDetectionKey(fire)}`,
+ });
+ try {
+ // Covered by another layer's card from the start: nothing selects or flies.
+ h.cover({ sourceId: 'earthquakes', entryId: 'quake:cover' });
+ h.click();
+ assert.equal(h.requests.length, 0);
+ assert.equal(h.layer.getSelectedInfo(), null);
+ // Uncovered, the card selects; covered again, the click is the other
+ // layer's and leaves that selection alone.
+ h.cover(null);
+ h.click();
+ assert.equal(h.requests.length, 1);
+ const selected = h.layer.getSelectedInfo();
+ assert.ok(selected);
+ h.cover({ sourceId: 'earthquakes', entryId: 'quake:cover' });
+ h.click();
+ assert.equal(h.requests.length, 1);
+ assert.deepEqual(h.layer.getSelectedInfo(), selected);
+ } finally {
+ h.cleanup();
+ }
+});
+
// The voice model reads these labels as data (track_entity, get_entity_context,
// pointer_context); the voice card translates them where it shows them.
test('fire labels stay English data in a translated interface', () => {
@@ -388,9 +450,9 @@ test('a click on neither sprite nor card clears without moving the camera', () =
}
});
-// Sibling layers surface heterogeneous pick shapes. Reading `picked.id`
-// directly recognized only bare strings, so an AIS sprite (or satellite, or
-// entity) under a fire card let BOTH layers issue a camera command.
+// Sibling layers surface heterogeneous pick shapes. Whatever is drawn under
+// it, the fire card painted on top takes the click (those layers stand aside
+// under another layer's card, so one click does one thing).
const SIBLING_PICKS = [
['flights', 'a1b2c3', { id: 'a1b2c3' }],
['flights', 'a1b2c3', { primitive: { id: 'a1b2c3' } }],
@@ -400,7 +462,7 @@ const SIBLING_PICKS = [
];
for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
- test(`a ${layerId} pick shaped ${JSON.stringify(picked)} wins over a card hit`, () => {
+ test(`a fire card wins over a ${layerId} pick shaped ${JSON.stringify(picked)}`, () => {
const fire = makeFire();
registerPickOwner(layerId, (pickedId) => pickedId === ownedId);
const h = harness({
@@ -410,11 +472,7 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
});
try {
h.click();
- assert.equal(
- h.requests.length,
- 0,
- `the ${layerId} layer is already acting on this click`,
- );
+ assert.equal(h.requests.length, 1, 'the card on top acts');
} finally {
h.cleanup();
unregisterPickOwner(layerId);
@@ -422,6 +480,135 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
});
}
+// A passive owner's pick (a directions route, a flight trail) acts for nobody:
+// a fire card over it still takes the click, and with no card the pick is
+// still not empty space, so the selection stays.
+test('a fire card acts over a passive pick; the bare pick leaves the selection', () => {
+ const fire = makeFire();
+ registerPickOwner('test-route', (pickedId) => pickedId === 'route:line');
+ const carded = harness({
+ fires: [fire],
+ picked: { id: 'route:line' },
+ cardHit: `fire:${fireDetectionKey(fire)}`,
+ });
+ try {
+ carded.click();
+ assert.equal(carded.requests.length, 1, 'the card acts over the route');
+ assert.ok(carded.layer.getSelectedInfo());
+ } finally {
+ carded.cleanup();
+ }
+ const bare = harness({ fires: [fire], picked: { id: 'route:line' } });
+ try {
+ bare.click();
+ assert.equal(bare.requests.length, 0);
+ assert.equal(
+ bare.layer.getSelectedInfo(),
+ null,
+ 'nothing to clear or pick',
+ );
+ } finally {
+ bare.cleanup();
+ unregisterPickOwner('test-route');
+ }
+});
+
+// A coarse tap on a fire card finds an aircraft nearby through the shared
+// touch contact. The card on top takes it; the aircraft layer stands aside.
+test('a fire card takes a tap over a touch contact its layer acts on', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const fire = makeFire();
+ registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1');
+ t.after(() => unregisterPickOwner('test-planes'));
+ const h = harness({
+ fires: [fire],
+ drilled: [{ id: 'plane:1' }],
+ cardHit: `fire:${fireDetectionKey(fire)}`,
+ });
+ try {
+ h.click();
+ assert.equal(h.requests.length, 1, 'the card takes the tap');
+ assert.ok(h.layer.getSelectedInfo());
+ } finally {
+ h.cleanup();
+ }
+});
+
+// A touch contact whose layer acts only on exact hits does not take the tap
+// from our card; with no card, a coarse tap near an aircraft still clears.
+test('a fire card keeps a tap whose contact does not act; bare taps still clear', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const fire = makeFire();
+ registerPickOwner('test-cameras', (pickedId) => pickedId === 'cam:1');
+ registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:1');
+ t.after(() => {
+ unregisterPickOwner('test-cameras');
+ unregisterPickOwner('test-planes');
+ });
+ const carded = harness({
+ fires: [fire],
+ drilled: [{ id: 'cam:1' }],
+ cardHit: `fire:${fireDetectionKey(fire)}`,
+ });
+ try {
+ carded.click();
+ assert.equal(carded.requests.length, 1, 'the card acts');
+ } finally {
+ carded.cleanup();
+ }
+ const bare = harness({
+ fires: [fire],
+ picked: glowPick('firms-7'),
+ drilled: [{ id: 'plane:1' }],
+ });
+ try {
+ bare.click();
+ assert.ok(bare.layer.getSelectedInfo(), 'a fire is selected');
+ // Nothing exact now; the touch contact is an aircraft, with no card.
+ bare.setPicked(null);
+ bare.click();
+ assert.equal(bare.layer.getSelectedInfo(), null, 'the bare tap clears');
+ } finally {
+ bare.cleanup();
+ }
+});
+
+// The aircraft layer runs first. Under the fire card painted over its plane
+// it stands aside, so the card takes the click: one action, in either order.
+test('a fire card over an aircraft takes the click; the aircraft does not track', (t) => {
+ const fire = makeFire();
+ let tracked = null;
+ registerPickOwner('test-planes', (pickedId) => pickedId === 'plane:9');
+ t.after(() => unregisterPickOwner('test-planes'));
+ const h = harness({
+ fires: [fire],
+ picked: { id: 'plane:9' },
+ cardHit: `fire:${fireDetectionKey(fire)}`,
+ firstClick: (event) => {
+ if (isUnderOtherCard(event)) return;
+ if (event.hit?.id === 'plane:9') tracked = 'plane:9';
+ },
+ });
+ try {
+ h.click();
+ assert.equal(tracked, null, 'the aircraft does not track');
+ assert.equal(h.requests.length, 1, 'the fire card acts');
+ assert.ok(h.layer.getSelectedInfo());
+ } finally {
+ h.cleanup();
+ }
+});
+
test('a stale card id resolves to nothing instead of an arbitrary fire', () => {
const h = harness({
picked: { primitive: {}, content: {}, featureId: 0 },
@@ -698,6 +885,7 @@ test('a click on a fire an application draws in place of the markers selects it
fireDetectionKey(fire),
'the stand-in decides, not the hidden glow under the click',
);
+ assert.equal('rangeM' in h.requests[0], false, 'the usual fire framing');
assert.equal(h.layer.getSelectedInfo().id, fireDetectionKey(fire));
assert.equal(getSelectedEntityContext().label, 'Fire · FRP 1520 MW');
assert.deepEqual(
@@ -716,6 +904,32 @@ test('a click on a fire an application draws in place of the markers selects it
}
});
+test('a stand-in that draws a fire larger says how far the camera stands from it', () => {
+ const fire = makeFire();
+ const asked = [];
+ let range = 24_000;
+ const h = harness({ fires: [fire] });
+ try {
+ h.layer.setMarkerStandIn({
+ hitTest: () => ({ ...fire }),
+ focusRangeM: (record) => {
+ asked.push(fireDetectionKey(record));
+ return range;
+ },
+ });
+ h.click();
+ assert.deepEqual(asked, [fireDetectionKey(fire)]);
+ assert.equal(h.requests.at(-1).rangeM, 24_000);
+ // No range for this fire: the usual fire framing.
+ range = null;
+ h.click();
+ assert.equal(h.requests.length, 2);
+ assert.equal('rangeM' in h.requests.at(-1), false);
+ } finally {
+ h.cleanup();
+ }
+});
+
test('a stand-in hit on a fire the layer does not show selects nothing', () => {
const fire = makeFire();
const h = harness({ fires: [fire] });
diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js
index 88566bc6e5..da6028ed2a 100644
--- a/src/data/localGeojsonCore.js
+++ b/src/data/localGeojsonCore.js
@@ -22,6 +22,7 @@ import {
import { createInfrastructureOverlayEntry } from './infrastructureOverlayEntry.js';
import { createGeojsonPins } from './geojsonPins.js';
import { inputFor as defaultInputFor } from '../input/dispatcher.js';
+import { isUnderOtherCard } from './pickRegistry.js';
import {
selectInfraLod,
applyInfraEvictionGrace,
@@ -1114,6 +1115,9 @@ export function createLocalGeoJsonLayer(
const input = inputFor(viewer);
_clickSubscription = input.onClick((event) => {
if (!_enabled || !_drawn) return;
+ // Another layer's card or label on top takes the click: the
+ // item under it neither acts nor reads as empty space.
+ if (isUnderOtherCard(event)) return;
const hit = event.drawHit;
if (!hit || !hit.set.startsWith(`${setPrefix}:`)) return;
const part = _drawn.parts.get(hit.id);
diff --git a/src/data/localGeojsonDraw.test.mjs b/src/data/localGeojsonDraw.test.mjs
index bbb993f042..255fb5d522 100644
--- a/src/data/localGeojsonDraw.test.mjs
+++ b/src/data/localGeojsonDraw.test.mjs
@@ -6,6 +6,7 @@ import {
} from './localGeojsonCore.js';
import { localGeoJsonServices } from '../app/localGeojsonServices.js';
import { getContextStore } from './contextStore.js';
+import { setClickCardHitTest } from './pickRegistry.js';
import { readEntityRecord } from './entityRecords.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
const feature = (id, geometry, properties = { name: `Feature ${id}` }) => ({
@@ -161,6 +162,24 @@ test('polygons fill the ground, lines drape, points stand on pins, all shown', a
assert.equal(record?.label, 'Feature p');
});
+// The card or label painted on top takes the click: a feature under another
+// layer's card is not selected.
+test("another layer's card over a drawn part keeps the click", async (t) => {
+ const env = await enabledLayer(t, [
+ feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
+ ]);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ const fills = env.fake.set('fills');
+ const at = { x: 5, y: 5 };
+ env.click({ screenPosition: at, drawHit: { set: fills.spec.id, id: 'p' } });
+ assert.equal(env.fake.flights.length, 0, 'covered: not selected');
+ top = null;
+ env.click({ screenPosition: at, drawHit: { set: fills.spec.id, id: 'p' } });
+ assert.equal(env.fake.flights.length, 1);
+});
+
test('a click on a drawn part selects its feature and flies above it', async (t) => {
const env = await enabledLayer(t, [
feature('p', { type: 'Polygon', coordinates: square(0, 0) }),
diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js
index 95243c02ee..f11f6e8553 100644
--- a/src/data/pickRegistry.js
+++ b/src/data/pickRegistry.js
@@ -145,3 +145,59 @@ export function pickContact(query, position, options = {}) {
}
return picked;
}
+
+/**
+ * The world overlay's hit test: the topmost interactive card or label painted
+ * at CSS-pixel coordinates, or null. Set by the overlay host while it runs.
+ * @type {((x: number, y: number) => {sourceId: string, entryId: string}|null)|null}
+ */
+let _overlayHitTest = null;
+/** @type {WeakMap} */
+const clickCards = new WeakMap();
+
+/**
+ * Sets (or with null, clears) the hit test that names the card or label
+ * painted at a click. The world-overlay host sets it while it runs.
+ * @param {((x: number, y: number) => object|null)|null} hitTest
+ * @returns {void}
+ */
+export function setClickCardHitTest(hitTest) {
+ _overlayHitTest = typeof hitTest === 'function' ? hitTest : null;
+}
+
+/**
+ * The topmost interactive card or label painted at a click, read once per
+ * click so every handler of it sees the same one whatever ran first.
+ * @param {{screenPosition?: {x: number, y: number}}|null|undefined} click
+ * @returns {{sourceId: string, entryId: string}|null}
+ */
+export function clickCard(click) {
+ if (!click || typeof click !== 'object') return null;
+ if (clickCards.has(click)) return clickCards.get(click);
+ const at = click.screenPosition;
+ let card = null;
+ try {
+ card = _overlayHitTest?.(at?.x, at?.y) ?? null;
+ } catch {
+ // a broken hit test must never break click handling
+ }
+ clickCards.set(click, card);
+ return card;
+}
+
+/**
+ * True when another layer's card or label is painted on top at a click. The
+ * card on top takes the click: a scene item under it does not act, and is
+ * not empty space either, so the layer leaves its selection alone.
+ * @param {object} click The shared dispatcher event.
+ * @param {Iterable} [ownSourceIds] The asking layer's overlay
+ * sources: its own card on top is its click.
+ * @returns {boolean}
+ */
+export function isUnderOtherCard(click, ownSourceIds = []) {
+ const card = clickCard(click);
+ if (!card) return false;
+ for (const sourceId of ownSourceIds)
+ if (card.sourceId === sourceId) return false;
+ return true;
+}
diff --git a/src/data/pickRegistry.test.mjs b/src/data/pickRegistry.test.mjs
index 924c956692..eb3347fe8c 100644
--- a/src/data/pickRegistry.test.mjs
+++ b/src/data/pickRegistry.test.mjs
@@ -17,6 +17,9 @@ import {
isOwnedByOtherLayer,
resolvePickId,
pickContact,
+ clickCard,
+ isUnderOtherCard,
+ setClickCardHitTest,
} from './pickRegistry.js';
// ---------------------------------------------------------------------------
@@ -197,3 +200,40 @@ test('touch picking tolerates a failing drill and preserves empty sky', (t) => {
])
assert.equal(pickContact(query(null, drillPick), { x: 1, y: 1 }), null);
});
+
+test("the card on top is read once per click, and only another layer's card counts", () => {
+ let top = { sourceId: 'quake-card', entryId: 'q1' };
+ let reads = 0;
+ setClickCardHitTest((x, y) => {
+ reads++;
+ assert.deepEqual([x, y], [4, 5]);
+ return top;
+ });
+ try {
+ const click = { screenPosition: { x: 4, y: 5 } };
+ assert.equal(isUnderOtherCard(click, ['vessel-card']), true);
+ assert.equal(isUnderOtherCard(click, ['quake-card']), false, 'own card');
+ // A card published later in the same click does not change it.
+ top = { sourceId: 'vessel-card', entryId: 'v1' };
+ assert.equal(clickCard(click).sourceId, 'quake-card');
+ assert.equal(reads, 1);
+ assert.equal(isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }), true);
+ top = null;
+ assert.equal(isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }), false);
+ } finally {
+ setClickCardHitTest(null);
+ }
+ assert.equal(
+ isUnderOtherCard({ screenPosition: { x: 4, y: 5 } }),
+ false,
+ 'no host',
+ );
+ setClickCardHitTest(() => {
+ throw new Error('broken');
+ });
+ try {
+ assert.equal(clickCard({ screenPosition: { x: 1, y: 1 } }), null);
+ } finally {
+ setClickCardHitTest(null);
+ }
+});
diff --git a/src/director/document.js b/src/director/document.js
index 2ab0e6ec32..a682605a00 100644
--- a/src/director/document.js
+++ b/src/director/document.js
@@ -36,7 +36,7 @@ function visual(value, path, legacy) {
const specs = {
bloom: { enabled: 'boolean', intensity: [-100, 10000], version: [1, 100] },
sharpen: { enabled: 'boolean', intensity: [0, 100] },
- hud: { visible: 'boolean', variant: 'string' },
+ hud: { visible: 'boolean', variant: 'string', sonar: 'boolean' },
detection: {
mode: 'string',
density: [0, 100],
diff --git a/src/director/document.test.mjs b/src/director/document.test.mjs
index 0a73f98edb..4e7e1112a5 100644
--- a/src/director/document.test.mjs
+++ b/src/director/document.test.mjs
@@ -168,3 +168,30 @@ test('captured scope and extended detection edits survive migration', () => {
project.scenes[0].shots[0].visual.detection,
);
});
+
+test('a shot keeps Sonar beside its HUD layout; one without it reads as before', () => {
+ const project = fixture();
+ const shot = project.scenes[0].shots[0];
+ shot.visual = { hud: { visible: true, variant: 'minimal', sonar: true } };
+ const read = (p) =>
+ normalizeProject(parseSceneDocument(JSON.stringify(p))).scenes[0].shots[0]
+ .visual.hud;
+ assert.deepEqual(read(project), {
+ visible: true,
+ variant: 'minimal',
+ sonar: true,
+ });
+ // Older shots name no Sonar: the layout alone, Cyber included, as before.
+ for (const variant of ['minimal', 'cyber']) {
+ shot.visual = { hud: { visible: true, variant } };
+ assert.deepEqual(read(project), { visible: true, variant });
+ }
+ // Off is the meaning of an absent field, so it is not kept.
+ shot.visual = { hud: { variant: 'minimal', sonar: false } };
+ assert.equal(Object.hasOwn(read(project), 'sonar'), false);
+ shot.visual = { hud: { variant: 'minimal', sonar: 'on' } };
+ assert.throws(
+ () => validateSceneDocument(project),
+ /\$\.scenes\[0\]\.shots\[0\]\.visual\.hud\.sonar/,
+ );
+});
diff --git a/src/firstRunCopy.js b/src/firstRunCopy.js
index d594d3d41a..b1daca0736 100644
--- a/src/firstRunCopy.js
+++ b/src/firstRunCopy.js
@@ -26,7 +26,17 @@ export function environmentalLabel(choice = ENVIRONMENTAL_LABEL_CHOICE) {
return { title: t(key) };
}
-/** The status line between missions. */
-export const FIRST_RUN_TIP = msg(
- 'Tip: the GEV MIC button in the dock lets you talk to the map.',
-);
+/**
+ * The outbound links the first-run card offers.
+ * @type {Readonly>}
+ */
+export const FIRST_RUN_LINKS = Object.freeze({
+ /** The open-source repository. */
+ source: 'https://github.com/bilawalsidhu/gods-eye-view',
+ youtube: 'https://www.youtube.com/@bilawalsidhu',
+ x: 'https://x.com/bilawalsidhu',
+ instagram: 'https://www.instagram.com/bilawal.ai',
+ linkedin: 'https://www.linkedin.com/in/bilawalsidhu',
+ website: 'https://bilawal.ai',
+ halfpixel: 'https://halfpixel.ai',
+});
diff --git a/src/firstRunExperience.js b/src/firstRunExperience.js
index 2f9ef9c514..3dbc02a6d0 100644
--- a/src/firstRunExperience.js
+++ b/src/firstRunExperience.js
@@ -23,13 +23,12 @@ import { createSurfaceKeyboard } from './ui/surfaceKeyboard.js';
import { t, msg } from './i18n/index.js';
import { EXCLUSIVE_SURFACE_CLASSES } from './exclusiveSurfaces.js';
-import { FIRST_RUN_TIP, environmentalLabel } from './firstRunCopy.js';
+import { environmentalLabel } from './firstRunCopy.js';
import { useFirstRunStore } from './ui/stores/firstRun.js';
import { applicationPinia } from './ui/vueRuntime.js';
export {
ENVIRONMENTAL_LABEL_CHOICE,
- FIRST_RUN_TIP,
environmentalLabel,
} from './firstRunCopy.js';
@@ -53,12 +52,12 @@ export const FIRST_RUN_SESSION_KEY = 'gev:first-run-mission-session:v1';
* TOUCHED, DURABLE layer enables for the mission's OWN layers, at
* `origin: 'user'` — identical to clicking those rows.
* Choosing ENVIRONMENTAL *is* choosing those layers.
- * TOUCHED, DURABLE the Context panel reveal, but only for the Contacts
- * mission, exactly as the visible Contacts tab does
- * it. Space Missions opens its own panel the way
- * switching its layer on does. The globe missions open
- * no panel at all — nothing there needs explaining,
- * and a panel-collapse write is a pref nobody chose.
+ * TOUCHED, DURABLE the Space Missions panel, which opens as it does when
+ * its layer is switched on from its Data Layers row.
+ * No mission reveals the Context panel, and the globe
+ * missions open no panel at all — nothing there needs
+ * explaining, and a panel-collapse write is a pref
+ * nobody chose.
* TOUCHED, SESSION the camera. Never persisted by anything.
* NOT TOUCHED detection mode + density. The reasonable-defaults
* landing owns the DENSE/75 start, and Contacts owns
@@ -67,8 +66,8 @@ export const FIRST_RUN_SESSION_KEY = 'gev:first-run-mission-session:v1';
* NOT TOUCHED `_detectionUserOverridden`. Setting it would mean "the
* operator hand-edited detection" and would silently
* kill the CRT/NVG/FLIR auto-preset contract for the
- * whole session. Missions run through setContextMode and
- * DataManager.setEnabled, neither of which writes it.
+ * whole session. Missions run through
+ * DataManager.setEnabled, which does not write it.
* NOT TOUCHED detection allocation (`gev:detection-allocation:v1`),
* 3D aircraft models, scope feather. All are defaults or
* separate durable prefs the visitor did not choose here.
@@ -76,19 +75,12 @@ export const FIRST_RUN_SESSION_KEY = 'gev:first-run-mission-session:v1';
* `_setModels3dMode`, which default to origin 'user' and
* would persist a 3D choice nobody made.
*
- * The Contacts mission deliberately reuses `styleManager.setContextMode`, the
- * same facade the visible tab and voice use, so Contacts detection ownership,
- * layer isolation and rollback stay in exactly one place. Space Missions is an
- * ordinary layer, switched on like clicking its row.
+ * Every mission is an ordinary layer choice, switched on like clicking its row,
+ * so no mission enters a Context mode.
*/
/** @type {Readonly>} */
export const FIRST_RUN_MISSIONS = Object.freeze({
- contacts: Object.freeze({
- kind: 'context',
- contextMode: 'contacts',
- busyKey: msg('Starting live contacts…'),
- }),
'space-missions': Object.freeze({
// An ordinary layer with its own panel: no camera flight, and its panel
// opens as it does for a click on its Data Layers row.
@@ -250,22 +242,17 @@ export function rememberFirstRunSessionDismissed(sessionStorageRef) {
*
* @param {string} choice Key of FIRST_RUN_MISSIONS.
* @param {object} deps
- * @param {(mode: string) => Promise} deps.setContextMode
* @param {(layerId: string) => Promise} deps.setLayerEnabled
* @param {() => Promise} deps.flyToGlobe
- * @returns {Promise<{ok: boolean, choice: string, result?: object, failedLayerIds?: string[]}>}
+ * @returns {Promise<{ok: boolean, choice: string, failedLayerIds?: string[]}>}
*/
export async function runFirstRunChoice(
choice,
- { setContextMode, setLayerEnabled, flyToGlobe },
+ { setLayerEnabled, flyToGlobe },
) {
const mission = FIRST_RUN_MISSIONS[choice];
if (!mission) return { ok: false, choice };
if (mission.kind === 'none') return { ok: true, choice };
- if (mission.kind === 'context') {
- const result = await setContextMode(mission.contextMode);
- return { ok: Boolean(result?.ok), choice, result };
- }
// Globe missions: start the pull-out and the layer work together so the
// camera is already moving while the feeds spin up. The flight is framing,
// not the mission — a stalled or superseded flight never fails the tile.
@@ -344,16 +331,14 @@ export function initFirstRunExperience({
closing: false,
state: null,
busy: null,
- status: t(FIRST_RUN_TIP),
+ // Empty until a mission reports progress or an error.
+ status: '',
// The tile name is owner-switchable from one constant, so paint it from
// the module rather than trusting the markup to match.
environmentalTitle: environmentalLabel().title,
environmentalSub: t(
'Live earthquakes and active fires, from USGS and NASA',
),
- description: t(
- 'It feels like a forbidden cockpit—then you realize the sources are public and the data is real.',
- ),
scrollable: null,
};
let signature = '';
@@ -379,7 +364,6 @@ export function initFirstRunExperience({
}
present({});
- const defaultStatus = view.status;
// An error or refused save stays on the status line until the next choice.
let stickyStatus = false;
let busy = false;
@@ -439,10 +423,14 @@ export function initFirstRunExperience({
globalThis.removeEventListener?.('resize', onViewportResize);
surfaceObserver?.disconnect();
const remove = () => {
+ root.removeEventListener('transitionend', onTransitionEnd);
store.connect(null);
present({ removed: true });
};
- root.addEventListener('transitionend', remove, { once: true });
+ const onTransitionEnd = (event) => {
+ if (event.target === root) remove();
+ };
+ root.addEventListener('transitionend', onTransitionEnd);
// `transitionend` never fires under prefers-reduced-motion (no transition),
// so a bounded fallback is what actually removes the node there.
globalThis.setTimeout?.(remove, 400);
@@ -459,7 +447,7 @@ export function initFirstRunExperience({
const patch = { state: next ? 'loading' : 'ready', busy: String(next) };
if (next)
patch.status = t(FIRST_RUN_MISSIONS[choice]?.busyKey || msg('Working…'));
- else if (!stickyStatus) patch.status = defaultStatus;
+ else if (!stickyStatus) patch.status = '';
present(patch);
};
@@ -471,19 +459,6 @@ export function initFirstRunExperience({
let outcome = null;
try {
outcome = await runFirstRunChoice(choice, {
- setContextMode: async (mode) => {
- const result = await styleManager.setContextMode(mode);
- if (result?.ok) {
- // setContextMode is also a voice/internal facade and deliberately
- // does not decide panel chrome. This first-run click is an explicit
- // visual choice, so reveal the result exactly as the visible
- // Contacts tab does.
- styleManager.setPanelCollapsed?.('global-context-panel', false, {
- explicit: true,
- });
- }
- return result;
- },
// `origin: 'user'` on purpose: a mission tile is a real person choosing
// these layers, so it persists exactly as clicking those rows would.
setLayerEnabled: (layerId) =>
@@ -500,9 +475,7 @@ export function initFirstRunExperience({
dismiss();
return;
}
- const failed = outcome?.failedLayerIds?.length
- ? outcome.failedLayerIds
- : outcome?.result?.failedLayerIds;
+ const failed = outcome?.failedLayerIds;
const detail =
Array.isArray(failed) && failed.length ? ` (${failed.join(', ')})` : '';
stickyStatus = true;
@@ -540,6 +513,9 @@ export function initFirstRunExperience({
isActive: () => !closing && isTopmost(),
onEscape: () => dismiss(),
fallbackFocus: () => documentRef.body,
+ // The card sits beside a usable map: Tab from the search bar or any
+ // other control follows the page's order instead of jumping back in.
+ claimOutsideFocus: false,
});
store.connect({
@@ -547,6 +523,7 @@ export function initFirstRunExperience({
// The same dismissal as ESC, for screens without a keyboard.
dismiss: () => dismiss(),
suppress: onSuppressChange,
+ refreshLayout: () => syncScrollAffordance(),
});
// Capture phase: the app binds its own global hotkeys (including bare letters
// that cycle detection and styles), and the launcher owns the keyboard first.
@@ -572,7 +549,7 @@ export function initFirstRunExperience({
present({ visible: true });
syncScrollAffordance();
root
- .querySelector('[data-first-run-choice]')
+ .querySelector('[data-first-run-primary]')
?.focus?.({ preventScroll: true });
});
};
diff --git a/src/firstRunExperience.test.mjs b/src/firstRunExperience.test.mjs
index e86dfc5c90..b6bb8e9c39 100644
--- a/src/firstRunExperience.test.mjs
+++ b/src/firstRunExperience.test.mjs
@@ -537,20 +537,13 @@ test('the launcher yields on engage and waits when a surface is already up', ()
// ── Per-mission behavior ─────────────────────────────────────────────────────
function missionSpy({
- contextOk = true,
layerResult = () => true,
globe = async () => ({ ok: true }),
} = {}) {
- const calls = { contextModes: [], layerIds: [], globeFlights: 0 };
+ const calls = { layerIds: [], globeFlights: 0 };
return {
calls,
deps: {
- setContextMode: async (mode) => {
- calls.contextModes.push(mode);
- return contextOk
- ? { ok: true, mode }
- : { ok: false, failedLayerIds: ['military-awareness'] };
- },
setLayerEnabled: async (layerId) => {
calls.layerIds.push(layerId);
return layerResult(layerId);
@@ -563,14 +556,14 @@ function missionSpy({
};
}
-test('the menu is the four owner-ordered missions', () => {
+test('the menu is the three owner-ordered missions', () => {
// INFRASTRUCTURE was removed after the owner playtested it: enabling all
// three bundled layers at once put ~5,700 entities on a full-earth view and
// tanked the frame rate. The layers stay reachable by hand and by voice; what
// went is the one-click globe-scale dump. Restoring the tile needs the
- // globe-LOD declutter first.
+ // globe-LOD declutter first. Live Contacts was dropped from the product, so
+ // it is not offered as a starting mission either.
assert.deepEqual(Object.keys(FIRST_RUN_MISSIONS), [
- 'contacts',
'space-missions',
'environmental',
'explore',
@@ -580,27 +573,17 @@ test('the menu is the four owner-ordered missions', () => {
undefined,
'the infrastructure mission must be gone, not dormant',
);
-});
-
-test('Live Contacts goes through the one setContextMode facade', async () => {
- const spy = missionSpy();
- const outcome = await runFirstRunChoice('contacts', spy.deps);
- assert.equal(outcome.ok, true);
- assert.deepEqual(spy.calls.contextModes, ['contacts']);
- // A Context mission owns no layers and no camera of its own — the facade does.
- assert.deepEqual(spy.calls.layerIds, []);
- assert.equal(spy.calls.globeFlights, 0);
+ assert.equal(
+ FIRST_RUN_MISSIONS.contacts,
+ undefined,
+ 'the contacts mission must be gone, not dormant',
+ );
});
test('Space Missions switches on its layer like a row click, without a flight', async () => {
const spy = missionSpy();
const outcome = await runFirstRunChoice('space-missions', spy.deps);
assert.equal(outcome.ok, true);
- assert.deepEqual(
- spy.calls.contextModes,
- [],
- 'Space Missions is not a Context mode',
- );
assert.deepEqual(spy.calls.layerIds, ['rocket-launches']);
assert.equal(spy.calls.globeFlights, 0, 'the layer frames the globe itself');
@@ -680,24 +663,9 @@ test('a refused layer fails the mission by name, and a stalled flight never does
test('Explore manually touches nothing at all, and an unknown choice is inert', async () => {
const spy = missionSpy();
assert.equal((await runFirstRunChoice('explore', spy.deps)).ok, true);
- assert.deepEqual(spy.calls, {
- contextModes: [],
- layerIds: [],
- globeFlights: 0,
- });
+ assert.deepEqual(spy.calls, { layerIds: [], globeFlights: 0 });
assert.equal((await runFirstRunChoice('nope', spy.deps)).ok, false);
- assert.deepEqual(spy.calls, {
- contextModes: [],
- layerIds: [],
- globeFlights: 0,
- });
-});
-
-test('a failed Context mission reports the layers the facade named', async () => {
- const spy = missionSpy({ contextOk: false });
- const outcome = await runFirstRunChoice('contacts', spy.deps);
- assert.equal(outcome.ok, false);
- assert.deepEqual(outcome.result.failedLayerIds, ['military-awareness']);
+ assert.deepEqual(spy.calls, { layerIds: [], globeFlights: 0 });
});
test('the fires/quakes tile name is switchable from one constant', () => {
@@ -748,23 +716,10 @@ test('no mission writes a preference the visitor did not choose by picking it',
);
}
- // The only durable panel write is the Context reveal, and only on the Context
- // mission — the globe missions open no panel at all, and Space Missions'
- // panel opens the way its layer row's switch opens it.
- const panelWrites = code.match(/setPanelCollapsed/g) || [];
- assert.equal(
- panelWrites.length,
- 1,
- 'exactly one panel reveal, on the Context path',
- );
- const contextPath = code.slice(
- code.indexOf('setContextMode: async (mode)'),
- code.indexOf('setLayerEnabled:'),
- );
- assert.match(
- contextPath,
- /result\?\.ok[\s\S]*?setPanelCollapsed\?\.\('global-context-panel', false, \{\s*explicit: true,?\s*\}\)/,
- );
+ // No mission writes panel chrome: the globe missions open no panel at all,
+ // and Space Missions' panel opens the way its layer row's switch opens it.
+ assert.doesNotMatch(code, /setPanelCollapsed/);
+ assert.doesNotMatch(code, /setContextMode/);
});
test('the decision table is written down where the next editor will read it', () => {
@@ -801,56 +756,19 @@ test('markup, startup ordering and accessibility remain pinned', async () => {
html,
/id="first-run-launcher" role="dialog"[^>]*aria-labelledby="first-run-title"[^>]*hidden/,
);
- assert.equal((html.match(/data-first-run-choice=/g) || []).length, 4);
+ assert.equal((html.match(/data-first-run-choice=/g) || []).length, 0);
+ assert.match(html, /data-first-run-next/);
+ assert.ok(
+ html.includes(
+ 'It feels like a forbidden cockpit—then you realize the sources are public and the data is real.
',
+ ),
+ 'the maintainer-authored first-run line stays verbatim',
+ );
assert.match(
html,
/data-first-run-status[^>]*role="status"[^>]*aria-live="polite"/,
);
assert.match(html, / /);
- assert.match(html, //);
- // Subcopy must name BOTH feeds the tile turns on — a tile that promised only
- // half of what it does is the defect this replaced. Only the VISIBLE
- // text counts; the comment beside it naturally says the words too.
- const envTile = html.slice(
- html.indexOf('data-first-run-choice="environmental"'),
- );
- const visible = envTile.slice(
- envTile.indexOf(''),
- envTile.indexOf(' '),
- );
- assert.match(visible, /earthquakes/i);
- assert.match(
- visible,
- /fires?/i,
- 'the tile must promise the fires it enables',
- );
-
- // The card's one persuasive line is OWNER-AUTHORED and pinned verbatim,
- // unspaced em dash included. This is copy, not prose to be improved in a
- // passing edit — changing it needs the owner, not a nicer-sounding rewrite.
- assert.ok(
- html.includes(
- ' It feels like a forbidden cockpit' +
- '—then you realize the sources are public and the data is real.
',
- ),
- 'the owner-authored first-run line must ship exactly as written',
- );
-
- // Menu order is the owner's, read straight off the markup.
- const order = [...html.matchAll(/data-first-run-choice="([a-z-]+)"/g)].map(
- (match) => match[1],
- );
- assert.deepEqual(order, [
- 'contacts',
- 'space-missions',
- 'environmental',
- 'explore',
- ]);
- assert.doesNotMatch(
- html,
- /data-first-run-choice="infrastructure"/,
- 'the removed tile must leave no markup behind',
- );
assert.match(startup, /styleManager\.initialRestorePromise/);
assert.ok(
@@ -905,40 +823,156 @@ test('markup, startup ordering and accessibility remain pinned', async () => {
assert.match(choicesBlock, /overflow-y: auto;/);
});
+test('the header text keeps clear of the centred step dots', () => {
+ const css = fs.readFileSync(
+ new URL('./ui/styles/first-run.css', import.meta.url),
+ 'utf8',
+ );
+ // Above 620px the dots are absolutely centred over the header row, so the
+ // kicker and Skip must stop short of them; long locales then wrap.
+ assert.match(css, /\.first-run-dots \{\s*position: absolute;\s*left: 50%;/);
+ assert.match(
+ css,
+ /@media \(min-width: 621px\) \{\s*\.first-run-kicker,\s*\.first-run-dismiss \{\s*max-width: calc\(50% - 2\.4rem\);\s*\}\s*\}/,
+ );
+ assert.match(
+ css,
+ /@media \(max-width: 620px\) \{\s*\.first-run-dots \{\s*position: static;/,
+ );
+});
+
+test('reduced motion stops every first-run animation, however specific', () => {
+ const css = fs.readFileSync(
+ new URL('./ui/styles/first-run.css', import.meta.url),
+ 'utf8',
+ );
+ // Every rule that starts an infinite animation must be matched by a
+ // reduced-motion rule at least as specific, or the animation keeps running.
+ const reduced = [
+ ...css.matchAll(
+ /@media \(prefers-reduced-motion: reduce\) \{([\s\S]*?)\n\}/g,
+ ),
+ ]
+ .map((m) => m[1])
+ .join('\n');
+ const squash = (selector) => selector.replace(/\s+/g, ' ').trim();
+ const reducedSelectors = new Set(
+ [...reduced.matchAll(/([^{}]+)\{[^}]*animation: none/g)].flatMap((m) =>
+ m[1].split(/,(?![^(]*\))/).map(squash),
+ ),
+ );
+ const animated = [
+ ...css.matchAll(/([^{}@]+)\{[^}]*animation: [^;]*infinite/g),
+ ]
+ .flatMap((m) => m[1].split(/,(?![^(]*\))/).map(squash))
+ .filter((selector) => !selector.startsWith('/*'));
+ assert.ok(animated.length > 5, 'found the animated rules');
+ const covered = (selector) => {
+ if (reducedSelectors.has(selector)) return true;
+ // An :is() group in the reduced block covers each of its members.
+ return [...reducedSelectors].some((reducedSelector) => {
+ const group = reducedSelector.match(/^(.*) :is\(([^)]*)\)$/);
+ return (
+ group &&
+ group[2]
+ .split(',')
+ .map((part) => `${group[1]} ${part.trim()}`)
+ .includes(selector)
+ );
+ });
+ };
+ const missing = animated.filter((selector) => !covered(selector));
+ assert.deepEqual(missing, [], 'animations reduced motion leaves running');
+});
+
+test('the welcome backdrop tints the globe without blurring it', () => {
+ const css = fs.readFileSync(
+ new URL('./ui/styles/first-run.css', import.meta.url),
+ 'utf8',
+ );
+ const backdrop = css.match(/\.first-run-backdrop \{([^}]*)\}/)?.[1] || '';
+ assert.match(backdrop, /background: rgba\(3, 8, 14, 0\.28\);/);
+ assert.match(backdrop, /pointer-events: none;/, 'click-through');
+ assert.doesNotMatch(backdrop, /backdrop-filter/);
+});
+
+test('every outbound first-run link opens without opener or referrer', () => {
+ const view = fs.readFileSync(
+ new URL('./ui/views/WelcomeView.vue', import.meta.url),
+ 'utf8',
+ );
+ const links = view.match(/]*target="_blank"[^>]*>/g) || [];
+ assert.ok(links.length >= 7, 'the source and Halfpixel chips are outbound');
+ for (const link of links) {
+ assert.match(link, /rel="noopener noreferrer"/, link);
+ }
+});
+
+test('the Stories announcement waits behind the welcome card', () => {
+ const css = fs.readFileSync(
+ new URL('./ui/styles/first-run.css', import.meta.url),
+ 'utf8',
+ );
+ // Hidden, not consumed: the popup keeps its unseen state and appears once
+ // the card is dismissed.
+ assert.match(
+ css,
+ /body:has\(#first-run-launcher\) #gev-stories #hPop,\s*body\.first-run-opening-stories #gev-stories #hPop \{\s*visibility: hidden;\s*pointer-events: none;\s*\}/,
+ );
+ // The selector only works while Stories still renders the popup as #hPop
+ // inside #gev-stories.
+ const stories = fs.readFileSync(
+ new URL('./ui/views/StoriesView.vue', import.meta.url),
+ 'utf8',
+ );
+ const root = stories.indexOf('= 0, 'StoriesView renders #gev-stories');
+ assert.ok(popup > root, 'StoriesView renders #hPop inside #gev-stories');
+});
+
test('the card closes without a keyboard: the ESC hint is a button, kept on phones', async () => {
const html = await renderApplicationHtml(
fs.readFileSync(new URL('../index.html', import.meta.url), 'utf8'),
);
// The whole stylesheet, so a hide rule added in any other file is caught too.
const css = readStylesheet(new URL('../style.css', import.meta.url));
- const footer = html.slice(
- html.indexOf('class="first-run-footer"'),
- html.indexOf('data-first-run-status'),
+ const header = html.slice(
+ html.indexOf('class="first-run-header"'),
+ html.indexOf('id="first-run-title"'),
);
assert.match(
- footer,
+ header,
/
/,
);
- assert.match(footer, />ESC to dismiss);
- assert.match(footer, />DISMISS);
+ assert.match(header, />SKIP · ESC);
+ assert.match(header, />SKIP);
// It closes the way ESC does, through the one dismiss path, so the session
// flag and focus handling are the same: firstRunLauncherView.test.mjs.
// Phones used to hide the hint, leaving no way out but picking a mission.
- assert.doesNotMatch(css, /first-run-footer > span:last-child/);
assert.doesNotMatch(css, /\.first-run-dismiss\s*\{[^}]*display:\s*none/);
- // A 44px touch target that does not add to the footer row's height.
+ // A 44px touch target that does not add to the header row's height.
assert.match(
css,
/\.first-run-dismiss::before \{[^}]*position: absolute;[^}]*height: 44px;/,
);
assert.doesNotMatch(css, /\.first-run-dismiss \{[^}]*min-height/);
- // Touch screens read DISMISS rather than a key they do not have.
+ // Touch screens read SKIP rather than a key they do not have.
assert.match(
css,
/@media \(hover: none\) and \(pointer: coarse\) \{\s*\.first-run-dismiss-key \{\s*display: none;/,
);
});
+test('a short landscape phone keeps the card inside the viewport', () => {
+ const css = readStylesheet(new URL('../style.css', import.meta.url));
+ // Above the tab bar, never taller than the space left between it and the top.
+ assert.match(
+ css,
+ /body\.mobile-shell #first-run-launcher \{[^}]*bottom: 5\.8rem;[^}]*max-height: calc\(100dvh - 6\.55rem\);/,
+ );
+});
+
test('the launcher keeps focus, restores it, and never disables the focused button', () => {
const module = fs.readFileSync(
new URL('./firstRunExperience.js', import.meta.url),
@@ -948,7 +982,8 @@ test('the launcher keeps focus, restores it, and never disables the focused butt
// drops the keyboard to and strands the visitor outside the launcher
// (firstRunLauncherView.test.mjs renders it).
assert.doesNotMatch(module, /\.disabled = /);
- // Tab is confined to the launcher, and ESC always releases it.
+ // Tab cycles inside the launcher once focus is in it, and ESC always
+ // releases it.
const keyboard = fs.readFileSync(
new URL('./ui/surfaceKeyboard.js', import.meta.url),
'utf8',
diff --git a/src/firstRunLauncherView.test.mjs b/src/firstRunLauncherView.test.mjs
index 16c76e1d95..204584a577 100644
--- a/src/firstRunLauncherView.test.mjs
+++ b/src/firstRunLauncherView.test.mjs
@@ -12,6 +12,7 @@ import {
initFirstRunExperience,
} from './firstRunExperience.js';
import { useFirstRunStore } from './ui/stores/firstRun.js';
+import { useStoriesStore } from './ui/stores/stories.js';
import WelcomeView from './ui/views/WelcomeView.vue';
function memoryStorage(key, { refuse = false } = {}) {
@@ -31,7 +32,14 @@ function memoryStorage(key, { refuse = false } = {}) {
}
/** The welcome view and an initialized launcher, revealed and painted. */
-async function launch(t, { styleManager = {}, refuse = false } = {}) {
+async function launch(
+ t,
+ {
+ styleManager = {},
+ dataManager = { setEnabled: async () => true },
+ refuse = false,
+ } = {},
+) {
document.body.replaceChildren();
// Where focus was before the launcher opened.
const opener = document.body.appendChild(document.createElement('button'));
@@ -47,7 +55,7 @@ async function launch(t, { styleManager = {}, refuse = false } = {}) {
const sessionStorageRef = memoryStorage(FIRST_RUN_SESSION_KEY);
const launcher = initFirstRunExperience({
styleManager,
- dataManager: { setEnabled: async () => true },
+ dataManager,
documentRef: document,
storage,
sessionStorageRef,
@@ -68,7 +76,31 @@ async function launch(t, { styleManager = {}, refuse = false } = {}) {
Object.defineProperty(list, 'clientHeight', { get: () => box.clientHeight });
for (const frame of frames.splice(0)) frame();
await nextTick();
- return { launcher, root, list, box, opener, storage, sessionStorageRef };
+ return {
+ launcher,
+ pinia,
+ root,
+ list,
+ box,
+ opener,
+ storage,
+ sessionStorageRef,
+ frames,
+ };
+}
+
+async function move(root, frames, selector = '[data-first-run-next]') {
+ root.querySelector(selector).click();
+ await settle(frames);
+}
+
+async function settle(frames) {
+ for (let i = 0; i < 4; i++) {
+ await nextTick();
+ for (const frame of frames.splice(0)) frame();
+ await new Promise((resolve) => setTimeout(resolve));
+ }
+ await nextTick();
}
test('the card is hidden until initialized, then revealed with its copy', async (t) => {
@@ -81,57 +113,185 @@ test('the card is hidden until initialized, then revealed with its copy', async
assert.equal(hidden.className, '');
app.unmount();
- const { root, list } = await launch(t);
+ const { root, list, frames } = await launch(t);
assert.equal(root.hidden, false);
assert.equal(root.classList.contains('visible'), true);
assert.equal(root.hasAttribute('aria-hidden'), false);
assert.equal(list.dataset.scrollable, 'true');
- assert.equal(
- root.querySelector('[data-first-run-status]').textContent,
- 'Tip: the GEV MIC button in the dock lets you talk to the map.',
+ assert.equal(root.querySelector('[data-first-run-status]').textContent, '');
+ assert.equal(root.querySelector('[data-first-run-choice]'), null);
+ assert.ok(
+ document.activeElement === root.querySelector('[data-first-run-primary]'),
+ );
+ await move(root, frames);
+ assert.deepEqual(
+ [...root.querySelectorAll('[data-first-run-start]')].map(
+ (node) => node.dataset.firstRunStart,
+ ),
+ ['space-missions', 'environmental', 'explore'],
+ );
+ const environmental = root.querySelector(
+ '[data-first-run-start="environmental"]',
);
assert.equal(
- root.querySelector('[data-first-run-environmental-title]').textContent,
+ environmental.querySelector('strong').textContent,
'ENVIRONMENTAL',
);
- assert.ok(
- document.activeElement === root.querySelector('[data-first-run-choice]'),
- 'the first mission has focus',
+ assert.match(
+ environmental.querySelector('small').textContent,
+ /earthquakes.*fires/i,
);
+ assert.equal(
+ root
+ .querySelector('[data-first-run-start="explore"]')
+ .getAttribute('aria-pressed'),
+ 'true',
+ );
+ assert.ok(
+ document.activeElement === root.querySelector('[data-first-run-primary]'),
+ );
+});
+
+test('a quick second click on NEXT moves on, and never launches', async (t) => {
+ let calls = 0;
+ const { root, frames } = await launch(t, {
+ dataManager: {
+ setEnabled: async () => {
+ calls++;
+ return true;
+ },
+ },
+ });
+ const primary = root.querySelector('[data-first-run-primary]');
+ const press = (detail) => {
+ primary.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ primary.dispatchEvent(new MouseEvent('click', { bubbles: true, detail }));
+ };
+ press(1);
+ await settle(frames);
+ assert.ok(root.querySelector('[data-first-run-start]'), 'on the second step');
+ // The second click of a double click, after the step settled, moves on.
+ press(2);
+ await settle(frames);
+ assert.equal(primary.dataset.firstRunChoice, 'explore', 'on the last step');
+ press(2);
+ await settle(frames);
+ assert.equal(calls, 0);
+ assert.equal(root.dataset.state ?? null, null, 'a double click never starts');
+ press(1);
+ await settle(frames);
+ assert.ok(root.dataset.state, 'a single click starts');
});
test('a busy mission marks the choices aria-disabled, never disabled', async (t) => {
let finish;
- const { root } = await launch(t, {
- styleManager: {
- setContextMode: () => new Promise((resolve) => (finish = resolve)),
+ let calls = 0;
+ const { root, frames } = await launch(t, {
+ dataManager: {
+ setEnabled: () => {
+ calls++;
+ return new Promise((resolve) => (finish = resolve));
+ },
},
});
- const contacts = root.querySelector('[data-first-run-choice="contacts"]');
- contacts.focus();
- contacts.click();
+ await move(root, frames);
+ root.querySelector('[data-first-run-start="space-missions"]').click();
+ await nextTick();
+ const primary = root.querySelector('[data-first-run-next]');
+ primary.click();
+ await nextTick();
+ const enter = root.querySelector('[data-first-run-primary]');
+ assert.equal(
+ enter,
+ primary,
+ 'one persistent button keeps native click counting and focus',
+ );
+ assert.equal(enter.dataset.firstRunChoice, 'space-missions');
+ enter.click();
+ assert.equal(
+ calls,
+ 0,
+ 'the new action cannot launch during the step transition',
+ );
+ // A press begun during the transition and released after it runs nothing.
+ enter.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ await settle(frames);
+ enter.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 1 }));
+ assert.equal(calls, 0, 'a press held through the step change never launches');
+ assert.ok(
+ document.activeElement === enter,
+ 'the primary action retains focus',
+ );
+ assert.deepEqual(enter.getAttribute('aria-describedby').split(' '), [
+ 'first-run-title',
+ 'first-run-description',
+ ]);
+ const announcement = root.querySelector('.first-run-step-announcement');
+ assert.equal(announcement.getAttribute('aria-live'), 'polite');
+ assert.equal(announcement.getAttribute('aria-atomic'), 'true');
+ assert.equal(
+ announcement.textContent,
+ root.querySelector('#first-run-title').textContent,
+ );
+ for (const id of enter.getAttribute('aria-describedby').split(' ')) {
+ assert.ok(root.querySelector(`#${id}`).textContent.trim());
+ }
+ enter.dispatchEvent(new MouseEvent('click', { bubbles: true, detail: 2 }));
+ assert.equal(calls, 0, 'a second click from Next never confirms a mission');
+ const repeated = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ repeat: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ enter.dispatchEvent(repeated);
+ assert.equal(repeated.defaultPrevented, true);
+ // A fresh keyboard/assistive click has detail 0 and remains supported.
+ enter.click();
+ assert.equal(calls, 1);
await nextTick();
assert.equal(root.dataset.state, 'loading');
assert.equal(root.getAttribute('aria-busy'), 'true');
- for (const button of root.querySelectorAll('[data-first-run-choice]')) {
- assert.equal(button.getAttribute('aria-disabled'), 'true');
- assert.equal(button.disabled, false);
- }
- assert.ok(document.activeElement === contacts, 'focus stays on the choice');
+ assert.equal(enter.getAttribute('aria-disabled'), 'true');
+ assert.equal(enter.disabled, false);
+ assert.ok(document.activeElement === enter, 'focus stays on the action');
assert.equal(
root.querySelector('[data-first-run-status]').textContent,
- 'Starting live contacts…',
+ 'Opening space missions…',
);
+ root.querySelector('.first-run-back').click();
+ await nextTick();
+ assert.equal(
+ root.querySelector('[data-first-run-next]'),
+ null,
+ 'Back is inert while busy',
+ );
+ enter.click();
+ assert.equal(calls, 1, 'a busy action cannot start a second request');
// A failed mission says so and stays on the card.
- finish({ ok: false });
+ finish(false);
await new Promise((resolve) => setTimeout(resolve));
await nextTick();
assert.equal(root.dataset.state, 'ready');
- assert.equal(contacts.getAttribute('aria-disabled'), 'false');
+ assert.equal(enter.getAttribute('aria-disabled'), 'false');
assert.match(
root.querySelector('[data-first-run-status]').textContent,
/^Could not open that mission/,
);
+ await move(root, frames, '.first-run-back');
+ assert.equal(
+ root
+ .querySelector('[data-first-run-start="space-missions"]')
+ .getAttribute('aria-pressed'),
+ 'true',
+ );
+ root.querySelector('.first-run-back').focus();
+ await move(root, frames, '.first-run-back');
+ assert.equal(root.querySelector('.first-run-back'), null);
+ assert.ok(
+ document.activeElement === root.querySelector('[data-first-run-primary]'),
+ 'focus moves when Back is removed',
+ );
});
test('a refused write takes the tick back and says why', async (t) => {
@@ -156,25 +316,106 @@ test('a saved tick stays ticked', async (t) => {
assert.equal(storage.read(), 'suppressed');
});
-test('the DISMISS button closes the card the way ESC does', async (t) => {
+test('the SKIP button closes the card the way ESC does', async (t) => {
const { root, sessionStorageRef } = await launch(t);
root.querySelector('[data-first-run-dismiss]').click();
await nextTick();
assert.equal(root.classList.contains('visible'), false);
assert.equal(root.getAttribute('aria-hidden'), 'true');
assert.notEqual(sessionStorageRef.read(), null, 'dismissed for the session');
+ root
+ .querySelector('.first-run-step')
+ .dispatchEvent(new Event('transitionend', { bubbles: true }));
+ await nextTick();
+ assert.equal(
+ document.getElementById('first-run-launcher'),
+ root,
+ 'child transitions do not finish dismissal',
+ );
root.dispatchEvent(new Event('transitionend'));
await nextTick();
assert.equal(document.getElementById('first-run-launcher') === null, true);
});
+test('BROWSE STORIES closes the card and opens Stories in place', async (t) => {
+ const { root, pinia, frames, sessionStorageRef } = await launch(t);
+ const stories = useStoriesStore(pinia);
+ let opened = 0;
+ let finishLoading;
+ stories.connect({
+ open: () => {
+ opened++;
+ return new Promise((resolve) => (finishLoading = resolve));
+ },
+ });
+ await move(root, frames);
+ await move(root, frames);
+ const button = root.querySelector('[data-first-run-stories]');
+ assert.ok(button, 'the Stories card offers its button on the last step');
+ assert.equal(button.tagName, 'BUTTON', 'opens in the app, not a new tab');
+ assert.equal(button.hasAttribute('href'), false);
+ button.click();
+ await nextTick();
+ assert.equal(opened, 1, 'Stories opened once');
+ assert.equal(root.classList.contains('visible'), false, 'the card closed');
+ assert.notEqual(sessionStorageRef.read(), null, 'dismissed for the session');
+ assert.equal(
+ document.body.classList.contains('first-run-opening-stories'),
+ true,
+ 'the Stories announcement stays hidden while Stories loads',
+ );
+ finishLoading();
+ await new Promise((resolve) => setTimeout(resolve));
+ assert.equal(
+ document.body.classList.contains('first-run-opening-stories'),
+ false,
+ 'and may show again once Stories has opened (or failed to)',
+ );
+ button.dispatchEvent(new MouseEvent('click', { detail: 1 }));
+ await nextTick();
+ assert.equal(opened, 1, 'a closing card cannot open Stories again');
+});
+
+test('BROWSE STORIES keeps the welcome up when Stories refuses to open', async (t) => {
+ const { root, pinia, frames, sessionStorageRef } = await launch(t);
+ const stories = useStoriesStore(pinia);
+ stories.connect({ open: () => false });
+ await move(root, frames);
+ await move(root, frames);
+ root.querySelector('[data-first-run-stories]').click();
+ await nextTick();
+ assert.equal(root.classList.contains('visible'), true, 'the card stays');
+ assert.equal(sessionStorageRef.read(), null, 'not dismissed');
+ assert.equal(
+ document.body.classList.contains('first-run-opening-stories'),
+ false,
+ );
+});
+
+test('the Stories card is left out where Stories is not offered', async (t) => {
+ const { root, pinia, frames } = await launch(t);
+ const stories = useStoriesStore(pinia);
+ stories.available = false;
+ await move(root, frames);
+ await move(root, frames);
+ assert.equal(root.querySelector('.first-run-stories'), null);
+ assert.equal(root.querySelector('[data-first-run-stories]'), null);
+});
+
test('the scroll fade clears when the tiles fit after a resize', async (t) => {
- const { list, box } = await launch(t);
+ const { root, list, box, frames } = await launch(t);
assert.equal(list.dataset.scrollable, 'true');
box.scrollHeight = 200;
window.dispatchEvent(new Event('resize'));
await nextTick();
assert.equal(list.dataset.scrollable, 'false');
+ box.scrollHeight = 400;
+ await move(root, frames);
+ assert.equal(
+ list.dataset.scrollable,
+ 'true',
+ 'new step refreshes overflow without a resize',
+ );
});
test('ESC closes the card, returns focus, and removes it without a transition', async (t) => {
diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json
index 438338cdc7..fd73175edf 100644
--- a/src/i18n/locales/ar.json
+++ b/src/i18n/locales/ar.json
@@ -159,8 +159,6 @@
"REFRESHING LIVE DATA": "جارٍ تحديث البيانات المباشرة",
"Close data attribution": "إغلاق إسناد البيانات",
"MISSION CONTROL · FIRST LAUNCH": "مركز التحكم · أول تشغيل",
- "Choose your first view": "اختر عرضك الأول",
- "LIVE CONTACTS": "تتبّع الأهداف المباشر",
"Don't show this again": "لا تعرض هذا مرة أخرى",
"POWER UP": "تشغيل",
"GROUND STATION · PROVIDER SETTINGS": "المحطة الأرضية · إعدادات المزوّدين",
@@ -168,13 +166,10 @@
"SAVE KEYS": "حفظ المفاتيح",
"Saving…": "جارٍ الحفظ…",
"It feels like a forbidden cockpit—then you realize the sources are public and the data is real.": "يبدو الأمر كقمرة قيادة محظورة — ثم تدرك أن المصادر عامة والبيانات حقيقية.",
- "Aircraft, vessels and nearby intelligence": "طائرات وسفن ومعلومات استخباراتية قريبة",
"SPACE MISSIONS": "المهام الفضائية",
"Launches, spacecraft and orbital context": "عمليات إطلاق ومركبات فضائية وسياق مداري",
"EXPLORE MANUALLY": "استكشاف يدوي",
"Begin with a clean globe": "ابدأ بكرة أرضية نظيفة",
- "ESC to dismiss": "اضغط ESC للإغلاق",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "نصيحة: يتيح لك زر GEV MIC في الشريط السفلي التحدث إلى الخريطة.",
"Close key setup": "إغلاق إعداد المفاتيح",
"The globe already flies keyless. Every key below switches on another real feed — paste one and it's saved into this app's local configuration, then the server restarts itself. Server-side keys stay on this machine; Google Maps and Cesium ion run in the browser and must be provider-restricted. Keys you configured elsewhere are shown but never touched.": "تعمل الكرة الأرضية بلا مفاتيح أصلًا. كل مفتاح أدناه يفعّل مصدرًا حقيقيًا إضافيًا: الصق مفتاحًا فيُحفظ في إعدادات هذا التطبيق المحلية، ثم يعيد الخادم تشغيل نفسه. تبقى مفاتيح الخادم على هذا الجهاز، أما Google Maps وCesium ion فتعملان في المتصفح ويجب تقييدهما بحسب المزوّد. المفاتيح التي أعددتها في مكان آخر تظهر دون أن تُمَسّ.",
"ESC to close": "اضغط ESC للإغلاق",
@@ -186,7 +181,6 @@
"IMPORT": "استيراد",
"RUN LOG": "سجل التشغيل",
"Ready": "جاهز",
- "Starting live contacts…": "جارٍ بدء تتبّع الأهداف المباشر…",
"Opening space missions…": "جارٍ فتح المهام الفضائية…",
"Scanning active events…": "جارٍ مسح الأحداث النشطة…",
"Working…": "جارٍ العمل…",
@@ -687,6 +681,16 @@
"UNAVAILABLE": "غير متاح",
"Live Flights": "تتبّع الرحلات المباشر",
"Earthquakes (24h)": "الزلازل (24 ساعة)",
+ "earthquake|Minor": "طفيف",
+ "earthquake|Light": "خفيف",
+ "earthquake|Moderate": "معتدل",
+ "earthquake|Strong": "قوي",
+ "earthquake|Major": "كبير",
+ "earthquake|Great": "هائل",
+ "earthquake|Shallow": "ضحل",
+ "earthquake|Intermediate": "متوسط العمق",
+ "earthquake|Deep": "عميق",
+ "{km} km deep": "على عمق {km} كم",
"No selected data layers": "لا توجد طبقات بيانات محددة",
"Cleared {count} data layers": {
"zero": "لم تُمسح أي طبقة بيانات ({count})",
@@ -2199,6 +2203,7 @@
"Exit cockpit to fly to a target": "اخرج من القمرة للانتقال إلى هدف",
"Exit cockpit to fly to a vessel": "اخرج من القمرة للانتقال إلى سفينة",
"Exit cockpit to fly to a fire": "اخرج من القمرة للانتقال إلى حريق",
+ "Exit cockpit to fly to an earthquake": "اخرج من القمرة للانتقال إلى زلزال",
"Exit cockpit to fly to a route": "اخرج من القمرة للانتقال إلى مسار",
"Exit cockpit to fly to a file": "اخرج من القمرة للانتقال إلى ملف",
"Exit cockpit to fly to a scene": "اخرج من القمرة للانتقال إلى مشهد",
@@ -3674,6 +3679,8 @@
"Source: {value}": "المصدر: {value}",
"Click the card to open EMODnet ↗": "انقر على البطاقة لفتح EMODnet ↗",
"Click the card to open the source ↗": "انقر على البطاقة لفتح المصدر ↗",
+ "Open the source for {title}, {details}": "فتح مصدر «{title}»، {details}",
+ "Focus earthquake {title}, {details}": "التركيز على الزلزال {title}، {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata غير متاح؛ يُعرض EMODnet فقط",
"EMODnet unavailable; showing Wikidata only": "EMODnet غير متاح؛ يُعرض Wikidata فقط",
"Shipwrecks unavailable": "بيانات حطام السفن غير متاحة",
@@ -4699,5 +4706,38 @@
"Search places, layers and things on the map, or ask GEV": "ابحث عن أماكن وطبقات وعناصر على الخريطة، أو اسأل GEV",
"Search places, layers, flights… or ask GEV · > for commands": "ابحث عن أماكن وطبقات ورحلات جوية… أو اسأل GEV · > للأوامر",
"No matching command": "لا يوجد أمر مطابق",
- "Looks private, so nothing is searched or sent": "يبدو خاصًا، لذا لا يُبحث عنه ولا يُرسل"
+ "Looks private, so nothing is searched or sent": "يبدو خاصًا، لذا لا يُبحث عنه ولا يُرسل",
+ "Bilawal on YouTube": "بلاول على YouTube",
+ "BROWSE STORIES": "تصفح القصص",
+ "ENTER GOD MODE": "ادخل وضع الإله",
+ "Go deeper": "تعمّق أكثر",
+ "The studio behind GEV": "الاستوديو الذي يقف خلف GEV",
+ "Visual presets": "الأنماط البصرية",
+ "Open source. Self-host, fork, add a layer.": "مفتوح المصدر. استضفه بنفسك، أنشئ نسخة، أضف طبقة.",
+ "Choose your mode": "اختر الوضع",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "منظار القمر الصناعي التجسسي: عرض دائري، واجهة تكتيكية، كاميرا سينمائية. للاستكشاف.",
+ "Welcome to God's Eye View": "مرحبًا بك في God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "عرض أنظف وأسهل قراءة يُظهر فيه كل رقم مصدره. للبحث وإعداد التقارير.",
+ "Keyhole HUD": "واجهة المنظار",
+ "Analyst": "المحلل",
+ "God": "الإله",
+ "COMING SOON": "قريبًا",
+ "More from Halfpixel": "المزيد من Halfpixel",
+ "Start with": "ابدأ بـ",
+ "FUN": "ممتع",
+ "Where do you want to start?": "من أين تريد أن تبدأ؟",
+ "Three things to know": "ثلاثة أمور يجب معرفتها",
+ "Pick one to begin with. You can change everything later.": "اختر واحدة لتبدأ بها. يمكنك تغيير كل شيء لاحقًا.",
+ "That is all you need to get going.": "هذا كل ما تحتاج إليه للبدء.",
+ "SKIP · ESC": "تخطّي · ESC",
+ "SKIP": "تخطّي",
+ "Search places": "البحث عن أماكن",
+ "Type a place into the search bar.": "اكتب اسم مكان في شريط البحث.",
+ "Turn on layers": "تشغيل الطبقات",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "شغّل الطبقات لرؤية الرحلات الجوية والسفن والكاميرات والطقس والمزيد.",
+ "Click anything": "انقر على أي عنصر",
+ "Select a map item to see its details.": "اختر عنصرًا على الخريطة لرؤية تفاصيله.",
+ "Bilawal on {site}": "بلال على {site}",
+ "Bilawal's website": "موقع بلال الإلكتروني",
+ "BACK": "رجوع"
}
diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json
index d47cbf6324..9f18360ee8 100644
--- a/src/i18n/locales/de.json
+++ b/src/i18n/locales/de.json
@@ -155,7 +155,6 @@
"ENVIRONMENTAL": "UMWELT",
"EARTH WATCH": "ERDBEOBACHTUNG",
"ACTIVE EVENTS": "AKTIVE EREIGNISSE",
- "Starting live contacts…": "Live-Kontakte werden gestartet…",
"Opening space missions…": "Raummissionen werden geöffnet…",
"Scanning active events…": "Aktive Ereignisse werden gescannt…",
"Live earthquakes and active fires, from USGS and NASA": "Live-Erdbeben und aktive Brände, von USGS und NASA",
@@ -647,6 +646,16 @@
"Live Flights": "Live-Flüge",
"Military Flights": "Militärflüge",
"Earthquakes (24h)": "Erdbeben (24 h)",
+ "earthquake|Minor": "Schwach",
+ "earthquake|Light": "Leicht",
+ "earthquake|Moderate": "Mittel",
+ "earthquake|Strong": "Stark",
+ "earthquake|Major": "Schwer",
+ "earthquake|Great": "Gewaltig",
+ "earthquake|Shallow": "Flach",
+ "earthquake|Intermediate": "Mitteltief",
+ "earthquake|Deep": "Tief",
+ "{km} km deep": "{km} km tief",
"Satellites": "Satelliten",
"Place names": "Ortsnamen",
"Space Missions (30d)": "Raummissionen (30 T)",
@@ -1037,15 +1046,10 @@
"Copy share link": "Link zum Teilen kopieren",
"Reset camera and return to full globe view": "Kamera zurücksetzen und zur Vollglobus-Ansicht zurückkehren",
"MISSION CONTROL · FIRST LAUNCH": "MISSION CONTROL · ERSTER START",
- "Choose your first view": "Erste Ansicht wählen",
- "LIVE CONTACTS": "LIVE-KONTAKTE",
- "Aircraft, vessels and nearby intelligence": "Flugzeuge, Schiffe und Lagebild der Umgebung",
"Launches, spacecraft and orbital context": "Starts, Raumfahrzeuge und Orbit-Kontext",
"EXPLORE MANUALLY": "MANUELL ERKUNDEN",
"Begin with a clean globe": "Mit einem leeren Globus beginnen",
"Don't show this again": "Nicht mehr anzeigen",
- "ESC to dismiss": "ESC zum Schließen",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Tipp: Mit der Mikrofontaste im Dock lässt sich die Karte per Sprache steuern.",
"Pick a shape, then click the map.": "Form wählen, dann auf die Karte klicken.",
"Enter to place the pin, Esc to cancel.": "Enter setzt den Pin, Esc bricht ab.",
"Click where the pin goes.": "Auf die Stelle für den Pin klicken.",
@@ -2078,6 +2082,7 @@
"Exit cockpit to fly to a target": "Cockpit verlassen, um zu einem Ziel zu fliegen",
"Exit cockpit to fly to a vessel": "Cockpit verlassen, um zu einem Schiff zu fliegen",
"Exit cockpit to fly to a fire": "Cockpit verlassen, um zu einem Brand zu fliegen",
+ "Exit cockpit to fly to an earthquake": "Cockpit verlassen, um zu einem Erdbeben zu fliegen",
"Exit cockpit to fly to a route": "Cockpit verlassen, um zu einer Route zu fliegen",
"Exit cockpit to fly to a file": "Cockpit verlassen, um zu einer Datei zu fliegen",
"Exit cockpit to fly to a scene": "Cockpit verlassen, um zu einer Szene zu fliegen",
@@ -3330,6 +3335,8 @@
"Source: {value}": "Quelle: {value}",
"Click the card to open EMODnet ↗": "Eintrag anklicken, um EMODnet zu öffnen ↗",
"Click the card to open the source ↗": "Eintrag anklicken, um die Quelle zu öffnen ↗",
+ "Open the source for {title}, {details}": "Quelle für {title} öffnen, {details}",
+ "Focus earthquake {title}, {details}": "Erdbeben {title} fokussieren, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata nicht verfügbar; nur EMODnet wird angezeigt",
"EMODnet unavailable; showing Wikidata only": "EMODnet nicht verfügbar; nur Wikidata wird angezeigt",
"Shipwrecks unavailable": "Schiffswracks nicht verfügbar",
@@ -4275,5 +4282,38 @@
"Search places, layers and things on the map, or ask GEV": "Suche Orte, Ebenen und Kartenelemente oder frage GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Orte, Ebenen, Flüge suchen… oder GEV fragen · > für Befehle",
"No matching command": "Kein passender Befehl",
- "Looks private, so nothing is searched or sent": "Sieht privat aus, daher wird nichts gesucht oder gesendet"
+ "Looks private, so nothing is searched or sent": "Sieht privat aus, daher wird nichts gesucht oder gesendet",
+ "Bilawal on YouTube": "Bilawal auf YouTube",
+ "BROWSE STORIES": "STORIES ANSEHEN",
+ "ENTER GOD MODE": "GOTT-MODUS STARTEN",
+ "Go deeper": "Mehr entdecken",
+ "The studio behind GEV": "Das Studio hinter GEV",
+ "Visual presets": "Visuelle Presets",
+ "Open source. Self-host, fork, add a layer.": "Open Source. Selbst hosten, forken, eine Ebene hinzufügen.",
+ "Choose your mode": "Modus wählen",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "Das Spionagesatelliten-Schlüsselloch: runder Bildausschnitt, taktisches HUD, filmische Kamera. Zum Erkunden.",
+ "Welcome to God's Eye View": "Willkommen bei God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Eine klarere, gut lesbare Ansicht, in der jeder Wert seine Quelle zeigt. Für Recherche und Berichte.",
+ "Keyhole HUD": "Schlüsselloch-HUD",
+ "Analyst": "Analyse",
+ "God": "Gott",
+ "COMING SOON": "DEMNÄCHST",
+ "More from Halfpixel": "Mehr von Halfpixel",
+ "Start with": "Starten mit",
+ "FUN": "SPASS",
+ "Where do you want to start?": "Wo möchtest du anfangen?",
+ "Three things to know": "Drei Dinge, die du wissen solltest",
+ "Pick one to begin with. You can change everything later.": "Wähle zum Einstieg eine Option. Du kannst später alles ändern.",
+ "That is all you need to get going.": "Das ist alles, was du für den Einstieg brauchst.",
+ "SKIP · ESC": "ÜBERSPRINGEN · ESC",
+ "SKIP": "ÜBERSPRINGEN",
+ "Search places": "Orte suchen",
+ "Type a place into the search bar.": "Gib einen Ort in die Suchleiste ein.",
+ "Turn on layers": "Ebenen einschalten",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Schalte Ebenen ein, um Flüge, Schiffe, Kameras, Wetter und mehr zu sehen.",
+ "Click anything": "Klicke auf ein Element",
+ "Select a map item to see its details.": "Wähle ein Kartenelement aus, um seine Details zu sehen.",
+ "Bilawal on {site}": "Bilawal auf {site}",
+ "Bilawal's website": "Bilawals Website",
+ "BACK": "ZURÜCK"
}
diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json
index 489fd34eba..8bb3db1509 100644
--- a/src/i18n/locales/es.json
+++ b/src/i18n/locales/es.json
@@ -548,6 +548,16 @@
"UNAVAILABLE": "NO DISPONIBLE",
"Live Flights": "Vuelos en vivo",
"Earthquakes (24h)": "Terremotos (24 h)",
+ "earthquake|Minor": "Menor",
+ "earthquake|Light": "Ligero",
+ "earthquake|Moderate": "Moderado",
+ "earthquake|Strong": "Fuerte",
+ "earthquake|Major": "Mayor",
+ "earthquake|Great": "Gran",
+ "earthquake|Shallow": "Superficial",
+ "earthquake|Intermediate": "Intermedio",
+ "earthquake|Deep": "Profundo",
+ "{km} km deep": "{km} km de profundidad",
"No selected data layers": "No hay capas de datos seleccionadas",
"Cleared {count} data layers": {
"one": "Se limpió {count} capa de datos",
@@ -926,8 +936,6 @@
"sightings filter|CONFIRMED": "CONFIRMADOS",
"PAD / RTLS": "PLATAFORMA / RTLS",
"MISSION CONTROL · FIRST LAUNCH": "CENTRO DE MANDO · PRIMER INICIO",
- "Choose your first view": "Elige tu primera vista",
- "LIVE CONTACTS": "CONTACTOS EN VIVO",
"Don't show this again": "No volver a mostrar",
"POWER UP": "ENCENDER",
"GROUND STATION · PROVIDER SETTINGS": "ESTACIÓN TERRENA · AJUSTES DE PROVEEDORES",
@@ -935,12 +943,9 @@
"SAVE KEYS": "GUARDAR CLAVES",
"Saving…": "Guardando…",
"It feels like a forbidden cockpit—then you realize the sources are public and the data is real.": "Parece una cabina prohibida—hasta que descubres que las fuentes son públicas y los datos son reales.",
- "Aircraft, vessels and nearby intelligence": "Aeronaves, buques e inteligencia cercana",
"Launches, spacecraft and orbital context": "Lanzamientos, naves y contexto orbital",
"EXPLORE MANUALLY": "EXPLORAR MANUALMENTE",
"Begin with a clean globe": "Empieza con un globo limpio",
- "ESC to dismiss": "ESC para cerrar",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Consejo: el botón GEV MIC del dock te permite hablar con el mapa.",
"Close key setup": "Cerrar la configuración de claves",
"The globe already flies keyless. Every key below switches on another real feed — paste one and it's saved into this app's local configuration, then the server restarts itself. Server-side keys stay on this machine; Google Maps and Cesium ion run in the browser and must be provider-restricted. Keys you configured elsewhere are shown but never touched.": "El globo ya funciona sin claves. Cada clave de abajo activa otra fuente real — pega una y queda guardada en la configuración local de esta app, y luego el servidor se reinicia solo. Las claves del servidor se quedan en esta máquina; Google Maps y Cesium ion funcionan en el navegador y sus claves deben restringirse en la consola del proveedor. Las claves que configuraste en otro lugar se muestran, pero nunca se modifican.",
"ESC to close": "ESC para cerrar",
@@ -949,7 +954,6 @@
"UPDATE SHOT": "ACTUALIZAR PLANO",
"IMPORT": "IMPORTAR",
"RUN LOG": "REGISTRO DE EJECUCIÓN",
- "Starting live contacts…": "Iniciando contactos en vivo…",
"Opening space missions…": "Abriendo misiones espaciales…",
"Scanning active events…": "Escaneando eventos activos…",
"Working…": "Trabajando…",
@@ -2619,6 +2623,7 @@
"Exit cockpit to fly to a target": "Sal de la cabina para volar a un objetivo",
"Exit cockpit to fly to a vessel": "Sal de la cabina para volar a un buque",
"Exit cockpit to fly to a fire": "Sal de la cabina para volar a un incendio",
+ "Exit cockpit to fly to an earthquake": "Sal de la cabina para volar a un terremoto",
"Exit cockpit to fly to a route": "Sal de la cabina para volar a una ruta",
"Exit cockpit to fly to a file": "Sal de la cabina para volar a un archivo",
"Exit cockpit to fly to a scene": "Sal de la cabina para volar a una escena",
@@ -3416,6 +3421,8 @@
"Source: {value}": "Fuente: {value}",
"Click the card to open EMODnet ↗": "Haz clic en la tarjeta para abrir EMODnet ↗",
"Click the card to open the source ↗": "Haz clic en la tarjeta para abrir la fuente ↗",
+ "Open the source for {title}, {details}": "Abrir la fuente de {title}, {details}",
+ "Focus earthquake {title}, {details}": "Enfocar el terremoto {title}, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata no disponible; solo se muestra EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet no disponible; solo se muestra Wikidata",
"Shipwrecks unavailable": "Naufragios no disponibles",
@@ -4381,5 +4388,38 @@
"Search places, layers and things on the map, or ask GEV": "Busca lugares, capas y elementos del mapa, o pregunta a GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Busca lugares, capas, vuelos… o pregunta a GEV · > para comandos",
"No matching command": "Ningún comando coincide",
- "Looks private, so nothing is searched or sent": "Parece privado, así que no se busca ni se envía nada"
+ "Looks private, so nothing is searched or sent": "Parece privado, así que no se busca ni se envía nada",
+ "Bilawal on YouTube": "Bilawal en YouTube",
+ "BROWSE STORIES": "VER STORIES",
+ "ENTER GOD MODE": "ENTRAR EN MODO DIOS",
+ "Go deeper": "Ir más allá",
+ "The studio behind GEV": "El estudio detrás de GEV",
+ "Visual presets": "Preajustes visuales",
+ "Open source. Self-host, fork, add a layer.": "Código abierto. Alójalo tú mismo, haz un fork, añade una capa.",
+ "Choose your mode": "Elige tu modo",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "La mirilla del satélite espía: visor circular, HUD táctico, cámara cinematográfica. Para explorar.",
+ "Welcome to God's Eye View": "Bienvenido a God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Una vista más limpia y legible en la que cada valor muestra su fuente. Para investigar e informar.",
+ "Keyhole HUD": "HUD de mirilla",
+ "Analyst": "Analista",
+ "God": "Dios",
+ "COMING SOON": "PRÓXIMAMENTE",
+ "More from Halfpixel": "Más de Halfpixel",
+ "Start with": "Empezar con",
+ "FUN": "DIVERSIÓN",
+ "Where do you want to start?": "¿Por dónde quieres empezar?",
+ "Three things to know": "Tres cosas que debes saber",
+ "Pick one to begin with. You can change everything later.": "Elige una opción para empezar. Puedes cambiarlo todo después.",
+ "That is all you need to get going.": "Eso es todo lo que necesitas para empezar.",
+ "SKIP · ESC": "OMITIR · ESC",
+ "SKIP": "OMITIR",
+ "Search places": "Buscar lugares",
+ "Type a place into the search bar.": "Escribe un lugar en la barra de búsqueda.",
+ "Turn on layers": "Activar capas",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Activa capas para ver vuelos, barcos, cámaras, tiempo y más.",
+ "Click anything": "Haz clic en cualquier elemento",
+ "Select a map item to see its details.": "Selecciona un elemento del mapa para ver sus detalles.",
+ "Bilawal on {site}": "Bilawal en {site}",
+ "Bilawal's website": "Sitio web de Bilawal",
+ "BACK": "ATRÁS"
}
diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json
index aec90d6fd9..26447fb193 100644
--- a/src/i18n/locales/fr.json
+++ b/src/i18n/locales/fr.json
@@ -406,7 +406,6 @@
"ENVIRONMENTAL": "ENVIRONNEMENT",
"EARTH WATCH": "VEILLE TERRE",
"ACTIVE EVENTS": "ÉVÉNEMENTS ACTIFS",
- "Starting live contacts…": "Démarrage des contacts en direct…",
"Opening space missions…": "Ouverture des missions spatiales…",
"Scanning active events…": "Analyse des événements actifs…",
"Live earthquakes and active fires, from USGS and NASA": "Séismes et feux actifs en direct, via USGS et NASA",
@@ -1499,6 +1498,7 @@
"Exit cockpit to fly to a target": "Quittez le cockpit pour rejoindre une cible",
"Exit cockpit to fly to a vessel": "Quittez le cockpit pour rejoindre un navire",
"Exit cockpit to fly to a fire": "Quittez le cockpit pour rejoindre un incendie",
+ "Exit cockpit to fly to an earthquake": "Quittez le cockpit pour rejoindre un séisme",
"Exit cockpit to fly to a route": "Quittez le cockpit pour rejoindre un itinéraire",
"Exit cockpit to fly to a file": "Quittez le cockpit pour rejoindre un fichier",
"Exit cockpit to fly to a scene": "Quittez le cockpit pour rejoindre une scène",
@@ -1958,6 +1958,16 @@
"Live Flights": "Vols en direct",
"Military Flights": "Vols militaires",
"Earthquakes (24h)": "Séismes (24 h)",
+ "earthquake|Minor": "Mineur",
+ "earthquake|Light": "Léger",
+ "earthquake|Moderate": "Modéré",
+ "earthquake|Strong": "Fort",
+ "earthquake|Major": "Majeur",
+ "earthquake|Great": "Exceptionnel",
+ "earthquake|Shallow": "Superficiel",
+ "earthquake|Intermediate": "Intermédiaire",
+ "earthquake|Deep": "Profond",
+ "{km} km deep": "{km} km de profondeur",
"Satellites": "Satellites",
"Place names": "Noms de lieux",
"Space Missions (30d)": "Missions spatiales (30 j)",
@@ -3170,15 +3180,10 @@
"Reset map bearing to north": "Réinitialiser l'orientation de la carte vers le nord",
"Reset camera and return to full globe view": "Réinitialiser la caméra et revenir à la vue du globe entier",
"MISSION CONTROL · FIRST LAUNCH": "CENTRE DE CONTRÔLE · PREMIER LANCEMENT",
- "Choose your first view": "Choisissez votre première vue",
- "LIVE CONTACTS": "CONTACTS EN DIRECT",
- "Aircraft, vessels and nearby intelligence": "Avions, navires et renseignements à proximité",
"Launches, spacecraft and orbital context": "Lancements, vaisseaux et contexte orbital",
"EXPLORE MANUALLY": "EXPLORER MANUELLEMENT",
"Begin with a clean globe": "Commencer avec un globe vierge",
"Don't show this again": "Ne plus afficher",
- "ESC to dismiss": "ESC pour fermer",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Astuce : le bouton GEV MIC du dock permet de parler à la carte.",
"Malformed cyclone snapshot": "Instantané cyclonique mal formé",
"Cyclone request timed out": "Délai dépassé pour la requête cyclonique",
"{lower} to {upper}": "De {lower} à {upper}",
@@ -3416,6 +3421,8 @@
"Source: {value}": "Source : {value}",
"Click the card to open EMODnet ↗": "Cliquez sur la fiche pour ouvrir EMODnet ↗",
"Click the card to open the source ↗": "Cliquez sur la fiche pour ouvrir la source ↗",
+ "Open the source for {title}, {details}": "Ouvrir la source de {title}, {details}",
+ "Focus earthquake {title}, {details}": "Centrer sur le séisme {title}, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata indisponible ; seul EMODnet est affiché",
"EMODnet unavailable; showing Wikidata only": "EMODnet indisponible ; seul Wikidata est affiché",
"Shipwrecks unavailable": "Épaves indisponibles",
@@ -4381,5 +4388,38 @@
"Search places, layers and things on the map, or ask GEV": "Recherchez des lieux, des couches et des éléments sur la carte, ou interrogez GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Recherchez des lieux, des couches, des vols… ou interrogez GEV · > pour les commandes",
"No matching command": "Aucune commande correspondante",
- "Looks private, so nothing is searched or sent": "Semble privé, donc rien n’est recherché ni envoyé"
+ "Looks private, so nothing is searched or sent": "Semble privé, donc rien n’est recherché ni envoyé",
+ "Bilawal on YouTube": "Bilawal sur YouTube",
+ "BROWSE STORIES": "PARCOURIR LES STORIES",
+ "ENTER GOD MODE": "ENTRER EN MODE DIEU",
+ "Go deeper": "Aller plus loin",
+ "The studio behind GEV": "Le studio derrière GEV",
+ "Visual presets": "Préréglages visuels",
+ "Open source. Self-host, fork, add a layer.": "Open source. Hébergez-le, forkez-le, ajoutez une couche.",
+ "Choose your mode": "Choisissez votre mode",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "Le viseur du satellite espion : vue circulaire, HUD tactique, caméra cinématographique. Pour explorer.",
+ "Welcome to God's Eye View": "Bienvenue dans God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Une vue plus épurée et lisible où chaque valeur indique sa source. Pour la recherche et le reportage.",
+ "Keyhole HUD": "HUD viseur",
+ "Analyst": "Analyste",
+ "God": "Dieu",
+ "COMING SOON": "BIENTÔT",
+ "More from Halfpixel": "Plus de Halfpixel",
+ "Start with": "Commencer par",
+ "FUN": "LOISIR",
+ "Where do you want to start?": "Par où voulez-vous commencer ?",
+ "Three things to know": "Trois choses à savoir",
+ "Pick one to begin with. You can change everything later.": "Choisissez une option pour commencer. Vous pourrez tout modifier ensuite.",
+ "That is all you need to get going.": "C’est tout ce qu’il vous faut pour commencer.",
+ "SKIP · ESC": "PASSER · ESC",
+ "SKIP": "PASSER",
+ "Search places": "Rechercher des lieux",
+ "Type a place into the search bar.": "Saisissez un lieu dans la barre de recherche.",
+ "Turn on layers": "Activer des couches",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Activez des couches pour voir les vols, les navires, les caméras, la météo et plus encore.",
+ "Click anything": "Cliquez sur un élément",
+ "Select a map item to see its details.": "Sélectionnez un élément de la carte pour voir ses détails.",
+ "Bilawal on {site}": "Bilawal sur {site}",
+ "Bilawal's website": "Site web de Bilawal",
+ "BACK": "RETOUR"
}
diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json
index 0dcb7f001d..0221989c99 100644
--- a/src/i18n/locales/he.json
+++ b/src/i18n/locales/he.json
@@ -299,8 +299,6 @@
"ENVIRONMENTAL": "סביבתי",
"EARTH WATCH": "EARTH WATCH",
"ACTIVE EVENTS": "אירועים פעילים",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "טיפ: לחצן ה-MIC של GEV בעגינה מאפשר לדבר עם המפה.",
- "Starting live contacts…": "מתחיל מגעים חיים…",
"Opening space missions…": "פותח משימות חלל…",
"Scanning active events…": "סורק אירועים פעילים…",
"Live earthquakes and active fires, from USGS and NASA": "רעידות אדמה חיות ושריפות פעילות, מ-USGS ו-NASA",
@@ -1382,6 +1380,7 @@
"Exit cockpit to fly to a target": "צא מתא הטייס כדי לטוס אל מטרה",
"Exit cockpit to fly to a vessel": "צא מתא הטייס כדי לטוס אל אונייה",
"Exit cockpit to fly to a fire": "צא מתא הטייס כדי לטוס אל שריפה",
+ "Exit cockpit to fly to an earthquake": "צא מתא הטייס כדי לטוס אל רעידת אדמה",
"Exit cockpit to fly to a sighting": "צא מתא הטייס כדי לטוס אל תצפית",
"Exit cockpit to fly to a sighting area": "צא מתא הטייס כדי לטוס אל אזור תצפית",
"Exit cockpit to fly to a route": "צא מתא הטייס כדי לטוס אל מסלול",
@@ -1796,6 +1795,16 @@
"Live Flights": "טיסות חיות",
"Military Flights": "טיסות צבאיות",
"Earthquakes (24h)": "רעידות אדמה (24 שע׳)",
+ "earthquake|Minor": "קל מאוד",
+ "earthquake|Light": "קל",
+ "earthquake|Moderate": "בינוני",
+ "earthquake|Strong": "חזק",
+ "earthquake|Major": "חזק מאוד",
+ "earthquake|Great": "עצום",
+ "earthquake|Shallow": "רדוד",
+ "earthquake|Intermediate": "עומק בינוני",
+ "earthquake|Deep": "עמוק",
+ "{km} km deep": "בעומק {km} ק״מ",
"Satellites": "לוויינים",
"Space Missions (30d)": "משימות חלל (30 יום)",
"Street Traffic": "תנועה ברחובות",
@@ -2397,14 +2406,10 @@
"Shot name": "שם השוט",
"DEL": "מחיקה",
"MISSION CONTROL · FIRST LAUNCH": "חדר בקרה · שיגור ראשון",
- "Choose your first view": "בחירת התצוגה הראשונה",
- "LIVE CONTACTS": "מגעים חיים",
- "Aircraft, vessels and nearby intelligence": "מטוסים, אוניות ומודיעין סמוך",
"Launches, spacecraft and orbital context": "שיגורים, חלליות והקשר המסלולי",
"EXPLORE MANUALLY": "חקירה ידנית",
"Begin with a clean globe": "התחלה מגלובוס נקי",
"Don't show this again": "אל תציג זאת שוב",
- "ESC to dismiss": "Esc להסתרה",
"DISMISS": "הסתרה",
"CONTACTS CONTEXT OFF": "הקשר המגעים כבוי",
"SELECT CONTACTS TO LOAD OBSERVED / MAPPED PROXIMITY": "בחר מגעים לטעינת קרבה נצפית / ממופה",
@@ -3558,6 +3563,8 @@
"Click the card to open EMODnet ↗": "לחץ על הכרטיס כדי לפתוח את EMODnet ↗",
"Click the card to open the article ↗": "לחץ על הכרטיס כדי לפתוח את הערך ↗",
"Click the card to open the source ↗": "לחץ על הכרטיס כדי לפתוח את המקור ↗",
+ "Open the source for {title}, {details}": "פתיחת המקור של {title}, {details}",
+ "Focus earthquake {title}, {details}": "התמקדות ברעידת האדמה {title}, {details}",
"All years": "כל השנים",
"Period": "תקופה",
"From": "מ-",
@@ -4381,5 +4388,38 @@
"Search places, layers and things on the map, or ask GEV": "חפשו מקומות, שכבות ופריטים במפה, או שאלו את GEV",
"Search places, layers, flights… or ask GEV · > for commands": "חיפוש מקומות, שכבות וטיסות… או שאלה ל‑GEV · > לפקודות",
"No matching command": "אין פקודה תואמת",
- "Looks private, so nothing is searched or sent": "נראה פרטי, ולכן שום דבר לא מחופש או נשלח"
+ "Looks private, so nothing is searched or sent": "נראה פרטי, ולכן שום דבר לא מחופש או נשלח",
+ "Where do you want to start?": "מאיפה תרצו להתחיל?",
+ "Three things to know": "שלושה דברים שכדאי לדעת",
+ "Pick one to begin with. You can change everything later.": "בחרו אפשרות אחת להתחלה. אפשר לשנות הכול בהמשך.",
+ "That is all you need to get going.": "זה כל מה שצריך כדי להתחיל.",
+ "SKIP · ESC": "דילוג · ESC",
+ "SKIP": "דילוג",
+ "Search places": "חיפוש מקומות",
+ "Type a place into the search bar.": "הקלידו מקום בשורת החיפוש.",
+ "Turn on layers": "הפעלת שכבות",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "הפעילו שכבות כדי לראות טיסות, ספינות, מצלמות, מזג אוויר ועוד.",
+ "Click anything": "לחצו על פריט כלשהו",
+ "Select a map item to see its details.": "בחרו פריט במפה כדי לראות את פרטיו.",
+ "Bilawal on {site}": "בילוואל ב־{site}",
+ "Bilawal's website": "האתר של בילוואל",
+ "BACK": "חזרה",
+ "Welcome to God's Eye View": "ברוכים הבאים ל־God's Eye View",
+ "Choose your mode": "בחרו מצב",
+ "God": "אלוהים",
+ "FUN": "בשביל הכיף",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "מבט דרך לוויין ריגול: תצוגה עגולה, תצוגה עילית טקטית ומצלמה קולנועית. לחקירה וגילוי.",
+ "Keyhole HUD": "תצוגה עילית עגולה",
+ "Visual presets": "הגדרות תצוגה מוכנות",
+ "Analyst": "אנליסט",
+ "COMING SOON": "בקרוב",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "תצוגה נקייה וקריאה יותר, שבה כל ערך מציג את מקורו. למחקר ולדיווח.",
+ "Start with": "התחילו עם",
+ "Go deeper": "להעמיק",
+ "BROWSE STORIES": "עיון בסיפורים",
+ "More from Halfpixel": "עוד מ־Halfpixel",
+ "Bilawal on YouTube": "בילוואל ב־YouTube",
+ "The studio behind GEV": "הסטודיו שמאחורי GEV",
+ "Open source. Self-host, fork, add a layer.": "קוד פתוח. אירוח עצמאי, יצירת עותק והוספת שכבה.",
+ "ENTER GOD MODE": "כניסה למצב אלוהים"
}
diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json
index f517b67208..a6d1bb283d 100644
--- a/src/i18n/locales/it.json
+++ b/src/i18n/locales/it.json
@@ -406,7 +406,6 @@
"ENVIRONMENTAL": "AMBIENTE",
"EARTH WATCH": "OSSERVATORIO TERRA",
"ACTIVE EVENTS": "EVENTI ATTIVI",
- "Starting live contacts…": "Avvio dei contatti live…",
"Opening space missions…": "Apertura delle missioni spaziali…",
"Scanning active events…": "Scansione degli eventi attivi…",
"Live earthquakes and active fires, from USGS and NASA": "Terremoti e incendi attivi in tempo reale, da USGS e NASA",
@@ -1499,6 +1498,7 @@
"Exit cockpit to fly to a target": "Esci dal cockpit per volare a un obiettivo",
"Exit cockpit to fly to a vessel": "Esci dal cockpit per volare a una nave",
"Exit cockpit to fly to a fire": "Esci dal cockpit per volare a un incendio",
+ "Exit cockpit to fly to an earthquake": "Esci dal cockpit per volare a un terremoto",
"Exit cockpit to fly to a route": "Esci dal cockpit per volare a un percorso",
"Exit cockpit to fly to a file": "Esci dal cockpit per volare a un file",
"Exit cockpit to fly to a scene": "Esci dal cockpit per volare a una scena",
@@ -1958,6 +1958,16 @@
"Live Flights": "Voli live",
"Military Flights": "Voli militari",
"Earthquakes (24h)": "Terremoti (24 h)",
+ "earthquake|Minor": "Minore",
+ "earthquake|Light": "Leggero",
+ "earthquake|Moderate": "Moderato",
+ "earthquake|Strong": "Forte",
+ "earthquake|Major": "Maggiore",
+ "earthquake|Great": "Grande",
+ "earthquake|Shallow": "Superficiale",
+ "earthquake|Intermediate": "Intermedio",
+ "earthquake|Deep": "Profondo",
+ "{km} km deep": "{km} km di profondità",
"Satellites": "Satelliti",
"Place names": "Nomi dei luoghi",
"Space Missions (30d)": "Missioni spaziali (30 g)",
@@ -3170,15 +3180,10 @@
"Reset map bearing to north": "Riporta l'orientamento della mappa a nord",
"Reset camera and return to full globe view": "Ripristina la camera e torna alla vista del globo intero",
"MISSION CONTROL · FIRST LAUNCH": "CONTROLLO MISSIONE · PRIMO AVVIO",
- "Choose your first view": "Scegli la tua prima vista",
- "LIVE CONTACTS": "CONTATTI LIVE",
- "Aircraft, vessels and nearby intelligence": "Aerei, navi e intelligence nelle vicinanze",
"Launches, spacecraft and orbital context": "Lanci, veicoli spaziali e contesto orbitale",
"EXPLORE MANUALLY": "ESPLORA MANUALMENTE",
"Begin with a clean globe": "Inizia con un globo pulito",
"Don't show this again": "Non mostrare più",
- "ESC to dismiss": "ESC per chiudere",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Suggerimento: il pulsante GEV MIC nel dock ti permette di parlare con la mappa.",
"Malformed cyclone snapshot": "Snapshot dei cicloni non valido",
"Cyclone request timed out": "La richiesta dei cicloni è andata in timeout",
"{lower} to {upper}": "Da {lower} a {upper}",
@@ -3416,6 +3421,8 @@
"Source: {value}": "Fonte: {value}",
"Click the card to open EMODnet ↗": "Fai clic sulla scheda per aprire EMODnet ↗",
"Click the card to open the source ↗": "Fai clic sulla scheda per aprire la fonte ↗",
+ "Open the source for {title}, {details}": "Apri la fonte di {title}, {details}",
+ "Focus earthquake {title}, {details}": "Inquadra il terremoto {title}, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata non disponibile; solo EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet non disponibile; solo Wikidata",
"Shipwrecks unavailable": "Relitti non disponibili",
@@ -4381,5 +4388,38 @@
"Search places, layers and things on the map, or ask GEV": "Cerca luoghi, livelli ed elementi sulla mappa oppure chiedi a GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Cerca luoghi, livelli, voli… oppure chiedi a GEV · > per i comandi",
"No matching command": "Nessun comando corrispondente",
- "Looks private, so nothing is searched or sent": "Sembra privato, quindi non viene cercato né inviato nulla"
+ "Looks private, so nothing is searched or sent": "Sembra privato, quindi non viene cercato né inviato nulla",
+ "Bilawal on YouTube": "Bilawal su YouTube",
+ "BROWSE STORIES": "SFOGLIA LE STORIES",
+ "ENTER GOD MODE": "ENTRA IN MODALITÀ DIO",
+ "Go deeper": "Approfondisci",
+ "The studio behind GEV": "Lo studio dietro GEV",
+ "Visual presets": "Preset visivi",
+ "Open source. Self-host, fork, add a layer.": "Open source. Ospitalo tu, fai un fork, aggiungi un livello.",
+ "Choose your mode": "Scegli la modalità",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "Il mirino del satellite spia: vista circolare, HUD tattico, camera cinematografica. Per esplorare.",
+ "Welcome to God's Eye View": "Benvenuto in God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Una vista più pulita e leggibile in cui ogni valore mostra la sua fonte. Per ricerca e reportage.",
+ "Keyhole HUD": "HUD a mirino",
+ "Analyst": "Analista",
+ "God": "Dio",
+ "COMING SOON": "IN ARRIVO",
+ "More from Halfpixel": "Altro da Halfpixel",
+ "Start with": "Inizia con",
+ "FUN": "SVAGO",
+ "Where do you want to start?": "Da dove vuoi iniziare?",
+ "Three things to know": "Tre cose da sapere",
+ "Pick one to begin with. You can change everything later.": "Scegli un’opzione per iniziare. Potrai cambiare tutto in seguito.",
+ "That is all you need to get going.": "È tutto ciò che serve per iniziare.",
+ "SKIP · ESC": "SALTA · ESC",
+ "SKIP": "SALTA",
+ "Search places": "Cerca luoghi",
+ "Type a place into the search bar.": "Digita un luogo nella barra di ricerca.",
+ "Turn on layers": "Attiva i livelli",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Attiva i livelli per vedere voli, navi, telecamere, meteo e altro.",
+ "Click anything": "Fai clic su un elemento",
+ "Select a map item to see its details.": "Seleziona un elemento della mappa per vederne i dettagli.",
+ "Bilawal on {site}": "Bilawal su {site}",
+ "Bilawal's website": "Sito web di Bilawal",
+ "BACK": "INDIETRO"
}
diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json
index 2bebb3bcc9..882a005589 100644
--- a/src/i18n/locales/ja.json
+++ b/src/i18n/locales/ja.json
@@ -386,7 +386,6 @@
"ENVIRONMENTAL": "環境",
"EARTH WATCH": "地球監視",
"ACTIVE EVENTS": "発生中のイベント",
- "Starting live contacts…": "ライブコンタクトを開始中…",
"Opening space missions…": "宇宙ミッションを開いています…",
"Scanning active events…": "発生中のイベントをスキャン中…",
"Live earthquakes and active fires, from USGS and NASA": "USGSとNASAによる地震と火災のライブ情報",
@@ -1453,6 +1452,7 @@
"Exit cockpit to fly to a target": "ターゲットへ移動するにはコックピットを終了してください",
"Exit cockpit to fly to a vessel": "船舶へ移動するにはコックピットを終了してください",
"Exit cockpit to fly to a fire": "火災へ移動するにはコックピットを終了してください",
+ "Exit cockpit to fly to an earthquake": "地震へ移動するにはコックピットを終了してください",
"Exit cockpit to fly to a route": "ルートへ移動するにはコックピットを終了してください",
"Exit cockpit to fly to a file": "ファイルの位置へ移動するにはコックピットを終了してください",
"Exit cockpit to fly to a scene": "シーンへ移動するにはコックピットを終了してください",
@@ -1880,6 +1880,16 @@
"Live Flights": "ライブフライト",
"Military Flights": "軍用機",
"Earthquakes (24h)": "地震(24時間)",
+ "earthquake|Minor": "微小",
+ "earthquake|Light": "軽微",
+ "earthquake|Moderate": "中規模",
+ "earthquake|Strong": "強い",
+ "earthquake|Major": "大規模",
+ "earthquake|Great": "巨大",
+ "earthquake|Shallow": "浅発",
+ "earthquake|Intermediate": "やや深発",
+ "earthquake|Deep": "深発",
+ "{km} km deep": "深さ {km} km",
"Satellites": "衛星",
"Place names": "地名",
"Space Missions (30d)": "宇宙ミッション(30日)",
@@ -3006,15 +3016,10 @@
"Reset map bearing to north": "地図の方位を北にリセット",
"Reset camera and return to full globe view": "カメラをリセットして地球全体ビューに戻す",
"MISSION CONTROL · FIRST LAUNCH": "ミッションコントロール · 初回起動",
- "Choose your first view": "最初のビューを選択",
- "LIVE CONTACTS": "ライブコンタクト",
- "Aircraft, vessels and nearby intelligence": "航空機、船舶、周辺のインテリジェンス",
"Launches, spacecraft and orbital context": "打ち上げ、宇宙機、軌道の状況",
"EXPLORE MANUALLY": "手動で探索",
"Begin with a clean globe": "まっさらな地球儀から始める",
"Don't show this again": "今後表示しない",
- "ESC to dismiss": "Escで閉じる",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "ヒント:ドックの[マイク]ボタンで地図に話しかけられます。",
"routing busy — too many routes at once": "ルート検索サービスが混雑しています。同時に要求されたルートが多すぎます",
"route proxy error": "ルート検索プロキシでエラーが発生しました",
"Malformed cyclone snapshot": "サイクロンのスナップショットの形式が不正です",
@@ -3244,6 +3249,8 @@
"Source: {value}": "出典:{value}",
"Click the card to open EMODnet ↗": "カードをクリックしてEMODnetを開く ↗",
"Click the card to open the source ↗": "カードをクリックして出典を開く ↗",
+ "Open the source for {title}, {details}": "{title}のソースを開く({details})",
+ "Focus earthquake {title}, {details}": "地震{title}にフォーカス({details})",
"Wikidata unavailable; showing EMODnet only": "Wikidataを利用できません。EMODnetのみ表示しています",
"EMODnet unavailable; showing Wikidata only": "EMODnetを利用できません。Wikidataのみ表示しています",
"Shipwrecks unavailable": "難破船データを利用できません",
@@ -4169,5 +4176,38 @@
"Search places, layers and things on the map, or ask GEV": "場所、レイヤー、マップ上の対象を検索するか、GEVに質問",
"Search places, layers, flights… or ask GEV · > for commands": "場所、レイヤー、航空便を検索… またはGEVに質問 · > でコマンド",
"No matching command": "一致するコマンドがありません",
- "Looks private, so nothing is searched or sent": "個人情報の可能性があるため、検索も送信もしません"
+ "Looks private, so nothing is searched or sent": "個人情報の可能性があるため、検索も送信もしません",
+ "Bilawal on YouTube": "YouTube の Bilawal",
+ "BROWSE STORIES": "STORIES を見る",
+ "ENTER GOD MODE": "ゴッドモードで開始",
+ "Go deeper": "さらに詳しく",
+ "The studio behind GEV": "GEV を手がけるスタジオ",
+ "Visual presets": "ビジュアルプリセット",
+ "Open source. Self-host, fork, add a layer.": "オープンソース。セルフホスト、フォーク、レイヤーの追加が可能。",
+ "Choose your mode": "モードを選択",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "偵察衛星の鍵穴ビュー:円形の視野、タクティカル HUD、映画のようなカメラ。探索向け。",
+ "Welcome to God's Eye View": "God's Eye View へようこそ",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "すべての値に出典が表示される、すっきり読みやすいビュー。調査やレポート向け。",
+ "Keyhole HUD": "鍵穴 HUD",
+ "Analyst": "アナリスト",
+ "God": "ゴッド",
+ "COMING SOON": "近日公開",
+ "More from Halfpixel": "Halfpixel のその他のコンテンツ",
+ "Start with": "ここから始める",
+ "FUN": "エンタメ",
+ "Where do you want to start?": "どこから始めますか?",
+ "Three things to know": "知っておきたい3つのこと",
+ "Pick one to begin with. You can change everything later.": "まずは1つ選んでください。後からすべて変更できます。",
+ "That is all you need to get going.": "これで始める準備は完了です。",
+ "SKIP · ESC": "スキップ · ESC",
+ "SKIP": "スキップ",
+ "Search places": "場所を検索",
+ "Type a place into the search bar.": "検索バーに場所を入力して探せます。",
+ "Turn on layers": "レイヤーを有効にする",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "レイヤーを有効にすると、航空機、船舶、カメラ、天気などを表示できます。",
+ "Click anything": "項目をクリック",
+ "Select a map item to see its details.": "地図上の項目を選択すると詳細が表示されます。",
+ "Bilawal on {site}": "{site}のBilawal",
+ "Bilawal's website": "Bilawalのウェブサイト",
+ "BACK": "戻る"
}
diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json
index 950f139a4b..e2a6dc60ed 100644
--- a/src/i18n/locales/pt.json
+++ b/src/i18n/locales/pt.json
@@ -406,7 +406,6 @@
"ENVIRONMENTAL": "AMBIENTAL",
"EARTH WATCH": "VIGILÂNCIA DA TERRA",
"ACTIVE EVENTS": "EVENTOS ATIVOS",
- "Starting live contacts…": "Iniciando contatos ao vivo…",
"Opening space missions…": "Abrindo missões espaciais…",
"Scanning active events…": "Varrendo eventos ativos…",
"Live earthquakes and active fires, from USGS and NASA": "Terremotos e incêndios ativos ao vivo, do USGS e da NASA",
@@ -1499,6 +1498,7 @@
"Exit cockpit to fly to a target": "Saia da cabine para voar até um alvo",
"Exit cockpit to fly to a vessel": "Saia da cabine para voar até uma embarcação",
"Exit cockpit to fly to a fire": "Saia da cabine para voar até um incêndio",
+ "Exit cockpit to fly to an earthquake": "Saia da cabine para voar até um terremoto",
"Exit cockpit to fly to a route": "Saia da cabine para voar até uma rota",
"Exit cockpit to fly to a file": "Saia da cabine para voar até um arquivo",
"Exit cockpit to fly to a scene": "Saia da cabine para voar até uma cena",
@@ -1958,6 +1958,16 @@
"Live Flights": "Voos ao vivo",
"Military Flights": "Voos militares",
"Earthquakes (24h)": "Terremotos (24 h)",
+ "earthquake|Minor": "Menor",
+ "earthquake|Light": "Leve",
+ "earthquake|Moderate": "Moderado",
+ "earthquake|Strong": "Forte",
+ "earthquake|Major": "Maior",
+ "earthquake|Great": "Grande",
+ "earthquake|Shallow": "Raso",
+ "earthquake|Intermediate": "Intermediário",
+ "earthquake|Deep": "Profundo",
+ "{km} km deep": "{km} km de profundidade",
"Satellites": "Satélites",
"Place names": "Nomes de lugares",
"Space Missions (30d)": "Missões espaciais (30 d)",
@@ -3172,15 +3182,10 @@
"Reset map bearing to north": "Redefinir a orientação do mapa para o norte",
"Reset camera and return to full globe view": "Redefinir a câmera e voltar à vista do globo completo",
"MISSION CONTROL · FIRST LAUNCH": "CENTRO DE CONTROLE · PRIMEIRO ACESSO",
- "Choose your first view": "Escolha sua primeira vista",
- "LIVE CONTACTS": "CONTATOS AO VIVO",
- "Aircraft, vessels and nearby intelligence": "Aeronaves, embarcações e informações da região",
"Launches, spacecraft and orbital context": "Lançamentos, espaçonaves e contexto orbital",
"EXPLORE MANUALLY": "EXPLORAR MANUALMENTE",
"Begin with a clean globe": "Comece com um globo limpo",
"Don't show this again": "Não mostrar novamente",
- "ESC to dismiss": "ESC para fechar",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Dica: o botão GEV MIC no dock permite falar com o mapa.",
"{lower} to {upper}": "{lower} a {upper}",
"Up to {upper}": "Até {upper}",
"From {lower}": "A partir de {lower}",
@@ -3416,6 +3421,8 @@
"Source: {value}": "Fonte: {value}",
"Click the card to open EMODnet ↗": "Clique no cartão para abrir o EMODnet ↗",
"Click the card to open the source ↗": "Clique no cartão para abrir a fonte ↗",
+ "Open the source for {title}, {details}": "Abrir a fonte de {title}, {details}",
+ "Focus earthquake {title}, {details}": "Focar terremoto {title}, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata indisponível; mostrando só o EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet indisponível; mostrando só o Wikidata",
"Shipwrecks unavailable": "Naufrágios indisponíveis",
@@ -4381,5 +4388,38 @@
"Search places, layers and things on the map, or ask GEV": "Busque lugares, camadas e elementos no mapa ou pergunte ao GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Busque lugares, camadas, voos… ou pergunte ao GEV · > para comandos",
"No matching command": "Nenhum comando correspondente",
- "Looks private, so nothing is searched or sent": "Parece privado, por isso nada é pesquisado nem enviado"
+ "Looks private, so nothing is searched or sent": "Parece privado, por isso nada é pesquisado nem enviado",
+ "Bilawal on YouTube": "Bilawal no YouTube",
+ "BROWSE STORIES": "VER STORIES",
+ "ENTER GOD MODE": "ENTRAR NO MODO DEUS",
+ "Go deeper": "Ir além",
+ "The studio behind GEV": "O estúdio por trás do GEV",
+ "Visual presets": "Predefinições visuais",
+ "Open source. Self-host, fork, add a layer.": "Código aberto. Hospede você mesmo, faça um fork, adicione uma camada.",
+ "Choose your mode": "Escolha seu modo",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "A mira do satélite espião: visão circular, HUD tático, câmera cinematográfica. Para explorar.",
+ "Welcome to God's Eye View": "Bem-vindo ao God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Uma visão mais limpa e legível em que cada valor mostra sua fonte. Para pesquisa e reportagem.",
+ "Keyhole HUD": "HUD de mira",
+ "Analyst": "Analista",
+ "God": "Deus",
+ "COMING SOON": "EM BREVE",
+ "More from Halfpixel": "Mais da Halfpixel",
+ "Start with": "Começar com",
+ "FUN": "DIVERSÃO",
+ "Where do you want to start?": "Por onde você quer começar?",
+ "Three things to know": "Três coisas a saber",
+ "Pick one to begin with. You can change everything later.": "Escolha uma opção para começar. Você pode mudar tudo depois.",
+ "That is all you need to get going.": "Isso é tudo que você precisa para começar.",
+ "SKIP · ESC": "PULAR · ESC",
+ "SKIP": "PULAR",
+ "Search places": "Pesquisar lugares",
+ "Type a place into the search bar.": "Digite um lugar na barra de busca.",
+ "Turn on layers": "Ativar camadas",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Ative camadas para ver voos, navios, câmeras, clima e muito mais.",
+ "Click anything": "Clique em qualquer elemento",
+ "Select a map item to see its details.": "Selecione um item do mapa para ver seus detalhes.",
+ "Bilawal on {site}": "Bilawal no {site}",
+ "Bilawal's website": "Site de Bilawal",
+ "BACK": "VOLTAR"
}
diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json
index 0cf2d61122..b323df4d5d 100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@ -152,7 +152,6 @@
"CARGO": "ГРУЗОВОЕ",
"TANKER": "ТАНКЕР",
"OTHER": "ДРУГОЕ",
- "Starting live contacts…": "Запуск контактов в реальном времени…",
"Opening space missions…": "Открытие космических миссий…",
"Scanning active events…": "Сканирование активных событий…",
"Live earthquakes and active fires, from USGS and NASA": "Землетрясения и активные пожары в реальном времени от USGS и NASA",
@@ -655,6 +654,16 @@
"Live Flights": "Рейсы онлайн",
"Military Flights": "Военные рейсы",
"Earthquakes (24h)": "Землетрясения (24 ч)",
+ "earthquake|Minor": "Слабое",
+ "earthquake|Light": "Лёгкое",
+ "earthquake|Moderate": "Умеренное",
+ "earthquake|Strong": "Сильное",
+ "earthquake|Major": "Мощное",
+ "earthquake|Great": "Катастрофическое",
+ "earthquake|Shallow": "Мелкофокусное",
+ "earthquake|Intermediate": "Среднефокусное",
+ "earthquake|Deep": "Глубокофокусное",
+ "{km} km deep": "глубина {km} км",
"Satellites": "Спутники",
"Place names": "Названия мест",
"Space Missions (30d)": "Космические миссии (30 дн.)",
@@ -1021,15 +1030,10 @@
"Globe actions": "Действия с глобусом",
"NO PLACE LEFT BEHIND": "НИ ОДНА ТОЧКА НЕ ОСТАНЕТСЯ ПОЗАДИ",
"ACTIVE STYLE": "АКТИВНЫЙ СТИЛЬ",
- "Choose your first view": "Выберите первый вид",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Совет: кнопка «МИК» в доке позволяет говорить с картой.",
- "Aircraft, vessels and nearby intelligence": "Самолёты, суда и разведданные поблизости",
"Launches, spacecraft and orbital context": "Пуски, космические аппараты и орбитальный контекст",
"Begin with a clean globe": "Начните с чистого глобуса",
"MISSION CONTROL · FIRST LAUNCH": "ЦЕНТР УПРАВЛЕНИЯ · ПЕРВЫЙ ЗАПУСК",
"Don't show this again": "Больше не показывать",
- "ESC to dismiss": "ESC — скрыть",
- "LIVE CONTACTS": "КОНТАКТЫ ОНЛАЙН",
"EXPLORE MANUALLY": "ИЗУЧИТЬ ВРУЧНУЮ",
"Celestial ring — reveal the full globe": "Небесное кольцо — показать весь глобус",
"Celestial ring — available in Normal style": "Небесное кольцо — доступно в стиле «Обычный»",
@@ -2671,6 +2675,7 @@
"Exit cockpit to fly to a target": "Выйдите из кабины, чтобы перелететь к цели",
"Exit cockpit to fly to a vessel": "Выйдите из кабины, чтобы перелететь к судну",
"Exit cockpit to fly to a fire": "Выйдите из кабины, чтобы перелететь к пожару",
+ "Exit cockpit to fly to an earthquake": "Выйдите из кабины, чтобы перелететь к землетрясению",
"Exit cockpit to fly to a route": "Выйдите из кабины, чтобы перелететь к маршруту",
"Exit cockpit to fly to a file": "Выйдите из кабины, чтобы перелететь к файлу",
"Exit cockpit to fly to a scene": "Выйдите из кабины, чтобы перелететь к сцене",
@@ -3502,6 +3507,8 @@
"Source: {value}": "Источник: {value}",
"Click the card to open EMODnet ↗": "Нажмите на карточку, чтобы открыть EMODnet ↗",
"Click the card to open the source ↗": "Нажмите на карточку, чтобы открыть источник ↗",
+ "Open the source for {title}, {details}": "Открыть источник: {title}, {details}",
+ "Focus earthquake {title}, {details}": "Фокус на землетрясении {title}, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показан только EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet недоступен; показана только Wikidata",
"Shipwrecks unavailable": "Данные о кораблекрушениях недоступны",
@@ -4487,5 +4494,38 @@
"Search places, layers and things on the map, or ask GEV": "Ищите места, слои и объекты на карте или спросите GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Ищите места, слои, рейсы… или спросите GEV · > для команд",
"No matching command": "Подходящая команда не найдена",
- "Looks private, so nothing is searched or sent": "Похоже на личные данные, поэтому ничего не ищется и не отправляется"
+ "Looks private, so nothing is searched or sent": "Похоже на личные данные, поэтому ничего не ищется и не отправляется",
+ "Bilawal on YouTube": "Билавал на YouTube",
+ "BROWSE STORIES": "СМОТРЕТЬ STORIES",
+ "ENTER GOD MODE": "ВОЙТИ В РЕЖИМ БОГА",
+ "Go deeper": "Глубже",
+ "The studio behind GEV": "Студия, создавшая GEV",
+ "Visual presets": "Визуальные пресеты",
+ "Open source. Self-host, fork, add a layer.": "Открытый код. Разверните у себя, сделайте форк, добавьте слой.",
+ "Choose your mode": "Выберите режим",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "Замочная скважина спутника-шпиона: круглый обзор, тактический HUD, кинематографичная камера. Для исследования.",
+ "Welcome to God's Eye View": "Добро пожаловать в God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Более чистый и читаемый вид, где у каждого значения указан источник. Для исследований и отчётов.",
+ "Keyhole HUD": "HUD-скважина",
+ "Analyst": "Аналитик",
+ "God": "Бог",
+ "COMING SOON": "СКОРО",
+ "More from Halfpixel": "Ещё от Halfpixel",
+ "Start with": "Начать с",
+ "FUN": "ИГРА",
+ "Where do you want to start?": "С чего хотите начать?",
+ "Three things to know": "Три вещи, которые стоит знать",
+ "Pick one to begin with. You can change everything later.": "Выберите один вариант для начала. Позже всё можно изменить.",
+ "That is all you need to get going.": "Это всё, что нужно для начала.",
+ "SKIP · ESC": "ПРОПУСТИТЬ · ESC",
+ "SKIP": "ПРОПУСТИТЬ",
+ "Search places": "Поиск мест",
+ "Type a place into the search bar.": "Введите место в строке поиска.",
+ "Turn on layers": "Включайте слои",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Включайте слои, чтобы видеть самолёты, суда, камеры, погоду и многое другое.",
+ "Click anything": "Нажмите на объект",
+ "Select a map item to see its details.": "Выберите объект на карте, чтобы увидеть подробности.",
+ "Bilawal on {site}": "Билал на {site}",
+ "Bilawal's website": "Сайт Билала",
+ "BACK": "НАЗАД"
}
diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json
index 25b5f37976..b457512d26 100644
--- a/src/i18n/locales/sv.json
+++ b/src/i18n/locales/sv.json
@@ -155,7 +155,6 @@
"ENVIRONMENTAL": "MILJÖ",
"EARTH WATCH": "JORDBEVAKNING",
"ACTIVE EVENTS": "AKTIVA HÄNDELSER",
- "Starting live contacts…": "Startar livekontakter …",
"Opening space missions…": "Öppnar rymduppdrag …",
"Scanning active events…": "Söker efter aktiva händelser …",
"Live earthquakes and active fires, from USGS and NASA": "Jordbävningar och aktiva bränder i realtid, från USGS och NASA",
@@ -601,6 +600,16 @@
"Live Flights": "Liveflyg",
"Military Flights": "Militärflyg",
"Earthquakes (24h)": "Jordbävningar (24 h)",
+ "earthquake|Minor": "Mindre",
+ "earthquake|Light": "Lätt",
+ "earthquake|Moderate": "Måttlig",
+ "earthquake|Strong": "Kraftig",
+ "earthquake|Major": "Stor",
+ "earthquake|Great": "Mycket stor",
+ "earthquake|Shallow": "Grund",
+ "earthquake|Intermediate": "Medeldjup",
+ "earthquake|Deep": "Djup",
+ "{km} km deep": "{km} km djup",
"Satellites": "Satelliter",
"Space Missions (30d)": "Rymduppdrag (30 d)",
"Street Traffic": "Gatutrafik",
@@ -953,15 +962,10 @@
"Copy share link": "Kopiera delningslänk",
"Reset camera and return to full globe view": "Återställ kameran och återgå till vy över hela globen",
"MISSION CONTROL · FIRST LAUNCH": "UPPDRAGSLEDNING · FÖRSTA START",
- "Choose your first view": "Välj första vy",
- "LIVE CONTACTS": "LIVEKONTAKTER",
- "Aircraft, vessels and nearby intelligence": "Flygplan, fartyg och lägesbild i närheten",
"Launches, spacecraft and orbital context": "Uppskjutningar, rymdfarkoster och omloppsbanor",
"EXPLORE MANUALLY": "UTFORSKA MANUELLT",
"Begin with a clean globe": "Börja med en tom glob",
"Don't show this again": "Visa inte igen",
- "ESC to dismiss": "ESC för att stänga",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Tips: med knappen MIK i dockan går det att prata med kartan.",
"Pick a shape, then click the map.": "Välj en form och klicka sedan på kartan.",
"Enter to place the pin, Esc to cancel.": "Enter placerar nålen, Esc avbryter.",
"Click where the pin goes.": "Klicka där nålen ska sitta.",
@@ -1994,6 +1998,7 @@
"Exit cockpit to fly to a target": "Lämna cockpiten för att flyga till ett mål",
"Exit cockpit to fly to a vessel": "Lämna cockpiten för att flyga till ett fartyg",
"Exit cockpit to fly to a fire": "Lämna cockpiten för att flyga till en brand",
+ "Exit cockpit to fly to an earthquake": "Lämna cockpiten för att flyga till en jordbävning",
"Exit cockpit to fly to a route": "Lämna cockpiten för att flyga till en rutt",
"Exit cockpit to fly to a file": "Lämna cockpiten för att flyga till en fil",
"Exit cockpit to fly to a scene": "Lämna cockpiten för att flyga till en scen",
@@ -3243,6 +3248,8 @@
"Click the card to open EMODnet ↗": "Klicka på kortet för att öppna EMODnet ↗",
"Click the card to open the article ↗": "Klicka på kortet för att öppna artikeln ↗",
"Click the card to open the source ↗": "Klicka på kortet för att öppna källan ↗",
+ "Open the source for {title}, {details}": "Öppna källan för {title}, {details}",
+ "Focus earthquake {title}, {details}": "Fokusera på jordbävningen {title}, {details}",
"All years": "Alla år",
"Period": "Period",
"From": "Från",
@@ -4275,5 +4282,38 @@
"Search places, layers and things on the map, or ask GEV": "Sök efter platser, lager och objekt på kartan eller fråga GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Sök efter platser, lager, flyg… eller fråga GEV · > för kommandon",
"No matching command": "Inget matchande kommando",
- "Looks private, so nothing is searched or sent": "Ser privat ut, så inget söks eller skickas"
+ "Looks private, so nothing is searched or sent": "Ser privat ut, så inget söks eller skickas",
+ "Where do you want to start?": "Var vill du börja?",
+ "Three things to know": "Tre saker att känna till",
+ "Pick one to begin with. You can change everything later.": "Välj ett alternativ att börja med. Du kan ändra allt senare.",
+ "That is all you need to get going.": "Det är allt du behöver för att komma igång.",
+ "SKIP · ESC": "HOPPA ÖVER · ESC",
+ "SKIP": "HOPPA ÖVER",
+ "Search places": "Sök platser",
+ "Type a place into the search bar.": "Skriv en plats i sökfältet.",
+ "Turn on layers": "Aktivera lager",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Aktivera lager för att se flyg, fartyg, kameror, väder och mer.",
+ "Click anything": "Klicka på ett objekt",
+ "Select a map item to see its details.": "Välj ett kartobjekt för att se detaljerna.",
+ "Bilawal on {site}": "Bilawal på {site}",
+ "Bilawal's website": "Bilawals webbplats",
+ "BACK": "TILLBAKA",
+ "Welcome to God's Eye View": "Välkommen till God's Eye View",
+ "Choose your mode": "Välj läge",
+ "God": "Gud",
+ "FUN": "NÖJE",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "Spionsatellitens nyckelhål: rund vy, taktisk HUD och filmisk kamera. För utforskning.",
+ "Keyhole HUD": "Nyckelhåls-HUD",
+ "Visual presets": "Visuella förval",
+ "Analyst": "Analytiker",
+ "COMING SOON": "KOMMER SNART",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "En renare, lättläst vy där varje värde visar sin källa. För research och rapportering.",
+ "Start with": "Börja med",
+ "Go deeper": "Gå djupare",
+ "BROWSE STORIES": "BLÄDDRA BLAND BERÄTTELSER",
+ "More from Halfpixel": "Mer från Halfpixel",
+ "Bilawal on YouTube": "Bilawal på YouTube",
+ "The studio behind GEV": "Studion bakom GEV",
+ "Open source. Self-host, fork, add a layer.": "Öppen källkod. Kör själv, skapa en egen variant, lägg till ett lager.",
+ "ENTER GOD MODE": "STARTA GUDLÄGE"
}
diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json
index 4293477add..edcce4e88d 100644
--- a/src/i18n/locales/uk.json
+++ b/src/i18n/locales/uk.json
@@ -416,7 +416,6 @@
"ENVIRONMENTAL": "ДОВКІЛЛЯ",
"EARTH WATCH": "СПОСТЕРЕЖЕННЯ ЗА ЗЕМЛЕЮ",
"ACTIVE EVENTS": "АКТИВНІ ПОДІЇ",
- "Starting live contacts…": "Запуск контактів у реальному часі…",
"Opening space missions…": "Відкриття космічних місій…",
"Scanning active events…": "Сканування активних подій…",
"Live earthquakes and active fires, from USGS and NASA": "Землетруси в реальному часі й активні пожежі від USGS та NASA",
@@ -1521,6 +1520,7 @@
"Exit cockpit to fly to a target": "Вийдіть із кабіни, щоб перелетіти до цілі",
"Exit cockpit to fly to a vessel": "Вийдіть із кабіни, щоб перелетіти до судна",
"Exit cockpit to fly to a fire": "Вийдіть із кабіни, щоб перелетіти до пожежі",
+ "Exit cockpit to fly to an earthquake": "Вийдіть із кабіни, щоб перелетіти до землетрусу",
"Exit cockpit to fly to a route": "Вийдіть із кабіни, щоб перелетіти до маршруту",
"Exit cockpit to fly to a file": "Вийдіть із кабіни, щоб перелетіти до файлу",
"Exit cockpit to fly to a scene": "Вийдіть із кабіни, щоб перелетіти до сцени",
@@ -1996,6 +1996,16 @@
"Live Flights": "Рейси онлайн",
"Military Flights": "Військові рейси",
"Earthquakes (24h)": "Землетруси (24 год)",
+ "earthquake|Minor": "Слабкий",
+ "earthquake|Light": "Легкий",
+ "earthquake|Moderate": "Помірний",
+ "earthquake|Strong": "Сильний",
+ "earthquake|Major": "Потужний",
+ "earthquake|Great": "Катастрофічний",
+ "earthquake|Shallow": "Мілкофокусний",
+ "earthquake|Intermediate": "Середньофокусний",
+ "earthquake|Deep": "Глибокофокусний",
+ "{km} km deep": "глибина {km} км",
"Satellites": "Супутники",
"Place names": "Назви місць",
"Space Missions (30d)": "Космічні місії (30 дн)",
@@ -3251,15 +3261,10 @@
"Reset map bearing to north": "Скинути азимут карти на північ",
"Reset camera and return to full globe view": "Скинути камеру та повернутися до вигляду всього глобуса",
"MISSION CONTROL · FIRST LAUNCH": "ЦЕНТР КЕРУВАННЯ · ПЕРШИЙ ЗАПУСК",
- "Choose your first view": "Виберіть, із чого почати",
- "LIVE CONTACTS": "КОНТАКТИ ОНЛАЙН",
- "Aircraft, vessels and nearby intelligence": "Літаки, судна й розвіддані поблизу",
"Launches, spacecraft and orbital context": "Запуски, космічні апарати та орбітальний контекст",
"EXPLORE MANUALLY": "ДОСЛІДИТИ ВРУЧНУ",
"Begin with a clean globe": "Почніть із чистого глобуса",
"Don't show this again": "Більше не показувати",
- "ESC to dismiss": "ESC — приховати",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "Порада: кнопка МІК у доку дає змогу говорити з картою.",
"fire confidence filter|All": "Усі",
"fire confidence filter|Nominal+": "Середня+",
"fire confidence filter|High": "Висока",
@@ -3502,6 +3507,8 @@
"Source: {value}": "Джерело: {value}",
"Click the card to open EMODnet ↗": "Клацніть картку, щоб відкрити EMODnet ↗",
"Click the card to open the source ↗": "Клацніть картку, щоб відкрити джерело ↗",
+ "Open the source for {title}, {details}": "Відкрити джерело: {title}, {details}",
+ "Focus earthquake {title}, {details}": "Фокус на землетрусі {title}, {details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata недоступна; показано лише EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet недоступний; показано лише Wikidata",
"Shipwrecks unavailable": "Дані про затонулі судна недоступні",
@@ -4487,5 +4494,38 @@
"Search places, layers and things on the map, or ask GEV": "Шукайте місця, шари й об’єкти на карті або запитайте GEV",
"Search places, layers, flights… or ask GEV · > for commands": "Шукайте місця, шари, рейси… або запитайте GEV · > для команд",
"No matching command": "Відповідної команди не знайдено",
- "Looks private, so nothing is searched or sent": "Схоже на особисті дані, тому нічого не шукається й не надсилається"
+ "Looks private, so nothing is searched or sent": "Схоже на особисті дані, тому нічого не шукається й не надсилається",
+ "Bilawal on YouTube": "Білавал на YouTube",
+ "BROWSE STORIES": "ПЕРЕГЛЯНУТИ STORIES",
+ "ENTER GOD MODE": "УВІЙТИ В РЕЖИМ БОГА",
+ "Go deeper": "Глибше",
+ "The studio behind GEV": "Студія, що створила GEV",
+ "Visual presets": "Візуальні пресети",
+ "Open source. Self-host, fork, add a layer.": "Відкритий код. Розгорніть у себе, зробіть форк, додайте шар.",
+ "Choose your mode": "Оберіть режим",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "Замкова шпарина супутника-шпигуна: круглий огляд, тактичний HUD, кінематографічна камера. Для дослідження.",
+ "Welcome to God's Eye View": "Ласкаво просимо до God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "Чистіший і зручний для читання вигляд, де кожне значення показує своє джерело. Для досліджень і звітів.",
+ "Keyhole HUD": "HUD-шпарина",
+ "Analyst": "Аналітик",
+ "God": "Бог",
+ "COMING SOON": "НЕЗАБАРОМ",
+ "More from Halfpixel": "Більше від Halfpixel",
+ "Start with": "Почати з",
+ "FUN": "ГРА",
+ "Where do you want to start?": "З чого хочете почати?",
+ "Three things to know": "Три речі, які варто знати",
+ "Pick one to begin with. You can change everything later.": "Виберіть один варіант для початку. Згодом усе можна змінити.",
+ "That is all you need to get going.": "Це все, що потрібно для початку.",
+ "SKIP · ESC": "ПРОПУСТИТИ · ESC",
+ "SKIP": "ПРОПУСТИТИ",
+ "Search places": "Пошук місць",
+ "Type a place into the search bar.": "Введіть місце в рядку пошуку.",
+ "Turn on layers": "Увімкніть шари",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "Увімкніть шари, щоб бачити літаки, судна, камери, погоду та інше.",
+ "Click anything": "Натисніть на об’єкт",
+ "Select a map item to see its details.": "Виберіть об’єкт на карті, щоб побачити подробиці.",
+ "Bilawal on {site}": "Білал на {site}",
+ "Bilawal's website": "Сайт Білала",
+ "BACK": "НАЗАД"
}
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index a7e5f73b91..05ddb36bc4 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -386,7 +386,6 @@
"ENVIRONMENTAL": "环境",
"EARTH WATCH": "地球监测",
"ACTIVE EVENTS": "活跃事件",
- "Starting live contacts…": "正在接入实时目标…",
"Opening space missions…": "正在打开太空任务…",
"Scanning active events…": "正在扫描活跃事件…",
"Live earthquakes and active fires, from USGS and NASA": "来自 USGS 和 NASA 的实时地震与活跃火点",
@@ -1428,6 +1427,7 @@
"Exit cockpit to fly to a target": "请先退出座舱,再飞往目标",
"Exit cockpit to fly to a vessel": "请先退出座舱,再飞往船舶",
"Exit cockpit to fly to a fire": "请先退出座舱,再飞往火点",
+ "Exit cockpit to fly to an earthquake": "请先退出座舱,再飞往地震",
"Exit cockpit to fly to a route": "请先退出座舱,再飞往路线",
"Exit cockpit to fly to a file": "请先退出座舱,再飞往文件位置",
"Exit cockpit to fly to a scene": "请先退出座舱,再飞往场景",
@@ -1856,6 +1856,16 @@
"Live Flights": "实时航班",
"Military Flights": "军用航班",
"Earthquakes (24h)": "地震(24 小时)",
+ "earthquake|Minor": "微弱",
+ "earthquake|Light": "轻微",
+ "earthquake|Moderate": "中等",
+ "earthquake|Strong": "强烈",
+ "earthquake|Major": "重大",
+ "earthquake|Great": "巨大",
+ "earthquake|Shallow": "浅源",
+ "earthquake|Intermediate": "中源",
+ "earthquake|Deep": "深源",
+ "{km} km deep": "震源深度 {km} km",
"Satellites": "卫星",
"Place names": "地名",
"Space Missions (30d)": "太空任务(30 天)",
@@ -2910,15 +2920,10 @@
"Reset map bearing to north": "重置地图方位为正北",
"Reset camera and return to full globe view": "重置相机并返回完整地球视图",
"MISSION CONTROL · FIRST LAUNCH": "任务控制 · 首次启动",
- "Choose your first view": "选择初始视图",
- "LIVE CONTACTS": "实时目标",
- "Aircraft, vessels and nearby intelligence": "飞机、船舶及周边情报",
"Launches, spacecraft and orbital context": "发射、航天器与轨道态势",
"EXPLORE MANUALLY": "手动探索",
"Begin with a clean globe": "从空白地球开始",
"Don't show this again": "不再显示",
- "ESC to dismiss": "按 ESC 关闭",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "提示:可通过停靠栏中的 GEV 麦克风按钮用语音操控地图。",
"hemisphere|N": "N",
"hemisphere|S": "S",
"hemisphere|E": "E",
@@ -3244,6 +3249,8 @@
"Source: {value}": "来源:{value}",
"Click the card to open EMODnet ↗": "点击卡片打开 EMODnet ↗",
"Click the card to open the source ↗": "点击卡片打开来源 ↗",
+ "Open the source for {title}, {details}": "打开 {title} 的来源,{details}",
+ "Focus earthquake {title}, {details}": "聚焦地震 {title},{details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata 不可用;仅显示 EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet 不可用;仅显示 Wikidata",
"Shipwrecks unavailable": "沉船数据不可用",
@@ -4169,5 +4176,38 @@
"Search places, layers and things on the map, or ask GEV": "搜索地点、图层和地图上的对象,或向 GEV 提问",
"Search places, layers, flights… or ask GEV · > for commands": "搜索地点、图层、航班… 或问 GEV · > 输入命令",
"No matching command": "没有匹配的命令",
- "Looks private, so nothing is searched or sent": "疑似隐私信息,因此不会搜索或发送"
+ "Looks private, so nothing is searched or sent": "疑似隐私信息,因此不会搜索或发送",
+ "Bilawal on YouTube": "Bilawal 的 YouTube",
+ "BROWSE STORIES": "浏览 STORIES",
+ "ENTER GOD MODE": "进入上帝模式",
+ "Go deeper": "深入了解",
+ "The studio behind GEV": "GEV 背后的工作室",
+ "Visual presets": "视觉预设",
+ "Open source. Self-host, fork, add a layer.": "开源。可自行托管、派生、添加图层。",
+ "Choose your mode": "选择模式",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "间谍卫星锁孔视图:圆形视野、战术 HUD、电影级镜头。适合探索。",
+ "Welcome to God's Eye View": "欢迎使用 God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "更简洁易读的视图,每个数值都标明来源。适合研究和报道。",
+ "Keyhole HUD": "锁孔 HUD",
+ "Analyst": "分析师",
+ "God": "上帝",
+ "COMING SOON": "即将推出",
+ "More from Halfpixel": "更多来自 Halfpixel",
+ "Start with": "从这里开始",
+ "FUN": "娱乐",
+ "Where do you want to start?": "您想从哪里开始?",
+ "Three things to know": "需要了解的三件事",
+ "Pick one to begin with. You can change everything later.": "先选择一项,之后可以随时更改。",
+ "That is all you need to get going.": "了解这些就可以开始了。",
+ "SKIP · ESC": "跳过 · ESC",
+ "SKIP": "跳过",
+ "Search places": "搜索地点",
+ "Type a place into the search bar.": "在搜索栏中输入地点。",
+ "Turn on layers": "开启图层",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "开启图层以查看航班、船舶、摄像头、天气等。",
+ "Click anything": "点击任意项目",
+ "Select a map item to see its details.": "选择地图上的项目以查看详情。",
+ "Bilawal on {site}": "Bilawal 的 {site} 主页",
+ "Bilawal's website": "Bilawal 的网站",
+ "BACK": "返回"
}
diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json
index 9af1d69dfe..a84085e7e4 100644
--- a/src/i18n/locales/zh-Hant.json
+++ b/src/i18n/locales/zh-Hant.json
@@ -386,7 +386,6 @@
"ENVIRONMENTAL": "環境",
"EARTH WATCH": "地球監測",
"ACTIVE EVENTS": "活躍事件",
- "Starting live contacts…": "正在接入實時目標…",
"Opening space missions…": "正在打開太空任務…",
"Scanning active events…": "正在掃描活躍事件…",
"Live earthquakes and active fires, from USGS and NASA": "來自 USGS 和 NASA 的實時地震與活躍火點",
@@ -1428,6 +1427,7 @@
"Exit cockpit to fly to a target": "請先退出座艙,再飛往目標",
"Exit cockpit to fly to a vessel": "請先退出座艙,再飛往船舶",
"Exit cockpit to fly to a fire": "請先退出座艙,再飛往火點",
+ "Exit cockpit to fly to an earthquake": "請先退出座艙,再飛往地震",
"Exit cockpit to fly to a route": "請先退出座艙,再飛往路線",
"Exit cockpit to fly to a file": "請先退出座艙,再飛往文件位置",
"Exit cockpit to fly to a scene": "請先退出座艙,再飛往場景",
@@ -1856,6 +1856,16 @@
"Live Flights": "實時航班",
"Military Flights": "軍用航班",
"Earthquakes (24h)": "地震(24 小時)",
+ "earthquake|Minor": "微弱",
+ "earthquake|Light": "輕微",
+ "earthquake|Moderate": "中等",
+ "earthquake|Strong": "強烈",
+ "earthquake|Major": "重大",
+ "earthquake|Great": "巨大",
+ "earthquake|Shallow": "淺源",
+ "earthquake|Intermediate": "中源",
+ "earthquake|Deep": "深源",
+ "{km} km deep": "震源深度 {km} km",
"Satellites": "衛星",
"Place names": "地名",
"Space Missions (30d)": "太空任務(30 天)",
@@ -2910,15 +2920,10 @@
"Reset map bearing to north": "重置地圖方位為正北",
"Reset camera and return to full globe view": "重置相機並返回完整地球視圖",
"MISSION CONTROL · FIRST LAUNCH": "任務控制 · 首次啟動",
- "Choose your first view": "選擇初始視圖",
- "LIVE CONTACTS": "實時目標",
- "Aircraft, vessels and nearby intelligence": "飛機、船舶及周邊情報",
"Launches, spacecraft and orbital context": "發射、航天器與軌道態勢",
"EXPLORE MANUALLY": "手動探索",
"Begin with a clean globe": "從空白地球開始",
"Don't show this again": "不再顯示",
- "ESC to dismiss": "按 ESC 關閉",
- "Tip: the GEV MIC button in the dock lets you talk to the map.": "提示:可通過停靠欄中的 GEV 麥克風按鈕用語音操控地圖。",
"hemisphere|N": "N",
"hemisphere|S": "S",
"hemisphere|E": "E",
@@ -3244,6 +3249,8 @@
"Source: {value}": "來源:{value}",
"Click the card to open EMODnet ↗": "點擊卡片打開 EMODnet ↗",
"Click the card to open the source ↗": "點擊卡片打開來源 ↗",
+ "Open the source for {title}, {details}": "打開 {title} 的來源,{details}",
+ "Focus earthquake {title}, {details}": "聚焦地震 {title},{details}",
"Wikidata unavailable; showing EMODnet only": "Wikidata 不可用;僅顯示 EMODnet",
"EMODnet unavailable; showing Wikidata only": "EMODnet 不可用;僅顯示 Wikidata",
"Shipwrecks unavailable": "沉船數據不可用",
@@ -4169,5 +4176,38 @@
"Search places, layers and things on the map, or ask GEV": "搜索地點、圖層和地圖上的對象,或向 GEV 提問",
"Search places, layers, flights… or ask GEV · > for commands": "搜索地點、圖層、航班… 或問 GEV · > 輸入命令",
"No matching command": "沒有匹配的命令",
- "Looks private, so nothing is searched or sent": "疑似隱私信息,因此不會搜索或發送"
+ "Looks private, so nothing is searched or sent": "疑似隱私信息,因此不會搜索或發送",
+ "Bilawal on YouTube": "Bilawal 的 YouTube",
+ "BROWSE STORIES": "瀏覽 STORIES",
+ "ENTER GOD MODE": "進入上帝模式",
+ "Go deeper": "深入瞭解",
+ "The studio behind GEV": "GEV 背後的工作室",
+ "Visual presets": "視覺預設",
+ "Open source. Self-host, fork, add a layer.": "開源。可自行託管、派生、添加圖層。",
+ "Choose your mode": "選擇模式",
+ "The spy-satellite keyhole: circular viewport, tactical HUD, cinematic camera. For exploring.": "間諜衛星鎖孔視圖:圓形視野、戰術 HUD、電影級鏡頭。適合探索。",
+ "Welcome to God's Eye View": "歡迎使用 God's Eye View",
+ "A cleaner, readable view where every value shows its source. For research and reporting.": "更簡潔易讀的視圖,每個數值都標明來源。適合研究和報道。",
+ "Keyhole HUD": "鎖孔 HUD",
+ "Analyst": "分析師",
+ "God": "上帝",
+ "COMING SOON": "即將推出",
+ "More from Halfpixel": "更多來自 Halfpixel",
+ "Start with": "從這裡開始",
+ "FUN": "娛樂",
+ "Where do you want to start?": "您想從哪裡開始?",
+ "Three things to know": "需要了解的三件事",
+ "Pick one to begin with. You can change everything later.": "先選擇一項,之後可以隨時更改。",
+ "That is all you need to get going.": "瞭解這些就可以開始了。",
+ "SKIP · ESC": "跳過 · ESC",
+ "SKIP": "跳過",
+ "Search places": "搜索地點",
+ "Type a place into the search bar.": "在搜索欄中輸入地點。",
+ "Turn on layers": "開啟圖層",
+ "Turn layers on to see flights, ships, cameras, weather and more.": "開啟圖層以查看航班、船舶、攝像頭、天氣等。",
+ "Click anything": "點擊任意項目",
+ "Select a map item to see its details.": "選擇地圖上的項目以查看詳情。",
+ "Bilawal on {site}": "Bilawal 的 {site} 主頁",
+ "Bilawal's website": "Bilawal 的網站",
+ "BACK": "返回"
}
diff --git a/src/input/dispatcher.js b/src/input/dispatcher.js
index b5c8fa86cf..6ae4e125c0 100644
--- a/src/input/dispatcher.js
+++ b/src/input/dispatcher.js
@@ -182,6 +182,12 @@ function topHitOf(hit, foreign) {
* when the adapter has none.
* @property {unknown} pick `native.pick`, for code still bound to the
* 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. A
+ * target the world overlay paints (a Space Missions label) is also the
+ * card on top for every handler (`clickCard` in src/data/pickRegistry.js),
+ * so nothing under it acts.
* @property {(width: number, height: number) => unknown} pickWindow
* `native.pickWindow`, the same.
*/
@@ -192,7 +198,9 @@ function topHitOf(hit, foreign) {
* Ambient click subscription. Returns its unsubscribe.
* @property {(fn: (event: ClickEvent) => boolean) => () => void} onOverlayClick
* Hit-test a painted overlay before ambient clicks. Return true after
- * handling its topmost target to stop delivery to the geometry beneath it.
+ * handling its topmost target: the geometry beneath it is not picked, and
+ * the click subscribers hear the click as one on that target (`overlay`
+ * true, `topHit` a hit with no set and no id, nothing drilled).
* @property {(type: 'down'|'move'|'up'|'click'|'dblclick', fn: Function, options?: {lease?: object|(() => object|null)}) => () => void} onPointer
* Raw pointer subscription: `click` gets the {@link ClickEvent}, the others
* `{position}` (`move`: `{startPosition, endPosition, pickPosition}`, its
@@ -331,7 +339,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
click: (ev) => {
if (!unmodifiedLeft(ev)) return;
const ambient = free();
- const event = createClickEvent(
+ const { event, cover } = createClickEvent(
viewer,
queryOf,
xy(ev.position),
@@ -340,7 +348,12 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
if (ambient) {
for (const handle of [...overlayClicks]) {
try {
- if (handle(event) === true) return;
+ // A handled overlay target hides the geometry beneath it; every
+ // subscriber still hears the click, as a click on that target.
+ if (handle(event) === true) {
+ cover();
+ break;
+ }
} catch (error) {
console.error('Pointer input handler failed', error);
}
@@ -437,6 +450,10 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
return self;
}
+/** What a click handled by a painted overlay target hits: that target,
+ * drawn outside the draw port and named by no pick id. */
+const OVERLAY_HIT = Object.freeze({ set: '', id: null, surface: false });
+
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
const DRILL_DEPTH = 16;
@@ -446,7 +463,8 @@ const DRILL_DEPTH = 16;
* @param {() => import('../render/contract/query').QueryPort|null} queryOf
* @param {{x: number, y: number}} at Where the click is, CSS pixels.
* @param {ClickGesture} gesture
- * @returns {ClickEvent}
+ * @returns {{event: ClickEvent, cover: () => void}} The click, and how a
+ * handled overlay target hides the geometry beneath it from the click.
*/
function createClickEvent(viewer, queryOf, at, gesture) {
const position = sensorPickPosition(viewer, at, canvasOf(viewer));
@@ -465,11 +483,25 @@ function createClickEvent(viewer, queryOf, at, gesture) {
};
/** @type {Map} */
const drills = new Map();
+ let covered = false;
+ const cover = () => {
+ covered = true;
+ memo.clear();
+ drills.clear();
+ memo.set('top', OVERLAY_HIT);
+ memo.set('hit', OVERLAY_HIT);
+ memo.set('id', null);
+ memo.set('ownerId', null);
+ memo.set('native', null);
+ };
- return {
+ const event = {
screenPosition: at,
position,
gesture,
+ get overlay() {
+ return covered;
+ },
get topHit() {
return once('top', () => {
const hit = pick();
@@ -515,6 +547,7 @@ function createClickEvent(viewer, queryOf, at, gesture) {
return !this.hit;
},
windowHit(width, height) {
+ if (covered) return { id: null, drawHit: null, surface: false };
return once(`windowHit:${width}x${height}`, () => {
const picked = pick({ width, height });
void native()?.native.pickWindow(width, height);
@@ -535,7 +568,7 @@ function createClickEvent(viewer, queryOf, at, gesture) {
// A deeper pass already made holds these. (One that came back short
// may not hold every hit: it drops what is not a draw-set item.)
if (done && limit <= done.limit) return done.hits.slice(0, limit);
- const q = query();
+ const q = covered ? null : query();
if (!q) return [];
// Only the default window is shared between layers; round that one up.
const depth =
@@ -568,4 +601,5 @@ function createClickEvent(viewer, queryOf, at, gesture) {
return native()?.native.pickWindow(width, height);
},
};
+ return { event, cover };
}
diff --git a/src/input/dispatcher.test.mjs b/src/input/dispatcher.test.mjs
index c88e1af8b1..965c63374d 100644
--- a/src/input/dispatcher.test.mjs
+++ b/src/input/dispatcher.test.mjs
@@ -145,7 +145,8 @@ test('a painted overlay can claim a click before its underlying owner', (t) => {
h.input.onPointer('click', () => clicks.push('ambient pointer'));
h.click();
- assert.deepEqual(clicks, ['mission label']);
+ // The click still reaches every subscriber, as one on the label.
+ assert.deepEqual(clicks, ['mission label', 'ambient pointer', null]);
assert.equal(h.calls.pick, 0);
h.click(11, 10);
@@ -154,12 +155,71 @@ test('a painted overlay can claim a click before its underlying owner', (t) => {
assert.deepEqual(clicks, [
'mission label',
'ambient pointer',
+ null,
+ 'ambient pointer',
'satellites',
'ambient pointer',
'satellites',
]);
});
+test('a click a painted overlay handles still reaches subscribers that clear selection', (t) => {
+ const h = harness({
+ pick: () => ({ set: 'flights', id: 'abc123' }),
+ drillPick: () => [{ set: 'flights', id: 'abc123' }],
+ });
+ t.after(() => h.input.destroy());
+ let seenByOverlay = null;
+ h.input.onOverlayClick((event) => {
+ seenByOverlay = event;
+ return true;
+ });
+ const seen = [];
+ h.input.onClick((event) => {
+ seen.push({
+ same: event === seenByOverlay,
+ overlay: event.overlay,
+ topHit: event.topHit,
+ drawHit: event.drawHit,
+ hit: event.hit,
+ id: event.id,
+ ownerId: event.ownerId,
+ surface: event.surface,
+ drill: event.drill(4),
+ windowHit: event.windowHit(8, 8),
+ pick: event.pick,
+ });
+ });
+ h.click();
+ assert.deepEqual(seen, [
+ {
+ same: true,
+ overlay: true,
+ topHit: { set: '', id: null, surface: false },
+ drawHit: null,
+ hit: { set: '', id: null, surface: false },
+ id: null,
+ ownerId: null,
+ surface: false,
+ drill: [],
+ windowHit: { id: null, drawHit: null, surface: false },
+ pick: undefined,
+ },
+ ]);
+ assert.equal(h.calls.pick, 0, 'the geometry beneath is not picked');
+ assert.equal(h.calls.drillPick, 0);
+
+ // Without an overlay target the same click picks the geometry.
+ seen.length = 0;
+ h.input.destroy();
+ const g = harness({ pick: () => ({ set: 'flights', id: 'abc123' }) });
+ t.after(() => g.input.destroy());
+ g.input.onClick((event) => seen.push([event.overlay, event.topHit]));
+ g.click();
+ assert.equal(seen[0][0], false);
+ assert.equal(g.calls.pick, 1);
+});
+
test('the gesture carries summed travel and press time', (t) => {
const h = harness();
t.after(() => h.input.destroy());
diff --git a/src/input/testDoubles.mjs b/src/input/testDoubles.mjs
index 028e88e5fa..93c74b15a3 100644
--- a/src/input/testDoubles.mjs
+++ b/src/input/testDoubles.mjs
@@ -18,6 +18,8 @@ import { rendererOf } from '../render/rendererOf.js';
import { fakeScenePicks } from '../testSupport/fakeCesiumScene.mjs';
import { provideStyleStageAlias } from '../styles/styleStages.js';
import { inputFor } from './dispatcher.js';
+import { setClickCardHitTest } from '../data/pickRegistry.js';
+import { ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID } from '../layers/launches/policy.js';
/** Cesium's own event types, the ones the input port binds. */
export const FAKE_EVENT_TYPES = Cesium.ScreenSpaceEventType;
@@ -140,3 +142,40 @@ export function fakeInput(viewer, { now } = {}) {
destroy: () => input.destroy(),
};
}
+
+/** The Space Missions label {@link fakeInputUnderLabel} paints: an
+ * interactive entry of the missions' world-overlay source. */
+export const MISSION_LABEL = Object.freeze({
+ sourceId: ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
+ entryId: 'launch:L1',
+});
+
+/**
+ * `fakeInput` with a Space Missions label painted over the map: 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, and the pick registry names it as the card on top
+ * (`clickCard`), as the world-overlay host's hit test names an interactive
+ * mission label. `destroy` also clears that hit test.
+ * @param {object} viewer
+ * @param {{now?: () => number, beneath?: () => ({sourceId: string, entryId: string}|null)}} [options]
+ * `beneath`: the card painted under the label, on top when the label is
+ * not over the click.
+ */
+export function fakeInputUnderLabel(
+ viewer,
+ { beneath = () => null, ...options } = {},
+) {
+ const fake = fakeInput(viewer, options);
+ const label = { over: false };
+ fake.input.onOverlayClick(() => label.over);
+ setClickCardHitTest(() => (label.over ? MISSION_LABEL : beneath()));
+ return {
+ ...fake,
+ label,
+ destroy() {
+ setClickCardHitTest(null);
+ fake.destroy();
+ },
+ };
+}
diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js
index 72aa334c5c..4df9f28305 100644
--- a/src/layers/alpr/presentation.js
+++ b/src/layers/alpr/presentation.js
@@ -1,5 +1,6 @@
import { isFollowing } from '../../data/followed.js';
import { inputFor } from '../../input/dispatcher.js';
+import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import {
LAYER_ID,
@@ -581,6 +582,9 @@ export function createAlprPresentation({ state, services, source }) {
if (state.clickSubscription) return;
state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard(event)) return;
// The painted overlay answers first; the scene is picked only if not.
const hit = event.drawHit;
const id =
diff --git a/src/layers/alpr/presentation.test.mjs b/src/layers/alpr/presentation.test.mjs
new file mode 100644
index 0000000000..c74dfe802f
--- /dev/null
+++ b/src/layers/alpr/presentation.test.mjs
@@ -0,0 +1,176 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import * as Cesium from 'cesium';
+import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
+import { setClickCardHitTest } from '../../data/pickRegistry.js';
+import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
+import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
+import { createAlprMarkerSet } from './markerState.js';
+import { createAlprPresentation } from './presentation.js';
+
+/** One camera drawn and painted at (100, 100), over a viewer whose clicks a
+ * label may take. */
+function harness(t) {
+ const previousImage = globalThis.Image;
+ const project = Cesium.SceneTransforms.worldToWindowCoordinates;
+ globalThis.Image = class {
+ complete = true;
+ naturalWidth = 128;
+ };
+ Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 100, y: 100 });
+ const record = {
+ id: 'camera:0',
+ latitude: 30,
+ longitude: -97,
+ directionDeg: 90,
+ };
+ const drawPort = fakeDrawPort();
+ const markers = createAlprMarkerSet();
+ markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
+ const viewer = {
+ camera: {
+ positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500),
+ pickEllipsoid: () => Cesium.Cartesian3.fromDegrees(-97, 30),
+ },
+ scene: {
+ canvas: { clientWidth: 800, clientHeight: 600 },
+ globe: { show: true, getHeight: () => 150 },
+ pick: () => null,
+ },
+ };
+ const { unbind } = bindFakeCesiumScene(viewer, { draw: drawPort });
+ const fake = fakeInputUnderLabel(viewer);
+ const state = {
+ viewer,
+ enabled: true,
+ selectedId: null,
+ markers,
+ records: [record],
+ recordById: new Map([[record.id, record]]),
+ renderRevision: 0,
+ lastAnchorSampleAt: 0,
+ };
+ let selected = null;
+ let paint;
+ const presentation = createAlprPresentation({
+ state,
+ source: { label: 'Test cameras' },
+ services: {
+ render: { governorRequestRender() {} },
+ context: {
+ clearSelectedEntityContextForLayer() {
+ selected = null;
+ },
+ getSelectedEntityContext: () => selected,
+ registerEntityContext() {},
+ removeEntityContextsForLayer() {},
+ selectEntityContext(carrier) {
+ selected = { id: carrier.id, layerId: 'alpr-cameras' };
+ },
+ },
+ groundFloor: { cachedGroundFloor: () => 150 },
+ overlays: {
+ registerPaintLane(_lane, painter) {
+ paint = painter;
+ return { setActive() {}, requestPaint() {}, unregister() {} };
+ },
+ keyholeAlpha: () => 1,
+ },
+ },
+ });
+ presentation.initOverlay();
+ presentation.installInteraction(viewer);
+ t.after(() => {
+ presentation.destroyOverlay();
+ fake.destroy();
+ unbind();
+ if (previousImage === undefined) delete globalThis.Image;
+ else globalThis.Image = previousImage;
+ Cesium.SceneTransforms.worldToWindowCoordinates = project;
+ });
+ presentation.renderRecords();
+ const ctx = {
+ globalAlpha: 1,
+ save() {},
+ restore() {},
+ beginPath() {},
+ moveTo() {},
+ lineTo() {},
+ closePath() {},
+ stroke() {},
+ fill() {},
+ createLinearGradient: () => ({ addColorStop() {} }),
+ drawImage() {},
+ };
+ paint({ ctx, width: 800, height: 600 });
+ return { state, fake, at: { x: 100, y: 100 } };
+}
+
+test('a click on a mission label over a camera never selects it, and keeps the selected camera', (t) => {
+ const h = harness(t);
+ h.fake.label.over = true;
+ h.fake.click(h.at);
+ assert.equal(h.state.selectedId, null, 'the camera under the label');
+
+ // Off the label, the same click selects the camera.
+ h.fake.label.over = false;
+ h.fake.click(h.at);
+ assert.equal(h.state.selectedId, 'camera:0');
+
+ // The label on top is its own click: the selection stays.
+ h.fake.label.over = true;
+ h.fake.click(h.at);
+ assert.equal(h.state.selectedId, 'camera:0', 'the selection stays');
+});
+
+// The card or label painted on top takes the click: ALPR does not even pick
+// under another layer's card, so no camera is selected or released there.
+test("another layer's card over an ALPR camera keeps the click", (t) => {
+ let picks = 0;
+ const viewer = {
+ scene: {
+ canvas: new EventTarget(),
+ pick: () => {
+ picks++;
+ return null;
+ },
+ },
+ };
+ const input = fakeInput(viewer);
+ const noop = () => {};
+ const state = {
+ enabled: true,
+ viewer,
+ clickSubscription: null,
+ markers: { icons: null },
+ recordById: new Map(),
+ selectedId: null,
+ };
+ const presentation = createAlprPresentation({
+ state,
+ services: {
+ render: { governorRequestRender: noop },
+ context: {
+ clearSelectedEntityContextForLayer: noop,
+ getSelectedEntityContext: () => null,
+ registerEntityContext: noop,
+ removeEntityContextsForLayer: noop,
+ selectEntityContext: noop,
+ },
+ groundFloor: { cachedGroundFloor: () => null },
+ },
+ });
+ presentation.installInteraction(viewer);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => {
+ setClickCardHitTest(null);
+ state.clickSubscription?.();
+ input.destroy();
+ });
+ input.tap({ x: 10, y: 10 });
+ assert.equal(picks, 0, 'covered: the scene under the card is not picked');
+ top = null;
+ input.tap({ x: 10, y: 10 });
+ assert.ok(picks > 0, 'open map: the click reaches the scene');
+});
diff --git a/src/layers/bikeshare/selection.js b/src/layers/bikeshare/selection.js
index cb3a5bf315..b28ca4e3b1 100644
--- a/src/layers/bikeshare/selection.js
+++ b/src/layers/bikeshare/selection.js
@@ -1,5 +1,6 @@
import { t } from '../../i18n/index.js';
import { inputFor } from '../../input/dispatcher.js';
+import { isUnderOtherCard } from '../../data/pickRegistry.js';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
@@ -179,6 +180,9 @@ export function createSelection({
if (layerState._clickSubscription) return;
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard(event)) return;
const hit = event.drawHit;
if (hit) {
diff --git a/src/layers/bikeshare/selection.test.mjs b/src/layers/bikeshare/selection.test.mjs
new file mode 100644
index 0000000000..e75dc93050
--- /dev/null
+++ b/src/layers/bikeshare/selection.test.mjs
@@ -0,0 +1,68 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createSelection } from './selection.js';
+import { fakeInput } from '../../input/testDoubles.mjs';
+import { setClickCardHitTest } from '../../data/pickRegistry.js';
+
+/** A station layer's selection on a viewer whose pick is scripted. */
+function harness(t) {
+ const previousDocument = globalThis.document;
+ globalThis.document = new EventTarget();
+ let picked = null;
+ const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
+ const input = fakeInput(viewer);
+ const noop = () => {};
+ const state = {
+ _selectedKey: null,
+ _clickSubscription: null,
+ _stationRenderMap: new Map([['nyc:1', { position: { x: 1, y: 0, z: 0 } }]]),
+ _stationSet: { id: 'bikeshare:stations', upsert: noop },
+ _selectedSet: {
+ id: 'bikeshare:selected',
+ set: noop,
+ size: () => 0,
+ clear: noop,
+ },
+ _overlayHost: { setEntries: noop, clearSource: noop },
+ };
+ const selection = createSelection({
+ state,
+ services: {},
+ parts: { rendering: { stationItem: () => ({}) } },
+ });
+ selection._installClickHandler(viewer);
+ t.after(() => {
+ state._clickSubscription?.();
+ input.destroy();
+ if (previousDocument === undefined) delete globalThis.document;
+ else globalThis.document = previousDocument;
+ });
+ return {
+ state,
+ click(hit) {
+ picked = hit ? { id: hit } : null;
+ input.tap({ x: 10, y: 10 });
+ },
+ };
+}
+
+// The card or label painted on top takes the click: a station under another
+// layer's card is neither selected nor let go.
+test("another layer's card over a station keeps the click", (t) => {
+ const h = harness(t);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ const station = { set: 'bikeshare:stations', id: 'nyc:1' };
+ h.click(station);
+ assert.equal(h.state._selectedKey, null, 'covered: not selected');
+ top = null;
+ h.click(station);
+ assert.equal(h.state._selectedKey, 'nyc:1');
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ h.click(null);
+ assert.equal(h.state._selectedKey, 'nyc:1', 'covered: kept');
+ top = null;
+ h.click(null);
+ assert.equal(h.state._selectedKey, null, 'open map lets it go');
+});
diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js
index 233a2b38e7..e49b8a85bb 100644
--- a/src/layers/cctv/lifecycle.js
+++ b/src/layers/cctv/lifecycle.js
@@ -23,7 +23,7 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
- const { resolvePickId, registerPickOwner, unregisterPickOwner } =
+ const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -391,6 +391,20 @@ export function createLifecycle({
(event) => {
if (!layerState._enabled) return;
const picked = event.topHit;
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: a live card of ours acts whatever
+ // is drawn under it; another layer's is that layer's click.
+ const top = clickCard?.(event) ?? null;
+ if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
+ if (top) {
+ // A card of ours that is going away is still not the scene.
+ if (layerState._recordById.has(top.entryId))
+ activateCctvCameraFromWorldClick(
+ top.entryId,
+ parts.selection.setActiveCamera,
+ );
+ return;
+ }
const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
@@ -401,29 +415,11 @@ export function createLifecycle({
);
return;
}
- // Any identified scene object owns this click even if its layer does not
- // register a shared pick predicate. This keeps selectable siblings ahead
- // of an overlapping CCTV card while ID-less globe/terrain/tile surfaces
- // remain eligible for true empty-space deselection.
- const pickedId = resolvePickId(picked);
- if (pickedId !== null) return;
- // Item A (owner round 2): the scene pick found no camera — try the
- // painted ambient cards. The cards canvas is pointer-events:none (this
- // handler owns the events), so a click landing on a card's rect selects
- // its camera exactly like a click on the icon. Click positions
- // and the recorded rects are both CSS px — direct comparison.
- const cardId = layerState._cctvOverlayHost.hitTest(
- event.screenPosition.x,
- event.screenPosition.y,
- { sourceId: CCTV_OVERLAY_SOURCE_ID },
- )?.entryId;
- if (cardId && layerState._recordById.has(cardId)) {
- activateCctvCameraFromWorldClick(
- cardId,
- parts.selection.setActiveCamera,
- );
- return;
- }
+ // Any identified scene object owns this click even if its layer
+ // does not register a shared pick predicate. This keeps selectable
+ // siblings ahead of the CCTV selection while ID-less globe, terrain
+ // and tile surfaces remain eligible for empty-space deselection.
+ if (resolvePickId(picked) !== null) return;
if (
parts.selection.cctvEmptyClickDeselects(picked, {
activeCameraId: layerState._activeCameraId,
diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs
index 205997721b..d8c3a4d8e9 100644
--- a/src/layers/cctv/lifecycle.test.mjs
+++ b/src/layers/cctv/lifecycle.test.mjs
@@ -1,6 +1,10 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
+import { createSelection } from './selection.js';
+import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
+import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
+import * as picking from '../../data/pickRegistry.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
@@ -72,3 +76,265 @@ 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 on a mission label over a camera's card never turns that camera on, and keeps the active one", async (t) => {
+ const { viewer } = viewerWithCamera();
+ viewer.scene = { canvas: {}, pick: () => null };
+ // The card of camera `cam-1` lies under every click, under the label.
+ const fake = fakeInputUnderLabel(viewer, {
+ beneath: () => ({ sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }),
+ });
+ t.after(() => fake.destroy());
+ const activated = [];
+ const deactivated = [];
+ const state = {};
+ const lifecycle = createLifecycle({
+ state,
+ services: {
+ activation: {
+ activateCctvCameraFromWorldClick: (id) => activated.push(id),
+ },
+ picking,
+ 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) && picking.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', {});
+
+ fake.label.over = true;
+ fake.click();
+ assert.deepEqual(activated, [], 'the camera under the label stays off');
+ assert.deepEqual(deactivated, [], 'the active camera stays on');
+
+ // Off the label, a click on the card turns its camera on.
+ fake.label.over = false;
+ fake.click();
+ assert.deepEqual(activated, ['cam-1']);
+});
+
+test('the card painted on top takes world clicks, whatever is drawn under it', async (t) => {
+ const noop = () => {};
+ const { viewer } = viewerWithCamera();
+ let picked = null;
+ viewer.scene = {
+ canvas: {},
+ pick: () => (picked ? { id: picked } : undefined),
+ drillPick: () => drilled.map((id) => ({ id })),
+ };
+ let drilled = [];
+ const input = fakeInput(viewer);
+ // An aircraft layer that runs before ours and tracks the plane it was
+ // clicked on, standing aside under another layer's card.
+ let tracked = null;
+ input.input.onClick((event) => {
+ if (picking.isUnderOtherCard(event)) return;
+ if (event.hit?.id === 'plane:9') tracked = 'plane:9';
+ });
+ const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
+ const foreignCard = {
+ sourceId: 'earthquake-card',
+ entryId: 'earthquake-card:qa',
+ };
+ let painted = [];
+ const actions = [];
+ // The card on top at a click, as the host answers the pick registry.
+ picking.setClickCardHitTest(() => painted[0] ?? null);
+ const state = {
+ _cctvOverlayHost: {
+ hitTest: (_x, _y, options = {}) =>
+ painted.find(
+ (hit) => !options.sourceId || hit.sourceId === options.sourceId,
+ ) ?? null,
+ },
+ };
+ const parts = {
+ calibration: { loadCalibrationStore: () => new Map() },
+ catalog: {
+ loadCameraSources: async () => [],
+ buildCatalogFromSources: () => [],
+ seedCatalog: () => [],
+ },
+ ground: {
+ resolveGroundPriors: async () => [],
+ currentSurfaceRegime: () => 'terrain-globe',
+ },
+ cards: { teardownAmbientCards: noop },
+ projection: { clearProjectionOverlay: noop },
+ geometryQueue: { stopGeometryLoadQueue: noop },
+ rendering: {
+ createCameraIcons: noop,
+ refreshHorizonCulling: () => false,
+ refreshCoverageStyles: noop,
+ extractPickedCameraId: (hit) =>
+ hit?.set === 'cctv:fixture' ? hit.id : null,
+ },
+ hover: { handleHoverMove: noop },
+ health: { syncHealthState: async () => {} },
+ presentation: { notifyListeners: noop },
+ };
+ const services = {
+ sprites: {},
+ focus: { onFocusTargetAppear: () => noop },
+ render: { releaseContinuousRender: noop },
+ picking,
+ activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) },
+ };
+ parts.selection = createSelection({ state, services, parts });
+ parts.selection.deactivateActiveCamera = () => actions.push('clear');
+ const lifecycle = createLifecycle({ state, services, parts });
+ t.after(() => {
+ state._clickSubscription?.();
+ lifecycle.detachViewListeners();
+ input.destroy();
+ picking.setClickCardHitTest(null);
+ picking.unregisterPickOwner('area-control');
+ picking.unregisterPickOwner('test-trails');
+ picking.unregisterPickOwner('test-planes');
+ picking.unregisterPickOwner('test-tracking');
+ picking.unregisterPickOwner('test-exact');
+ });
+ await lifecycle.methods.init(viewer);
+ state._enabled = true;
+ state._activeCameraId = 'cam-1';
+ state._recordById.set('cam-1', { camera: { id: 'cam-1' } });
+ const click = (hit, cards, expected) => {
+ picked = hit;
+ painted = cards;
+ actions.length = 0;
+ input.tap();
+ assert.deepEqual(actions, expected, JSON.stringify({ hit, cards }));
+ };
+ const drone = {
+ set: 'drone-airspace:1:fills',
+ id: 'drone-airspace:zone:0',
+ surface: false,
+ };
+ const perimeter = {
+ set: 'fire-perimeters:1:lines',
+ id: 'fire-perimeter:incident:0',
+ surface: false,
+ };
+ const quake = { set: 'earthquakes:1', id: 'earthquake:q1', surface: false };
+ const cable = { set: 'submarine-cables:1:lines', id: 'c:0', surface: false };
+ const launch = {
+ set: 'launches:1:markers',
+ id: 'rocket-x:1',
+ surface: false,
+ };
+ const backgrounds = [drone, perimeter, quake, cable, launch];
+ for (const area of backgrounds) {
+ click(area, [ownCard], ['cam-1']);
+ click(area, [], []);
+ click(area, [foreignCard, ownCard], []);
+ }
+ // The live top card acts over anything drawn under it; with no card an
+ // identified object is not empty map.
+ for (const hit of [
+ { set: 'flights:1', id: 'aircraft', surface: false },
+ { set: '', id: 'unregistered-local-entity', surface: false },
+ { ...drone, set: 'unrelated:1:fills' },
+ { ...drone, id: 'unregistered-local-entity' },
+ ]) {
+ click(hit, [ownCard], ['cam-1']);
+ click(hit, [], []);
+ }
+ // A trail under the live top card: the card keeps the click, and with no
+ // card the owned pick is not empty map.
+ const trail = { set: 'trails:1', id: 'gev-trail:fl-1:head', surface: false };
+ picking.registerPickOwner('test-trails', (id) => id === trail.id);
+ click(trail, [ownCard], ['cam-1']);
+ click(trail, [], []);
+ click(trail, [foreignCard, ownCard], []);
+ picking.unregisterPickOwner('test-trails');
+ // A coarse tap whose touch contact is an aircraft (a layer that acts on
+ // nearby contacts) under a live CCTV card is the card's.
+ const previousMatch = globalThis.matchMedia;
+ const restoreMatch = () => {
+ if (previousMatch) globalThis.matchMedia = previousMatch;
+ else delete globalThis.matchMedia;
+ };
+ // Restored below for the fine-pointer clicks that follow; here too, so a
+ // failing assertion cannot leave the coarse pointer for later tests.
+ t.after(restoreMatch);
+ globalThis.matchMedia = () => ({ matches: true });
+ picking.registerPickOwner('test-planes', (id) => id === 'plane:1');
+ drilled = ['plane:1'];
+ click(null, [ownCard], ['cam-1']);
+ // With no card, the bare tap near the aircraft still deselects.
+ click(null, [], ['clear']);
+ // A contact whose layer acts only on exact hits leaves the card its tap.
+ picking.registerPickOwner('test-exact', (id) => id === 'exact:1');
+ drilled = ['exact:1'];
+ click(null, [ownCard], ['cam-1']);
+ picking.unregisterPickOwner('test-exact');
+ drilled = [];
+ click(null, [ownCard], ['cam-1']);
+ picking.unregisterPickOwner('test-planes');
+ restoreMatch();
+ // The live card over an aircraft takes the click; the aircraft layer,
+ // run first, stands aside and does not track.
+ picking.registerPickOwner('test-tracking', (id) => id === 'plane:9');
+ click(
+ { set: 'flights:1', id: 'plane:9', surface: false },
+ [ownCard],
+ ['cam-1'],
+ );
+ assert.equal(tracked, null, 'the aircraft did not track');
+ picking.unregisterPickOwner('test-tracking');
+ picking.registerPickOwner('area-control', (id) => id === drone.id);
+ click(drone, [ownCard], ['cam-1']);
+ picking.unregisterPickOwner('area-control');
+ click(null, [foreignCard, ownCard], []);
+ click(null, [ownCard], ['cam-1']);
+ click(null, [], ['clear']);
+ click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
+ // A card of ours that is going away is still not the scene under it: no
+ // camera beneath it activates, and nothing clears.
+ const staleCard = { ...ownCard, entryId: 'stale-camera' };
+ click({ set: 'cctv:fixture', id: 'cam-1' }, [staleCard], []);
+ click(null, [staleCard], []);
+ // A camera icon under another layer's card is that card's click.
+ click({ set: 'cctv:fixture', id: 'cam-1' }, [foreignCard, ownCard], []);
+ click({ set: 'cctv:fixture', id: 'cam-1' }, [], ['cam-1']);
+});
diff --git a/src/layers/cyclones/index.js b/src/layers/cyclones/index.js
index 02c3b5cad3..1d81f94274 100644
--- a/src/layers/cyclones/index.js
+++ b/src/layers/cyclones/index.js
@@ -1,7 +1,6 @@
-import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
-import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { inputFor } from '../../input/dispatcher.js';
import {
+ clickCard,
registerPickOwner,
unregisterPickOwner,
} from '../../data/pickRegistry.js';
@@ -79,7 +78,6 @@ const intensityText = (storm) => {
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
export function createCyclonesLayer({
feed,
- hitTestOverlay = hitTestWorldOverlay,
overlayHost,
context = null,
createRendering = createCycloneRendering,
@@ -97,8 +95,7 @@ export function createCyclonesLayer({
selectionIntent = 'auto',
navigationGeneration = 0,
selectionOwner = null,
- selectedContextStormId = null,
- removeClickCapture = null;
+ selectedContextStormId = null;
let enabled = false,
loading = false,
error = null,
@@ -169,75 +166,28 @@ export function createCyclonesLayer({
rendering?.setSelection(id);
}
function installSelection() {
- const canvas = canvasOf(viewer);
- if (selectionOwner || !canvas) return;
+ if (selectionOwner || !canvasOf(viewer)) return;
const owner = {};
selectionOwner = owner;
- // Snapshot before sibling bubble listeners can rebuild the overlay hit
- // rectangles. A vessel selection does that synchronously in the same click.
- let capturedHit = null;
- const overlayHit = (x, y) => {
- const hit = hitTestOverlay(x, y);
- return { sourceId: hit?.sourceId, entryId: hit?.entryId };
- };
- const capture = (event) => {
- capturedHit = null;
- const point = event.changedTouches?.[0] || event;
- if (!Number.isFinite(point.clientX) || !Number.isFinite(point.clientY))
- return;
- const rect = canvas.getBoundingClientRect();
- const x = point.clientX - rect.left,
- y = point.clientY - rect.top;
- capturedHit = { x, y, ...overlayHit(x, y) };
- };
- const resetCapture = () => {
- capturedHit = null;
- };
- const resetEvents = [
- 'pointerdown',
- 'mousedown',
- 'touchstart',
- 'pointercancel',
- 'touchcancel',
- ];
- for (const type of resetEvents)
- canvas.addEventListener?.(type, resetCapture, { capture: true });
- const events = ['pointerup', 'mouseup', 'touchend'];
- for (const type of events)
- canvas.addEventListener?.(type, capture, { capture: true });
- removeClickCapture = () => {
- for (const type of events)
- canvas.removeEventListener?.(type, capture, { capture: true });
- for (const type of resetEvents)
- canvas.removeEventListener?.(type, resetCapture, { capture: true });
- capturedHit = null;
- };
const unsubscribe = inputFor(viewer).onClick((event) => {
- const nativeHit = capturedHit;
- capturedHit = null;
// Ambient selection yields to draw tools and Director (the dispatcher
// skips a held pointer); it never claims the pointer, camera, or
// tracking state.
const position = event.screenPosition;
if (!enabled || destroyed || selectionOwner !== owner || !position)
return;
- // AIS cards paint above the globe on a pointer-events:none canvas. The
- // vessel handler resolves this same topmost hit before cyclone geometry.
- const captureMatches =
- nativeHit &&
- Math.abs(nativeHit.x - position.x) < 1 &&
- Math.abs(nativeHit.y - position.y) < 1;
- const hit = captureMatches
- ? nativeHit
- : overlayHit(position.x, position.y);
- if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
+ // The card or label painted on top, as it was when the click landed.
+ const card = clickCard(event);
// Storm cards and lead-hour labels paint on the same canvas; a click on
// one selects its storm. An id from a superseded advisory changes nothing.
- if (hit.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
- const id = cycloneStormIdFromEntryId(hit.entryId);
+ if (card?.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
+ const id = cycloneStormIdFromEntryId(card.entryId);
if (id) layer.setParams({ stormId: id });
return;
}
+ // Another layer's card on top takes the click: the storm under it does
+ // not act, and the click is not empty map either.
+ if (card) return;
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
// clears the selection.
const id = rendering?.pickStorm(event.drawHit);
@@ -249,8 +199,6 @@ export function createCyclonesLayer({
function removeSelection() {
const owner = selectionOwner;
selectionOwner = null;
- removeClickCapture?.();
- removeClickCapture = null;
owner?.unsubscribe?.();
}
const layer = {
diff --git a/src/layers/cyclones/index.test.mjs b/src/layers/cyclones/index.test.mjs
index a053531dc8..c6b64a6e1e 100644
--- a/src/layers/cyclones/index.test.mjs
+++ b/src/layers/cyclones/index.test.mjs
@@ -6,7 +6,10 @@ import {
releasePointer,
isPointerFree,
} from '../../data/inputOwnership.js';
-import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
+import {
+ isOwnedByOtherLayer,
+ setClickCardHitTest,
+} from '../../data/pickRegistry.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
@@ -77,7 +80,7 @@ const deferred = () => {
return { promise, resolve };
};
-test('map selection yields to pointer owners and owns only its enabled handler', async () => {
+test('map selection yields to pointer owners and owns only its enabled handler', async (t) => {
const handlers = [],
// A pick of an item in one of the layer's draw sets, and one of another
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
@@ -109,11 +112,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
createRendering: () => rendering,
- hitTestOverlay: () => {
- overlayTests++;
- return overlayHit;
- },
});
+ setClickCardHitTest(() => {
+ overlayTests++;
+ return overlayHit;
+ });
+ t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
const viewer = {
@@ -180,41 +184,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
'foreground AIS card wins before scene picking',
);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
- // A native capture runs before an earlier sibling handler clears hit rects.
- const up = new Event('pointerup');
- Object.assign(up, { clientX: 110, clientY: 220 });
- canvas.dispatchEvent(up);
- overlayHit = null;
+ // Any other layer's card on top takes the click, not only a vessel's.
+ overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
handlers[0].click(click);
assert.equal(
layer.getDiagnostics().selectedId,
'ep152026',
- 'captured AIS hit survives synchronous sibling overlay rebuild',
+ 'a camera card over the storm keeps the click',
);
- // A captured background hit remains background even if a sibling adds a card.
- canvas.dispatchEvent(up);
- overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
- handlers[0].click(click);
- assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
- layer.setParams({ stormId: 'ep152026' });
- // A new gesture clears an unconsumed release snapshot.
- canvas.dispatchEvent(up);
- canvas.dispatchEvent(new Event('pointerdown'));
overlayHit = null;
- handlers[0].click(click);
- assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
- layer.setParams({ stormId: 'ep152026' });
- overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
- canvas.dispatchEvent(up);
- overlayHit = null;
- handlers[0].click({ position: { x: 15, y: 25 } });
- assert.equal(
- layer.getDiagnostics().selectedId,
- 'ep162026',
- 'a different click cannot reuse the captured card',
- );
- layer.setParams({ stormId: 'ep152026' });
- overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
const before = notices;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
@@ -264,13 +242,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
assert.equal(layer.getDiagnostics().selectionActive, false);
const afterDisable = picks;
const afterDisableOverlay = overlayTests;
- canvas.dispatchEvent(up);
+ handlers[0].click(click);
assert.equal(
overlayTests,
afterDisableOverlay,
- 'disable removes native capture listeners',
+ 'a disabled layer reads no card',
);
- handlers[0].click(click);
assert.equal(picks, afterDisable, 'queued disabled callback is inert');
layer.enable();
await layer.update();
@@ -289,7 +266,7 @@ test('map selection yields to pointer owners and owns only its enabled handler',
);
assert.equal(handlers[1].destroyed, true);
});
-test('a click on a storm card or lead-hour label selects that storm without picking', async () => {
+test('a click on a storm card or lead-hour label selects that storm without picking', async (t) => {
const handlers = [];
let picks = 0,
overlayHit = null,
@@ -309,8 +286,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
getDiagnostics: () => ({}),
};
},
- hitTestOverlay: () => overlayHit,
});
+ setClickCardHitTest(() => overlayHit);
+ t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
const viewer = {
@@ -343,15 +321,11 @@ test('a click on a storm card or lead-hour label selects that storm without pick
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:al019999' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
- // The native release snapshot carries the card identity too.
- const up = new Event('pointerup');
- Object.assign(up, { clientX: 10, clientY: 20 });
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:ep162026' };
- canvas.dispatchEvent(up);
- overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
assert.equal(picks, 0, 'card clicks never fall through to the scene');
+ overlayHit = null;
handlers[0].click(click);
assert.equal(picks, 1);
assert.equal(layer.getDiagnostics().selectedId, null, 'empty map clears');
diff --git a/src/layers/directions/index.js b/src/layers/directions/index.js
index 54ec30c095..53a68aa720 100644
--- a/src/layers/directions/index.js
+++ b/src/layers/directions/index.js
@@ -1584,6 +1584,9 @@ export function createDirectionsLayer({ services, source }) {
// yields the moment a tool (this one included) owns the click.
const offSelect = input.onClick((event) => {
if (!_enabled) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (services.picking?.isUnderOtherCard?.(event)) return;
let hit = null;
try {
hit = event.drawHit;
diff --git a/src/layers/droneAirspace/index.js b/src/layers/droneAirspace/index.js
index 8bb8b72423..b83ccdaaf1 100644
--- a/src/layers/droneAirspace/index.js
+++ b/src/layers/droneAirspace/index.js
@@ -130,12 +130,11 @@ 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 },
- );
- if (cardHit && cardHit.entryId === _selectedCardId) return;
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: this area's shapes are background to
+ // another layer's card or label painted over them, and a click on our
+ // own card leaves the selection as it is.
+ if (picking.clickCard?.(event)) return;
const picked = event.topHit;
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
if (zoneId) {
diff --git a/src/layers/droneAirspace/ownership.test.mjs b/src/layers/droneAirspace/ownership.test.mjs
index 3dbb16a583..2a40e510f0 100644
--- a/src/layers/droneAirspace/ownership.test.mjs
+++ b/src/layers/droneAirspace/ownership.test.mjs
@@ -2,7 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createDroneAirspaceLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
-import { fakeInput } from '../../input/testDoubles.mjs';
+import { clickCard } from '../../data/pickRegistry.js';
+import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
// The fills set of the layer the last harness made: zone picks name it.
@@ -19,11 +20,12 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
const owners = new Map();
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
- const input = fakeInput(viewer);
+ const input = fakeInputUnderLabel(viewer);
const clicks = {
handler: (click) => input.click(click.position),
+ // Only the label's own overlay handler is left.
get destroyed() {
- return input.input.subscriberCount() === 0 ? 1 : 0;
+ return input.input.subscriberCount() === 1 ? 1 : 0;
},
};
const layer = createDroneAirspaceLayer({
@@ -47,6 +49,11 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
+ // The card on top at a click, as the registry answers from the host.
+ // A mission label painted over everything comes first.
+ clickCard: (click) =>
+ clickCard(click) ??
+ cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
});
layer.init(viewer);
@@ -61,6 +68,8 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
overlay,
clicks,
owners,
+ /** A label painted over the map: while `over`, it takes each click. */
+ label: input.label,
};
}
@@ -143,6 +152,86 @@ test('clicking a zone publishes its card; empty space clears it', async () => {
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
});
+test('a click on a mission label over the open zone card keeps it open and takes no zone beneath', async () => {
+ let pickResult = null;
+ let cardHitResult = null;
+ const h = harness(
+ { getSnapshot: async () => [row] },
+ { pick: () => pickResult, cardHit: () => cardHitResult },
+ );
+ await h.layer.update(h.viewer);
+ pickResult = zonePick('drone-airspace:310:0');
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ const [card] = h.overlay.entries.get('drone-airspace');
+
+ // The open card and its zone lie under the label: the label on top is
+ // its own click, so the card stays open.
+ cardHitResult = { sourceId: 'drone-airspace', entryId: card.id };
+ h.label.over = true;
+ h.clicks.handler({ position: { x: 12, y: 12 } });
+ assert.equal(h.overlay.entries.get('drone-airspace')?.[0]?.id, card.id);
+ pickResult = null;
+ cardHitResult = null;
+ h.clicks.handler({ position: { x: 12, y: 12 } });
+ assert.equal(
+ h.overlay.entries.get('drone-airspace')?.[0]?.id,
+ card.id,
+ 'a label over bare map is not empty space either',
+ );
+
+ // Off the label, the same click on bare map closes the card.
+ h.label.over = false;
+ h.clicks.handler({ position: { x: 12, y: 12 } });
+ assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
+ h.layer.destroy();
+});
+
+// Another layer's card or label painted over the area (a quake's card or
+// magnitude label) is that layer's click: the area under it stands aside.
+test("another layer's overlay on top keeps a click off the area", async () => {
+ let pickResult = null;
+ let foreignOnTop = false;
+ const h = harness(
+ { getSnapshot: async () => [row] },
+ {
+ pick: () => pickResult,
+ // Unfiltered: the topmost entry of any source.
+ // As the host does: drone-airspace cards are not interactive, so only
+ // another layer's card painted on top is ever hit.
+ cardHit: (_x, _y, options) =>
+ foreignOnTop && !options?.sourceId
+ ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }
+ : null,
+ },
+ );
+ await h.layer.update(h.viewer);
+ pickResult = zonePick('drone-airspace:310:0');
+ foreignOnTop = true;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
+ // With nothing painted over it, the same click selects the area.
+ foreignOnTop = false;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(
+ h.overlay.entries.get('drone-airspace')[0].id,
+ 'drone-airspace-card:310',
+ );
+ // An overlay on top covers the selected area's card.
+ foreignOnTop = true;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(
+ h.overlay.entries.get('drone-airspace')[0].id,
+ 'drone-airspace-card:310',
+ );
+ pickResult = null;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(
+ h.overlay.entries.get('drone-airspace')[0].id,
+ 'drone-airspace-card:310',
+ 'the foreground overlay preserves selection over bare map too',
+ );
+});
+
test('late refresh cannot publish after disable or destroy', async () => {
for (const action of ['disable', 'destroy']) {
let resolve, signal;
diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js
index 90d70e9a90..c513011334 100644
--- a/src/layers/earthquakes/index.js
+++ b/src/layers/earthquakes/index.js
@@ -1,6 +1,10 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
+import {
+ isTrackingClickGesture,
+ isTrackingSelectionGesture,
+} from '../../data/trackingClickGesture.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
@@ -11,6 +15,11 @@ import {
selectEarthquakeOverlayCohort,
mapAnalystRecord,
earthquakeCoverage,
+ earthquakeMarkLabel,
+ earthquakeMagnitudeTitle,
+ earthquakeZoomLabel,
+ earthquakeDiscRadiusM,
+ describeEarthquake,
} from './model.js';
export * from './model.js';
export { createUsgsEarthquakeSource } from './source.js';
@@ -25,6 +34,20 @@ const msg = (text) => text;
* as `Hit.set`.
*/
export const EARTHQUAKE_DISC_SET_ID = 'earthquakes';
+export const EARTHQUAKES_LAYER_ID = 'earthquakes';
+/** The overlay source the clicked quake's detail card is shown in. */
+export const EARTHQUAKE_CARD_SOURCE_ID = 'earthquake-card';
+/** A disc's item id is this prefix and the event's stable id. */
+const PICK_PREFIX = 'earthquake:';
+/** Fly-to range per metre of disc radius: 220 km frames an M6 (64 km). */
+const EARTHQUAKE_FOCUS_RANGE_PER_RADIUS = 3.5;
+/** The selected quake's flat fill, faint under the painted gradient. */
+const SELECTED_DISC_ALPHA = 0.04;
+const CARD_HOST_OPTIONS = Object.freeze({
+ cohortLimit: 1,
+ collisionCapacity: 1,
+ moving: false,
+});
let instances = 0;
/**
@@ -33,8 +56,48 @@ let instances = 0;
* The discs are one renderer draw set (`drawOf(viewer)`), made at `init`.
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
+ *
+ * Clicking a disc shows that quake's detail card and selects it in the
+ * shared context. The application gives the click and selection services;
+ * without `input` and `picking` the discs are drawn but take no clicks.
+ * @param {object} options
+ * @param {object} options.source Snapshot source.
+ * @param {object} options.overlayHost World-overlay host.
+ * @param {(viewer: object) => {onClick: Function}} [options.input] The
+ * viewer's click dispatcher.
+ * @param {{resolvePickId: Function, isOwnedByOtherLayer: Function,
+ * clickCard?: Function}} [options.picking] The pick
+ * registry; `clickCard` names the card or label painted on top of a
+ * click, which takes it (the quake card and labels need it to act).
+ * @param {{registerEntityContext: Function, selectEntityContext: Function,
+ * clearSelectedEntityContextForLayer: Function,
+ * getContextStore: Function}} [options.context] Shared selection store.
+ * @param {{isPointerFree: () => boolean}} [options.pointer]
+ * @param {(url: string) => void} [options.openExternal]
+ * @param {{requestWorldFocus: (detail: object) => boolean}} [options.focus]
+ * The camera transfer a clicked magnitude label asks for.
+ * @param {{show: (target: {id: string, lon: number, lat: number,
+ * heightM?: number, heightAt?: () => number|null, radiusM: number,
+ * color: string}) => void, hide: () => void}} [options.ripples]
+ * The selected quake's animated contour rings.
+ * @param {(viewer: object, lon: number, lat: number) => number|null} [options.groundHeight]
+ * The loaded ground height under a point, so the rings sit on the disc
+ * that is draped there; null (or no service) draws them at sea level.
+ * @param {object} [options.text] Card formatters (see describeEarthquake).
*/
-export function createEarthquakesLayer({ source, overlayHost } = {}) {
+export function createEarthquakesLayer({
+ source,
+ overlayHost,
+ input = null,
+ picking = null,
+ context = null,
+ pointer = null,
+ openExternal = null,
+ focus = null,
+ ripples = null,
+ groundHeight = null,
+ text = undefined,
+} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Earthquakes require a snapshot source');
if (!overlayHost) throw new TypeError('Earthquakes require an overlay host');
@@ -60,6 +123,307 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_marksKey = key;
worldClock.coverageChanged();
};
+ // The drawn events by stable id, for clicks; the selected one's id, card
+ // and the context record it was published as.
+ let _eventById = new Map();
+ let _selectedId = null;
+ let _selectedCardId = null;
+ let _selectedLink = null;
+ let _contextId = null;
+ let _clickHandler = null;
+ const canSelect = () => Boolean(input && picking);
+ // The disc whose flat fill is faded while the painter draws its gradient.
+ let _fadedDiscId = null;
+
+ /**
+ * A quake's disc: filled 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. A selected
+ * quake's disc is all but clear: the ripples painter fills it with a
+ * gradient instead, and the faint fill keeps it pickable.
+ */
+ function discItem(event, faded = false) {
+ const radius = earthquakeDiscRadiusM(event.mag);
+ const [r, g, b] = depthColor(event.depthKm || 0);
+ const fillAlpha = faded
+ ? SELECTED_DISC_ALPHA
+ : event.mag >= 5.0
+ ? 0.4
+ : 0.3;
+ return {
+ id: `${PICK_PREFIX}${event.stableId}`,
+ geometry: {
+ kind: 'ellipse',
+ center: { lon: event.lon, lat: event.lat },
+ semiMajor: radius,
+ semiMinor: radius,
+ },
+ fill: [r, g, b, fillAlpha],
+ height: 'clampGround',
+ clampTo: 'both',
+ };
+ }
+
+ /** Fade one disc's flat fill (and restore the one faded before). */
+ function fadeDisc(stableId) {
+ if (!ripples || !_discs || _fadedDiscId === stableId) return;
+ const changed = [];
+ const before = _eventById.get(_fadedDiscId);
+ if (before) changed.push(discItem(before, false));
+ const next = _eventById.get(stableId);
+ if (next) changed.push(discItem(next, true));
+ _fadedDiscId = next ? stableId : null;
+ if (changed.length) _discs.upsert(changed);
+ }
+
+ /** The drawn event a pick id names, or null. */
+ function eventOfPickId(pickId) {
+ if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
+ return null;
+ return _eventById.get(pickId.slice(PICK_PREFIX.length)) ?? null;
+ }
+
+ /** The drawn event a click's draw hit is on: an item of this layer's set. */
+ function pickedEvent(hit) {
+ if (!hit || hit.surface || !_discs || hit.set !== _discs.id) return null;
+ return eventOfPickId(hit.id);
+ }
+
+ /**
+ * Show the selected quake's card, context and contours. `user`: a click or
+ * a label's activation, which claims the shared selection and runs the
+ * contours again; a feed refresh only brings them up to date, so it never
+ * takes back a selection made since, nor restarts the animation.
+ */
+ function publishCard({ user = false } = {}) {
+ const event = _selectedId ? _eventById.get(_selectedId) : null;
+ if (!_enabled || !event) {
+ // A refresh that no longer carries the selected quake evicts it, as
+ // other feeds report; anything else is a deliberate clear.
+ clearSelection({ evicted: _enabled && Boolean(_selectedId) && !user });
+ return;
+ }
+ const { title, details, link, accessibilityLabel } = describeEarthquake(
+ event,
+ { ...text, canOpen: Boolean(openExternal) },
+ );
+ _selectedLink = link && openExternal ? link : null;
+ const card = {
+ id: `earthquake-card:${event.stableId}`,
+ selected: true,
+ // Always hit-testable (the host only hit-tests interactive entries),
+ // so a click on a card with no link keeps it rather than falling
+ // through to the ground under it and clearing the selection.
+ interactive: true,
+ title,
+ details,
+ accent: depthAccent(event.depthKm || 0),
+ priority: Number.MAX_SAFE_INTEGER,
+ gapPx: 15,
+ verticalOnly: true,
+ placement: 'above',
+ stateless: true,
+ horizonCull: true,
+ position: fromDegrees(event.lon, event.lat),
+ };
+ if (_selectedLink) {
+ const target = _selectedLink;
+ card.accessibilityLabel = accessibilityLabel;
+ card.activate = () => {
+ openExternal(target);
+ return true;
+ };
+ } else if (focus?.requestWorldFocus) {
+ // No source to open: the card's keyboard action flies to its quake,
+ // as a fire card's focuses its fire, so it stays in the action list.
+ const stableId = event.stableId;
+ card.accessibilityLabel = accessibilityLabel;
+ card.activate = () => selectAndFocus(stableId);
+ }
+ _selectedCardId = card.id;
+ overlayHost.setEntries(
+ EARTHQUAKE_CARD_SOURCE_ID,
+ [card],
+ CARD_HOST_OPTIONS,
+ );
+ overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, true);
+ publishContext(event, user);
+ fadeDisc(event.stableId);
+ let heightM = null;
+ try {
+ heightM = groundHeight?.(_viewer, event.lon, event.lat) ?? null;
+ } catch {
+ heightM = null;
+ }
+ ripples?.show?.(
+ {
+ id: event.stableId,
+ lon: event.lon,
+ lat: event.lat,
+ heightM: Number.isFinite(heightM) ? heightM : 0,
+ // Read again as the ground loads: a label's fly-to starts far away.
+ heightAt: groundHeight
+ ? () => groundHeight(_viewer, event.lon, event.lat)
+ : null,
+ radiusM: earthquakeDiscRadiusM(event.mag),
+ color: depthAccent(event.depthKm || 0),
+ },
+ { restart: user },
+ );
+ }
+
+ /**
+ * Select the event in the shared context store, so "what's selected"
+ * (voice, the Cockpit) answers with it, as a clicked fire does.
+ */
+ function publishContext(event, select) {
+ if (!context) return;
+ const id = `${PICK_PREFIX}${event.stableId}`;
+ try {
+ if (_contextId && _contextId !== id)
+ context.getContextStore().entities.delete(_contextId);
+ const carrier = { show: true };
+ context.registerEntityContext(carrier, {
+ id,
+ layerId: EARTHQUAKES_LAYER_ID,
+ layerName: layer.name,
+ source: 'USGS',
+ // Hidden with the layer: the context store reads its `show`.
+ dataSource: _discs,
+ targetPosition: fromDegrees(event.lon, event.lat),
+ // i18n-ignore: English entity label, as the analyst records are
+ label: `Earthquake · ${earthquakeMarkLabel(event)}`,
+ latitude: event.lat,
+ longitude: event.lon,
+ properties: {
+ magnitude: event.mag,
+ depthKm: event.depthKm ?? null,
+ place: event.place ?? null,
+ time: Number.isFinite(event.time)
+ ? new Date(event.time).toISOString()
+ : null,
+ usgsId: event.usgsId ?? null,
+ },
+ });
+ _contextId = id;
+ if (select) context.selectEntityContext(carrier);
+ } catch {
+ // No context store (no window): the card still shows.
+ }
+ }
+
+ function clearContext({ evicted = false } = {}) {
+ if (!context || !_contextId) return;
+ try {
+ context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID, {
+ evicted,
+ });
+ context.getContextStore().entities.delete(_contextId);
+ } catch {
+ // store unavailable: nothing to clean
+ }
+ _contextId = null;
+ }
+
+ function clearSelection({ evicted = false } = {}) {
+ const had = _selectedId || _selectedCardId;
+ _selectedId = null;
+ _selectedCardId = null;
+ _selectedLink = null;
+ clearContext({ evicted });
+ ripples?.hide?.();
+ fadeDisc(null);
+ if (had)
+ overlayHost.setEntries(EARTHQUAKE_CARD_SOURCE_ID, [], CARD_HOST_OPTIONS);
+ }
+
+ function installClickHandler() {
+ if (!canSelect() || _clickHandler || !_viewer) return;
+ // Deliberately NOT registered in the pick-ownership registry, like drone
+ // airspace and fire perimeters: siblings yield to owned picks before
+ // their own card hit-tests and treat an owned pick as not empty space,
+ // so claiming these large discs would make their cards inert and their
+ // selections stick anywhere over a quake. Unowned, a disc reads as
+ // empty space to them; this handler finds its own discs by draw set.
+ // A viewer with no renderer input bound takes no clicks.
+ let clicks = null;
+ try {
+ clicks = input(_viewer) ?? null;
+ } catch {
+ clicks = null;
+ }
+ if (!clicks) return;
+ _clickHandler = clicks.onClick((click) => {
+ if (!_enabled || (pointer && !pointer.isPointerFree())) return;
+ // A pan that ends near where it began still raises a click. As for the
+ // tracking layers and Context, a press that travelled is a drag, not a
+ // pick; opening the source and clearing also need a short press.
+ if (!isTrackingSelectionGesture(click.gesture)) return;
+ const clean = isTrackingClickGesture(click.gesture);
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: another layer's is that layer's click
+ // (the disc under it is background), and ours acts whatever is drawn
+ // under it.
+ const top = picking.clickCard?.(click) ?? null;
+ if (top?.sourceId === EARTHQUAKE_CARD_SOURCE_ID) {
+ // The card's action, as its keyboard action: open the source, or
+ // with none, fly to the quake.
+ if (top.entryId !== _selectedCardId) return;
+ if (_selectedLink) {
+ if (clean) openExternal(_selectedLink);
+ } else if (focus?.requestWorldFocus && _selectedId)
+ selectAndFocus(_selectedId);
+ return;
+ }
+ // A magnitude label is what a far view (the whole globe) can click:
+ // it selects the quake and flies to it.
+ if (top?.sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) {
+ if (_eventById.has(top.entryId)) selectAndFocus(top.entryId);
+ return;
+ }
+ if (top) return;
+ // Another layer's pick (an aircraft, a camera, a flight trail) is not
+ // empty space and not this layer's: leave the selection alone.
+ const hit = click.hit;
+ const pickId = picking.resolvePickId(hit);
+ if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
+ return;
+ const event = pickedEvent(hit);
+ if (event) {
+ _selectedId = event.stableId;
+ publishCard({ user: true });
+ return;
+ }
+ if (clean) clearSelection();
+ });
+ }
+
+ /** Select a drawn quake, show its card, and ask the camera to go there. */
+ function selectAndFocus(stableId) {
+ const event = _eventById.get(stableId);
+ if (!_enabled || !event) return false;
+ _selectedId = stableId;
+ publishCard({ user: true });
+ focus?.requestWorldFocus?.({
+ kind: 'earthquake',
+ id: `${PICK_PREFIX}${stableId}`,
+ label: earthquakeMagnitudeTitle(event.mag),
+ position: fromDegrees(event.lon, event.lat),
+ // The whole disc in view: the framing's range fits an M6 disc, so only
+ // a larger one asks for its own range (the framing stays the floor).
+ radiusM: earthquakeDiscRadiusM(event.mag),
+ rangeM:
+ event.mag > 6
+ ? earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS
+ : undefined,
+ });
+ return true;
+ }
+
+ function removeClickHandler() {
+ _clickHandler?.();
+ _clickHandler = null;
+ }
const layer = {
id: 'earthquakes',
@@ -93,6 +457,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
// layer has no per-frame animator to keep the render loop alive for.
if (_discs) _discs.show = true;
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
+ installClickHandler();
coverageChanged();
},
@@ -101,6 +466,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_request = null;
_enabled = false;
if (_discs) _discs.show = false;
+ removeClickHandler();
+ clearSelection();
+ overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID);
+ overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false);
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
coverageChanged();
@@ -132,41 +501,52 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
time,
} of rows) {
count++;
- const baseRadius = Math.pow(2, mag) * 1000;
- const color = depthColor(depthKm || 0);
- const [r, g, b] = color;
- const isSignificant = mag >= 5.0;
- const fillAlpha = isSignificant ? 0.4 : 0.3;
-
const position = fromDegrees(lon, lat);
- nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat });
- // 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.
- nextDiscs.push({
- id: `earthquake:${stableId}`,
- geometry: {
- kind: 'ellipse',
- center: { lon, lat },
- semiMajor: baseRadius,
- semiMinor: baseRadius,
- },
- fill: [r, g, b, fillAlpha],
- height: 'clampGround',
- clampTo: 'both',
- });
- overlayEntries.push(
- createEarthquakeOverlayEntry({
- id: String(stableId),
- position,
- magnitude: mag,
- accent: depthAccent(depthKm || 0),
- }),
+ const event = {
+ stableId: String(stableId),
+ usgsId,
+ mag,
+ place,
+ time,
+ depthKm,
+ lon,
+ lat,
+ };
+ nextEvents.push(event);
+ nextDiscs.push(
+ discItem(event, Boolean(ripples) && event.stableId === _selectedId),
);
+ const label = createEarthquakeOverlayEntry({
+ id: String(stableId),
+ position,
+ magnitude: mag,
+ accent: depthAccent(depthKm || 0),
+ });
+ if (canSelect()) {
+ const id = String(stableId);
+ label.interactive = true;
+ label.accessibilityLabel = earthquakeZoomLabel(
+ { mag, place },
+ text,
+ );
+ label.activate = () => selectAndFocus(id);
+ }
+ overlayEntries.push(label);
}
+ // Bigger quakes first, so a small quake inside a big one's disc is
+ // drawn, and picked, on top of it.
+ nextDiscs.sort((a, b) => b.geometry.semiMajor - a.geometry.semiMajor);
_discs.set(nextDiscs);
_events = nextEvents;
+ _eventById = new Map(
+ nextEvents.map((event) => [event.stableId, event]),
+ );
+ _fadedDiscId =
+ ripples && _eventById.has(_selectedId) ? _selectedId : null;
+ // A selected quake still in the feed keeps its card, refreshed; one
+ // that left the 24 h window loses it.
+ if (_selectedId) publishCard();
coverageChanged();
if (_enabled) {
overlayHost.setEntries(
@@ -199,13 +579,19 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
destroy(viewer = _viewer) {
_request?.abort();
_request = null;
+ removeClickHandler();
+ clearSelection();
+ ripples?.dispose?.();
_viewer = null;
_enabled = false;
+ overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID);
+ overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false);
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
_discs?.dispose();
_discs = null;
_events = [];
+ _eventById = new Map();
_uncover?.();
_uncover = null;
_marksKey = null;
diff --git a/src/layers/earthquakes/model.js b/src/layers/earthquakes/model.js
index 25570e7243..4e0abaf107 100644
--- a/src/layers/earthquakes/model.js
+++ b/src/layers/earthquakes/model.js
@@ -23,6 +23,12 @@ export const EARTHQUAKE_MARK_MAGNITUDE = 6;
/** The longest place a timeline mark's label carries, ellipsis and all. */
const MARK_PLACE_LENGTH = 40;
+/**
+ * The longest place line the detail card shows, ellipsis and all, so a long
+ * place or translation keeps the card inside a phone's width. The card's
+ * accessible name carries the whole place.
+ */
+const CARD_PLACE_LENGTH = 48;
/** A magnitude as the map's labels show it: `M6.4`. */
export const earthquakeMagnitudeTitle = (magnitude) =>
@@ -123,6 +129,332 @@ export function createEarthquakeOverlayEntry({
};
}
+/** Where USGS publishes one event's page, its event id appended. */
+export const USGS_EVENT_PAGE_URL =
+ 'https://earthquake.usgs.gov/earthquakes/eventpage/';
+
+/**
+ * The USGS page for an event id, or null when there is no usable id (a
+ * fallback `event-N` id never names a USGS page, and is never sent).
+ * @param {unknown} usgsId
+ * @returns {string|null}
+ */
+export function earthquakeEventLink(usgsId) {
+ const id =
+ typeof usgsId === 'string' || typeof usgsId === 'number'
+ ? String(usgsId).trim()
+ : '';
+ return /^[A-Za-z0-9_-]{1,64}$/.test(id)
+ ? `${USGS_EVENT_PAGE_URL}${id}`
+ : null;
+}
+
+// The package carries no i18n: with no translator given, the card stays
+// English, its `{name}` slots filled in.
+const english = (text, values) =>
+ String(text).replace(/\{(\w+)\}/g, (all, key) =>
+ values && Object.hasOwn(values, key) ? String(values[key]) : all,
+ );
+const utcMinute = (time) =>
+ `${new Date(time).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
+const oneDecimal = (value) => String(Math.round(value * 10) / 10);
+
+/**
+ * The detail card one clicked earthquake shows: its magnitude as the title,
+ * then where, when and how deep, and the source. With a USGS event id the
+ * card opens that event's page.
+ * @param {{mag: number, place?: string|null, time?: number|null,
+ * depthKm?: number|null, usgsId?: string|null}} event
+ * @param {object} [text] The application's formatters.
+ * @param {(text: string, values?: object) => string} [text.t] Translator.
+ * @param {(time: number) => string} [text.formatTime] An event time.
+ * @param {(value: number) => string} [text.formatDepth] A depth in km.
+ * @param {boolean} [text.canOpen] Whether a link can be opened here (an
+ * opener is injected); without one the card offers no link to click.
+ * @returns {{title: string, details: string[], link: string|null,
+ * accessibilityLabel: string}} `accessibilityLabel` names the card's
+ * action, with its details: opening the source, or focusing the quake.
+ */
+export function describeEarthquake(
+ event,
+ {
+ t = english,
+ formatTime = utcMinute,
+ formatDepth = oneDecimal,
+ canOpen = true,
+ } = {},
+) {
+ const details = [];
+ // What the card says, spoken: depth, the whole place, and the time.
+ const spoken = [];
+ // Severity at a glance, right under the title: the class meter, then
+ // where in the crust it broke.
+ const glance = [earthquakeSeverityMeter(event?.mag)];
+ if (Number.isFinite(event?.depthKm)) {
+ const depth = `${earthquakeDepthBandName(event.depthKm, t)} · ${t(
+ '{km} km deep',
+ { km: formatDepth(event.depthKm) },
+ )}`;
+ glance.push(depth);
+ spoken.push(depth);
+ }
+ details.push(glance.join(' '));
+ const place =
+ typeof event?.place === 'string'
+ ? event.place.replace(/\s+/g, ' ').trim()
+ : '';
+ if (place) {
+ // Cut by characters, not UTF-16 units, so a pair is never split.
+ const chars = Array.from(place);
+ details.push(
+ chars.length > CARD_PLACE_LENGTH
+ ? `${chars
+ .slice(0, CARD_PLACE_LENGTH - 1)
+ .join('')
+ .trimEnd()}…`
+ : place,
+ );
+ spoken.push(place);
+ }
+ if (Number.isFinite(event?.time)) {
+ const time = formatTime(event.time);
+ details.push(time);
+ spoken.push(time);
+ }
+ const source = t('Source: {value}', { value: 'USGS' });
+ details.push(source);
+ // The source closes the spoken details, so they are never empty.
+ spoken.push(source);
+ const link = earthquakeEventLink(event?.usgsId);
+ const opens = Boolean(link) && canOpen;
+ if (opens) details.push(t('Click the card to open the source ↗'));
+ const title = `${earthquakeMagnitudeTitle(event?.mag)} · ${earthquakeSeverityName(
+ event?.mag,
+ t,
+ )}`;
+ const summary = { title, details: spoken.join(', ') };
+ return {
+ title,
+ details,
+ link,
+ accessibilityLabel: opens
+ ? t('Open the source for {title}, {details}', summary)
+ : t('Focus earthquake {title}, {details}', summary),
+ };
+}
+
+/**
+ * USGS's magnitude classes, weakest first: minor (under 4; the feed starts
+ * at M2.5), light, moderate, strong, major, great (8 and up).
+ */
+export const EARTHQUAKE_SEVERITY_LEVELS = 6;
+
+/**
+ * A magnitude's USGS class, 0 (minor) to 5 (great).
+ * @param {number} magnitude
+ * @returns {number}
+ */
+export function earthquakeSeverityLevel(magnitude) {
+ const mag = Number(magnitude);
+ if (!Number.isFinite(mag) || mag < 4) return 0;
+ return Math.min(EARTHQUAKE_SEVERITY_LEVELS - 1, Math.floor(mag) - 3);
+}
+
+/** A magnitude's class, as a word in the page's language. */
+export function earthquakeSeverityName(magnitude, t = english) {
+ switch (earthquakeSeverityLevel(magnitude)) {
+ case 5:
+ return t('Great', { context: 'earthquake' });
+ case 4:
+ return t('Major', { context: 'earthquake' });
+ case 3:
+ return t('Strong', { context: 'earthquake' });
+ case 2:
+ return t('Moderate', { context: 'earthquake' });
+ case 1:
+ return t('Light', { context: 'earthquake' });
+ default:
+ return t('Minor', { context: 'earthquake' });
+ }
+}
+
+/**
+ * The class as a six-step meter, one filled block per class up to this one:
+ * `■■□□□□` for a light quake. Plain text, so the card shows it as it is.
+ * @param {number} magnitude
+ * @returns {string}
+ */
+export function earthquakeSeverityMeter(magnitude) {
+ const filled = earthquakeSeverityLevel(magnitude) + 1;
+ return '■'.repeat(filled) + '□'.repeat(EARTHQUAKE_SEVERITY_LEVELS - filled);
+}
+
+/**
+ * The depth band the disc's colour shows, as a word: shallow (under 70 km,
+ * red), intermediate (to 300 km, orange), deep (yellow).
+ */
+export function earthquakeDepthBandName(depthKm, t = english) {
+ const band = depthBand(depthKm);
+ if (band === SHALLOW) return t('Shallow', { context: 'earthquake' });
+ if (band === INTERMEDIATE)
+ return t('Intermediate', { context: 'earthquake' });
+ return t('Deep', { context: 'earthquake' });
+}
+
+/**
+ * A quake's disc radius on the ground, in metres: it doubles with each
+ * magnitude step (about 5.7 km at M2.5, 32 km at M5, 64 km at M6).
+ * @param {number} magnitude
+ * @returns {number}
+ */
+export const earthquakeDiscRadiusM = (magnitude) =>
+ Math.pow(2, magnitude) * 1000;
+
+/** How many contour lines run out from a selected quake at once. */
+export const EARTHQUAKE_RIPPLE_RINGS = 6;
+/** How long one contour line takes from the marker to the disc's edge. */
+export const EARTHQUAKE_RIPPLE_PERIOD_MS = 4800;
+/** Every this many lines one is an index contour, drawn heavier. */
+export const EARTHQUAKE_INDEX_CONTOUR_EVERY = 3;
+
+/**
+ * How far a contour line dents in from the circle, as a share of its
+ * radius. Kept with the drift below so nested lines never cross: a line's
+ * radius grows with `fraction` faster than its dents move (see
+ * earthquakeContourScale).
+ */
+export const EARTHQUAKE_CONTOUR_WOBBLE = 0.24;
+const CONTOUR_HARMONICS = Object.freeze([2, 3, 5]);
+const CONTOUR_WEIGHTS = Object.freeze([1, 0.6, 0.3]);
+const CONTOUR_MAX_DRIFT = 1.5;
+
+/** A stable 32-bit hash of a string (FNV-1a). */
+function hashString(text) {
+ let h = 0x811c9dc5;
+ for (const ch of String(text ?? '')) {
+ h ^= ch.codePointAt(0);
+ h = Math.imul(h, 0x01000193);
+ }
+ return h >>> 0;
+}
+
+/**
+ * One quake's contour shape: a few harmonics around the circle, each with
+ * its own phase and a drift that turns it as a line runs outward, seeded by
+ * the quake's id so the same quake always draws the same contours.
+ * @param {string} seed The quake's stable id.
+ * @returns {ReadonlyArray<{harmonic: number, weight: number, phase: number, drift: number}>}
+ */
+export function earthquakeContourShape(seed) {
+ let state = hashString(seed) || 1;
+ // xorshift32: a small, stable stream from the seed.
+ const next = () => {
+ state ^= state << 13;
+ state ^= state >>> 17;
+ state ^= state << 5;
+ return (state >>> 0) / 0x100000000;
+ };
+ return Object.freeze(
+ CONTOUR_HARMONICS.map((harmonic, i) =>
+ Object.freeze({
+ harmonic,
+ weight: CONTOUR_WEIGHTS[i],
+ phase: next() * 2 * Math.PI,
+ drift: (next() * 2 - 1) * CONTOUR_MAX_DRIFT,
+ }),
+ ),
+ );
+}
+
+/**
+ * Where a contour line runs at `angle` (radians), as a share of a circle of
+ * the same `fraction`: between 1 - EARTHQUAKE_CONTOUR_WOBBLE and 1, so the
+ * outermost line never leaves the disc. The dents turn as `fraction` grows,
+ * and no faster than the line grows, so lines never cross: with wobble A
+ * and drift D, d(fraction · scale)/d(fraction) ≥ 1 - A - A·D/2 > 0.
+ * @param {ReturnType} shape
+ * @param {number} angle
+ * @param {number} fraction 0 at the marker, 1 at the disc's edge.
+ * @returns {number}
+ */
+export function earthquakeContourScale(shape, angle, fraction) {
+ let sum = 0;
+ let total = 0;
+ for (const { harmonic, weight, phase, drift } of shape) {
+ sum += weight * Math.sin(harmonic * angle + phase + drift * fraction);
+ total += weight;
+ }
+ const n = total > 0 ? sum / total : 0;
+ return 1 - (EARTHQUAKE_CONTOUR_WOBBLE * (1 - n)) / 2;
+}
+
+/**
+ * The selected quake's contour lines at a time: each runs from the marker
+ * (`fraction` 0) out to the disc's edge (1), evenly staggered, fading in
+ * just after it starts and out as it reaches the edge; every
+ * EARTHQUAKE_INDEX_CONTOUR_EVERY-th is an index contour. Pure: the painter
+ * gives the clock.
+ * @param {number} timeMs Any steady clock, in milliseconds.
+ * @param {{count?: number, periodMs?: number}} [options]
+ * @returns {Array<{fraction: number, alpha: number, index: boolean}>}
+ */
+export function earthquakeRippleRings(
+ timeMs,
+ {
+ count = EARTHQUAKE_RIPPLE_RINGS,
+ periodMs = EARTHQUAKE_RIPPLE_PERIOD_MS,
+ } = {},
+) {
+ const phase = Number.isFinite(timeMs) && periodMs > 0 ? timeMs / periodMs : 0;
+ const rings = [];
+ for (let k = 0; k < count; k++) {
+ const fraction = (((phase + k / count) % 1) + 1) % 1;
+ rings.push({
+ fraction,
+ alpha: earthquakeRippleAlpha(fraction),
+ index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0,
+ });
+ }
+ return rings;
+}
+
+/**
+ * Still contour lines, for viewers who ask for reduced motion: the same
+ * lines as the animation, held evenly spaced out to the edge.
+ * @param {number} [count]
+ * @returns {Array<{fraction: number, alpha: number, index: boolean}>}
+ */
+export function earthquakeContourRings(count = EARTHQUAKE_RIPPLE_RINGS) {
+ const rings = [];
+ for (let k = 1; k <= count; k++)
+ rings.push({
+ fraction: k / count,
+ alpha: 0.7,
+ index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0,
+ });
+ return rings;
+}
+
+const RIPPLE_FADE_IN = 0.12;
+/** A ring's opacity where it is: in from 0 near the marker, out to 0 at the edge. */
+function earthquakeRippleAlpha(fraction) {
+ if (fraction <= 0 || fraction >= 1) return 0;
+ return fraction < RIPPLE_FADE_IN
+ ? fraction / RIPPLE_FADE_IN
+ : (1 - fraction) / (1 - RIPPLE_FADE_IN);
+}
+
+/**
+ * What a magnitude label says to assistive technology: activating it zooms
+ * to the quake (`Zoom to M5.0 · 42 km SW of Anchorage, Alaska`).
+ * @param {{mag: number, place?: string|null}} event
+ * @param {{t?: (text: string, values?: object) => string}} [text]
+ * @returns {string}
+ */
+export function earthquakeZoomLabel(event, { t = english } = {}) {
+ return t('Zoom to {name}', { name: earthquakeMarkLabel(event) });
+}
+
/** Keep the largest events, with stable identity as the tie-break. */
export function selectEarthquakeOverlayCohort(
entries,
diff --git a/src/layers/earthquakes/records.js b/src/layers/earthquakes/records.js
index 397b4bb1c8..caaf8bc879 100644
--- a/src/layers/earthquakes/records.js
+++ b/src/layers/earthquakes/records.js
@@ -28,10 +28,15 @@ export function normalizeEarthquakeSnapshot(geojson) {
return null;
// A missing magnitude cannot establish that this event meets M2.5+.
if (mag == null || mag < 2.5) continue;
- const stableId =
- feature.id == null || feature.id === ''
- ? `event-${index + 1}`
- : String(feature.id);
+ // An id-less event is named by what it is (time, position, depth and
+ // magnitude), not by its row, so a refresh that inserts a row keeps the
+ // selection on the same quake; a revision to any of those names a new
+ // one. Two id-less events that match exactly fall back to the row.
+ const idless = feature.id == null || feature.id === '';
+ let stableId = idless
+ ? `event-${[properties.time ?? 'na', lon, lat, depthKm ?? 'na', mag].join(':')}`
+ : String(feature.id);
+ if (idless && ids.has(stableId)) stableId = `${stableId}:${index + 1}`;
if (ids.has(stableId)) return null;
ids.add(stableId);
rows.push({
diff --git a/src/layers/earthquakes/records.test.mjs b/src/layers/earthquakes/records.test.mjs
index cd7b6a8741..bc3447db2b 100644
--- a/src/layers/earthquakes/records.test.mjs
+++ b/src/layers/earthquakes/records.test.mjs
@@ -37,7 +37,7 @@ test('normalizeEarthquakeSnapshot parses valid GeoJSON earthquake features', ()
});
});
-test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is missing or blank', () => {
+test('normalizeEarthquakeSnapshot names id-less events by their content, not their row', () => {
const geojson = {
features: [
{
@@ -55,10 +55,35 @@ test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is mi
const rows = normalizeEarthquakeSnapshot(geojson);
assert.equal(rows.length, 2);
- assert.equal(rows[0].stableId, 'event-1');
+ assert.equal(rows[0].stableId, 'event-1711930000000:139.6917:35.6895:25:3.5');
assert.equal(rows[0].usgsId, null);
- assert.equal(rows[1].stableId, 'event-2');
+ assert.equal(
+ rows[1].stableId,
+ 'event-1711931000000:-70.6693:-33.4489:45.2:5.1',
+ );
assert.equal(rows[1].usgsId, '');
+ // A row inserted ahead of them keeps each id-less quake's id, so a selected
+ // one stays selected across the refresh.
+ const inserted = normalizeEarthquakeSnapshot({
+ features: [
+ {
+ id: 'us7000new',
+ geometry: { type: 'Point', coordinates: [10, 20, 5] },
+ properties: { mag: 4, place: 'New', time: 1711932000000 },
+ },
+ ...geojson.features,
+ ],
+ });
+ assert.deepEqual(
+ inserted.map((row) => row.stableId).slice(1),
+ rows.map((row) => row.stableId),
+ );
+ // Two id-less events that match exactly stay apart.
+ const twins = normalizeEarthquakeSnapshot({
+ features: [geojson.features[0], geojson.features[0]],
+ });
+ assert.equal(twins.length, 2);
+ assert.notEqual(twins[0].stableId, twins[1].stableId);
});
test('normalizeEarthquakeSnapshot filters events below M2.5 without dropping the feed', () => {
diff --git a/src/layers/earthquakes/selection.test.mjs b/src/layers/earthquakes/selection.test.mjs
new file mode 100644
index 0000000000..3c677362e7
--- /dev/null
+++ b/src/layers/earthquakes/selection.test.mjs
@@ -0,0 +1,1222 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
+import * as picking from '../../data/pickRegistry.js';
+// Registers the shared `gev-trail:` owner as passive, as the app does.
+import '../../data/trailRenderer.js';
+import { createSelection as createFireSelection } from '../firms/selection.js';
+import { fakeInput } from '../../input/testDoubles.mjs';
+import { createDroneAirspaceLayer } from '../droneAirspace/index.js';
+import {
+ EARTHQUAKE_CARD_SOURCE_ID,
+ EARTHQUAKE_OVERLAY_SOURCE_ID,
+ createEarthquakesLayer,
+ describeEarthquake,
+ earthquakeEventLink,
+ earthquakeRippleRings,
+ earthquakeContourRings,
+ earthquakeContourShape,
+ earthquakeContourScale,
+ EARTHQUAKE_CONTOUR_WOBBLE,
+ EARTHQUAKE_RIPPLE_PERIOD_MS,
+ earthquakeSeverityName,
+ earthquakeSeverityMeter,
+ earthquakeDepthBandName,
+} from './index.js';
+
+const quake = (id, extra = {}) => ({
+ stableId: id,
+ usgsId: id,
+ lon: -153.3,
+ lat: 60.0,
+ depthKm: 112.4,
+ mag: 2.5,
+ place: '42 km W of Fixture, Alaska',
+ time: Date.UTC(2026, 10, 13, 15, 37),
+ ...extra,
+});
+
+/** A layer whose globe clicks, card hits and context store the test drives. */
+function harness(
+ rows,
+ {
+ context = null,
+ ripples = null,
+ groundHeight = null,
+ input: inputFactory = null,
+ } = {},
+) {
+ let snapshot = rows;
+ const handlers = [];
+ const opened = [];
+ const cards = [];
+ const visible = new Map();
+ const labels = [];
+ const focused = [];
+ // What the overlay hit test finds under the click, per source.
+ const overlayHits = new Map();
+ // Another layer's interactive entry painted on top, if any.
+ let foreignTop = null;
+ const viewer = {};
+ const { draw } = bindFakeDraw(viewer);
+ const overlayHost = {
+ setEntries(sourceId, entries) {
+ if (sourceId === EARTHQUAKE_CARD_SOURCE_ID) cards.push(entries);
+ if (sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) labels.push(entries);
+ },
+ setVisible: (sourceId, show) => visible.set(sourceId, show),
+ clearSource() {},
+ // As the real host does, only an interactive entry painted now is hit.
+ hitTest(_x, _y, { sourceId } = {}) {
+ // Unfiltered, as the host answers: another layer's entry on top
+ // first, else this layer's own.
+ if (!sourceId)
+ return (
+ foreignTop ??
+ this.hitTest(_x, _y, { sourceId: EARTHQUAKE_CARD_SOURCE_ID }) ??
+ this.hitTest(_x, _y, { sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID })
+ );
+ const hit = overlayHits.get(sourceId);
+ const painted =
+ sourceId === EARTHQUAKE_CARD_SOURCE_ID ? cards.at(-1) : labels.at(-1);
+ const entry = painted?.find((e) => e.id === hit?.entryId);
+ return hit && entry?.interactive === true ? hit : null;
+ },
+ };
+ // The card on top at a click, as the host answers the pick registry.
+ picking.setClickCardHitTest((x, y) => overlayHost.hitTest(x, y));
+ const layer = createEarthquakesLayer({
+ source: { getSnapshot: async () => snapshot },
+ overlayHost,
+ input:
+ inputFactory ??
+ (() => ({
+ onClick(callback) {
+ const handler = { callback, destroyed: false };
+ handlers.push(handler);
+ return () => {
+ handler.destroyed = true;
+ };
+ },
+ })),
+ picking,
+ context,
+ ripples,
+ groundHeight,
+ pointer: { isPointerFree: () => true },
+ openExternal: (url) => opened.push(url),
+ focus: {
+ requestWorldFocus: (detail) => {
+ focused.push(detail);
+ return true;
+ },
+ },
+ });
+ layer.init(viewer);
+ const discs = () => draw.find('earthquakes:');
+ const live = () => handlers.filter((h) => !h.destroyed);
+ return {
+ layer,
+ viewer,
+ opened,
+ cards,
+ visible,
+ focused,
+ handlers,
+ overlayHost,
+ overlayHits,
+ discs,
+ setRows(next) {
+ snapshot = next;
+ },
+ /** Click a quake's disc (by stable id), something else, or the map. */
+ click(hit, resolvedHit = hit, gesture = { travelPx: 0, durationMs: 0 }) {
+ for (const { callback } of live())
+ callback({
+ screenPosition: { x: 10, y: 10 },
+ topHit: hit,
+ hit: resolvedHit,
+ drawHit: hit && !hit.surface ? hit : null,
+ gesture,
+ });
+ },
+ clickDisc(id) {
+ this.click({ set: discs().spec.id, id: `earthquake:${id}` });
+ },
+ clickCard(entryId) {
+ this.clickOverlay(EARTHQUAKE_CARD_SOURCE_ID, entryId);
+ },
+ /** Click a magnitude label, as the overlay host paints it. */
+ clickLabel(id) {
+ this.clickOverlay(EARTHQUAKE_OVERLAY_SOURCE_ID, id);
+ },
+ clickOverlay(sourceId, entryId) {
+ this.clickOverlayWith(sourceId, entryId, null);
+ },
+ /** Click another layer's card painted on top, with `hit` under it. */
+ clickForeignCard(sourceId, entryId, hit) {
+ foreignTop = { sourceId, entryId };
+ this.click(hit);
+ foreignTop = null;
+ },
+ /** Click an overlay entry with `hit` drawn under the same pixel. */
+ clickOverlayWith(sourceId, entryId, hit, resolvedHit = hit) {
+ overlayHits.set(sourceId, { sourceId, entryId });
+ this.click(hit, resolvedHit);
+ overlayHits.delete(sourceId);
+ },
+ lastCard: () => cards.at(-1),
+ lastLabels: () => labels.at(-1),
+ };
+}
+
+test('clicking a quake disc shows its detail card; empty map clears it', async () => {
+ const h = harness([quake('ak1'), quake('ak2', { mag: 4.1 })]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ assert.equal(h.cards.length, 0, 'no card before a click');
+
+ h.clickDisc('ak2');
+ const [card] = h.lastCard();
+ assert.equal(card.id, 'earthquake-card:ak2');
+ assert.equal(card.title, 'M4.1 · Light');
+ assert.deepEqual(card.details, [
+ '■■□□□□ Intermediate · 112.4 km deep',
+ '42 km W of Fixture, Alaska',
+ '2026-11-13 15:37 UTC',
+ 'Source: USGS',
+ 'Click the card to open the source ↗',
+ ]);
+ assert.equal(card.interactive, true);
+ assert.equal(
+ card.accessibilityLabel,
+ 'Open the source for M4.1 · Light, Intermediate · 112.4 km deep, 42 km W of Fixture, Alaska, 2026-11-13 15:37 UTC, Source: USGS',
+ );
+ assert.equal(h.visible.get(EARTHQUAKE_CARD_SOURCE_ID), true);
+
+ h.click(null);
+ assert.deepEqual(h.lastCard(), [], 'a click on the map clears the card');
+ h.layer.destroy();
+});
+
+test('the card opens the USGS event page, from a click or the keyboard', async () => {
+ const h = harness([quake('ak1')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ h.clickCard('earthquake-card:ak1');
+ assert.deepEqual(h.opened, [
+ 'https://earthquake.usgs.gov/earthquakes/eventpage/ak1',
+ ]);
+ assert.equal(h.lastCard()[0].activate(), true);
+ assert.equal(h.opened.length, 2);
+ assert.equal(h.lastCard().length, 1, 'opening the source keeps the card');
+ h.layer.destroy();
+});
+
+test('a quake with no USGS id gets a card with no link', async () => {
+ const h = harness([quake('event-1', { usgsId: null })]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('event-1');
+ const [card] = h.lastCard();
+ assert.equal(card.interactive, true, 'hit-testable, so a click keeps it');
+ assert.ok(!card.details.some((line) => line.includes('Click the card')));
+ // No source to open: a click on the card flies to the quake instead.
+ h.clickCard(card.id);
+ assert.deepEqual(h.opened, []);
+ assert.equal(h.focused.length, 1);
+ // Its keyboard action does the same, so it still has a place in the
+ // action list.
+ assert.match(card.accessibilityLabel, /^Focus earthquake M2\.5 · Minor, /);
+ assert.equal(card.activate(), true);
+ assert.equal(h.focused.length, 2);
+ assert.deepEqual(h.opened, []);
+ assert.equal(h.lastCard()[0].id, card.id, 'the card stays');
+ h.layer.destroy();
+});
+
+test("another layer's pick leaves the card; discs stay unowned, as area layers do", async () => {
+ const h = harness([quake('ak1')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ // Like drone airspace and fire perimeters, the discs are not registered:
+ // siblings read a disc as empty space, so their cards and deselection
+ // work over a quake (a fire card, a radio near-miss, a followed plane).
+ assert.equal(picking.findPickOwner('earthquake:ak1'), null);
+ assert.equal(picking.isOwnedByOtherLayer('firms', 'earthquake:ak1'), false);
+ picking.registerPickOwner('test-other', (id) => id === 'plane-1');
+ try {
+ h.clickDisc('ak1');
+ const before = h.cards.length;
+ h.click({ set: 'flights:1', id: 'plane-1' });
+ assert.equal(h.cards.length, before, 'the card stays');
+ // A pick of the same id from another set is not a quake.
+ h.click({ set: 'other:1', id: 'earthquake:ak1' });
+ assert.deepEqual(h.lastCard(), []);
+ } finally {
+ picking.unregisterPickOwner('test-other');
+ h.layer.destroy();
+ }
+ assert.equal(picking.findPickOwner('earthquake:ak1'), null);
+});
+
+test('a refresh keeps the selected quake while it is in the feed', async () => {
+ const h = harness([quake('ak1'), quake('ak2')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ h.setRows([quake('ak1', { mag: 2.7 }), quake('ak2')]);
+ await h.layer.update(h.viewer);
+ assert.equal(
+ h.lastCard()[0].title,
+ 'M2.7 · Minor',
+ 'the card follows the feed',
+ );
+ h.setRows([quake('ak2')]);
+ await h.layer.update(h.viewer);
+ assert.deepEqual(h.lastCard(), [], 'a quake that left the feed loses it');
+ h.layer.destroy();
+});
+
+test('disable removes the click handler and the card', async () => {
+ const h = harness([quake('ak1')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ h.layer.disable(h.viewer);
+ assert.deepEqual(h.lastCard(), []);
+ assert.equal(
+ h.handlers.every((handler) => handler.destroyed),
+ true,
+ );
+ assert.equal(picking.findPickOwner('earthquake:ak1'), null);
+ h.layer.enable(h.viewer);
+ assert.equal(
+ h.handlers.filter((handler) => !handler.destroyed).length,
+ 1,
+ 'one handler again, not two',
+ );
+ h.layer.destroy();
+});
+
+test('a small quake inside a big one is drawn on top of it', async () => {
+ const h = harness([quake('small', { mag: 2.6 }), quake('big', { mag: 6 })]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ assert.deepEqual(
+ [...h.discs().items.keys()],
+ ['earthquake:big', 'earthquake:small'],
+ );
+ h.layer.destroy();
+});
+
+test('the clicked quake is the selected context, cleared with the card', async () => {
+ const entities = new Map();
+ const calls = [];
+ const context = {
+ getContextStore: () => ({ entities }),
+ registerEntityContext(carrier, metadata) {
+ entities.set(metadata.id, { ...metadata, entity: carrier });
+ },
+ selectEntityContext: (carrier) => calls.push(['select', carrier]),
+ clearSelectedEntityContextForLayer: (layerId) =>
+ calls.push(['clear', layerId]),
+ };
+ const h = harness([quake('ak1'), quake('ak2')], { context });
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ const record = entities.get('earthquake:ak1');
+ assert.equal(record.layerId, 'earthquakes');
+ assert.equal(record.label, 'Earthquake · M2.5 · 42 km W of Fixture, Alaska');
+ assert.equal(record.properties.usgsId, 'ak1');
+ assert.equal(record.dataSource.show, true, 'hidden with the discs');
+ assert.equal(calls.at(-1)[0], 'select');
+ h.clickDisc('ak2');
+ assert.deepEqual([...entities.keys()], ['earthquake:ak2'], 'one record');
+ h.click(null);
+ assert.equal(entities.size, 0);
+ assert.deepEqual(calls.at(-1), ['clear', 'earthquakes']);
+ h.layer.destroy();
+});
+
+test('without click services the layer draws and takes no clicks', async () => {
+ const viewer = {};
+ bindFakeDraw(viewer);
+ const layer = createEarthquakesLayer({
+ source: { getSnapshot: async () => [quake('ak1')] },
+ overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
+ });
+ layer.init(viewer);
+ layer.enable(viewer);
+ assert.equal(await layer.update(viewer), true);
+ assert.equal(picking.findPickOwner('earthquake:ak1'), null);
+ layer.destroy();
+});
+
+test('describeEarthquake translates through the given formatters', () => {
+ const card = describeEarthquake(quake('ak1', { place: ' far away ' }), {
+ t: (text, values) => `<${text}>${JSON.stringify(values ?? {})}`,
+ formatTime: () => 'TIME',
+ formatDepth: (km) => `~${km}`,
+ });
+ assert.equal(card.title, 'M2.5 · {"context":"earthquake"}');
+ assert.deepEqual(card.details, [
+ '■□□□□□ {"context":"earthquake"} · <{km} km deep>{"km":"~112.4"}',
+ 'far away',
+ 'TIME',
+ '{"value":"USGS"}',
+ '{}',
+ ]);
+ const bare = describeEarthquake({ mag: 3, place: null, time: null });
+ assert.equal(bare.title, 'M3.0 · Minor');
+ assert.deepEqual(bare.details, ['■□□□□□', 'Source: USGS']);
+ assert.equal(bare.link, null);
+ assert.equal(
+ bare.accessibilityLabel,
+ 'Focus earthquake M3.0 · Minor, Source: USGS',
+ );
+ // A place cut short never splits a character made of a surrogate pair.
+ const emoji = describeEarthquake(quake('ak9', { place: '🌋'.repeat(60) }));
+ assert.equal(Array.from(emoji.details[1]).length, 48);
+ assert.ok(!/[\uD800-\uDBFF]…$/.test(emoji.details[1]));
+ // A long place is cut short on the card; the accessible name keeps it all.
+ const long = 'A very long place name '.repeat(4).trim();
+ const wide = describeEarthquake(quake('ak9', { place: long }));
+ assert.equal(Array.from(wide.details[1]).length, 48);
+ assert.ok(wide.details[1].endsWith('…'));
+ assert.ok(wide.accessibilityLabel.includes(long));
+ // With no opener to follow a link, the card does not offer one.
+ const closed = describeEarthquake(quake('ak9'), { canOpen: false });
+ assert.ok(!closed.details.some((line) => line.includes('Click the card')));
+ assert.match(closed.accessibilityLabel, /^Focus earthquake /);
+});
+
+test('severity follows the USGS magnitude classes; depth bands the disc colours', () => {
+ const cases = [
+ [2.5, 'Minor', '■□□□□□'],
+ [3.99, 'Minor', '■□□□□□'],
+ [4, 'Light', '■■□□□□'],
+ [5.4, 'Moderate', '■■■□□□'],
+ [6.1, 'Strong', '■■■■□□'],
+ [7.8, 'Major', '■■■■■□'],
+ [8.2, 'Great', '■■■■■■'],
+ [9.5, 'Great', '■■■■■■'],
+ [Number.NaN, 'Minor', '■□□□□□'],
+ ];
+ for (const [mag, name, meter] of cases) {
+ assert.equal(earthquakeSeverityName(mag), name, String(mag));
+ assert.equal(earthquakeSeverityMeter(mag), meter, String(mag));
+ }
+ assert.equal(earthquakeDepthBandName(10), 'Shallow');
+ assert.equal(earthquakeDepthBandName(69.9), 'Shallow');
+ assert.equal(earthquakeDepthBandName(70), 'Intermediate');
+ assert.equal(earthquakeDepthBandName(299), 'Intermediate');
+ assert.equal(earthquakeDepthBandName(300), 'Deep');
+});
+
+test('earthquakeEventLink accepts only plain USGS ids', () => {
+ assert.equal(
+ earthquakeEventLink('us7000abcd'),
+ 'https://earthquake.usgs.gov/earthquakes/eventpage/us7000abcd',
+ );
+ for (const bad of [null, '', ' ', '../x', 'a/b', 'a?b=1', 'x'.repeat(65)])
+ assert.equal(earthquakeEventLink(bad), null, String(bad));
+});
+
+test('clicking a magnitude label selects the quake and flies to it', async () => {
+ const h = harness([
+ quake('ak1'),
+ quake('jp1', { mag: 5, lon: 142, lat: 38 }),
+ ]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ const label = h.lastLabels().find((entry) => entry.id === 'jp1');
+ assert.equal(label.interactive, true, 'labels take clicks');
+ assert.equal(
+ label.accessibilityLabel,
+ 'Zoom to M5.0 · 42 km W of Fixture, Alaska',
+ );
+
+ h.clickLabel('jp1');
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:jp1');
+ assert.equal(h.focused.length, 1);
+ const [detail] = h.focused;
+ assert.equal(detail.kind, 'earthquake');
+ assert.equal(detail.id, 'earthquake:jp1');
+ assert.equal(detail.label, 'M5.0');
+ assert.ok(
+ Math.hypot(detail.position.x, detail.position.y, detail.position.z) > 6e6,
+ );
+ // The whole disc in view: the radius scales with the magnitude; up to M6
+ // the framing's own range fits the disc.
+ assert.equal(detail.radiusM, 32000);
+ assert.equal(detail.rangeM, undefined);
+
+ // The keyboard path does the same.
+ assert.equal(
+ h
+ .lastLabels()
+ .find((e) => e.id === 'ak1')
+ .activate(),
+ true,
+ );
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1');
+ assert.equal(h.focused.at(-1).id, 'earthquake:ak1');
+
+ // A disc click only selects: the camera stays where it is.
+ h.clickDisc('jp1');
+ assert.equal(h.focused.length, 2);
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:jp1');
+
+ // A label id the layer no longer draws is not a quake.
+ h.clickLabel('gone');
+ assert.deepEqual(h.lastCard(), []);
+ assert.equal(h.focused.length, 2);
+ h.layer.destroy();
+});
+
+test('without click services the labels stay non-interactive', async () => {
+ const viewer = {};
+ bindFakeDraw(viewer);
+ const published = [];
+ const layer = createEarthquakesLayer({
+ source: { getSnapshot: async () => [quake('ak1')] },
+ overlayHost: {
+ setEntries: (_source, entries) => published.push(entries),
+ setVisible() {},
+ clearSource() {},
+ },
+ });
+ layer.init(viewer);
+ layer.enable(viewer);
+ await layer.update(viewer);
+ const [label] = published.at(-1);
+ assert.equal(label.interactive, false);
+ assert.equal(label.activate, undefined);
+ layer.destroy();
+});
+
+test('the selected quake runs contour rings to its disc edge; clearing stops them', async () => {
+ const calls = [];
+ const ripples = {
+ show: (target) => calls.push(['show', target]),
+ hide: () => calls.push(['hide']),
+ dispose: () => calls.push(['dispose']),
+ };
+ // The ground the disc is draped on: the rings are drawn at its height.
+ const heights = [];
+ const h = harness(
+ [quake('ak1', { mag: 5, depthKm: 10 }), quake('ak2', { mag: 3 })],
+ {
+ ripples,
+ groundHeight: (viewer, lon, lat) => {
+ heights.push([lon, lat]);
+ return lon === -153.3 ? 1840 : null;
+ },
+ },
+ );
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ const shown = calls.findLast(([kind]) => kind === 'show')[1];
+ const { heightAt, ...rest } = shown;
+ assert.deepEqual(rest, {
+ id: 'ak1',
+ lon: -153.3,
+ lat: 60,
+ heightM: 1840,
+ radiusM: 32000,
+ color: 'rgb(255,0,0)',
+ });
+ assert.deepEqual(heights.at(-1), [-153.3, 60]);
+ // The painter can read the ground again as it loads (a label's fly-to).
+ assert.equal(heightAt(), 1840);
+ assert.equal(
+ h.discs().items.get('earthquake:ak1').geometry.semiMajor,
+ shown.radiusM,
+ 'the rings end at the disc edge',
+ );
+ h.clickDisc('ak2');
+ assert.equal(calls.findLast(([kind]) => kind === 'show')[1].radiusM, 8000);
+ h.click(null);
+ assert.deepEqual(calls.at(-1), ['hide']);
+ h.clickDisc('ak1');
+ h.layer.disable(h.viewer);
+ assert.deepEqual(calls.at(-1), ['hide']);
+ h.layer.destroy();
+ assert.deepEqual(calls.at(-1), ['dispose']);
+});
+
+test('ripple rings run from the marker to the edge, staggered, fading at both ends', () => {
+ const rings = earthquakeRippleRings(0, { count: 3, periodMs: 3000 });
+ assert.deepEqual(
+ rings.map(({ fraction }) => Number(fraction.toFixed(4))),
+ [0, 0.3333, 0.6667],
+ );
+ assert.equal(rings[0].alpha, 0, 'a ring at the marker is not yet seen');
+ // Each ring moves outward with time and wraps back to the marker.
+ const later = earthquakeRippleRings(1000, { count: 3, periodMs: 3000 });
+ assert.ok(later[1].fraction > rings[1].fraction);
+ assert.ok(later[2].fraction < rings[2].fraction, 'the outer ring wrapped');
+ for (let t = 0; t < 6000; t += 37)
+ for (const { fraction, alpha } of earthquakeRippleRings(t)) {
+ assert.ok(fraction >= 0 && fraction < 1);
+ assert.ok(alpha >= 0 && alpha <= 1);
+ }
+ const near = (f) =>
+ earthquakeRippleRings(f * EARTHQUAKE_RIPPLE_PERIOD_MS, { count: 1 })[0]
+ .alpha;
+ assert.ok(near(0.99) < 0.02, 'fades out at the edge');
+ assert.ok(near(0.12) > 0.999, 'fully in just after the start');
+ assert.deepEqual(
+ earthquakeContourRings(3).map(({ fraction }) => fraction),
+ [1 / 3, 2 / 3, 1],
+ );
+});
+
+test('a quake keeps its own contour shape; nested lines never cross', () => {
+ const a = earthquakeContourShape('us7000abcd');
+ assert.deepEqual(
+ earthquakeContourShape('us7000abcd'),
+ a,
+ 'same id, same shape',
+ );
+ assert.notDeepEqual(earthquakeContourShape('ak2026xyz'), a);
+ for (const id of ['us7000abcd', 'ak2026xyz', 'event-1', '']) {
+ const shape = earthquakeContourShape(id);
+ for (let i = 0; i < 180; i++) {
+ const angle = (2 * Math.PI * i) / 180;
+ let previous = 0;
+ for (let step = 1; step <= 200; step++) {
+ const fraction = step / 200;
+ const scale = earthquakeContourScale(shape, angle, fraction);
+ assert.ok(scale <= 1 + 1e-12, 'never past the disc edge');
+ assert.ok(scale >= 1 - EARTHQUAKE_CONTOUR_WOBBLE - 1e-12);
+ const reach = fraction * scale;
+ assert.ok(reach > previous, `${id}: lines cross at ${angle}`);
+ previous = reach;
+ }
+ }
+ }
+});
+
+test("the selected quake's flat disc fades under its gradient and comes back", async () => {
+ const ripples = { show() {}, hide() {}, dispose() {} };
+ const h = harness([quake('ak1', { mag: 5 }), quake('ak2')], { ripples });
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ const alpha = (id) => h.discs().items.get(`earthquake:${id}`).fill[3];
+ assert.equal(alpha('ak1'), 0.4);
+ h.clickDisc('ak1');
+ assert.equal(alpha('ak1'), 0.04, 'faint, still pickable');
+ h.clickDisc('ak2');
+ assert.equal(alpha('ak1'), 0.4, 'restored');
+ assert.equal(alpha('ak2'), 0.04);
+ // A refresh keeps the selected disc faded.
+ await h.layer.update(h.viewer);
+ assert.equal(alpha('ak2'), 0.04);
+ assert.equal(alpha('ak1'), 0.4);
+ h.click(null);
+ assert.equal(alpha('ak2'), 0.3);
+ h.layer.destroy();
+});
+
+test('without the ripples painter the selected disc keeps its fill', async () => {
+ const h = harness([quake('ak1')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ assert.equal(h.discs().items.get('earthquake:ak1').fill[3], 0.3);
+ h.layer.destroy();
+});
+
+test('a feed refresh neither retakes the selection nor restarts the contours', async () => {
+ const calls = [];
+ const shows = [];
+ const entities = new Map();
+ const context = {
+ getContextStore: () => ({ entities }),
+ registerEntityContext(carrier, metadata) {
+ entities.set(metadata.id, { ...metadata, entity: carrier });
+ },
+ selectEntityContext: () => calls.push('select'),
+ clearSelectedEntityContextForLayer: () => calls.push('clear'),
+ };
+ const ripples = {
+ show: (target, options) => shows.push(options),
+ hide() {},
+ dispose() {},
+ };
+ const h = harness([quake('ak1', { mag: 4 })], { context, ripples });
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ assert.deepEqual(calls, ['select']);
+ assert.deepEqual(shows, [{ restart: true }]);
+ // Another layer's selection happens here; then the feed refreshes.
+ h.setRows([quake('ak1', { mag: 4.3 })]);
+ await h.layer.update(h.viewer);
+ assert.deepEqual(calls, ['select'], 'not selected again by a refresh');
+ assert.deepEqual(shows.at(-1), { restart: false });
+ assert.equal(
+ entities.get('earthquake:ak1').label,
+ 'Earthquake · M4.3 · 42 km W of Fixture, Alaska',
+ 'the record is kept up to date',
+ );
+ // Clicking it again is the user's: it selects and runs again.
+ h.clickDisc('ak1');
+ assert.deepEqual(calls, ['select', 'select']);
+ assert.deepEqual(shows.at(-1), { restart: true });
+ h.layer.destroy();
+});
+
+// The label painted on top takes the click: the object drawn under it does not.
+test("a magnitude label takes the click over another layer's object", async () => {
+ const h = harness([quake('ak1')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ picking.registerPickOwner('test-plane', (id) => id === 'plane-9');
+ try {
+ // The click lands on the label and on a plane drawn there.
+ h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak1', {
+ set: 'flights:1',
+ id: 'plane-9',
+ });
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1', 'selected');
+ assert.equal(h.focused.length, 1, 'and the camera flies');
+ // The plane alone, with no label over it, is not empty space.
+ h.click({ set: 'flights:1', id: 'plane-9' });
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1', 'kept');
+ } finally {
+ picking.unregisterPickOwner('test-plane');
+ h.layer.destroy();
+ }
+});
+
+test('a touch-expanded quake hit selects its disc without flying', async () => {
+ const h = harness([quake('ak1')]);
+ try {
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.click(null, { set: h.discs().spec.id, id: 'earthquake:ak1' });
+ assert.equal(h.lastCard()?.[0]?.id, 'earthquake-card:ak1');
+ assert.equal(h.focused.length, 0);
+ } finally {
+ h.layer.destroy();
+ }
+});
+
+test('a quake label takes the click over a touch-expanded sibling hit', async () => {
+ const h = harness([quake('ak1'), quake('ak2')]);
+ try {
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ picking.registerPickOwner('test-plane', (id) => id === 'plane-9');
+ h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', null, {
+ set: 'flights:1',
+ id: 'plane-9',
+ });
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:ak2');
+ assert.equal(h.focused.length, 1);
+ } finally {
+ picking.unregisterPickOwner('test-plane');
+ h.layer.destroy();
+ }
+});
+
+test("another layer's card over a quake disc takes the click, and the disc yields", async () => {
+ const h = harness([quake('ak1', { mag: 6 })]);
+ try {
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ // A fire's card painted over the disc: the disc is what the scene picks.
+ h.clickForeignCard('firms', 'fire:x', {
+ set: h.discs().spec.id,
+ id: 'earthquake:ak1',
+ });
+ assert.equal(h.cards.length, 0, 'the quake is not selected');
+ assert.equal(h.focused.length, 0);
+ // The same disc with nothing painted over it selects the quake.
+ h.clickDisc('ak1');
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:ak1');
+ } finally {
+ h.layer.destroy();
+ }
+});
+
+for (const coarse of [false, true]) {
+ test(`a quake card takes the click over an aircraft, which does not track (${coarse ? 'coarse' : 'exact'} hit)`, async (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: coarse });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const plane = { set: 'flights:1', id: 'plane-9' };
+ let sceneHit = null;
+ let nearby = null;
+ let tracked = null;
+ let tracks = 0;
+ let input;
+ const h = harness([quake('ak1')], {
+ input(viewer) {
+ viewer.scene = {
+ pick: () => (sceneHit ? { id: sceneHit } : null),
+ drillPick: () => (nearby ? [{ id: nearby }] : []),
+ };
+ input = fakeInput(viewer);
+ // The aircraft layer runs first; like every layer, it leaves a
+ // click under another layer's card to that card.
+ input.input.onClick((event) => {
+ if (picking.isUnderOtherCard(event)) return;
+ const id = event.hit?.id;
+ if (id !== plane.id || tracked === id) return;
+ tracked = id;
+ tracks++;
+ });
+ return input.input;
+ },
+ });
+ picking.registerPickOwner('test-plane', (id) => id === plane.id);
+ t.after(() => {
+ picking.unregisterPickOwner('test-plane');
+ h.layer.destroy();
+ input?.destroy();
+ });
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ sceneHit = { set: h.discs().spec.id, id: 'earthquake:ak1' };
+ input.click();
+ const card = h.lastCard()[0];
+ h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, {
+ sourceId: EARTHQUAKE_CARD_SOURCE_ID,
+ entryId: card.id,
+ });
+ sceneHit = coarse ? null : plane;
+ nearby = coarse ? plane : null;
+
+ input.click();
+ assert.equal(tracks, 0, 'the aircraft under the card does not track');
+ assert.deepEqual(h.opened, [
+ 'https://earthquake.usgs.gov/earthquakes/eventpage/ak1',
+ ]);
+ assert.equal(h.lastCard()[0].id, card.id, 'the card stays');
+
+ // Without the card the aircraft takes it, and the quake stays selected.
+ h.overlayHits.clear();
+ input.click();
+ assert.equal(tracks, 1, 'the bare aircraft tracks');
+ assert.equal(h.opened.length, 1);
+ assert.equal(h.lastCard()[0].id, card.id);
+ });
+}
+
+for (const kind of ['card', 'label']) {
+ for (const areaFirst of [false, true]) {
+ test(`quake ${kind} over an unowned area takes the click once (${areaFirst ? 'area' : 'quake'} handler first)`, async () => {
+ let sceneHit = null;
+ let painted = null;
+ const viewer = {
+ scene: { pick: () => (sceneHit ? { id: sceneHit } : null) },
+ };
+ const { draw, unbind } = bindFakeDraw(viewer);
+ const input = fakeInput(viewer);
+ const entries = new Map();
+ const opened = [];
+ const focused = [];
+ // As the real host does, hits are what was last painted: a card a
+ // subscriber publishes during a click changes nothing for the others
+ // until the next paint, so the outcome cannot depend on their order.
+ let screen = new Map();
+ const paint = () => {
+ screen = new Map(entries);
+ };
+ const host = {
+ setEntries: (source, rows) => entries.set(source, rows),
+ setVisible() {},
+ clearSource: (source) => entries.delete(source),
+ hitTest(_x, _y, { sourceId } = {}) {
+ if (!painted || (sourceId && sourceId !== painted.sourceId))
+ return null;
+ const entry = screen
+ .get(painted.sourceId)
+ ?.find((e) => e.id === painted.entryId);
+ return entry?.interactive ? { ...painted, entry } : null;
+ },
+ };
+ const click = () => {
+ paint();
+ input.click();
+ };
+ picking.setClickCardHitTest((x, y) => host.hitTest(x, y));
+ const q = createEarthquakesLayer({
+ source: { getSnapshot: async () => [quake('ak1')] },
+ overlayHost: host,
+ input: () => input.input,
+ picking,
+ openExternal: (url) => opened.push(url),
+ focus: { requestWorldFocus: (detail) => focused.push(detail) },
+ });
+ const area = createDroneAirspaceLayer({
+ source: {
+ getSnapshot: async () => [
+ {
+ stableId: '310',
+ name: 'Fixture area',
+ typeCode: 'P',
+ type: 'Prohibited',
+ lowerAltitude: 'SFC',
+ upperAltitude: '18000',
+ polygons: [
+ [
+ [
+ [-153.4, 59.9],
+ [-153.2, 59.9],
+ [-153.2, 60.1],
+ [-153.4, 59.9],
+ ],
+ ],
+ ],
+ },
+ ],
+ },
+ overlayHost: host,
+ inputFor: () => input.input,
+ picking,
+ });
+ const layers = areaFirst ? [area, q] : [q, area];
+ try {
+ for (const layer of layers) {
+ layer.init(viewer);
+ layer.enable(viewer);
+ await layer.update(viewer);
+ }
+ const ownHit = {
+ set: draw.find('earthquakes:').spec.id,
+ id: 'earthquake:ak1',
+ };
+ const areaSet = [...draw.sets.values()].find(
+ (set) =>
+ set.spec.id.startsWith('drone-airspace:') &&
+ set.spec.id.endsWith(':fills'),
+ );
+ const areaHit = { set: areaSet.spec.id, id: 'drone-airspace:310:0' };
+ assert.equal(picking.findPickOwner(areaHit.id), null);
+ sceneHit = ownHit;
+ click();
+ assert.equal(
+ entries.get('earthquake-card')[0].id,
+ 'earthquake-card:ak1',
+ );
+ assert.equal(entries.get('drone-airspace')?.length ?? 0, 0);
+ painted = {
+ sourceId:
+ kind === 'card'
+ ? EARTHQUAKE_CARD_SOURCE_ID
+ : EARTHQUAKE_OVERLAY_SOURCE_ID,
+ entryId: kind === 'card' ? 'earthquake-card:ak1' : 'ak1',
+ };
+ sceneHit = areaHit;
+ click();
+ // The quake's card or label painted on top takes the click; the
+ // zone under it is background and stands aside: one action.
+ assert.equal(
+ entries.get('drone-airspace')?.length ?? 0,
+ 0,
+ 'the area under the overlay is not selected',
+ );
+ assert.equal(
+ entries.get('earthquake-card')[0].id,
+ 'earthquake-card:ak1',
+ 'the quake card stays',
+ );
+ assert.equal(opened.length, kind === 'card' ? 1 : 0);
+ assert.equal(focused.length, kind === 'label' ? 1 : 0);
+ // The same painted action works over its own disc and over open ground.
+ for (const hit of [ownHit, null]) {
+ sceneHit = hit;
+ click();
+ }
+ assert.equal(opened.length, kind === 'card' ? 3 : 0);
+ assert.equal(focused.length, kind === 'label' ? 3 : 0);
+ // With no overlay the area is selected and the quake deselects.
+ painted = null;
+ sceneHit = areaHit;
+ click();
+ assert.equal(entries.get('drone-airspace')?.length, 1);
+ assert.equal(entries.get('earthquake-card')?.length ?? 0, 0);
+ } finally {
+ for (const layer of layers) layer.destroy();
+ input.destroy();
+ unbind();
+ }
+ });
+ }
+}
+
+// Layers that never act on clicks still draw pickable items (air quality
+// stations, traffic heat lines, OSM places). They are not a click target, so
+// the quake card and labels painted over them keep working.
+test('quake card and label work over pickable items no layer acts on', async () => {
+ const h = harness([quake('ak1'), quake('ak2', { mag: 4 })]);
+ try {
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ const decorative = [
+ { set: 'air-quality-markers:1', id: 'aq:station-1' },
+ { set: 'traffic:1:heat', id: 'traffic:segment-9' },
+ { set: 'osm-places:1:points', id: 'osm:node-3' },
+ ];
+ for (const hit of decorative) {
+ h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', hit);
+ }
+ assert.equal(h.opened.length, decorative.length, 'the card opens USGS');
+ h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', decorative[1]);
+ assert.equal(h.focused.at(-1)?.id, 'earthquake:ak2', 'the label flies');
+ } finally {
+ h.layer.destroy();
+ }
+});
+
+// The quake card or a magnitude label on top takes the click over whatever is
+// drawn under it: a flight trail, a route, a route step or an aircraft.
+test('quake card and label act over trails, routes, steps and aircraft', async () => {
+ const h = harness([quake('ak1'), quake('ak2', { mag: 4 })]);
+ picking.registerPickOwner('test-directions', (id) =>
+ String(id).startsWith('directions:'),
+ );
+ picking.registerPickOwner('test-plane', (id) => id === 'plane-9');
+ try {
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ const trail = { set: 'trail:1:lines', id: 'gev-trail:fl-a1b2c3:head' };
+ const route = { set: 'directions:1:route', id: 'directions:route' };
+ assert.equal(picking.findPickOwner(trail.id), 'trails');
+ h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', trail);
+ h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak1', route);
+ assert.equal(h.opened.length, 2, 'the card opens USGS over both');
+ h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', trail);
+ assert.equal(h.focused.at(-1)?.id, 'earthquake:ak2', 'the label flies');
+ // A route step under the label: the label still takes it.
+ h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak1', {
+ set: 'directions:1:steps',
+ id: 'directions:step:2',
+ });
+ assert.equal(h.focused.at(-1)?.id, 'earthquake:ak1', 'over a step');
+ // So does the card over an aircraft.
+ h.clickOverlayWith(EARTHQUAKE_OVERLAY_SOURCE_ID, 'ak2', null);
+ h.clickOverlayWith(EARTHQUAKE_CARD_SOURCE_ID, 'earthquake-card:ak2', {
+ set: 'flights:1',
+ id: 'plane-9',
+ });
+ assert.equal(h.opened.length, 3, 'over an aircraft');
+ // A plain click on a trail is still not empty space: the card stays.
+ h.click(trail);
+ assert.equal(h.lastCard()[0].id, 'earthquake-card:ak2');
+ } finally {
+ picking.unregisterPickOwner('test-directions');
+ picking.unregisterPickOwner('test-plane');
+ h.layer.destroy();
+ }
+});
+
+test('quake overlays take the click over a nearby or exact fire; a bare fire acts once', async (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ let sceneHit = null;
+ const fireHit = { set: 'firms:test', id: 'fire:test' };
+ let input;
+ const h = harness([quake('ak1')], {
+ input(viewer) {
+ viewer.scene = {
+ pick: () => (sceneHit ? { id: sceneHit } : null),
+ drillPick: () => [{ id: fireHit }],
+ };
+ input ??= fakeInput(viewer);
+ return input.input;
+ },
+ });
+ const fire = { lat: 60, lon: -153, frp: 5, acqMs: 1, sensor: 'test' };
+ const fireFocus = [];
+ const state = {
+ _viewer: h.viewer,
+ _icons: { id: fireHit.set },
+ _pickIndexById: new Map([[fireHit.id, fire]]),
+ _fireByCardId: new Map(),
+ _contextIds: new Set(),
+ };
+ const selection = createFireSelection({
+ layerState: state,
+ services: {
+ picking,
+ context: {},
+ focus: { requestWorldFocus: (x) => fireFocus.push(x) },
+ },
+ components: {
+ cards: { rebuildAmbientLabels() {} },
+ model: { firePosition: () => ({ x: 1, y: 2, z: 3 }) },
+ },
+ config: { id: 'firms', name: 'FIRMS', overlayHost: h.overlayHost },
+ feed: {},
+ });
+ try {
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ selection.installClickHandler();
+ picking.registerPickOwner('firms', (id) => state._pickIndexById.has(id));
+ h.overlayHits.set(EARTHQUAKE_OVERLAY_SOURCE_ID, {
+ sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID,
+ entryId: 'ak1',
+ });
+ input.click();
+ assert.equal(h.focused.length, 1, 'label acts on the exact miss');
+ assert.equal(fireFocus.length, 0, 'nearby fire does not act');
+ h.overlayHits.clear();
+ h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, {
+ sourceId: EARTHQUAKE_CARD_SOURCE_ID,
+ entryId: 'earthquake-card:ak1',
+ });
+ input.click();
+ assert.equal(h.opened.length, 1, 'selected card opens once');
+ assert.equal(fireFocus.length, 0);
+ sceneHit = fireHit;
+ input.click();
+ assert.equal(fireFocus.length, 0, 'an exact fire under the card does not');
+ assert.equal(h.opened.length, 2, 'the card on top acts');
+ h.overlayHits.clear();
+ input.click();
+ assert.equal(fireFocus.length, 1, 'the bare fire acts');
+ assert.equal(h.opened.length, 2);
+ } finally {
+ selection.removeClickHandler();
+ picking.unregisterPickOwner('firms');
+ h.layer.destroy();
+ input?.destroy();
+ }
+});
+
+// A tap that drifts more than the tracking click travel is a drag: the quake
+// card ignores it, as the aircraft layers do.
+test('a quake card takes a still tap beside an aircraft but not a dragged one', async (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const plane = { set: 'flights:1', id: 'plane-9' };
+ let sceneHit = null;
+ let nearby = null;
+ let input;
+ const h = harness([quake('ak1')], {
+ input(viewer) {
+ viewer.scene = {
+ pick: () => (sceneHit ? { id: sceneHit } : null),
+ drillPick: () => (nearby ? [{ id: nearby }] : []),
+ };
+ input = fakeInput(viewer);
+ return input.input;
+ },
+ });
+ picking.registerPickOwner('test-plane', (id) => id === plane.id);
+ t.after(() => {
+ picking.unregisterPickOwner('test-plane');
+ h.layer.destroy();
+ input?.destroy();
+ });
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ sceneHit = { set: h.discs().spec.id, id: 'earthquake:ak1' };
+ input.click();
+ const card = h.lastCard()[0];
+ h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, {
+ sourceId: EARTHQUAKE_CARD_SOURCE_ID,
+ entryId: card.id,
+ });
+ sceneHit = null;
+ nearby = plane;
+ // A still tap: the card on top takes it over the aircraft's contact.
+ input.tap({ x: 10, y: 10 });
+ assert.equal(h.opened.length, 1);
+ // A tap that drifts 10 px: the aircraft ignores it, so the card opens.
+ input.down({ x: 10, y: 10 });
+ input.move({ x: 20, y: 10 }, { x: 10, y: 10 });
+ input.up({ x: 20, y: 10 });
+ input.click({ x: 20, y: 10 });
+ assert.equal(h.opened.length, 1, 'a drag opens nothing');
+});
+
+// A pan that ends near where it began still raises a click: it must not
+// select a quake, fly to one, open its source or clear the selection.
+test('a drag that ends on a quake does nothing; a long press selects but neither opens nor clears', async () => {
+ const drag = { travelPx: 12, durationMs: 120 };
+ const hold = { travelPx: 0, durationMs: 900 };
+ const h = harness([quake('ak1'), quake('ak2')]);
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ const disc = (id) => ({ set: h.discs().spec.id, id: `earthquake:${id}` });
+ h.click(disc('ak1'), disc('ak1'), drag);
+ assert.equal(h.cards.length, 0, 'a drag over a disc selects nothing');
+ h.overlayHits.set(EARTHQUAKE_OVERLAY_SOURCE_ID, {
+ sourceId: EARTHQUAKE_OVERLAY_SOURCE_ID,
+ entryId: 'ak2',
+ });
+ h.click(null, null, drag);
+ h.overlayHits.clear();
+ assert.equal(h.focused.length, 0, 'a drag over a label does not fly');
+ h.click(disc('ak1'), disc('ak1'), hold);
+ const card = h.lastCard()[0];
+ assert.ok(card, 'a long press on a disc selects it');
+ h.overlayHits.set(EARTHQUAKE_CARD_SOURCE_ID, {
+ sourceId: EARTHQUAKE_CARD_SOURCE_ID,
+ entryId: card.id,
+ });
+ h.click(null, null, hold);
+ h.overlayHits.clear();
+ assert.deepEqual(h.opened, [], 'a long press does not open the source');
+ const cardsBefore = h.cards.length;
+ h.click(null, null, drag);
+ h.click(null, null, hold);
+ assert.equal(
+ h.cards.length,
+ cardsBefore,
+ 'a drag or hold on the map keeps it',
+ );
+ assert.ok(h.lastCard().length, 'still selected');
+ h.click(null);
+ assert.deepEqual(h.lastCard(), [], 'a clean click on the map clears it');
+ h.layer.destroy();
+});
+
+// A refresh that no longer carries the selected quake evicts it, as other
+// feeds report; a click on empty map is a deliberate clear.
+test('a quake that ages out of the feed is cleared as evicted', async () => {
+ const clears = [];
+ const context = {
+ registerEntityContext: (record) => ({ ...record, id: record.id }),
+ selectEntityContext() {},
+ clearSelectedEntityContextForLayer: (layerId, options) =>
+ clears.push([layerId, options?.evicted === true]),
+ getContextStore: () => ({ entities: new Map() }),
+ };
+ const h = harness([quake('ak1'), quake('ak2')], { context });
+ h.layer.enable(h.viewer);
+ await h.layer.update(h.viewer);
+ h.clickDisc('ak1');
+ h.setRows([quake('ak2')]);
+ await h.layer.update(h.viewer);
+ assert.deepEqual(clears.at(-1), ['earthquakes', true], 'aged out: evicted');
+ h.clickDisc('ak2');
+ h.click(null);
+ assert.deepEqual(clears.at(-1), ['earthquakes', false], 'empty map');
+ h.layer.destroy();
+});
diff --git a/src/layers/firms/lifecycle.js b/src/layers/firms/lifecycle.js
index e866894c3b..53aa729667 100644
--- a/src/layers/firms/lifecycle.js
+++ b/src/layers/firms/lifecycle.js
@@ -78,8 +78,11 @@ export function createLifecycle({
* answers a detection record from the same source, or null) selects it
* and moves the camera to it as a click on its marker does, the selected
* fire's card shows, and a click on empty space clears the selection.
+ * Its optional `focusRangeM(record)` gives how far, in metres, the camera
+ * stands from a fire it draws when moving to it, for fires drawn larger
+ * than a marker; without one, or for null, the usual fire framing holds.
* `null` brings the markers back. The selection is kept either way.
- * @param {?{hitTest: (screenPosition: {x: number, y: number}) => ?Object}} standIn
+ * @param {?{hitTest: (screenPosition: {x: number, y: number}) => ?Object, focusRangeM?: (record: Object) => ?number}} standIn
*/
setMarkerStandIn(standIn) {
layerState._standIn =
diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js
index c3e076ff37..4da3da2c5b 100644
--- a/src/layers/firms/selection.js
+++ b/src/layers/firms/selection.js
@@ -13,7 +13,7 @@ export function createSelection({
config,
feed,
}) {
- const { resolvePickId, isOwnedByOtherLayer } = services.picking;
+ const { resolvePickId, isOwnedByOtherLayer, clickCard } = services.picking;
const { requestWorldFocus } = services.focus;
const {
selectEntityContext,
@@ -21,7 +21,7 @@ export function createSelection({
getContextStore,
registerEntityContext,
} = services.context;
- const { id, name, overlayHost } = config;
+ const { id, name } = config;
/**
* Install the LEFT_CLICK handler for fire selection (enable-time only,
@@ -34,10 +34,19 @@ export function createSelection({
if (layerState._clickSubscription || !layerState._viewer) return;
const input = inputFor(layerState._viewer);
layerState._clickSubscription = input.onClick((event) => {
- const picked = event.topHit;
- const pickedId = picked ? resolvePickId(picked) : null;
- // A pick that belongs to a sibling layer (e.g. an aircraft) is not
- // "empty space" — leave the selection alone and let that layer handle it.
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: ours acts whatever is drawn under it;
+ // another layer's is that layer's click.
+ const top = clickCard?.(event) ?? null;
+ if (top) {
+ if (top.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return;
+ const carded = layerState._fireByCardId.get(top.entryId);
+ if (carded) selectAndFocusFire(carded);
+ return;
+ }
+ const pickedId = resolvePickId(event.topHit ?? null);
+ // A pick that belongs to a sibling layer (an aircraft, a flight trail)
+ // is not "empty space": leave the selection alone.
const otherLayer = Boolean(pickedId && isOwnedByOtherLayer(id, pickedId));
// The stand-in is asked where markers are picked: the click corrected
// for the sensor style (`event.position`), and only when no sibling
@@ -52,18 +61,6 @@ export function createSelection({
return;
}
if (otherLayer) return;
- const cardHit = 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);
- return;
- }
clearFireSelection();
});
}
@@ -77,11 +74,15 @@ export function createSelection({
function selectAndFocusFire(fire) {
selectFire(fire);
+ // A stand-in that draws the fire larger than a marker says how far the
+ // camera stands from it (`setMarkerStandIn`).
+ const rangeM = layerState._standIn?.focusRangeM?.(fire);
requestWorldFocus({
kind: 'fire',
id: fireDetectionKey(fire),
label: t('FIRE'),
position: components.model.firePosition(fire),
+ ...(Number.isFinite(rangeM) && rangeM > 0 ? { rangeM } : {}),
});
}
diff --git a/src/layers/firms/selection.test.mjs b/src/layers/firms/selection.test.mjs
new file mode 100644
index 0000000000..4c55729dfe
--- /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 { clickCard, 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 Space Missions label may
+ * take, with a fire's card under every click. */
+function selectionHarness(t) {
+ const viewer = { scene: { canvas: {}, pick: () => null } };
+ const fake = fakeInputUnderLabel(viewer, {
+ beneath: () => ({
+ sourceId: FIRMS_OVERLAY_SOURCE_ID,
+ entryId: 'firms-card:1',
+ }),
+ });
+ 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, clickCard },
+ 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',
+ },
+ });
+ selection.installClickHandler();
+ t.after(() => selection.removeClickHandler());
+ return { fake, layerState, fire, focused, cleared };
+}
+
+test("a click on a mission label over a fire's card 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 on a mission label keeps 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']);
+ // The label on top is its own click: the fire stays selected.
+ h.fake.label.over = true;
+ h.fake.click();
+ assert.equal(h.layerState._selectedFire, h.fire);
+ assert.deepEqual(h.cleared, []);
+ assert.deepEqual(h.focused, ['fire']);
+});
diff --git a/src/layers/flights/ownership.test.mjs b/src/layers/flights/ownership.test.mjs
index 6fa9f9d511..47175ff6ed 100644
--- a/src/layers/flights/ownership.test.mjs
+++ b/src/layers/flights/ownership.test.mjs
@@ -4,6 +4,8 @@ import { createCivilFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createEnrichment } from './enrichment.js';
import { createTracking } from './tracking.js';
+import { fakeInput } from '../../input/testDoubles.mjs';
+import * as picking from '../../data/pickRegistry.js';
import { LiveSourceError } from '../../sources/live/contract.js';
function services() {
@@ -609,6 +611,50 @@ test('a route answer for a callsign the plane no longer flies is dropped', async
flightState.lifetime.abort();
});
+// The card or label painted on top takes the click: an aircraft under another
+// layer's card is not even picked, so it is neither tracked nor released.
+test("another layer's card over an aircraft keeps the click", (t) => {
+ const previousDocument = globalThis.document;
+ globalThis.document = Object.assign(new EventTarget(), {
+ body: { classList: { contains: () => false } },
+ });
+ let picks = 0;
+ const viewer = {
+ scene: {
+ canvas: new EventTarget(),
+ pick: () => {
+ picks++;
+ return null;
+ },
+ },
+ };
+ const input = fakeInput(viewer);
+ const flightState = createFlightState({ services: services() });
+ flightState._trackedEntityChangedRemove = () => {};
+ const tracking = createTracking({
+ flightState,
+ services: { ...services(), picking },
+ parts: {},
+ layer: {},
+ });
+ tracking._installClickHandler(viewer);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ picking.setClickCardHitTest(() => top);
+ t.after(() => {
+ picking.setClickCardHitTest(null);
+ flightState._clickSubscription?.();
+ input.destroy();
+ flightState.lifetime.abort();
+ if (previousDocument === undefined) delete globalThis.document;
+ else globalThis.document = previousDocument;
+ });
+ input.tap({ x: 10, y: 10 });
+ assert.equal(picks, 0, 'covered: the scene under the card is not picked');
+ top = null;
+ input.tap({ x: 10, y: 10 });
+ assert.ok(picks > 0, 'open map: the click reaches the scene');
+});
+
test("a type lookup overrides the feed's type and fills the type name", async () => {
const queries = [];
const source = {
diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js
index 1243ae267d..d4aa51a710 100644
--- a/src/layers/flights/tracking.js
+++ b/src/layers/flights/tracking.js
@@ -88,7 +88,8 @@ export function createTracking({
const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout;
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
services.camera;
- const { resolvePickId, isOwnedByOtherLayer } = services.picking;
+ const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
+ services.picking;
const flightsLayer = layer;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
@@ -1316,6 +1317,9 @@ export function createTracking({
// first-person reference. A globe click must not fall through to the
// normal empty-space deselection path; cockpit has explicit exit controls.
if (document.body.classList.contains('cockpit-mode')) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard?.(event)) return;
const picked = event.hit;
if (picked) {
diff --git a/src/layers/ghostMaps/index.js b/src/layers/ghostMaps/index.js
index df94883845..a88d661e60 100644
--- a/src/layers/ghostMaps/index.js
+++ b/src/layers/ghostMaps/index.js
@@ -707,13 +707,19 @@ export function createGhostMapsLayer({
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
- const cardHit = overlayHost.hitTest?.(
- event.screenPosition?.x,
- event.screenPosition?.y,
- { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID },
- );
- if (cardHit && cardHit.entryId === _selectedCardId) {
- if (_selectedLink && openExternal) openExternal(_selectedLink);
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: ours opens its source whatever is drawn
+ // under it; another layer's is that layer's click, so the maps under
+ // it do not act and the selection stays.
+ const cardHit = picking.clickCard?.(event) ?? null;
+ if (cardHit) {
+ if (
+ cardHit.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID &&
+ cardHit.entryId === _selectedCardId &&
+ _selectedLink &&
+ openExternal
+ )
+ openExternal(_selectedLink);
return;
}
const picked = event.topHit;
diff --git a/src/layers/ghostMaps/lifecycle.test.mjs b/src/layers/ghostMaps/lifecycle.test.mjs
index 675bdefa24..9bf2c8648d 100644
--- a/src/layers/ghostMaps/lifecycle.test.mjs
+++ b/src/layers/ghostMaps/lifecycle.test.mjs
@@ -1,8 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { setLocale } from '../../i18n/index.js';
-import { createGhostMapsLayer } from './index.js';
+import { createGhostMapsLayer, GHOSTMAPS_OVERLAY_SOURCE_ID } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
+import { inputFor } from '../../input/dispatcher.js';
+import { MISSION_LABEL } from '../../input/testDoubles.mjs';
+import { clickCard, setClickCardHitTest } from '../../data/pickRegistry.js';
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
function element(localName, children = [], value = '', attributes = {}) {
@@ -672,3 +675,109 @@ 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 click on a mission label over the open card never opens the card's link, and keeps the card open", async (t) => {
+ const cards = [];
+ const opened = [];
+ let cardUnder = null;
+ // A Space Missions label painted over the map: while it is over, it takes
+ // each click and is the card on top; under it may lie our open card.
+ let labelOver = false;
+ setClickCardHitTest(() =>
+ labelOver
+ ? MISSION_LABEL
+ : cardUnder
+ ? { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID, entryId: cardUnder }
+ : null,
+ );
+ t.after(() => setClickCardHitTest(null));
+ const { layer, viewer, click } = fixture(t, {
+ now: () => Date.UTC(2026, 10, 3, 12),
+ reports: [
+ {
+ name: 'Linked',
+ description:
+ 'Date 11/2/2026 ' +
+ 'Source report
',
+ },
+ ],
+ controls: {
+ overlayHost: { setEntries: (_id, entries) => cards.push(entries) },
+ picking: { resolvePickId: (picked) => picked?.id ?? null, clickCard },
+ openExternal: (url) => opened.push(url),
+ },
+ });
+ inputFor(viewer).onOverlayClick(() => labelOver);
+ await layer.update(viewer);
+ click('ghostmaps:cip:0:0');
+ const [card] = cards.at(-1);
+ assert.equal(card.interactive, true);
+
+ // The open card lies under the label: the click opens nothing, and the
+ // label on top is its own click, so the card stays open.
+ cardUnder = card.id;
+ labelOver = true;
+ click(null);
+ assert.deepEqual(opened, [], 'the link beneath the label is not opened');
+ assert.equal(cards.at(-1)[0]?.id, card.id, 'the card stays open');
+
+ // Off the label, a click on the open card opens its link.
+ labelOver = false;
+ click(null);
+ assert.deepEqual(opened, ['https://example.com/report']);
+});
+
+test('a covered selected card yields while genuine GhostMaps markers still select', async (t) => {
+ const cards = [];
+ const opened = [];
+ let painted = [];
+ const { layer, viewer, click } = fixture(t, {
+ reports: [
+ {
+ name: 'First',
+ description: 'Source ',
+ },
+ {
+ name: 'Second',
+ description: 'Source ',
+ },
+ ],
+ controls: {
+ overlayHost: {
+ setEntries: (_id, entries) => cards.push(entries),
+ hitTest: (_x, _y, { sourceId } = {}) =>
+ painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null,
+ },
+ picking: {
+ resolvePickId: (picked) => picked,
+ // The card on top at a click, as the registry answers from the host.
+ clickCard: () => painted[0] ?? null,
+ },
+ openExternal: (url) => opened.push(url),
+ },
+ });
+ await layer.update(viewer);
+ click('ghostmaps:cip:0:0');
+ const first = cards.at(-1)[0];
+ const foreign = {
+ sourceId: 'earthquake-card',
+ entryId: 'earthquake-card:ak1',
+ };
+ painted = [foreign, { sourceId: 's2-ghostmaps', entryId: first.id }];
+ click(null);
+ assert.deepEqual(opened, []);
+ assert.equal(cards.at(-1)[0].id, first.id);
+ // A marker under another layer's card is that card's click too.
+ click('ghostmaps:cip:1:0');
+ assert.equal(cards.at(-1)[0].id, first.id, 'a covered marker yields');
+ painted = [];
+ click('ghostmaps:cip:1:0');
+ const second = cards.at(-1)[0];
+ assert.notEqual(second.id, first.id, 'a bare marker selects');
+ painted = [{ sourceId: 's2-ghostmaps', entryId: second.id }];
+ click(null);
+ assert.deepEqual(opened, ['https://example.com/second']);
+ painted = [];
+ click(null);
+ assert.deepEqual(cards.at(-1), [], 'bare map still clears the selection');
+});
diff --git a/src/layers/installations/selection.js b/src/layers/installations/selection.js
index 323b7a1549..28a9301d0b 100644
--- a/src/layers/installations/selection.js
+++ b/src/layers/installations/selection.js
@@ -1,4 +1,5 @@
import { inputFor } from '../../input/dispatcher.js';
+import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
export function createSelection({
@@ -52,6 +53,9 @@ export function createSelection({
const input = inputFor(viewer);
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard(event)) return;
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
const hit = event.drawHit;
diff --git a/src/layers/installations/selection.test.mjs b/src/layers/installations/selection.test.mjs
index ae6cc71fda..7844afb3ba 100644
--- a/src/layers/installations/selection.test.mjs
+++ b/src/layers/installations/selection.test.mjs
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
+import { setClickCardHitTest } from '../../data/pickRegistry.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -186,6 +187,30 @@ test('a click on a named marker point selects its site; again releases it', (t)
h.assertSelected(false);
});
+// The card or label painted on top takes the click: a site under another
+// layer's card neither selects nor releases.
+test("another layer's card over a site keeps the click", (t) => {
+ const h = harness(t);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ const setId = h.parts.namedMarkers.setId;
+ const item = h.draw.set(setId).items.get(namedPointId('base'));
+ const pointPick = { id: { set: setId, id: item.id, meta: item.meta } };
+ h.click(pointPick);
+ h.assertSelected(true);
+ h.click(undefined);
+ h.assertSelected(true);
+ h.state.selectedId = null;
+ context.clearSelectedEntityContextForLayer('military-installations');
+ h.parts.rendering.renderRecords();
+ h.click(pointPick);
+ h.assertSelected(false);
+ top = null;
+ h.click(pointPick);
+ h.assertSelected(true);
+});
+
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
const h = harness(t);
h.state.selectedId = null;
diff --git a/src/layers/launches/clickYield.test.mjs b/src/layers/launches/clickYield.test.mjs
new file mode 100644
index 0000000000..6e79243749
--- /dev/null
+++ b/src/layers/launches/clickYield.test.mjs
@@ -0,0 +1,109 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createLifecycle } from './lifecycle.js';
+import { createOverlays } from './overlays.js';
+import {
+ ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
+ ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
+} from './policy.js';
+import { fakeInput } from '../../input/testDoubles.mjs';
+import * as picking from '../../data/pickRegistry.js';
+
+/** Any part method is a no-op unless the test supplies it. */
+const stubs = (given = {}) =>
+ new Proxy(given, {
+ get: (target, key) => (key in target ? target[key] : () => undefined),
+ });
+
+// A mission label on top takes its click through the overlay handler first;
+// here an overlay entry under the pointer is another layer's card or label
+// painted over the mission (a quake label), and that layer takes the click,
+// so the mission is not also selected.
+test('a card painted over a launch marker keeps its click; with none the mission selects', () => {
+ const viewer = {
+ scene: {
+ pick: () => null,
+ canvas: { clientWidth: 100, clientHeight: 100 },
+ },
+ };
+ const input = fakeInput(viewer);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ const selected = [];
+ const state = { _launches: [{ id: 'L1' }], _enabled: false };
+ const { methods: lifecycle } = createLifecycle({
+ state,
+ services: {
+ render: { holdContinuousRender() {}, releaseContinuousRender() {} },
+ // The card on top at a click, as the registry answers from the host.
+ picking: { ...picking, clickCard: () => top },
+ },
+ parts: {
+ panel: stubs(),
+ overlays: stubs(),
+ launchPad: stubs(),
+ orbitRendering: stubs(),
+ replay: stubs(),
+ ingestion: stubs(),
+ rendering: stubs({
+ missionsShown: () => true,
+ missionHitsAt: () => [{ id: 'mission:L1' }],
+ launchIdFromPicks: (hits) =>
+ hits.some((hit) => hit?.id === 'mission:L1') ? 'L1' : null,
+ }),
+ selection: stubs({ setSelectedMission: (id) => selected.push(id) }),
+ },
+ source: {},
+ });
+ try {
+ // init installs the click handler; enable would start a feed load.
+ lifecycle.init(viewer);
+ state._enabled = true;
+ input.click();
+ assert.deepEqual(selected, [], 'the mission stands aside');
+ top = null;
+ input.click();
+ assert.deepEqual(
+ selected,
+ ['L1'],
+ 'with no card on top, the mission selects',
+ );
+ } finally {
+ state._inputSubscription?.();
+ input.destroy();
+ }
+});
+
+// A mission label is an interactive world-overlay entry, so the host's hit
+// test names it and every other layer reads it as the card on top: a click
+// on it never acts on what lies under it.
+test('a mission label is the card on top for every other layer', (t) => {
+ const overlays = createOverlays({
+ state: {},
+ services: {},
+ parts: {},
+ source: {},
+ });
+ const launch = {
+ id: 'L1',
+ name: 'Starlink Group 1',
+ launchTime: '2026-11-01T00:00:00Z',
+ };
+ for (const selected of [false, true]) {
+ const entry = overlays.createRocketMissionMarkerOverlayEntry(
+ launch,
+ { x: 1, y: 2, z: 3 },
+ selected,
+ );
+ assert.equal(entry.interactive, true, `selected: ${selected}`);
+ }
+ for (const sourceId of [
+ ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
+ ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
+ ]) {
+ picking.setClickCardHitTest(() => ({ sourceId, entryId: 'launch:L1' }));
+ t.after(() => picking.setClickCardHitTest(null));
+ const click = { screenPosition: { x: 10, y: 10 } };
+ assert.equal(picking.isUnderOtherCard(click, ['vessels']), true);
+ assert.equal(picking.isUnderOtherCard(click, [sourceId]), false);
+ }
+});
diff --git a/src/layers/launches/failedEntry.test.mjs b/src/layers/launches/failedEntry.test.mjs
index de7b8719b3..40436d7a9e 100644
--- a/src/layers/launches/failedEntry.test.mjs
+++ b/src/layers/launches/failedEntry.test.mjs
@@ -623,6 +623,153 @@ test('a Satellites enable that never settles still lets mission disable complete
stuck.resolve();
}
await f.settle();
+ // The saved Satellites state was kept: turning Space Missions off again
+ // once Satellites settles gives back the Satellites it turned on.
+ assert.equal(f.manager.isEnabled('satellites'), true);
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ await f.settle();
+ assert.equal(f.manager.isEnabled('rocket-launches'), false);
+ assert.equal(f.manager.isEnabled('satellites'), false);
+});
+
+test('Space Missions turned on again after a busy restore switches Satellites on', async (t) => {
+ const f = await fixture(t);
+ f.upstream.status = 200;
+ assert.equal(
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
+ true,
+ );
+ await f.settle();
+ f.state.satelliteSettleTimeoutMs = 50;
+ const satellites = f.manager.layers.get('satellites').module;
+ const enable = satellites.enable;
+ const stuck = Promise.withResolvers();
+ satellites.enable = () => stuck.promise;
+ try {
+ await f.manager.setEnabled('satellites', false);
+ void f.manager.setEnabled('satellites', true);
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ } finally {
+ satellites.enable = enable;
+ stuck.resolve();
+ }
+ await f.settle();
+ // Something else switches Satellites off, then Space Missions comes back.
+ await f.manager.setEnabled('satellites', false);
+ await f.settle();
+ assert.equal(f.manager.isEnabled('satellites'), false);
+ assert.equal(
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
+ true,
+ );
+ await f.settle();
+ assert.equal(f.manager.isEnabled('satellites'), true);
+ // Its own off still gives back the Satellites from before the first start.
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ await f.settle();
+ assert.equal(f.manager.isEnabled('satellites'), false);
+});
+
+test('a Satellites switch made between missions is what the next mission gives back', async (t) => {
+ const f = await fixture(t);
+ f.upstream.status = 200;
+ assert.equal(
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
+ true,
+ );
+ await f.settle();
+ f.state.satelliteSettleTimeoutMs = 50;
+ const satellites = f.manager.layers.get('satellites').module;
+ const enable = satellites.enable;
+ const stuck = Promise.withResolvers();
+ satellites.enable = () => stuck.promise;
+ try {
+ await f.manager.setEnabled('satellites', false);
+ void f.manager.setEnabled('satellites', true);
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ } finally {
+ satellites.enable = enable;
+ stuck.resolve();
+ }
+ await f.settle();
+ // The person switches Satellites on, then something else switches it off.
+ await f.manager.setEnabled('satellites', true, { origin: 'user' });
+ await f.settle();
+ await f.manager.setEnabled('satellites', false);
+ await f.settle();
+ assert.equal(
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
+ true,
+ );
+ await f.settle();
+ assert.equal(f.manager.isEnabled('satellites'), true);
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ await f.settle();
+ assert.equal(f.manager.isEnabled('satellites'), false);
+});
+
+test('a Satellites setting changed between missions survives the next one', async (t) => {
+ const f = await fixture(t);
+ f.upstream.status = 200;
+ assert.equal(
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
+ true,
+ );
+ await f.settle();
+ f.state.satelliteSettleTimeoutMs = 50;
+ const satellites = f.manager.layers.get('satellites').module;
+ const enable = satellites.enable;
+ const stuck = Promise.withResolvers();
+ satellites.enable = () => stuck.promise;
+ try {
+ await f.manager.setEnabled('satellites', false);
+ void f.manager.setEnabled('satellites', true);
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ } finally {
+ satellites.enable = enable;
+ stuck.resolve();
+ }
+ await f.settle();
+ f.manager.setLayerParams(
+ 'satellites',
+ { showOrbits: false },
+ { origin: 'user' },
+ );
+ await f.settle();
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
+ await f.settle();
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ await f.settle();
+ assert.equal(f.manager.getLayerParams('satellites').showOrbits, false);
+});
+
+test('tracking stopped by a place search during a mission stays stopped after it', async (t) => {
+ const f = await fixture(t);
+ f.upstream.status = 200;
+ assert.equal(
+ await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
+ true,
+ );
+ await f.settle();
+ f.manager.setLayerParams(
+ 'satellites',
+ { selectedSatTrackingId: 25544 },
+ { origin: 'voice' },
+ );
+ await f.settle();
+ // A place search stops tracking with the tool origin.
+ f.manager.setLayerParams(
+ 'satellites',
+ { selectedSatTrackingId: null },
+ { origin: 'tool' },
+ );
+ await f.settle();
+ await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
+ await f.settle();
+ assert.equal(
+ f.manager.getLayerParams('satellites').selectedSatTrackingId ?? null,
+ null,
+ );
});
test('a failed Satellites restore still clears the selected mission panel', async (t) => {
diff --git a/src/layers/launches/ingestion.js b/src/layers/launches/ingestion.js
index 35a4c47771..d16bd398b4 100644
--- a/src/layers/launches/ingestion.js
+++ b/src/layers/launches/ingestion.js
@@ -1,4 +1,8 @@
-import { MAX_POST_TLE_RETRIES, POST_TLE_RETRY_DELAY_MS } from './policy.js';
+import {
+ MAX_POST_TLE_RETRIES,
+ POST_TLE_RETRY_DELAY_MS,
+ cockpitActive,
+} from './policy.js';
/**
* Let pending Satellites work finish, including requests that join it while
@@ -108,7 +112,7 @@ export function createIngestion({
async function captureSatelliteDependency() {
const manager = layerState._dataManager;
- if (!manager || layerState._satelliteStateBeforeMission) return;
+ if (!manager) return;
const token = layerState._lifecycleToken;
// Let a pending Satellites action finish before reserving dependency ON.
// A successful explicit OFF can cancel this mission entry while we wait.
@@ -127,12 +131,24 @@ export function createIngestion({
!manager.isEffectivelyEnabled('rocket-launches'))
)
return;
- layerState._satelliteStateBeforeMission = {
- enabled: manager.isEnabled('satellites'),
- params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
- manager.getLayerParams('satellites'),
- ),
- };
+ // A saved state kept by a restore that could not finish (Satellites was
+ // busy) is still the one from before the mission: keep it, and switch
+ // Satellites on for the mission again. A Satellites switch the person
+ // made since (restoreVisibility false) settled its visibility, so it
+ // is taken as it is now; its params are still the saved ones.
+ const kept = layerState._satelliteStateBeforeMission;
+ if (kept?.restoreVisibility === false)
+ layerState._satelliteStateBeforeMission = {
+ enabled: manager.isEnabled('satellites'),
+ params: kept.params,
+ };
+ else if (!kept)
+ layerState._satelliteStateBeforeMission = {
+ enabled: manager.isEnabled('satellites'),
+ params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
+ manager.getLayerParams('satellites'),
+ ),
+ };
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsForSpaceMissions(
@@ -179,18 +195,21 @@ export function createIngestion({
layerState._satelliteStateBeforeMission !== snapshot
)
return;
+ // An accepted Satellites action owns visibility through mission teardown.
+ const restoreVisibility = snapshot.restoreVisibility !== false;
+ // Satellites is still busy: change nothing and keep the saved state, so
+ // turning Space Missions off again can finish the restore.
+ if (restoreVisibility && !idle)
+ throw new Error(
+ 'Space Missions could not restore the satellites layer: it did not settle',
+ );
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsAfterSpaceMissions(snapshot.params),
);
- // An accepted Satellites action owns visibility through mission teardown.
- if (snapshot.restoreVisibility === false) return;
- if (!idle)
- throw new Error(
- 'Space Missions could not restore the satellites layer: it did not settle',
- );
+ if (!restoreVisibility) return;
const restored = await manager.setEnabled('satellites', snapshot.enabled);
if (
restored === false ||
@@ -249,7 +268,9 @@ export function createIngestion({
parts.selection.setSelectedMission(null, false);
} else {
parts.selection.setSelectedMission(layerState._selectedLaunchId, true);
- if (layerState._focusAfterActiveLookup) {
+ // The cockpit holds the camera: a mission picked there is not flown
+ // to when its orbit arrives.
+ if (layerState._focusAfterActiveLookup && !cockpitActive()) {
parts.selection.focusMission(
launches.find(
(launch) => launch.id === layerState._selectedLaunchId,
diff --git a/src/layers/launches/labelClick.test.mjs b/src/layers/launches/labelClick.test.mjs
index 592b5ccaaf..bd44c62187 100644
--- a/src/layers/launches/labelClick.test.mjs
+++ b/src/layers/launches/labelClick.test.mjs
@@ -54,6 +54,7 @@ function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
};
const state = createState({ services });
const focused = [];
+ const moved = [];
const restoreFailure = { error: null };
const parts = {
panel: stub(),
@@ -63,6 +64,7 @@ function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
orbitRendering: stub(),
selection: stub({
setSelectedMission: (id) => focused.push(id),
+ focusMission: (launch) => moved.push(launch.id),
}),
satelliteIntents: stub(),
ingestion: stub({
@@ -97,6 +99,7 @@ function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
});
return {
focused,
+ moved,
ambient,
state,
lifecycle,
@@ -118,11 +121,16 @@ const label = (
entryId,
});
-test('a mission label click focuses its launch and stops the click there', (t) => {
- const r = rig(t, { overlayHit: label('launch:L2') });
+test('a mission label click focuses its launch and covers the geometry beneath', (t) => {
+ const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
r.click();
- assert.deepEqual(r.focused, ['L2']);
- assert.equal(r.ambient.length, 0, 'the layers beneath do not see it');
+ assert.deepEqual(r.focused, ['L2'], 'the mission beneath is not picked');
+ // Other layers still hear it, as a click on the label rather than on the
+ // geometry beneath; the label is the card on top, so they keep their
+ // selections.
+ assert.equal(r.ambient.length, 1);
+ assert.equal(r.ambient[0].overlay, true);
+ assert.equal(r.ambient[0].drawHit, null);
r.setHit(label('launch:L1', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID));
r.click();
@@ -156,17 +164,20 @@ test('a throwing globe-pick listener does not stop the pick', (t) => {
r.click();
assert.deepEqual(r.focused, ['L1']);
assert.deepEqual(heard, ['L1']);
- assert.equal(r.ambient.length, 0);
+ assert.equal(r.ambient.length, 1);
+ assert.equal(r.ambient[0].overlay, true);
});
-test('a mission label for an unknown launch falls through to other layers', (t) => {
+test('a mission label for an unknown launch selects nothing', (t) => {
const r = rig(t, {
overlayHit: label('launch:gone'),
geometryLaunchId: 'L1',
});
r.click();
assert.deepEqual(r.focused, [], 'nothing is focused');
- assert.equal(r.ambient.length, 1, 'other layers still get the click');
+ // Other layers hear the click; the label is still the card on top for
+ // them (clickYield.test.mjs), so none acts under it.
+ assert.equal(r.ambient.length, 1);
});
test("another layer's label keeps the click above mission geometry", (t) => {
@@ -185,8 +196,8 @@ test("another layer's label keeps the click above mission geometry", (t) => {
assert.deepEqual(r.focused, ['L1']);
});
-test('a mission label leaves the click to the cockpit while it is on', (t) => {
- const r = rig(t, { overlayHit: label('launch:L2') });
+test('in the cockpit a mission label or dot selects its mission without moving the camera', (t) => {
+ const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
@@ -200,8 +211,28 @@ test('a mission label leaves the click to the cockpit while it is on', (t) => {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
- assert.deepEqual(r.focused, []);
- assert.equal(r.ambient.length, 1, 'the cockpit click handler gets it');
+ assert.deepEqual(r.focused, ['L2'], 'the mission is selected');
+ assert.deepEqual(r.moved, [], 'the cockpit keeps the camera');
+ // The dot, with no label over it, does the same.
+ r.setHit(null);
+ Object.defineProperty(globalThis, 'document', {
+ configurable: true,
+ value: {
+ body: { classList: { contains: (name) => name === 'cockpit-mode' } },
+ },
+ });
+ try {
+ r.click();
+ } finally {
+ if (previous) Object.defineProperty(globalThis, 'document', previous);
+ else delete globalThis.document;
+ }
+ assert.deepEqual(r.focused, ['L2', 'L1']);
+ assert.deepEqual(r.moved, []);
+ r.setHit(label('launch:L2'));
+ // Out of the cockpit the same click moves there too.
+ r.click();
+ assert.deepEqual(r.moved, ['L2']);
});
test('destroy releases the click handlers when the Satellites restore fails', async (t) => {
diff --git a/src/layers/launches/lifecycle.js b/src/layers/launches/lifecycle.js
index 8cfc4970d9..947c4750d1 100644
--- a/src/layers/launches/lifecycle.js
+++ b/src/layers/launches/lifecycle.js
@@ -5,6 +5,7 @@ import { worldClock } from '../../time/worldClock.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
+ cockpitActive,
} from './policy.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -154,13 +155,6 @@ function restoreCameraView(viewer, view, landedView) {
/** The longest name a timeline mark carries, as in the mission index. */
const MARK_LABEL_LENGTH = 27;
-/** Whether the cockpit view is on. */
-function cockpitActive() {
- return Boolean(
- globalThis.document?.body?.classList?.contains?.('cockpit-mode'),
- );
-}
-
function markerLaunchId(hit) {
if (
hit?.sourceId !== ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID &&
@@ -181,12 +175,12 @@ export function createLifecycle({
services.overlays?.hitTestWorldOverlay?.(position?.x, position?.y);
const missionsShown = () =>
layerState._enabled && parts.rendering.missionsShown();
- const focusLaunch = (id) => {
+ const focusLaunch = (id, { move = true } = {}) => {
if (!id) return false;
const launch = layerState._launches.find((entry) => entry.id === id);
if (!launch) return false;
parts.selection.setSelectedMission(launch.id);
- parts.selection.focusMission(launch);
+ if (move) parts.selection.focusMission(launch);
for (const listener of [...layerState._globePickListeners]) {
try {
listener(launch.id);
@@ -245,21 +239,31 @@ export function createLifecycle({
const input = inputFor(viewer);
const overlayClicks = new WeakSet();
const unsubscribeLabelClick = input.onOverlayClick((event) => {
- // The cockpit reads ambient clicks; a mission label must not take them.
- if (!missionsShown() || cockpitActive()) return false;
+ if (!missionsShown()) return false;
const hit = overlayAt(event.screenPosition);
if (!hit) return false;
// Capture the painted hit before other handlers can invalidate the
// overlay. An unrelated label keeps the click above mission geometry.
overlayClicks.add(event);
- return focusLaunch(markerLaunchId(hit));
+ // The label is the card on top, so every other layer and the cockpit
+ // leave its click alone. In the cockpit, which holds the camera, the
+ // label and the dot select the mission without moving there.
+ return focusLaunch(markerLaunchId(hit), { move: !cockpitActive() });
});
const unsubscribeClick = input.onClick((event) => {
- if (!missionsShown() || overlayClicks.has(event)) return;
+ // Another layer's card or label on top is that layer's click, read
+ // once per click as every layer reads it.
+ if (
+ !missionsShown() ||
+ overlayClicks.has(event) ||
+ services.picking?.clickCard?.(event)
+ )
+ return;
focusLaunch(
parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
),
+ { move: !cockpitActive() },
);
});
hover = createLaunchHover({
diff --git a/src/layers/launches/missionCycler.test.mjs b/src/layers/launches/missionCycler.test.mjs
index 1f07a12cff..06bf4bf0bf 100644
--- a/src/layers/launches/missionCycler.test.mjs
+++ b/src/layers/launches/missionCycler.test.mjs
@@ -177,3 +177,36 @@ test('without a Satellites action the exit restores the pre-mission visibility',
['enabled', 'satellites', false],
]);
});
+
+test('a Satellites layer that does not settle keeps the saved state for the next exit', async () => {
+ const r = satelliteRig({ enabledBefore: false });
+ let idle = false;
+ r.state._dataManager.waitForLayerIdle = async () => idle;
+ await assert.rejects(
+ r.ingestion.restoreSatelliteDependency(),
+ /did not settle/,
+ );
+ assert.deepEqual(r.calls, [], 'nothing changes while Satellites is busy');
+ assert.deepEqual(r.state._satelliteStateBeforeMission, {
+ enabled: false,
+ params: { mode: 'before' },
+ });
+
+ // Turning Space Missions off again once Satellites settles finishes it.
+ idle = true;
+ await r.ingestion.restoreSatelliteDependency();
+ assert.deepEqual(r.calls, [
+ ['params', 'satellites', { mode: 'before' }],
+ ['enabled', 'satellites', false],
+ ]);
+ assert.equal(r.state._satelliteStateBeforeMission, null);
+});
+
+test('a Satellites action the person took still gets its parameters back when Satellites is busy', async () => {
+ const r = satelliteRig({ enabledBefore: false });
+ r.state._dataManager.waitForLayerIdle = async () => false;
+ r.state._satelliteStateBeforeMission.restoreVisibility = false;
+ await r.ingestion.restoreSatelliteDependency();
+ assert.deepEqual(r.calls, [['params', 'satellites', { mode: 'before' }]]);
+ assert.equal(r.state._satelliteStateBeforeMission, null);
+});
diff --git a/src/layers/launches/panel.js b/src/layers/launches/panel.js
index 470adc9d9e..9dc827d5ca 100644
--- a/src/layers/launches/panel.js
+++ b/src/layers/launches/panel.js
@@ -380,14 +380,20 @@ export function createPanel({ state: layerState, services, parts, source }) {
function scheduleMissionRosterPreview(index) {
const launch = layerState._launches[index];
- if (!launch || layerState._selectedLaunchId) return;
+ // Once the layer is going off (its Satellites restore may still be
+ // running) hovering or focusing a roster row moves no camera.
+ if (!launch || layerState._selectedLaunchId || !layerState._enabled) return;
if (layerState._missionRosterHoverTimer)
clearTimeout(layerState._missionRosterHoverTimer);
layerState._hoveredRosterLaunchId = launch.id;
parts.overlays.syncMissionOverlayEntries();
layerState._missionRosterHoverTimer = setTimeout(() => {
layerState._missionRosterHoverTimer = null;
- if (layerState._hoveredRosterLaunchId !== launch.id) return;
+ if (
+ layerState._hoveredRosterLaunchId !== launch.id ||
+ !layerState._enabled
+ )
+ return;
const currentLaunch = resolveMissionRosterPreviewLaunch(
layerState._launches,
launch.id,
diff --git a/src/layers/launches/panel.test.mjs b/src/layers/launches/panel.test.mjs
index 9075d5e5cb..4e0a558944 100644
--- a/src/layers/launches/panel.test.mjs
+++ b/src/layers/launches/panel.test.mjs
@@ -9,6 +9,7 @@ function fixture() {
const state = createState({
services: { overlays: {}, render: {} },
});
+ state._enabled = true;
const calls = [];
const parts = {
overlays: {
@@ -194,3 +195,26 @@ test('the panel commands act on the selected mission', () => {
['select', null, undefined],
]);
});
+
+test('a roster row hovered or focused while the layer goes off moves no camera', async () => {
+ const { state, panel, calls } = fixture();
+ state._launches = [launch('a'), launch('b')];
+ panel.createMissionPanel();
+ panel.renderMissionRoster();
+
+ // Hovered just before the layer goes off: the pending preview is dropped.
+ panel.commands.rosterPointerEnter(0);
+ state._enabled = false;
+ await new Promise((resolve) => setTimeout(resolve, 160));
+
+ // Hovered or focused after it went off, while the panel still shows.
+ panel.commands.rosterPointerEnter(1);
+ panel.commands.rosterFocus(1);
+ assert.equal(state._missionRosterHoverTimer, null, 'no preview is pending');
+ await new Promise((resolve) => setTimeout(resolve, 160));
+ assert.deepEqual(
+ calls.filter(([name]) => name === 'preview'),
+ [],
+ );
+ panel.clearMissionPanel();
+});
diff --git a/src/layers/launches/policy.js b/src/layers/launches/policy.js
index 34dcaae5bb..07718c26f6 100644
--- a/src/layers/launches/policy.js
+++ b/src/layers/launches/policy.js
@@ -103,3 +103,10 @@ export const TRAJECTORY_STAGE_COLORS = [
'#ffd166',
'#60a5fa',
];
+
+/** Whether the cockpit view is on; it holds the camera while it is. */
+export function cockpitActive() {
+ return Boolean(
+ globalThis.document?.body?.classList?.contains?.('cockpit-mode'),
+ );
+}
diff --git a/src/layers/launches/satelliteIntents.js b/src/layers/launches/satelliteIntents.js
index 7e646fb2fa..0870dc351b 100644
--- a/src/layers/launches/satelliteIntents.js
+++ b/src/layers/launches/satelliteIntents.js
@@ -16,6 +16,15 @@ function isExplicitOrigin(origin) {
return origin === 'user' || origin === 'voice';
}
+/**
+ * A setting changed on purpose: by the person, by voice, or by a tool such
+ * as a place search (the layer state's own rule, isExplicitLayerStateOrigin
+ * in src/data/layerState.js).
+ */
+function isDeliberateOrigin(origin) {
+ return isExplicitOrigin(origin) || origin === 'tool';
+}
+
export function createSatelliteIntents({ state: layerState }) {
const requestOrder = new Map();
let sequence = 0;
@@ -93,6 +102,25 @@ export function createSatelliteIntents({ state: layerState }) {
return stop;
}
+ /**
+ * Keep a Satellites setting changed on purpose while Space Missions holds
+ * its saved state ("show orbits" off, tracking a satellite, or a place
+ * search that stops tracking): it survives the mission teardown, as a
+ * visibility choice does.
+ */
+ function handleParams(change) {
+ if (
+ change?.type !== 'params' ||
+ change.layerId !== 'satellites' ||
+ !isDeliberateOrigin(change.origin)
+ )
+ return;
+ const previous = layerState._satelliteStateBeforeMission;
+ const requested = change.requestedParams;
+ if (!previous || !requested || typeof requested !== 'object') return;
+ previous.params = { ...previous.params, ...requested };
+ }
+
/** Settle once a Satellites OFF has finished stopping Space Missions. */
function settled() {
return pendingStop ?? Promise.resolve(false);
@@ -108,6 +136,7 @@ export function createSatelliteIntents({ state: layerState }) {
manager.subscribeVisibilityRequests?.(recordRequest) ?? null;
const unsubscribeChanges =
manager.subscribe?.((change) => {
+ handleParams(change);
void handleVisibility(change);
}) ?? null;
unsubscribe = () => {
@@ -120,6 +149,7 @@ export function createSatelliteIntents({ state: layerState }) {
connect,
settled,
handleVisibility,
+ handleParams,
recordRequest,
offFollowsMissionsEntry,
};
diff --git a/src/layers/launches/selection.js b/src/layers/launches/selection.js
index 0f35eb28dc..281d0ee85c 100644
--- a/src/layers/launches/selection.js
+++ b/src/layers/launches/selection.js
@@ -11,7 +11,11 @@ import {
toRadians,
vec,
} from '../../geo/vector.js';
-import { MISSION_GLOBE_VIEW_RANGE_M, MISSION_FOCUS_RANGE_M } from './policy.js';
+import {
+ MISSION_GLOBE_VIEW_RANGE_M,
+ MISSION_FOCUS_RANGE_M,
+ cockpitActive,
+} from './policy.js';
import { cameraOf, canvasOf, findCamera } from '../../render/rendererOf.js';
export function createSelection({
@@ -122,6 +126,9 @@ export function createSelection({
function focusMission(launch) {
if (!layerState._viewer || !launch || !layerState._enabled) return;
+ // The cockpit holds the camera: a mission chosen there, by its label,
+ // its dot or the layer row's arrows, is selected without flying to it.
+ if (cockpitActive()) return;
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
const camera = cameraOf(layerState._viewer);
diff --git a/src/layers/launches/worldTime.test.mjs b/src/layers/launches/worldTime.test.mjs
index 73eb0b16f3..76f1b02c4e 100644
--- a/src/layers/launches/worldTime.test.mjs
+++ b/src/layers/launches/worldTime.test.mjs
@@ -36,10 +36,14 @@ function scene(t) {
],
};
const viewer = { scene: {} };
+ const flights = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: {
pose: () => ({ position: { x: 2e7, y: 0, z: 0 } }),
on: () => () => {},
+ flyTo: (...args) => flights.push(args),
+ lookAt: noop,
+ release: noop,
},
});
t.after(unbind);
@@ -69,6 +73,7 @@ function scene(t) {
};
parts.selection = createSelection({ state, services, parts });
const rendering = createRendering({ state, services, parts });
+ parts.rendering = rendering;
rendering.attach(viewer);
rendering.showMissions(true);
rendering.addLaunchEntity(launch, null);
@@ -88,7 +93,7 @@ function scene(t) {
path: item(`rocket-trajectory:${launch.id}:0`).show,
};
};
- return { state, rendering, launch, syncs, shown, draw };
+ return { state, rendering, launch, syncs, shown, draw, parts, flights };
}
test('live shows every launch in the window, lifted off or not', (t) => {
@@ -127,3 +132,21 @@ test('the live orbit rings turn at the frame time, not the wall clock', (t) => {
);
assert.deepEqual(orbits.spec.motionClock, { kind: 'scene' });
});
+
+test('in the cockpit a chosen mission is not flown to', (t) => {
+ const { launch, parts, flights } = scene(t);
+ const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
+ Object.defineProperty(globalThis, 'document', {
+ configurable: true,
+ value: {
+ body: { classList: { contains: (name) => name === 'cockpit-mode' } },
+ },
+ });
+ try {
+ parts.selection.focusMission(launch);
+ } finally {
+ if (previous) Object.defineProperty(globalThis, 'document', previous);
+ else delete globalThis.document;
+ }
+ assert.deepEqual(flights, [], 'the cockpit keeps the camera');
+});
diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js
index 4d550bd08a..d1555e521d 100644
--- a/src/layers/localAdsb/index.js
+++ b/src/layers/localAdsb/index.js
@@ -703,6 +703,9 @@ export function createLocalAdsbLayer({
if (clickSubscription || !viewer) return;
clickSubscription = inputFor(viewer).onClick((event) => {
if (!enabled) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (services.picking.isUnderOtherCard?.(event)) return;
const target = clickTarget(event);
// Clicking a local aircraft always (re)selects it and republishes its
// card, including the one already selected: its card may have been
diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs
index 3e53c9bbeb..acd0b0c3fc 100644
--- a/src/layers/localAdsb/index.test.mjs
+++ b/src/layers/localAdsb/index.test.mjs
@@ -15,9 +15,14 @@ import {
} from './index.js';
import { createLocalAdsbModels } from './models.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
-import { resolvePickId } from '../../data/pickRegistry.js';
+import {
+ isUnderOtherCard,
+ resolvePickId,
+ setClickCardHitTest,
+} from '../../data/pickRegistry.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
-import { fakeInput } from '../../input/testDoubles.mjs';
+import { inputFor } from '../../input/dispatcher.js';
+import { MISSION_LABEL, fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -1174,7 +1179,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 +1188,8 @@ function clickHarness() {
pick() {
return scene.pickResult;
},
+ drillPick: () =>
+ (base.viewer.drillHits ?? []).map((hit) => ({ primitive: {}, id: hit })),
};
const base = fakeViewer({ scene });
return {
@@ -1213,6 +1221,41 @@ test('clicking the selected aircraft keeps it selected and republishes its card'
assert.deepEqual(calls.cleared, []);
});
+// The card or label painted on top takes the click: a local aircraft under
+// another layer's card is neither selected nor released.
+test("another layer's card over a local aircraft keeps the click", async (t) => {
+ const receiver = fakeReceiver({ mode: 'adsb', connected: true });
+ const clock = { now: 100_000 };
+ const harness = clickHarness();
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
+ viewer: harness.viewer,
+ services: {
+ picking: {
+ registerPickOwner() {},
+ unregisterPickOwner() {},
+ resolvePickId,
+ isUnderOtherCard,
+ },
+ },
+ });
+ t.after(() => layer.destroy());
+ receiver.set({ aircraft: [record()] });
+ await layer.update();
+ harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
+ harness.click();
+ assert.deepEqual(calls.selected, [], 'covered: not selected');
+ top = null;
+ harness.click();
+ assert.deepEqual(calls.selected, ['local-adsb:abc123']);
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ harness.scene.pickResult = null;
+ harness.click();
+ assert.deepEqual(calls.cleared, [], 'covered: the selection stays');
+});
+
test('a click on a local aircraft under an unowned or trail pick still selects it', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
@@ -1265,6 +1308,52 @@ 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 on a mission label over a local aircraft never selects the aircraft, and keeps the selection', async (t) => {
+ const receiver = fakeReceiver({ mode: 'adsb', connected: true });
+ const clock = { now: 100_000 };
+ const harness = clickHarness();
+ // A Space Missions label painted over the map: while it is over, it takes
+ // each click and is the card on top.
+ const label = { over: true };
+ setClickCardHitTest(() => (label.over ? MISSION_LABEL : null));
+ t.after(() => setClickCardHitTest(null));
+ const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
+ viewer: harness.viewer,
+ services: {
+ picking: {
+ registerPickOwner() {},
+ unregisterPickOwner() {},
+ resolvePickId,
+ isUnderOtherCard,
+ },
+ },
+ });
+ t.after(() => layer.destroy());
+ receiver.set({ aircraft: [record()] });
+ await layer.update();
+ 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; the label on top is its own
+ // click, so the selection stays.
+ 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, 0, 'the selection stays');
+});
+
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/military/ownership.test.mjs b/src/layers/military/ownership.test.mjs
index 3915f5d785..c8f90d0385 100644
--- a/src/layers/military/ownership.test.mjs
+++ b/src/layers/military/ownership.test.mjs
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import { createMilitaryFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
+import { fakeInput } from '../../input/testDoubles.mjs';
+import * as picking from '../../data/pickRegistry.js';
function services() {
const names = [
@@ -294,3 +296,47 @@ test('a military layer without an icon set declines contact refreshes', () => {
assert.equal(layer.refreshTr3b('abc123'), false);
assert.equal(layer.trackById('abc123'), false);
});
+
+// The card or label painted on top takes the click: an aircraft under another
+// layer's card is not even picked, so it is neither tracked nor released.
+test("another layer's card over an aircraft keeps the click", (t) => {
+ const previousDocument = globalThis.document;
+ globalThis.document = Object.assign(new EventTarget(), {
+ body: { classList: { contains: () => false } },
+ });
+ let picks = 0;
+ const viewer = {
+ scene: {
+ canvas: new EventTarget(),
+ pick: () => {
+ picks++;
+ return null;
+ },
+ },
+ };
+ const input = fakeInput(viewer);
+ const flightState = createFlightState({ services: services() });
+ flightState._trackedEntityChangedRemove = () => {};
+ const tracking = createTracking({
+ flightState,
+ services: { ...services(), picking },
+ parts: {},
+ layer: {},
+ });
+ tracking._installClickHandler(viewer);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ picking.setClickCardHitTest(() => top);
+ t.after(() => {
+ picking.setClickCardHitTest(null);
+ flightState._clickSubscription?.();
+ input.destroy();
+ flightState.lifetime.abort();
+ if (previousDocument === undefined) delete globalThis.document;
+ else globalThis.document = previousDocument;
+ });
+ input.tap({ x: 10, y: 10 });
+ assert.equal(picks, 0, 'covered: the scene under the card is not picked');
+ top = null;
+ input.tap({ x: 10, y: 10 });
+ assert.ok(picks > 0, 'open map: the click reaches the scene');
+});
diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js
index 9f26bd39dd..f1ffefcd7d 100644
--- a/src/layers/military/tracking.js
+++ b/src/layers/military/tracking.js
@@ -86,7 +86,8 @@ export function createTracking({
const { clearFocusTarget } = services.focus;
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
services.camera;
- const { resolvePickId, isOwnedByOtherLayer } = services.picking;
+ const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
+ services.picking;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
viewer: () => flightState._viewer,
@@ -1229,6 +1230,9 @@ export function createTracking({
// first-person reference. Empty globe clicks are inert until the user
// exits with C, Escape, or the dedicated button.
if (document.body.classList.contains('cockpit-mode')) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard?.(event)) return;
const picked = event.hit;
if (picked) {
diff --git a/src/layers/news/index.js b/src/layers/news/index.js
index 4ad5826c27..3c228d32c0 100644
--- a/src/layers/news/index.js
+++ b/src/layers/news/index.js
@@ -8,8 +8,8 @@ import {
findFrame,
rendererOf,
} from '../../render/rendererOf.js';
-import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import {
+ clickCard,
isOwnedByOtherLayer,
registerPickOwner,
resolvePickId,
@@ -203,7 +203,6 @@ export function createNewsLayer({
inputFor = defaultInputFor,
matchMedia = globalThis.matchMedia?.bind(globalThis),
now = () => Date.now(),
- hitTestOverlay = hitTestWorldOverlay,
openUrl = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
getViewCentre = viewCentre,
registerCredit = registerDynamicCredit,
@@ -1348,11 +1347,13 @@ export function createNewsLayer({
clickOff = inputFor(viewer).onClick((event) => {
const at = event?.screenPosition;
if (!enabled || destroyed || !isPointerFree() || !at) return;
- const card = hitTestOverlay(at.x, at.y, {
- sourceId: NEWS_OVERLAY_SOURCE_ID,
- });
- if (card?.entry?.activate) {
- card.entry.activate();
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: our own card acts whatever is drawn
+ // under it; another layer's is that layer's click, so the pins under
+ // it do not act and the selection stays.
+ const card = clickCard(event);
+ if (card) {
+ if (card.sourceId === NEWS_OVERLAY_SOURCE_ID) card.entry?.activate?.();
return;
}
// What is on top under the click: a draw-set item, or null for the
diff --git a/src/layers/news/layer.test.mjs b/src/layers/news/layer.test.mjs
index 9804011d77..7313007e4b 100644
--- a/src/layers/news/layer.test.mjs
+++ b/src/layers/news/layer.test.mjs
@@ -5,7 +5,20 @@ import { fromDegrees } from '../../geo/ellipsoid.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { NEWS_KEY_PROVIDERS, createNewsLayer } from './index.js';
+import {
+ findPickOwner,
+ registerPickOwner,
+ setClickCardHitTest,
+ unregisterPickOwner,
+} from '../../data/pickRegistry.js';
+// Registers the shared `gev-trail:` no-op owner, as the app does.
+import '../../data/trailRenderer.js';
import { getSelectedEntityContext } from '../../data/contextStore.js';
+import {
+ MISSION_LABEL,
+ fakeInputUnderLabel,
+} from '../../input/testDoubles.mjs';
+import { NEWS_OVERLAY_SOURCE_ID } from './model.js';
const NOW = Date.parse('2026-10-28T10:00:00Z');
const hotspotsPayload = {
@@ -51,6 +64,8 @@ function fixture(
now = () => NOW,
quality,
pictureCards,
+ underLabel = false,
+ hitTestOverlay = () => null,
} = {},
) {
const calls = { feed: [], hotspots: 0, outline: 0 };
@@ -137,11 +152,22 @@ function fixture(
for (const fn of [...clickHandlers])
fn({ screenPosition: { x: 10, y: 10 }, topHit });
};
+ // Or the scene's own dispatcher, with a Space Missions label that may be
+ // painted over the map (`fake.label.over`).
+ let fake = null;
+ if (underLabel) {
+ viewer.scene = { canvas: {}, pick: () => null };
+ fake = fakeInputUnderLabel(viewer);
+ }
+ // The card on top at a click, as the host answers the pick registry: a
+ // mission label painted over the map comes first.
+ setClickCardHitTest((x, y) =>
+ fake?.label.over ? MISSION_LABEL : hitTestOverlay(x, y),
+ );
const layer = createNewsLayer({
source,
overlayHost,
- inputFor: () => input,
- hitTestOverlay: () => null,
+ inputFor: () => fake?.input ?? input,
now,
matchMedia: () => ({ matches: reduced }),
getViewCentre: () => centre(),
@@ -158,6 +184,8 @@ function fixture(
layer.attachShellServices({ runNavigation: (navigate) => navigate() });
t.after(() => {
layer.destroy();
+ fake?.destroy();
+ setClickCardHitTest(null);
unbind();
if (originalWindow === undefined) delete globalThis.window;
else globalThis.window = originalWindow;
@@ -172,6 +200,7 @@ function fixture(
items,
click,
clickHandlers,
+ fake,
};
}
@@ -1285,6 +1314,105 @@ test('a click on a marker selects its report, on a beacon chooses its hotspot, o
assert.equal(clickHandlers.size, 0);
});
+test("a click on a mission label over a report's card never opens the card, and keeps the report", async (t) => {
+ let activated = 0;
+ const { layer, fake } = fixture(t, {
+ height: 500_000,
+ underLabel: true,
+ // A report's card lies under every click.
+ hitTestOverlay: (_x, _y, { sourceId } = {}) =>
+ !sourceId || sourceId === NEWS_OVERLAY_SOURCE_ID
+ ? {
+ sourceId: NEWS_OVERLAY_SOURCE_ID,
+ entry: { activate: () => activated++ },
+ }
+ : null,
+ });
+ layer.enable();
+ await layer.update();
+ await flush();
+ layer.setParams({ reportId: 'major', pin: 0 });
+ assert.equal(layer.getRowControls().feed.selected.id, 'major');
+
+ fake.label.over = true;
+ fake.click();
+ assert.equal(activated, 0, 'the card beneath the label is not opened');
+ assert.equal(
+ layer.getRowControls().feed.selected.id,
+ 'major',
+ 'the label on top is its own click: the report stays selected',
+ );
+
+ // Off the label, the same click opens the card.
+ fake.label.over = false;
+ fake.click();
+ assert.equal(activated, 1);
+});
+
+test('a covered news card and pin yield; the top news card acts over a trail or a vessel', async (t) => {
+ let hits = [];
+ const { layer, items, entries, click, flights } = fixture(t, {
+ height: 500_000,
+ hitTestOverlay: (_x, _y, { sourceId } = {}) =>
+ hits.find((hit) => !sourceId || hit.sourceId === sourceId) || null,
+ });
+ layer.enable();
+ await layer.update();
+ await flush();
+ const marker = [...items('points'), ...items('icons')].find((item) =>
+ String(item.id).startsWith('news:report:major~'),
+ );
+ click({ set: 'news:1:points', id: marker.id, surface: false });
+ const card = entries.flat().find((entry) => entry.activate);
+ assert.ok(card, 'an actionable news card was published');
+ let activations = 0;
+ const activate = card.activate;
+ card.activate = () => {
+ activations++;
+ return activate();
+ };
+ hits = [
+ { sourceId: 'earthquakes', entryId: 'quake:cover' },
+ { sourceId: 'news', entry: card },
+ ];
+ const before = layer.getRowControls().feed;
+ const flightCount = flights.length;
+ click(null);
+ assert.equal(activations, 0, 'a covered news card does not activate');
+ assert.equal(layer.getRowControls().feed.selected.id, 'major');
+ assert.deepEqual(layer.getRowControls().feed.filters, before.filters);
+ assert.equal(flights.length, flightCount);
+ // A news pin under another layer's card is that card's click too.
+ layer.setParams({ clear: true });
+ click({ set: 'news:1:points', id: marker.id, surface: false });
+ assert.equal(layer.getRowControls().feed.selected, null, 'covered pin');
+ hits = [];
+ click({ set: 'news:1:points', id: marker.id, surface: false });
+ assert.equal(layer.getRowControls().feed.selected.id, 'major');
+ hits = [{ sourceId: 'news', entry: card }];
+ click(null);
+ assert.equal(activations, 1, 'the unobscured news card acts once');
+ // A flight trail is registered so every layer reads a click on it as a
+ // no-op (src/data/trailRenderer.js). Under the top news card it must not
+ // make the card dead.
+ assert.equal(findPickOwner('gev-trail:fl-a1b2c3:head'), 'trails');
+ click({
+ set: 'trail:1:lines',
+ id: 'gev-trail:fl-a1b2c3:head',
+ surface: false,
+ });
+ assert.equal(activations, 2, 'the news card acts over a flight trail');
+ // Over a vessel (a layer that acts on its pick) the card on top acts too;
+ // the vessel layer stands aside under it, so one click does one thing.
+ registerPickOwner('test-vessels', (id) => id === '353136000');
+ try {
+ click({ set: 'vessels:1', id: '353136000', surface: false });
+ assert.equal(activations, 3, 'the news card acts over a vessel');
+ } finally {
+ unregisterPickOwner('test-vessels');
+ }
+});
+
test('zoomed out, a hotspot is one beacon; off, nothing draws; destroyed, the sets go', async (t) => {
const { layer, items } = fixture(t);
assert.deepEqual(items('points'), []);
diff --git a/src/layers/perimeters/index.js b/src/layers/perimeters/index.js
index 3a5a180c48..8d0e1ab7ed 100644
--- a/src/layers/perimeters/index.js
+++ b/src/layers/perimeters/index.js
@@ -218,13 +218,18 @@ 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 },
- );
- if (cardHit && cardHit.entryId === _selectedCardId) {
- if (_selectedLink && openExternal) openExternal(_selectedLink);
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: this area's shapes are background to
+ // another layer's card or label painted over them.
+ const cardHit = picking.clickCard?.(event) ?? null;
+ if (cardHit) {
+ if (
+ cardHit.sourceId === PERIMETER_OVERLAY_SOURCE_ID &&
+ cardHit.entryId === _selectedCardId &&
+ _selectedLink &&
+ openExternal
+ )
+ openExternal(_selectedLink);
return;
}
const picked = event.topHit;
diff --git a/src/layers/perimeters/ownership.test.mjs b/src/layers/perimeters/ownership.test.mjs
index 61cfde2bbf..d0dd6075ee 100644
--- a/src/layers/perimeters/ownership.test.mjs
+++ b/src/layers/perimeters/ownership.test.mjs
@@ -1,7 +1,8 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createFirePerimetersLayer } from './index.js';
-import { fakeInput } from '../../input/testDoubles.mjs';
+import { clickCard } from '../../data/pickRegistry.js';
+import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
// The fills set of the layer the last harness made: perimeter picks name it.
@@ -30,11 +31,12 @@ function harness(
const opened = [];
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
- const input = fakeInput(viewer);
+ const input = fakeInputUnderLabel(viewer);
const clicks = {
handler: (click) => input.click(click.position),
+ // Only the label's own overlay handler is left.
get destroyed() {
- return input.input.subscriberCount() === 0 ? 1 : 0;
+ return input.input.subscriberCount() === 1 ? 1 : 0;
},
};
const layer = createFirePerimetersLayer({
@@ -58,6 +60,11 @@ function harness(
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
+ // The card on top at a click, as the registry answers from the host;
+ // a mission label painted over everything comes first.
+ clickCard: (click) =>
+ clickCard(click) ??
+ cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
inciwebSource: inciwebIndex
? { getIndex: async () => inciwebIndex }
@@ -78,6 +85,9 @@ function harness(
clicks,
owners,
opened,
+ /** A Space Missions label painted over the map: while `over`, it takes
+ * each click and is the card on top. */
+ label: input.label,
};
}
@@ -243,6 +253,43 @@ test('clicking a perimeter publishes its incident card; empty space clears it',
assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
});
+// Another layer's card or label painted over the area (a quake's card or
+// magnitude label) is that layer's click: the area under it stands aside.
+test("another layer's overlay on top keeps a click off the area", async () => {
+ let pickResult = null;
+ let foreignOnTop = false;
+ const h = harness(
+ { getSnapshot: async () => [row] },
+ {
+ pick: () => pickResult,
+ // Unfiltered: the topmost entry of any source.
+ cardHit: (_x, _y, options) =>
+ foreignOnTop && !options?.sourceId
+ ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }
+ : null,
+ },
+ );
+ await h.layer.update(h.viewer);
+ pickResult = perimeterPick('fire-perimeter:2026-NMGNF-000123:0');
+ foreignOnTop = true;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(h.overlay.entries.get('fire-perimeters')?.length ?? 0, 0);
+ // With nothing painted over it, the same click selects the area.
+ foreignOnTop = false;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(
+ h.overlay.entries.get('fire-perimeters')[0].id,
+ 'fire-perimeter-card:2026-NMGNF-000123',
+ );
+ // An overlay on top never clears an existing selection either.
+ foreignOnTop = true;
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ assert.equal(
+ h.overlay.entries.get('fire-perimeters')[0].id,
+ 'fire-perimeter-card:2026-NMGNF-000123',
+ );
+});
+
test('disable removes the click handler, pick ownership, and any card', async () => {
const h = harness(
{ getSnapshot: async () => [row] },
@@ -279,12 +326,16 @@ test('a matched incident card carries the InciWeb line and click-through', async
},
];
let cardHitResult = null;
+ let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => [{ ...row, name: 'Fixture' }] },
{
pick: () => null,
inciwebIndex,
- cardHit: () => cardHitResult,
+ cardHit: (_x, _y, options) =>
+ foreignOnTop && !options?.sourceId
+ ? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }
+ : cardHitResult,
},
);
await h.layer.update(h.viewer);
@@ -299,9 +350,15 @@ test('a matched incident card carries the InciWeb line and click-through', async
const entries = h.overlay.entries.get('fire-perimeters');
assert.equal(entries[0].details.at(-1), 'InciWeb ↗ · click card to open');
- // Clicking the card itself opens the InciWeb page.
- cardHitResult = { entryId: entries[0].id };
+ // A selected card covered by a quake card cannot open its hidden link.
+ cardHitResult = { sourceId: 'fire-perimeters', entryId: entries[0].id };
h.viewer.scene.pick = () => null;
+ foreignOnTop = true;
+ h.clicks.handler({ position: { x: 12, y: 12 } });
+ assert.deepEqual(h.opened, []);
+ assert.equal(h.overlay.entries.get('fire-perimeters')[0].id, entries[0].id);
+ // Removing the foreground card makes the incident card actionable again.
+ foreignOnTop = false;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']);
assert.equal(
@@ -311,6 +368,44 @@ test('a matched incident card carries the InciWeb line and click-through', async
);
});
+test('a click on a mission label over the incident card never opens its InciWeb page, and keeps the card open', async () => {
+ let cardHitResult = null;
+ const h = harness(
+ { getSnapshot: async () => [row] },
+ {
+ pick: () => perimeterPick('fire-perimeter:2026-NMGNF-000123:0'),
+ inciwebIndex: [
+ {
+ incident_id: '329300',
+ tau: 'NMGNF Fixture Fire',
+ incident_title: 'Fixture Fire',
+ },
+ ],
+ cardHit: () => cardHitResult,
+ },
+ );
+ await h.layer.update(h.viewer);
+ h.clicks.handler({ position: { x: 10, y: 10 } });
+ await new Promise((done) => setTimeout(done, 0));
+ const [card] = h.overlay.entries.get('fire-perimeters');
+ assert.equal(card.details.at(-1), 'InciWeb ↗ · click card to open');
+
+ // The open card lies under the label: the click opens nothing, and the
+ // label on top is its own click, so the card stays open.
+ cardHitResult = { sourceId: 'fire-perimeters', entryId: card.id };
+ h.viewer.scene.pick = () => null;
+ h.label.over = true;
+ h.clicks.handler({ position: { x: 12, y: 12 } });
+ assert.deepEqual(h.opened, [], 'the page beneath the label is not opened');
+ assert.equal(h.overlay.entries.get('fire-perimeters')?.[0]?.id, card.id);
+
+ // Off the label, a click on the open card opens its page.
+ h.label.over = false;
+ h.clicks.handler({ position: { x: 12, y: 12 } });
+ assert.deepEqual(h.opened, ['https://inciweb.wildfire.gov/node/329300']);
+ h.layer.destroy();
+});
+
test('an unmatched incident renders no InciWeb line and card clicks stay inert', async () => {
let cardHitResult = null;
const h = harness(
@@ -328,7 +423,7 @@ test('an unmatched incident renders no InciWeb line and card clicks stay inert',
entries[0].details.some((line) => line.includes('InciWeb')),
false,
);
- cardHitResult = { entryId: entries[0].id };
+ cardHitResult = { sourceId: 'fire-perimeters', entryId: entries[0].id };
h.viewer.scene.pick = () => null;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.deepEqual(h.opened, []);
diff --git a/src/layers/radio/interaction.js b/src/layers/radio/interaction.js
index cc129d491a..41674fcf84 100644
--- a/src/layers/radio/interaction.js
+++ b/src/layers/radio/interaction.js
@@ -15,6 +15,7 @@ export function createInteraction({
const {
resolvePickId,
isOwnedByOtherLayer,
+ isUnderOtherCard,
registerPickOwner,
unregisterPickOwner,
} = services.picking;
@@ -29,6 +30,9 @@ export function createInteraction({
*/
function pickedRadioStationAt(event) {
if (!event) return null;
+ // Another layer's card or label painted on top is that layer's click,
+ // read once per click so every layer agrees: no station under it acts.
+ if (isUnderOtherCard?.(event, [RADIO_OVERLAY_SOURCE_ID])) return null;
const stationFromPick = (picked) => {
const stationId = parts.rendering.radioStationIdFromPick(picked);
diff --git a/src/layers/radio/interaction.test.mjs b/src/layers/radio/interaction.test.mjs
index c88310bee9..c776180f43 100644
--- a/src/layers/radio/interaction.test.mjs
+++ b/src/layers/radio/interaction.test.mjs
@@ -62,3 +62,49 @@ test('a direct hit needs no drill, and another layer’s contact keeps its click
});
assert.equal(pickedRadioStationAt(other), null);
});
+
+// Another layer's card or label painted on top takes the click: no station
+// under it acts, whether radio found it through its window, as the tap's touch
+// contact or as the exact pick. Radio's own card on top is radio's click.
+test("a station under another layer's card does not act", () => {
+ let top = null;
+ const radio = createInteraction({
+ state: {
+ _stationById: new Map([
+ ['kexp', {}],
+ ['kuow', {}],
+ ]),
+ },
+ services: {
+ picking: {
+ resolvePickId: (picked) => picked?.id ?? null,
+ isOwnedByOtherLayer: () => false,
+ // The card on top at a click, as the registry answers from the host.
+ isUnderOtherCard: (_click, own = []) =>
+ Boolean(top) && !own.includes(top.sourceId),
+ registerPickOwner() {},
+ unregisterPickOwner() {},
+ },
+ overlays: { setOverlaySourceVisible() {} },
+ },
+ parts: { rendering: { radioStationIdFromPick } },
+ });
+ const station = hit('radio:kexp');
+ const tap = (contact = null, pick = null) => ({
+ ...clickEvent({ pick, windowHits: [station] }),
+ hit: contact,
+ screenPosition: { x: 5, y: 5 },
+ });
+ assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'open map');
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ assert.equal(radio.pickedRadioStationAt(tap()), null, 'window only');
+ assert.equal(radio.pickedRadioStationAt(tap(station)), null, 'contact');
+ assert.equal(
+ radio.pickedRadioStationAt(tap(hit('radio:kuow'))),
+ null,
+ 'another contact station',
+ );
+ assert.equal(radio.pickedRadioStationAt(tap(null, station)), null, 'exact');
+ top = { sourceId: 'radio', entryId: 'radio:kexp' };
+ assert.equal(radio.pickedRadioStationAt(tap()), 'kexp', 'our own card');
+});
diff --git a/src/layers/rail/follow.test.mjs b/src/layers/rail/follow.test.mjs
index 3d6aa1e1f2..2130bacebc 100644
--- a/src/layers/rail/follow.test.mjs
+++ b/src/layers/rail/follow.test.mjs
@@ -10,6 +10,7 @@ import {
SELECTION_FOLLOW_TRANSITION_S,
} from '../../data/trackedCamera.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
+import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { distance } from '../../geo/vector.js';
import {
ACTIVATION_EXIT_ALTITUDE_M,
@@ -203,6 +204,25 @@ test('a click on a train selects it; a click on the map lets it go', async (t) =
assert.equal(app.state()._selectedKey, key);
});
+// The card or label painted on top takes the click: a train under another
+// layer's card is neither selected nor let go.
+test("another layer's card over a train keeps the click", async (t) => {
+ const app = harness(t);
+ const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
+ const icons = app.drawn('icons');
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ app.click({ set: icons.spec.id, id: key, surface: false });
+ assert.equal(app.state()._selectedKey ?? null, null, 'covered: not selected');
+ top = null;
+ app.click({ set: icons.spec.id, id: key, surface: false });
+ assert.equal(app.state()._selectedKey, key);
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ app.click(null);
+ assert.equal(app.state()._selectedKey, key, 'covered: kept');
+});
+
test('a parked train, or one known from a single report, is flown to once', async (t) => {
const app = harness(t);
await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
diff --git a/src/layers/rail/selection.js b/src/layers/rail/selection.js
index 0fdee59bc8..d2663cf200 100644
--- a/src/layers/rail/selection.js
+++ b/src/layers/rail/selection.js
@@ -7,6 +7,7 @@ import {
} from './policy.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
import { inputFor } from '../../input/dispatcher.js';
+import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { t } from '../../i18n/index.js';
/**
@@ -173,6 +174,9 @@ export function createSelection({ state, services, parts }) {
if (!state._enabled) return;
// A held train keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard(event)) return;
const key = trainKeyOf(event.drawHit);
if (key) selectAndFocusTrain(key);
else if (state._selectedKey) clearSelection();
diff --git a/src/layers/satellites/interaction.js b/src/layers/satellites/interaction.js
index 643f637798..393fc072e7 100644
--- a/src/layers/satellites/interaction.js
+++ b/src/layers/satellites/interaction.js
@@ -7,7 +7,8 @@ export function createInteraction({
parts,
source,
}) {
- const { resolvePickId, isOwnedByOtherLayer } = services.picking;
+ const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
+ services.picking;
function _onKeyDown(e) {
// The Cockpit owns Escape while it rides the tracked satellite.
@@ -50,6 +51,9 @@ export function createInteraction({
// The Cockpit camera rides the tracked satellite: a click on the
// picture below must not untrack it or switch satellites.
if (parts.cockpit?._cockpitHeld()) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard?.(event)) return;
const picked = event.topHit;
const hit = event.drawHit;
diff --git a/src/layers/satellites/interaction.test.mjs b/src/layers/satellites/interaction.test.mjs
new file mode 100644
index 0000000000..163078e9ca
--- /dev/null
+++ b/src/layers/satellites/interaction.test.mjs
@@ -0,0 +1,65 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createInteraction } from './interaction.js';
+import { fakeInput } from '../../input/testDoubles.mjs';
+import * as picking from '../../data/pickRegistry.js';
+
+// The card or label painted on top takes the click: a satellite under another
+// layer's card is neither tracked nor let go.
+test("another layer's card over a satellite keeps the click", (t) => {
+ const previousDocument = globalThis.document;
+ globalThis.document = new EventTarget();
+ let picked = null;
+ const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
+ const input = fakeInput(viewer);
+ const calls = [];
+ const state = {
+ _enabled: true,
+ _trackedNorad: null,
+ _clickSubscription: null,
+ _trackedEntityChangedRemove: () => {},
+ _catalog: new Map([[25544, {}]]),
+ };
+ const interaction = createInteraction({
+ state,
+ services: { picking },
+ parts: {
+ rendering: {
+ _hitIsTracked: () => false,
+ _hitPointId: (hit) =>
+ hit?.set === 'satellites:dots' ? Number(hit.id) : null,
+ },
+ tracking: {
+ _cancelPendingTrackingRestore() {},
+ _trackSatellite: (id) => calls.push(['track', id]),
+ _clearTracking: () => calls.push(['clear']),
+ },
+ },
+ });
+ interaction._installClickHandler(viewer);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ picking.setClickCardHitTest(() => top);
+ t.after(() => {
+ picking.setClickCardHitTest(null);
+ state._clickSubscription?.();
+ input.destroy();
+ if (previousDocument === undefined) delete globalThis.document;
+ else globalThis.document = previousDocument;
+ });
+ const click = (hit) => {
+ picked = hit ? { id: hit } : null;
+ input.tap({ x: 10, y: 10 });
+ };
+ const dot = { set: 'satellites:dots', id: '25544' };
+ click(dot);
+ assert.deepEqual(calls, [], 'covered: not tracked');
+ state._trackedNorad = 1;
+ click(null);
+ assert.deepEqual(calls, [], 'covered: tracking kept');
+ top = null;
+ click(null);
+ assert.deepEqual(calls, [['clear']], 'open map lets it go');
+ state._trackedNorad = null;
+ click(dot);
+ assert.deepEqual(calls.at(-1), ['track', 25544]);
+});
diff --git a/src/layers/shipwrecks/index.js b/src/layers/shipwrecks/index.js
index c2c2db2814..8dcbe4bb7e 100644
--- a/src/layers/shipwrecks/index.js
+++ b/src/layers/shipwrecks/index.js
@@ -277,12 +277,18 @@ export function createShipwrecksLayer({
if (!clicks) return;
_clickHandler = clicks.onClick((click) => {
if (pointer && !pointer.isPointerFree()) return;
- const at = click.screenPosition;
- const cardHit = overlayHost.hitTest?.(at?.x, at?.y, {
- sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID,
- });
- if (cardHit && cardHit.entryId === _selectedCardId) {
- if (_selectedLink) openExternal(_selectedLink);
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: ours opens its source whatever is drawn
+ // under it; another layer's is that layer's click, so the markers
+ // under it do not act and the selection stays.
+ const cardHit = picking.clickCard?.(click) ?? null;
+ if (cardHit) {
+ if (
+ cardHit.sourceId === SHIPWRECKS_OVERLAY_SOURCE_ID &&
+ cardHit.entryId === _selectedCardId &&
+ _selectedLink
+ )
+ openExternal(_selectedLink);
return;
}
// A marker's item id is its pick id, `shipwreck:`. Read from what is
diff --git a/src/layers/shipwrecks/index.test.mjs b/src/layers/shipwrecks/index.test.mjs
index 7d69f2b457..5e5a29ef90 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,
@@ -36,7 +37,7 @@ function deferred() {
return { promise, resolve };
}
-function harness({ snapshots, now = () => 1 } = {}) {
+function harness({ snapshots, now = () => 1, cardHit = () => null } = {}) {
const cards = [];
const handlers = [];
const opened = [];
@@ -47,6 +48,8 @@ function harness({ snapshots, now = () => 1 } = {}) {
const { draw } = bindFakeDraw(viewer);
const queue = [...(snapshots || [])];
const requests = [];
+ // The card on top at a click, as the host answers the pick registry.
+ picking.setClickCardHitTest((x, y) => cardHit(x, y));
const layer = createShipwrecksLayer({
source: {
getSnapshot({ signal }) {
@@ -59,7 +62,7 @@ function harness({ snapshots, now = () => 1 } = {}) {
overlayHost: {
setEntries: (_source, entries) => cards.push(entries),
setVisible() {},
- hitTest: () => null,
+ hitTest: cardHit,
},
// The globe's clicks: one listener per click handler installed.
input: () => ({
@@ -393,3 +396,97 @@ 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 on a mission label over the open card never opens the card's link, and keeps the card open", async (t) => {
+ let picked = null;
+ const viewer = { scene: { canvas: {}, pick: () => picked } };
+ bindFakeDraw(viewer);
+ let cardUnder = null;
+ const fake = fakeInputUnderLabel(viewer, {
+ beneath: () =>
+ cardUnder ? { sourceId: 'shipwrecks', entryId: cardUnder } : null,
+ });
+ t.after(() => fake.destroy());
+ const cards = [];
+ const opened = [];
+ const layer = createShipwrecksLayer({
+ source: { getSnapshot: () => Promise.resolve(snapshot([wreck('a')])) },
+ overlayHost: {
+ setEntries: (_source, entries) => cards.push(entries),
+ setVisible() {},
+ },
+ 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, and the
+ // label on top is its own click, so the card stays open.
+ picked = null;
+ cardUnder = card.id;
+ fake.label.over = true;
+ fake.click();
+ assert.deepEqual(opened, [], 'the link beneath the label is not opened');
+ assert.equal(cards.at(-1)[0]?.id, card.id, 'the card stays open');
+
+ // Off the label, a click on the open card opens its link.
+ fake.label.over = false;
+ fake.click();
+ assert.equal(opened.length, 1);
+});
+
+test('a covered selected card and covered markers yield; bare markers select', async () => {
+ let painted = [];
+ const h = harness({
+ snapshots: [
+ snapshot([
+ wreck('a', { url: 'https://example.com/a' }),
+ wreck('b', { url: 'https://example.com/b' }),
+ ]),
+ ],
+ cardHit: (_x, _y, { sourceId } = {}) =>
+ painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null,
+ });
+ try {
+ h.layer.enable();
+ await h.layer.update();
+ const click = () => h.handlers[0].click({ screenPosition: { x: 1, y: 1 } });
+ h.pick('a');
+ click();
+ const first = h.lastCard()[0];
+ painted = [
+ { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' },
+ { sourceId: 'shipwrecks', entryId: first.id },
+ ];
+ h.pick(null);
+ click();
+ assert.deepEqual(h.opened, []);
+ assert.equal(h.lastCard()[0].id, first.id);
+ // A marker under another layer's card is that card's click too.
+ h.pick('b');
+ click();
+ assert.equal(h.lastCard()[0].id, first.id, 'a covered marker yields');
+ painted = [];
+ click();
+ assert.equal(h.lastCard()[0].id, 'shipwreck-card:b');
+ painted = [{ sourceId: 'shipwrecks', entryId: 'shipwreck-card:b' }];
+ h.pick(null);
+ click();
+ assert.deepEqual(h.opened, ['https://example.com/b']);
+ painted = [];
+ click();
+ assert.deepEqual(h.lastCard(), [], 'bare map still clears the selection');
+ } finally {
+ h.layer.destroy();
+ }
+});
diff --git a/src/layers/streetLevel/selection.js b/src/layers/streetLevel/selection.js
index 9e01729b62..409b0a9dce 100644
--- a/src/layers/streetLevel/selection.js
+++ b/src/layers/streetLevel/selection.js
@@ -23,8 +23,22 @@ export function createSelection({ state, parts }) {
/** The id carries a provider's prefix: that provider handles the pick. */
function onClick(event) {
if (!state.viewer || !state.enabled) return;
+ // Another layer's card or label painted on top takes the click, read once
+ // per click so every layer agrees: no image, sequence or ground under it
+ // opens. Street Level paints no cards of its own.
+ if (picking?.isUnderOtherCard?.(event)) return;
const hit = event.windowHit(CLICK_PICK_WINDOW_PX, CLICK_PICK_WINDOW_PX);
- const route = parts.router.resolve(pickIdOf(hit));
+ const windowId = pickIdOf(hit);
+ // A coarse tap's touch contact (event.hit) reaches farther than this
+ // window: an item of ours there is still ours.
+ const contact = event.hit;
+ const contactId =
+ contact && !contact.surface
+ ? pickIdOf({ drawHit: contact.set ? contact : null, id: event.id })
+ : null;
+ const route =
+ parts.router.resolve(windowId) ??
+ (contactId ? parts.router.resolve(contactId) : null);
// Not ours: the ground handler decides whether it is the map itself.
if (!route) {
parts.openAtGround?.({ surface: hit.surface, ground: groundOf(event) });
diff --git a/src/layers/streetLevel/selection.test.mjs b/src/layers/streetLevel/selection.test.mjs
index 07f55b9e19..f7647ec8e4 100644
--- a/src/layers/streetLevel/selection.test.mjs
+++ b/src/layers/streetLevel/selection.test.mjs
@@ -4,6 +4,7 @@ import * as Cesium from 'cesium';
import { createSelection } from './selection.js';
import { createPickRouter } from './pickRouter.js';
import { fakeInput } from '../../input/testDoubles.mjs';
+import * as pickRegistry from '../../data/pickRegistry.js';
/** The selection installed on a stand-in viewer, with what its clicks reach. */
function harness({
@@ -47,11 +48,13 @@ function harness({
...sceneExtras,
},
};
+ // The card on top at a click, as the host answers the pick registry.
+ pickRegistry.setClickCardHitTest(services.overlayHit ?? null);
const state = {
viewer,
enabled: true,
clickSubscription: null,
- services: { picking: null, input: null, ...services },
+ services: { picking: pickRegistry, input: null, ...services },
providers: new Map([
[
'mapillary',
@@ -105,6 +108,7 @@ function harness({
return event;
},
restore() {
+ pickRegistry.setClickCardHitTest(null);
selection.uninstall();
globalThis.document = saved;
},
@@ -289,3 +293,179 @@ test('a click on a provider line hands it the ground under the click, measured o
h.restore();
}
});
+
+// An image found only through Street Level's own window (not the exact pick)
+// under another layer's card or label is that card's click: its layer never
+// sees this window.
+test('an item found only in our window yields to a card painted over it', () => {
+ let top = null;
+ const h = harness({
+ services: { overlayHit: () => top },
+ sceneExtras: {
+ pick: (_position, width = 3) =>
+ width >= 9 ? { id: 'mly:img:near' } : null,
+ },
+ });
+ try {
+ h.click();
+ assert.deepEqual(h.opened, ['near'], 'open map: the window finds it');
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ h.click();
+ assert.deepEqual(h.opened, ['near'], 'under a card: the card keeps it');
+ assert.equal(h.groundClicks.length, 0);
+ } finally {
+ h.restore();
+ }
+});
+
+// The map itself under another layer's card or label is that card's click:
+// a ground click there must not also open the nearest street image.
+test("a click on the map under another layer's card opens no ground image", () => {
+ let top = null;
+ const h = harness({ services: { overlayHit: () => top } });
+ try {
+ h.click();
+ assert.equal(
+ h.groundClicks.length,
+ 1,
+ 'open map: the ground handler decides',
+ );
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ h.click();
+ assert.equal(h.groundClicks.length, 1, 'under a card: the card keeps it');
+ assert.deepEqual(h.opened, []);
+ } finally {
+ h.restore();
+ }
+});
+
+// A coarse tap's touch contact reaches farther than this window: on open map
+// Street Level takes it; under another layer's card the card does.
+test('a coarse touch contact beyond our window is ours to open, unless a card is on top', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ let top = { sourceId: 'earthquake-card', entryId: 'q' };
+ const h = harness({
+ services: { picking: pickRegistry, overlayHit: () => top },
+ sceneExtras: {
+ pick: () => null,
+ drillPick: () => [{ id: 'mly:img:contact' }],
+ },
+ });
+ try {
+ h.click();
+ assert.deepEqual(h.opened, [], 'under a card: the card keeps it');
+ top = null;
+ h.click();
+ assert.deepEqual(h.opened, ['contact']);
+ assert.equal(h.groundClicks.length, 0);
+ } finally {
+ h.restore();
+ }
+});
+
+// The exact hit or the touch contact on our line part under another layer's
+// card is that card's click; on open map it selects the sequence its part
+// picks as.
+test('an exact or contact hit on our line part acts only with no card on top', (t) => {
+ const part = {
+ set: 'street-level:mapillary-coverage:1',
+ id: 'mly:seq:abc#2',
+ meta: { pick: 'mly:seq:abc' },
+ };
+ let top = { sourceId: 'earthquake-card', entryId: 'q' };
+ const card = () => top;
+ const exact = harness({ services: { overlayHit: card } });
+ try {
+ exact.scene.under = part;
+ exact.click();
+ assert.deepEqual(exact.sequences.selects, [], 'under a card');
+ top = null;
+ exact.click();
+ assert.deepEqual(exact.sequences.selects, ['abc'], 'mouse, exact part');
+ } finally {
+ top = { sourceId: 'earthquake-card', entryId: 'q' };
+ exact.restore();
+ }
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const contact = harness({
+ services: { picking: pickRegistry, overlayHit: card },
+ sceneExtras: {
+ pick: (_position, width = 3) => (width >= 9 ? { id: part } : null),
+ drillPick: () => [{ id: part }],
+ },
+ });
+ try {
+ contact.click();
+ assert.deepEqual(contact.sequences.selects, [], 'coarse, under a card');
+ top = null;
+ contact.click();
+ assert.deepEqual(contact.sequences.selects, ['abc'], 'coarse contact');
+ } finally {
+ contact.restore();
+ }
+});
+
+// Our window catching another layer's item says nothing about our own touch
+// contact beyond it: that contact is still ours.
+test('a contact of ours acts even when our window finds another item', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const h = harness({
+ services: { picking: pickRegistry },
+ sceneExtras: {
+ pick: (_position, width = 3) =>
+ width >= 9 ? { id: { set: 'flights:1', id: 'flight:9' } } : null,
+ drillPick: () => [{ id: 'mly:img:contact' }],
+ },
+ });
+ try {
+ h.click();
+ assert.deepEqual(h.opened, ['contact']);
+ } finally {
+ h.restore();
+ }
+});
+
+// Under another layer's card nothing of ours opens, whatever our window or the
+// tap's touch contact names; on open map our window's item opens.
+test('under a card, neither our window item nor our touch contact opens', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ let top = { sourceId: 'earthquake-card', entryId: 'q' };
+ const h = harness({
+ services: { picking: pickRegistry, overlayHit: () => top },
+ sceneExtras: {
+ pick: (_position, width = 3) =>
+ width >= 9 ? { id: 'mly:img:window' } : null,
+ drillPick: () => [{ id: 'mly:img:contact' }],
+ },
+ });
+ try {
+ h.click();
+ assert.deepEqual(h.opened, []);
+ assert.equal(h.groundClicks.length, 0);
+ top = null;
+ h.click();
+ assert.deepEqual(h.opened, ['window']);
+ } finally {
+ h.restore();
+ }
+});
diff --git a/src/layers/submarineCables/index.js b/src/layers/submarineCables/index.js
index e38e69bf31..1f17a3d9de 100644
--- a/src/layers/submarineCables/index.js
+++ b/src/layers/submarineCables/index.js
@@ -8,6 +8,7 @@ import { inputFor as defaultInputFor } from '../../input/dispatcher.js';
export function createSubmarineCableLayer({
source,
overlayHost,
+ picking = null,
inputFor = defaultInputFor,
mapStackEventTarget = null,
sweepClock = defaultSweepClock,
@@ -23,6 +24,7 @@ export function createSubmarineCableLayer({
parts,
source,
inputFor,
+ picking,
mapStackEventTarget,
};
parts.rendering = createRendering(context);
diff --git a/src/layers/submarineCables/interaction.js b/src/layers/submarineCables/interaction.js
index de7470da27..0ff20ddd7a 100644
--- a/src/layers/submarineCables/interaction.js
+++ b/src/layers/submarineCables/interaction.js
@@ -1,11 +1,14 @@
import { toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
-export function createInteraction({ state, parts, inputFor }) {
+export function createInteraction({ state, parts, inputFor, picking }) {
function beginInteraction(viewer) {
if (state._clickSubscription) return;
state._clickSubscription = inputFor(viewer).onClick((event) => {
if (!state._enabled) return;
+ // Cable labels are not interactive, so any card or label painted on
+ // top is another layer's, painted over the cable: its click.
+ if (picking?.clickCard?.(event)) return;
const record = resolvePickRecord(event.drawHit);
if (!record?.reference) return;
flyToReference(viewer, record.reference);
diff --git a/src/layers/submarineCables/interaction.test.mjs b/src/layers/submarineCables/interaction.test.mjs
new file mode 100644
index 0000000000..44d9599610
--- /dev/null
+++ b/src/layers/submarineCables/interaction.test.mjs
@@ -0,0 +1,61 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createInteraction } from './interaction.js';
+import * as picking from '../../data/pickRegistry.js';
+
+/** The cable click handler, with its click and overlay seams faked. */
+function harness({ overlayTop = null } = {}) {
+ let onClick = null;
+ const picked = [];
+ let top = overlayTop;
+ const interaction = createInteraction({
+ state: { _enabled: true, _clickSubscription: null },
+ parts: {
+ rendering: {
+ pickInfo: (hit) => {
+ picked.push(hit);
+ return null;
+ },
+ },
+ },
+ inputFor: () => ({
+ onClick: (fn) => {
+ onClick = fn;
+ return () => (onClick = null);
+ },
+ }),
+ overlayHost: { hitTest: () => top },
+ // The card on top at a click, as the registry answers from the host.
+ picking: { clickCard: () => top },
+ });
+ interaction.beginInteraction({});
+ return {
+ picked,
+ setTop: (next) => {
+ top = next;
+ },
+ click: () =>
+ onClick({
+ screenPosition: { x: 5, y: 5 },
+ drawHit: { set: 'c', id: 'x' },
+ }),
+ };
+}
+
+// Cable labels are not interactive: an overlay entry under the pointer is
+// another layer's card or label painted over the cable (a quake card), and
+// that layer takes the click, so the cable does not also fly the camera.
+test('a card painted over a cable keeps its click; with none the cable reads the pick', () => {
+ const h = harness({
+ overlayTop: { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' },
+ });
+ h.click();
+ assert.equal(h.picked.length, 0, 'the cable stands aside');
+ h.setTop(null);
+ h.click();
+ assert.equal(
+ h.picked.length,
+ 1,
+ 'with no card on top, the cable reads its pick',
+ );
+});
diff --git a/src/layers/transit/lifecycle.test.mjs b/src/layers/transit/lifecycle.test.mjs
index 643aa57278..5647c07691 100644
--- a/src/layers/transit/lifecycle.test.mjs
+++ b/src/layers/transit/lifecycle.test.mjs
@@ -44,6 +44,7 @@ import {
uninstallRenderGovernor,
} from '../../renderGovernor.js';
import { fakeInput } from '../../input/testDoubles.mjs';
+import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindRenderer, rendererOf } from '../../render/rendererOf.js';
@@ -3745,6 +3746,30 @@ test('click handler selects a migrated scripted billboard and prepares its drape
assert.equal(entry.marker.show, true);
});
+// The card or label painted on top takes the click: a vehicle under another
+// layer's card is neither selected nor released.
+test("another layer's card over a vehicle keeps the click", async (t) => {
+ const app = harness(t, { floorAt: () => undefined });
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ app.layer.enable(app.viewer);
+ app.layer._loadTransitFleetForTest(4, BOSTON, 70);
+ const [first, second] = app.vehicles();
+ app.viewer.scene.pick = () => app.pickOf(first);
+ app.input.click(new Cesium.Cartesian2(500, 400));
+ assert.equal(app.state()._selectedKey, null, 'covered: not selected');
+ top = null;
+ app.input.click(new Cesium.Cartesian2(500, 400));
+ assert.equal(app.state()._selectedKey, first.key);
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ app.viewer.scene.pick = () => app.pickOf(second);
+ app.input.click(new Cesium.Cartesian2(500, 400));
+ app.viewer.scene.pick = () => undefined;
+ app.input.click(new Cesium.Cartesian2(500, 400));
+ assert.equal(app.state()._selectedKey, first.key, 'covered: kept');
+});
+
test('intercepted scripted reports resolve their explicit floor and wake without a preRender bootstrap', async (t) => {
const app = harness(t, { floorAt: () => undefined });
app.layer._setTransitFixtureFloorsForTest(['mbta:sim-straight'], 20);
diff --git a/src/layers/transit/selection.js b/src/layers/transit/selection.js
index 9566272eef..75a1c2b744 100644
--- a/src/layers/transit/selection.js
+++ b/src/layers/transit/selection.js
@@ -7,6 +7,7 @@ import {
} from './policy.js';
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
import { inputFor } from '../../input/dispatcher.js';
+import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { t } from '../../i18n/index.js';
/**
@@ -151,6 +152,9 @@ export function createSelection({ state, services, parts }) {
collection:
set === 'moving' ? 'animated' : set === 'still' ? 'stationary' : null,
};
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard(event)) return;
if (key) {
selectVehicle(key, { byUser: true });
return;
diff --git a/src/layers/vessels/selection.js b/src/layers/vessels/selection.js
index 7f8ddab832..369054e3a8 100644
--- a/src/layers/vessels/selection.js
+++ b/src/layers/vessels/selection.js
@@ -30,8 +30,23 @@ export function createSelection({
// The bridge view owns the selection: a click on open water must not
// deselect the vessel the camera is riding.
if (state.cockpitSubjectId) return;
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: a card of ours acts whatever is drawn
+ // under it; another layer's is that layer's click.
+ const top = services.picking.clickCard?.(event) ?? null;
+ if (top) {
+ if (top.sourceId !== VESSEL_OVERLAY_SOURCE_ID) return;
+ const id = String(top.entryId || '').startsWith('vessel:')
+ ? top.entryId.slice('vessel:'.length)
+ : null;
+ const carded = id ? state.records.byId.get(id) || null : null;
+ // A stale card id is not empty terrain and must not clear a newer
+ // selection. The next paint will evict its hit rectangle.
+ if (carded) selectAndFocusVessel(carded);
+ return;
+ }
const pickedId = event.id;
- let record = pickedId ? state.records.byId.get(pickedId) : null;
+ const record = pickedId ? state.records.byId.get(pickedId) : null;
// A vessel icon's pick is an item of the layer's icon set, whose id is
// its row id: the record's id, or an unkeyed row's. Removing a row
// removes its item, so an evicted vessel cannot be picked at all; a
@@ -44,49 +59,19 @@ export function createSelection({
// An own-layer row without a live map key is a strict no-op (FB-1
// residual). Trails carry no layer identity and hug their contacts, so any
- // `gev-trail:*` pick is also a no-op. Every other non-vessel pick — sibling
- // unowned scene picks dismiss the current vessel inspection.
+ // `gev-trail:*` pick is also a no-op. A pick a sibling layer owns (an
+ // aircraft, a route, a cyclone) is that layer's: preserve the current
+ // vessel selection and do not compete with its camera command. Every
+ // other non-vessel pick dismisses the current vessel inspection.
if (ownRecordPick && (!pickedId || !record)) return;
- if (pickedId && !record && String(pickedId).startsWith('gev-trail:'))
+ if (
+ !record &&
+ pickedId &&
+ (String(pickedId).startsWith('gev-trail:') ||
+ isOwnedByOtherLayer('ais-live-vessels', pickedId))
+ )
return;
- // A sibling layer already owns this click. Preserve the current vessel
- // selection and do not compete with its camera command.
- const siblingOwned =
- pickedId && isOwnedByOtherLayer('ais-live-vessels', pickedId);
- // Cyclone geometry is ambient context behind painted cards. Its handler
- // yields to the same foreground AIS hit. Keep moving-contact precedence
- // unchanged: those handlers may issue their own camera command.
- const cycloneBackground =
- siblingOwned && !isOwnedByOtherLayer('weather-cyclones', pickedId);
- if (siblingOwned && !cycloneBackground) return;
-
- // Cards are painted on a pointer-events:none canvas, so the scene pick is
- // usually terrain behind the card. Resolve against the host's current
- // actionable hit rectangles before treating the click as empty space.
- const cardHit = !record
- ? vesselState._vesselOverlayHost.hitTest?.(
- event.screenPosition?.x,
- event.screenPosition?.y,
- {
- ...(cycloneBackground
- ? {}
- : { sourceId: VESSEL_OVERLAY_SOURCE_ID }),
- },
- )
- : null;
- if (cycloneBackground && cardHit?.sourceId !== VESSEL_OVERLAY_SOURCE_ID)
- return;
- if (!record && cardHit) {
- const id = String(cardHit.entryId || '').startsWith('vessel:')
- ? cardHit.entryId.slice('vessel:'.length)
- : null;
- record = id ? state.records.byId.get(id) || null : null;
- // A stale card id is not empty terrain and must not clear a newer
- // selection. The next paint will evict its hit rectangle.
- if (!record) return;
- }
-
if (record) {
// A valid sprite or card click always transfers the camera exactly once,
// including a second click on the already-selected vessel.
diff --git a/src/layers/vessels/selection.test.mjs b/src/layers/vessels/selection.test.mjs
new file mode 100644
index 0000000000..a641b13fa3
--- /dev/null
+++ b/src/layers/vessels/selection.test.mjs
@@ -0,0 +1,88 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
+import { clickCard } from '../../data/pickRegistry.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 Space Missions label
+ * may take, with the vessel's card under every click. */
+function selectionHarness(t) {
+ const viewer = { scene: { canvas: {}, pick: () => null } };
+ const vessel = { id: 'v1', name: 'NORTHERN STAR', lat: 0, lon: 0 };
+ const fake = fakeInputUnderLabel(viewer, {
+ beneath: () => ({
+ sourceId: VESSEL_OVERLAY_SOURCE_ID,
+ entryId: `vessel:${vessel.id}`,
+ }),
+ });
+ t.after(() => fake.destroy());
+ 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 };
+ const selection = createSelection({
+ vesselState,
+ services: {
+ picking: { isOwnedByOtherLayer: () => false, clickCard },
+ 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 on a mission label over a vessel's card 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 on a mission label keeps 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']);
+ // The label on top is its own click: the vessel stays selected.
+ h.fake.label.over = true;
+ h.fake.click();
+ assert.equal(h.state.selectedRecord, h.vessel);
+ assert.deepEqual(h.focused, ['v1']);
+});
diff --git a/src/layers/wildlifeSightings/ownership.test.mjs b/src/layers/wildlifeSightings/ownership.test.mjs
index c7ab130a0f..6ad60b00c2 100644
--- a/src/layers/wildlifeSightings/ownership.test.mjs
+++ b/src/layers/wildlifeSightings/ownership.test.mjs
@@ -196,8 +196,9 @@ function harness(
},
setVisible: (id, value) => overlay.visible.set(id, value),
clearSource: (id) => overlay.entries.delete(id),
- hitTest: (_x, _y, { sourceId }) =>
- cardHit?.sourceId === sourceId ? cardHit : null,
+ // As the host does: unfiltered, the topmost entry.
+ hitTest: (_x, _y, { sourceId } = {}) =>
+ !sourceId || cardHit?.sourceId === sourceId ? cardHit : null,
},
input: () => ({
onClick(fn) {
@@ -220,6 +221,8 @@ function harness(
unregisterPickOwner: (id) => owners.delete(id),
resolvePickId: (pick) => pick?.id ?? pick?.primitive?.id,
isOwnedByOtherLayer: (_layerId, id) => id?.startsWith('other:'),
+ // The card on top at a click, as the registry answers from the host.
+ clickCard: () => cardHit,
},
sprites: { spriteDrawOrder: () => -9 },
render: { governorRequestRender: (reason) => renders.push(reason) },
diff --git a/src/layers/wildlifeSightings/selection.js b/src/layers/wildlifeSightings/selection.js
index dc0b7c126c..5156d6035a 100644
--- a/src/layers/wildlifeSightings/selection.js
+++ b/src/layers/wildlifeSightings/selection.js
@@ -482,19 +482,13 @@ export function createSelection({ state, services, parts }) {
state.clickHandler = input.onClick((click) => {
if (!state.enabled || services.pointer?.isPointerFree?.() === false)
return;
- const at = click.screenPosition;
- const hit =
- 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,
- });
+ // The card or label painted on top takes the click, read once per
+ // click so every layer agrees: ours acts whatever is drawn under it;
+ // another layer's is that layer's click, so the sightings under it do
+ // not act and the selection stays.
+ const hit = services.picking?.clickCard?.(click) ?? null;
if (hit) {
- hit.entry?.activate?.();
+ if (sourceIds.includes(hit.sourceId)) hit.entry?.activate?.();
return;
}
// A sighting icon's item id is its pick id, `wildlife:`.
diff --git a/src/layers/wildlifeSightings/selection.test.mjs b/src/layers/wildlifeSightings/selection.test.mjs
index bf623526bb..e719cd46e9 100644
--- a/src/layers/wildlifeSightings/selection.test.mjs
+++ b/src/layers/wildlifeSightings/selection.test.mjs
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createSelection } from './selection.js';
import { bindWildlifeViewer } from '../../testSupport/wildlifeViewer.mjs';
+import { clickCard } from '../../data/pickRegistry.js';
+import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
const row = {
stableId: 'inat:123',
@@ -21,6 +23,7 @@ function fixture(sighting = row, extraServices = {}) {
const seen = [];
const painted = new Set();
let hit = null;
+ let coveringHit = null;
let projections = 0;
let click;
const state = {
@@ -42,16 +45,17 @@ function fixture(sighting = row, extraServices = {}) {
},
};
bindWildlifeViewer(state.viewer);
+ const overlayHost = {
+ setEntries: (id, value) => entries.set(id, value),
+ clearSource: (id) => entries.delete(id),
+ setVisible() {},
+ hitTest: (_x, _y, { sourceId } = {}) =>
+ sourceId ? (hit?.sourceId === sourceId ? hit : null) : coveringHit || hit,
+ };
const selection = createSelection({
state,
services: {
- overlayHost: {
- setEntries: (id, value) => entries.set(id, value),
- clearSource: (id) => entries.delete(id),
- setVisible() {},
- hitTest: (_x, _y, { sourceId }) =>
- hit?.sourceId === sourceId ? hit : null,
- },
+ overlayHost,
now: () => row.observedAt + 60_000,
project: (_scene, anchor) => {
projections++;
@@ -66,6 +70,14 @@ function fixture(sighting = row, extraServices = {}) {
}),
eventTarget: new EventTarget(),
...extraServices,
+ // The card on top at a click, as the registry answers from the host;
+ // a mission label painted over everything comes first.
+ picking: {
+ clickCard: (c) =>
+ clickCard(c) ??
+ overlayHost.hitTest(c.screenPosition?.x, c.screenPosition?.y),
+ ...extraServices.picking,
+ },
},
parts: {
rendering: {
@@ -94,6 +106,9 @@ function fixture(sighting = row, extraServices = {}) {
?.find((entry) => entry.id === entryId);
hit = entry ? { sourceId, entryId, entry } : null;
},
+ cover(value) {
+ coveringHit = value;
+ },
paint(ids) {
painted.clear();
for (const id of ids) painted.add(id);
@@ -179,6 +194,38 @@ test('selected photo and name cards use the selected lane, select on click and n
}
});
+test('a covered sighting label and icon yield; the top label acts over trails and other scene items', () => {
+ const f = fixture(row, {
+ // Registered owners, as the app has them: an aircraft, and the flight
+ // trails every layer reads as a no-op (src/data/trailRenderer.js).
+ picking: {
+ isOwnedByOtherLayer: (_layer, id) =>
+ id === 'other:aircraft' || String(id).startsWith('gev-trail:'),
+ },
+ });
+ f.selection.install();
+ f.selection.refreshAmbient();
+ f.hit('wildlife-sightings-labels', 'wildlife-sightings-label:inat:123');
+ f.click(null);
+ assert.equal(f.flights.length, 1);
+ f.cover({ sourceId: 'earthquakes', entryId: 'quake:cover' });
+ f.click(null);
+ assert.equal(f.flights.length, 1);
+ assert.equal(f.state.selectedRow, row);
+ // A sighting icon under another layer's card is that card's click too.
+ f.click();
+ assert.equal(f.flights.length, 1, 'a covered sighting does not act');
+ f.cover(null);
+ // The top label acts over a flight trail: never a dead click.
+ f.click('gev-trail:fl-a1b2c3:head');
+ assert.equal(f.flights.length, 2, 'the label acts over a flight trail');
+ // And over another layer's scene item.
+ f.click('other:aircraft');
+ assert.equal(f.flights.length, 3, 'the top label acts');
+ assert.equal(f.state.selectedRow, row);
+ f.selection.remove();
+});
+
test('nearby duplicate display names yield to painted cards and higher-ranked labels using cached screens', () => {
const low = {
...row,
@@ -304,6 +351,44 @@ test('empty clicks and layer removal release the selected row and its overlay',
assert.equal(f.entries.size, 0);
});
+test("a click on a mission label over a sighting's card never selects the sighting, and keeps the selected one", (t) => {
+ let fake = null;
+ const f = fixture(row, {
+ input: (viewer) => {
+ fake ??= fakeInputUnderLabel(viewer);
+ return fake.input;
+ },
+ });
+ f.selection.install();
+ t.after(() => {
+ f.selection.remove();
+ fake.destroy();
+ });
+ f.selection.refreshAmbient();
+ // The sighting's name card lies under every click.
+ f.hit('wildlife-sightings-labels', 'wildlife-sightings-label:inat:123');
+
+ // Under the label, the card beneath it selects nothing.
+ fake.label.over = true;
+ fake.click();
+ assert.equal(f.state.selectedId, null);
+ assert.equal(f.flights.length, 0);
+
+ // Off the label, a click on the card selects and focuses the sighting.
+ fake.label.over = false;
+ fake.click();
+ assert.equal(f.state.selectedId, row.stableId);
+ assert.equal(f.flights.length, 1);
+
+ // The label on top is its own click: the sighting stays selected, and
+ // the camera is not sent to it again.
+ fake.label.over = true;
+ fake.click();
+ assert.equal(f.state.selectedId, row.stableId, 'the sighting stays');
+ assert.equal(f.state.selectedRow, row);
+ assert.equal(f.flights.length, 1, 'the camera is not sent to the sighting');
+});
+
test('a tap selects only a sighting exactly under it, not one the touch search found near it', () => {
const f = fixture();
f.selection.install();
diff --git a/src/navigationPolicy.js b/src/navigationPolicy.js
index 781161d137..6fd70f6c73 100644
--- a/src/navigationPolicy.js
+++ b/src/navigationPolicy.js
@@ -24,6 +24,7 @@ const COCKPIT_REFUSALS = Object.freeze({
target: msg('Exit cockpit to fly to a target'),
vessel: msg('Exit cockpit to fly to a vessel'),
fire: msg('Exit cockpit to fly to a fire'),
+ earthquake: msg('Exit cockpit to fly to an earthquake'),
sighting: msg('Exit cockpit to fly to a sighting'),
'sighting-area': msg('Exit cockpit to fly to a sighting area'),
train: msg('Exit cockpit to fly to a train'),
diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js
index 66649b6cf0..61fb8a6202 100644
--- a/src/overlays/worldOverlay.js
+++ b/src/overlays/worldOverlay.js
@@ -1,4 +1,5 @@
import { WORLD_OVERLAY_OCCLUDER_SELECTORS } from './worldOverlayChrome.js';
+import { setClickCardHitTest } from '../data/pickRegistry.js';
export { WORLD_OVERLAY_OCCLUDER_SELECTORS } from './worldOverlayChrome.js';
import {
createCyberSonarSampler,
@@ -884,7 +885,9 @@ function invalidateHost({ solve = true, layout = false } = {}) {
if (layout) _occludersDirty = true;
_canvasNeedsClear = true;
_paintRectCount = 0;
- _hitRectCount = 0;
+ // Hit rectangles stay what is painted on screen until the next paint
+ // rebuilds them: every click subscriber reads the same overlay, even after
+ // an earlier one republishes entries in that click (a selection card).
_paintRectByKey.clear();
requestOverlayRender();
}
@@ -2783,10 +2786,9 @@ function drawWorldOverlay() {
resetFrameDiagnostics();
_solveDirty = false;
if (_canvasNeedsClear || _detectionSurfaceNeedsClear) clearCanvas();
- if (_accessibilitySignature) {
- _hitRectCount = 0;
- syncAccessibleActions();
- }
+ // Nothing is painted now, so nothing can be hit.
+ _hitRectCount = 0;
+ if (_accessibilitySignature) syncAccessibleActions();
syncPaintVisibility(false);
return;
}
@@ -2868,6 +2870,8 @@ export function initWorldOverlay(viewer) {
};
window.addEventListener('gev:cockpit-mode-changed', _cockpitModeHandler);
_removePostRender = frame.on('postRender', () => drawWorldOverlay());
+ // Click handlers read the card painted on top through the pick registry.
+ setClickCardHitTest(hitTestWorldOverlay);
_removeMoveEnd = camera.on('moveEnd', () => invalidateHost());
installUiOccluderObservers();
// The backing store and the occluder inventory are both deferred to the
@@ -2953,6 +2957,7 @@ export function destroyWorldOverlay() {
_paintCount = 0;
_paintRectCount = 0;
_hitRectCount = 0;
+ setClickCardHitTest(null);
_uiOcclusionRects.length = 0;
_uiOcclusionRectPool.length = 0;
_destroyed = hadHost || _destroyed;
diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs
index 4b27e73aeb..d64d065978 100644
--- a/src/overlays/worldOverlay.test.mjs
+++ b/src/overlays/worldOverlay.test.mjs
@@ -1936,6 +1936,25 @@ test('paint rectangles publish from a pool and topmost interactive lookup wins',
env.cleanup();
});
+test('hit rectangles stay what is painted until the next paint, through a republish in the same click', () => {
+ const env = installMockEnvironment();
+ initWorldOverlay(env.viewer);
+ setOverlayEntries('cards', [selectedEntry('card', { interactive: true })]);
+ env.postRender.raise();
+ assert.equal(hitTestWorldOverlay(200, 120)?.entryId, 'card');
+ // An earlier click subscriber publishes its own selection card: later
+ // subscribers in the same click still see what the user clicked on.
+ setOverlayEntries('other', [selectedEntry('elsewhere', { interactive: true })]);
+ clearOverlaySource('cards');
+ assert.equal(hitTestWorldOverlay(200, 120)?.entryId, 'card');
+ assert.equal(hitTestWorldOverlay(200, 120, { sourceId: 'cards' })?.entryId, 'card');
+ // The next paint shows the change, and the hit test follows it.
+ env.postRender.raise();
+ assert.equal(hitTestWorldOverlay(200, 120, { sourceId: 'cards' }), null);
+ assert.equal(hitTestWorldOverlay(200, 120)?.entryId, 'elsewhere');
+ env.cleanup();
+});
+
test('CCTV stable frame slots gate ambient chrome and wire the exact host hit rectangle', () => {
const env = installMockEnvironment({ width: 500, height: 400, dpr: 1 });
initWorldOverlay(env.viewer);
diff --git a/src/render/cesium/cameraGoldens.test.mjs b/src/render/cesium/cameraGoldens.test.mjs
index 774b0a0114..d6983579cb 100644
--- a/src/render/cesium/cameraGoldens.test.mjs
+++ b/src/render/cesium/cameraGoldens.test.mjs
@@ -2,15 +2,93 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { recordCameraGoldens } from './cameraGoldens.js';
+import { near, nearAngle } from '../conformance/expect.js';
+
+// The recorder is deterministic, but platforms can differ in the last bits
+// of trigonometric arithmetic. Keep structure and discrete values exact.
+function compareTrace(actual, expected, path = []) {
+ const label = path.join('.');
+ if (typeof expected === 'number') {
+ const key = path.at(-1);
+ if (['step', 'frames', 'count'].includes(key) || path[0] === 'viewport') {
+ assert.equal(actual, expected, label);
+ return;
+ }
+ const metres =
+ path.at(-2) === 'position' ||
+ key === 'height' ||
+ (path.at(-2) === 'view' && Number(key) >= 12 && Number(key) <= 14);
+ // A few ulps of the value itself, so large untagged values (pick points,
+ // ray origins, the far plane) are not held below one ulp.
+ const tolerance = Math.max(
+ metres ? 1e-8 : 1e-14,
+ Math.abs(expected) * 4 * Number.EPSILON,
+ );
+ // Heading and roll wrap at 2π: a value just under it is one just over 0.
+ if (key === 'heading' || key === 'roll')
+ nearAngle(actual, expected, tolerance, label);
+ else near(actual, expected, tolerance, label);
+ return;
+ }
+ if (expected !== null && typeof expected === 'object') {
+ assert.ok(actual !== null && typeof actual === 'object', label);
+ assert.equal(Array.isArray(actual), Array.isArray(expected), label);
+ assert.deepEqual(Object.keys(actual), Object.keys(expected), label);
+ if (Array.isArray(expected))
+ assert.equal(actual.length, expected.length, label);
+ for (const key of Object.keys(expected))
+ compareTrace(actual[key], expected[key], [...path, key]);
+ return;
+ }
+ assert.equal(actual, expected, label);
+}
test('the committed camera traces are what the installed Cesium records', async () => {
- const committed = readFileSync(
- new URL('../conformance/goldens/camera.json', import.meta.url),
- 'utf8',
- );
- const recorded = `${JSON.stringify(await recordCameraGoldens(), null, 2)}\n`;
- assert.ok(
- recorded === committed,
- 'goldens/camera.json is out of date: run node scripts/record-camera-goldens.mjs and review the diff',
+ const committed = JSON.parse(
+ readFileSync(
+ new URL('../conformance/goldens/camera.json', import.meta.url),
+ 'utf8',
+ ),
);
+ compareTrace(await recordCameraGoldens(), committed);
+});
+
+test('trace comparison tolerates only numeric roundoff, preserving structure and counters', () => {
+ const expected = {
+ position: { x: 1000 },
+ pitch: 0.3,
+ frames: 2,
+ values: [1],
+ label: 'pose',
+ };
+ compareTrace(
+ { ...expected, position: { x: 1000 + 2e-9 }, pitch: 0.3 + 1e-16 },
+ expected,
+ );
+ for (const actual of [
+ { ...expected, extra: true },
+ { ...expected, values: [] },
+ { ...expected, position: { x: 1000 + 2e-8 } },
+ { ...expected, pitch: 0.3 + 2e-14 },
+ { ...expected, frames: 2 + 1e-15 },
+ { ...expected, pitch: NaN },
+ { ...expected, pitch: null },
+ { ...expected, pitch: '0.3' },
+ { ...expected, label: 'other' },
+ ])
+ assert.throws(() => compareTrace(actual, expected));
+ const { label, ...missing } = expected;
+ assert.throws(() => compareTrace(missing, expected));
+});
+
+test('trace comparison scales with the value and wraps heading and roll', () => {
+ // One ulp of a ground pick point (about 5e-10 at 3e6 m) is roundoff.
+ const far = 3_000_000.123;
+ compareTrace({ pick: far + 2 * Number.EPSILON * far }, { pick: far });
+ assert.throws(() => compareTrace({ pick: far + 1e-6 }, { pick: far }));
+ // A heading just under 2π is one just over 0.
+ compareTrace({ heading: 2 * Math.PI - 1e-16 }, { heading: 1e-16 });
+ compareTrace({ roll: 1e-16 }, { roll: 2 * Math.PI - 1e-16 });
+ assert.throws(() => compareTrace({ heading: 0.1 }, { heading: 0 }));
+ assert.throws(() => compareTrace({ heading: NaN }, { heading: 0 }));
});
diff --git a/src/render/cesium/cameraPort.test.mjs b/src/render/cesium/cameraPort.test.mjs
index 967ff1f761..9d81e928fa 100644
--- a/src/render/cesium/cameraPort.test.mjs
+++ b/src/render/cesium/cameraPort.test.mjs
@@ -416,7 +416,16 @@ test('a pose measures heading, pitch and roll as Cesium does, and leaves the cam
const pitch = camera.pitch;
const roll = camera.roll;
assert.equal(pose.heading, heading, `heading ${k}`);
- assert.ok(Math.abs(pose.pitch - pitch) < 1e-12, `pitch ${k}`);
+ assert.ok(
+ pose.pitch >= -Math.PI / 2 && pose.pitch <= Math.PI / 2,
+ `canonical pitch ${k}`,
+ );
+ // Near vertical, acos amplifies last-bit direction differences. Match
+ // the conformance suite's well-conditioned pitch comparison.
+ assert.ok(
+ Math.abs(Math.sin(pose.pitch) - Math.sin(pitch)) < 1e-12,
+ `pitch ${k}`,
+ );
const turn = Math.abs(pose.roll - roll);
assert.ok(Math.min(turn, 2 * Math.PI - turn) < 1e-12, `roll ${k}`);
}
diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs
index 63f42ad4ab..e524925b09 100644
--- a/src/render/cesium/draw.test.mjs
+++ b/src/render/cesium/draw.test.mjs
@@ -4452,19 +4452,28 @@ test('an aircraft layer draws its contacts as one GPU icon set moving on the del
}
assert.equal(host._recedeParams().scaleFloor, 0.45);
- // Drawn where the layer reads it, between its two fixes.
- const t = Date.now() - delayMs;
- const tau = set.seconds(julianAt(t));
- const drawn = set.position(row, tau);
- const read = icons._iconPosition('abc123');
- assert.ok(Cesium.Cartesian3.distance(drawn, read) < 0.5, 'same place');
- const lon = Cesium.Math.toDegrees(
- Cesium.Cartographic.fromCartesian(drawn).longitude,
- );
- assert.ok(lon > -97 && lon < -96.9, 'interpolating the fixes');
- assert.ok(
- Math.abs(set.course(row, tau) - icons._iconCourse('abc123')) < 0.01,
- );
+ // Drawn where the layer reads it, between its two fixes. The clock
+ // holds still while both are read: the contact covers half a metre in
+ // about a millisecond, so two readings of a moving clock may not agree.
+ const realNow = Date.now;
+ const frozen = realNow();
+ Date.now = () => frozen;
+ try {
+ const t = frozen - delayMs;
+ const tau = set.seconds(julianAt(t));
+ const drawn = set.position(row, tau);
+ const read = icons._iconPosition('abc123');
+ assert.ok(Cesium.Cartesian3.distance(drawn, read) < 0.5, 'same place');
+ const lon = Cesium.Math.toDegrees(
+ Cesium.Cartographic.fromCartesian(drawn).longitude,
+ );
+ assert.ok(lon > -97 && lon < -96.9, 'interpolating the fixes');
+ assert.ok(
+ Math.abs(set.course(row, tau) - icons._iconCourse('abc123')) < 0.01,
+ );
+ } finally {
+ Date.now = realNow;
+ }
assert.equal(state._icons.expires('abc123'), now - 20_000);
assert.deepEqual(
drawHitOf(host._pickObject('abc123', null, { show: true })),
diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js
index 7e5704910a..85efe4569a 100644
--- a/src/render/cesium/harness.js
+++ b/src/render/cesium/harness.js
@@ -117,6 +117,7 @@ export const CESIUM_CHECKS = new Set([
'frame.time',
'globe.base.vector',
'globe.imagery',
+ 'globe.imagery.decoded',
'globe.imagery.frames',
'globe.imagery.video',
'globe.sky',
diff --git a/src/render/cesium/iconSetPrimitive.js b/src/render/cesium/iconSetPrimitive.js
index f1559019d3..432f78ffd1 100644
--- a/src/render/cesium/iconSetPrimitive.js
+++ b/src/render/cesium/iconSetPrimitive.js
@@ -261,7 +261,12 @@ void main() {
if (overDepth && zclip >= -1.0 && zclip <= 1.0) {
gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH
- v_depthFromNearPlusOne = 1.0;
+ // Just past the near plane, not on it: czm_writeLogDepth discards a
+ // fragment at or below 0.9999999, and 1.0 interpolated across the quad
+ // can arrive a rounding step or two under that, dropping the icon for a
+ // frame as it moves (flicker). 1e-4 m past the near plane is still in
+ // front of everything the scene draws.
+ v_depthFromNearPlusOne = 1.0001;
#endif
}
diff --git a/src/render/cesium/imagery.js b/src/render/cesium/imagery.js
index c70baa8d43..183dc736ad 100644
--- a/src/render/cesium/imagery.js
+++ b/src/render/cesium/imagery.js
@@ -18,13 +18,21 @@
* `prefetch` frames loading unseen at alpha 0. A frame is ready
* (`frameReady`) once the globe's tiles drawn are drawn from its own
* imagery (`imageryFrames.js`).
+ *
+ * With `imageryDecoded`, a `decoded` source is drawn the same way, a layer
+ * a slot: the slot its clock shows, and the next `prefetch` of the slots the
+ * source holds ahead, each tile the image the source answers for it.
*/
import * as Cesium from 'cesium';
import { vectorBaseProvider } from './vectorBase.js';
import { creditMarkup } from './credits.js';
import { listenerList } from './common.js';
import {
+ MissingTile,
createTileVideos,
+ decodedHeld,
+ decodedProvider,
+ decodedShownAt,
framesOf,
heldFrames,
layerDrawn,
@@ -41,14 +49,6 @@ export const TILE_RETRY_DELAY_MS = 250;
/** Ion's world imagery assets, by contract style. */
const WORLD_ASSETS = { aerial: 2, aerialLabels: 3 };
-/** A tile the source says is not there: Cesium draws the parent's. */
-class MissingTile extends Error {
- constructor() {
- super('No tile here');
- this.name = 'MissingTile';
- }
-}
-
const rectangleOf = (rect) =>
rect &&
Cesium.Rectangle.fromDegrees(rect.west, rect.south, rect.east, rect.north);
@@ -676,11 +676,21 @@ export function createCesiumImagery(
};
if (capabilities.has('imageryFrames')) {
handle.setFrames = (source, options = {}) => {
+ const decoded = source?.kind === 'decoded';
+ if (decoded && !capabilities.has('imageryDecoded'))
+ throw new TypeError('decoded imagery needs imageryDecoded');
+ if (
+ decoded &&
+ (typeof source.slotAt !== 'function' ||
+ typeof source.tile !== 'function')
+ )
+ throw new TypeError('a decoded source needs slotAt and tile');
const frames = framesOf(source);
if (record.removed) return;
dropFrames(record);
record.timed = {
video: source.kind === 'video',
+ decoded: decoded ? source : null,
frames,
mode: options.mode === 'blend' ? 'blend' : 'nearest',
prefetch: Math.max(0, Math.floor(options.prefetch ?? 1)),
@@ -723,12 +733,24 @@ export function createCesiumImagery(
function frameLayer(record, frame) {
const timed = record.timed;
const spec = { ...record.spec, url: frame.url };
- const entry = { layer: null, host: null, offError: null };
+ const entry = {
+ layer: null,
+ host: null,
+ offError: null,
+ signals: new Set(),
+ };
let made;
try {
- made = timed.video
- ? videoProvider(record.spec, frame, timed.videos)
- : providerFor(spec, { worldDataToken: worldDataToken() });
+ made = timed.decoded
+ ? decodedProvider(record.spec, frame.slot, timed.decoded, {
+ laterFrame,
+ signals: entry.signals,
+ urgency: () =>
+ timed.at?.nearest === frame.slot ? 'shown' : 'prefetch',
+ })
+ : timed.video
+ ? videoProvider(record.spec, frame, timed.videos)
+ : providerFor(spec, { worldDataToken: worldDataToken() });
} catch (error) {
report(error);
made = Promise.reject(error);
@@ -746,7 +768,9 @@ export function createCesiumImagery(
} else {
entry.offError = record.watchErrors(made);
entry.layer = new Cesium.ImageryLayer(
- timed.video ? made : hookProvider(made, spec, record.ctx),
+ timed.video || timed.decoded
+ ? made
+ : hookProvider(made, spec, record.ctx),
layerOptions(spec),
);
}
@@ -756,6 +780,9 @@ export function createCesiumImagery(
function dropFrameLayer(entry) {
entry.removed = true;
+ // A decoded slot's tiles still asked for are not wanted any more.
+ for (const controller of entry.signals) controller.abort();
+ entry.signals.clear();
entry.offError?.();
if (usable(entry.host) && entry.host.contains(entry.layer))
entry.host.remove(entry.layer, true);
@@ -785,9 +812,15 @@ export function createCesiumImagery(
const timed = record.timed;
if (!timed || record.removed) continue;
const ms = timed.clock === 'own' ? (timed.own ?? NaN) : sceneMs;
- const at = shownAt(timed.frames, ms, timed.mode);
+ const at = timed.decoded
+ ? decodedShownAt(timed.decoded, ms)
+ : shownAt(timed.frames, ms, timed.mode);
timed.at = at;
- const held = at ? heldFrames(timed.frames, at, timed.prefetch) : [];
+ const held = !at
+ ? []
+ : timed.decoded
+ ? decodedHeld(timed.decoded, at, timed.prefetch, ms)
+ : heldFrames(timed.frames, at, timed.prefetch);
for (const [index, entry] of timed.layers)
if (!held.includes(index) || entry.layer.isDestroyed()) {
dropFrameLayer(entry);
@@ -802,7 +835,10 @@ export function createCesiumImagery(
for (const index of held.sort((a, b) => a - b)) {
let entry = timed.layers.get(index);
if (!entry) {
- entry = frameLayer(record, timed.frames[index]);
+ entry = frameLayer(
+ record,
+ timed.decoded ? { slot: index, url: '' } : timed.frames[index],
+ );
timed.layers.set(index, entry);
}
const layer = entry.layer;
@@ -846,7 +882,9 @@ export function createCesiumImagery(
const timed = record.timed;
// A layer removed by another's listener says nothing.
if (record.removed || !timed?.at || !record.show) continue;
- const time = timed.frames[timed.at.nearest].time;
+ const time = timed.decoded
+ ? timed.at.nearest
+ : timed.frames[timed.at.nearest].time;
if (time === timed.announced) continue;
if (!timed.at.shown.every((s) => frameDrawn(timed.layers.get(s.index))))
continue;
diff --git a/src/render/cesium/imageryFrames.js b/src/render/cesium/imageryFrames.js
index 735649814b..d3dba47a24 100644
--- a/src/render/cesium/imageryFrames.js
+++ b/src/render/cesium/imageryFrames.js
@@ -11,10 +11,22 @@
* steps a segment): a time is shown by the step nearest it, its offset into
* the segment's videos in proportion; outside every segment, the nearest
* segment end is the nearest frame.
+ *
+ * A `decoded` source (`imageryDecoded`) has no list: the slot a time shows
+ * is the source's `slotAt`, the slots held ahead its `prefetch`, and each
+ * slot's tiles are the images its `tile` answers.
*/
import * as Cesium from 'cesium';
import { globeTilesDrawn } from './internals.js';
+/** A tile the source says is not there: Cesium draws the parent's. */
+export class MissingTile extends Error {
+ constructor() {
+ super('No tile here');
+ this.name = 'MissingTile';
+ }
+}
+
/** How far apart the times a video segment is seen at are, ms. */
export const VIDEO_STEP_MS = 250;
/** The most times one video segment is seen at. */
@@ -61,6 +73,7 @@ export function framesOf(source) {
}
return frames.sort((a, b) => a.time - b.time);
}
+ if (source?.kind === 'decoded') return [];
if (source?.kind === 'frames')
return (source.frames ?? [])
.filter((f) => Number.isFinite(f?.time) && typeof f?.url === 'string')
@@ -408,3 +421,74 @@ export function layerDrawn(scene, layer) {
}
return true;
}
+
+/**
+ * What `ms` shows of a `decoded` source: its slot, as `shownAt` answers for
+ * a list (the slot standing for the index), or null with none.
+ * @returns {{nearest: number, shown: Array<{index: number, weight: number}>}|null}
+ */
+export function decodedShownAt(source, ms) {
+ if (!Number.isFinite(ms)) return null;
+ const slot = source.slotAt(ms);
+ if (!Number.isFinite(slot)) return null;
+ return { nearest: slot, shown: [{ index: slot, weight: 1 }] };
+}
+
+/**
+ * The slots of a `decoded` source to hold for `ms`: the one shown, and the
+ * first `prefetch` of those the source holds ahead (finite, not shown, each
+ * once).
+ * @returns {number[]}
+ */
+export function decodedHeld(source, at, prefetch, ms) {
+ const held = [at.nearest];
+ if (prefetch <= 0 || typeof source.prefetch !== 'function') return held;
+ for (const slot of source.prefetch(ms) ?? []) {
+ if (held.length > prefetch) break;
+ if (Number.isFinite(slot) && !held.includes(slot)) held.push(slot);
+ }
+ return held;
+}
+
+/**
+ * A provider drawing one slot of a `decoded` source: each tile the image
+ * the source answers for it, in the spec's tiling (an `xyz` spec), or one
+ * image over the layer's rectangle (any other). A deferred tile is asked
+ * again on a later frame (`laterFrame`); a missing one draws the parent's.
+ * @param {import('../contract/globe').ImagerySpec} spec
+ * @param {number} slot
+ * @param {Extract} source
+ * @param {{laterFrame: () => Promise, signals: Set,
+ * urgency: () => 'shown'|'prefetch'}} ctx
+ */
+export function decodedProvider(spec, slot, source, ctx) {
+ // The same tiling and bounds a video frame's provider draws in.
+ const provider = videoProvider(spec, { url: '', fraction: 0 }, null);
+ provider.requestImage = async (x, y, level) => {
+ const controller = new AbortController();
+ ctx.signals.add(controller);
+ try {
+ for (;;) {
+ const answer = await source.tile({
+ tile: { x, y, level },
+ slot,
+ signal: controller.signal,
+ urgency: ctx.urgency(),
+ });
+ // An image no longer wanted is let go at once.
+ if (controller.signal.aborted) answer?.image?.close?.();
+ controller.signal.throwIfAborted();
+ if (answer?.defer) {
+ await ctx.laterFrame();
+ controller.signal.throwIfAborted();
+ continue;
+ }
+ if (!answer?.image) throw new MissingTile();
+ return answer.image;
+ }
+ } finally {
+ ctx.signals.delete(controller);
+ }
+ };
+ return provider;
+}
diff --git a/src/render/cesium/imageryFrames.test.mjs b/src/render/cesium/imageryFrames.test.mjs
index c810ab485b..c6a8fe3f94 100644
--- a/src/render/cesium/imageryFrames.test.mjs
+++ b/src/render/cesium/imageryFrames.test.mjs
@@ -2,7 +2,11 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test, { mock } from 'node:test';
import {
+ MissingTile,
createTileVideos,
+ decodedHeld,
+ decodedProvider,
+ decodedShownAt,
framesOf,
heldFrames,
layerDrawn,
@@ -336,3 +340,98 @@ test('a video’s length is learnt with a longer wait, and a failed one is not l
restore();
}
});
+
+/** A decoded source over slots 0, 100, 200, with what its tiles answer. */
+function decodedSource(answers = () => ({ missing: true })) {
+ const asked = [];
+ return {
+ asked,
+ kind: 'decoded',
+ slotAt: (ms) => (ms < 0 ? null : Math.min(200, Math.round(ms / 100) * 100)),
+ prefetch: (ms) => [Math.round(ms / 100) * 100, 300, NaN, 300, 400, 500],
+ tile: async (request) => {
+ asked.push(request);
+ return answers(request);
+ },
+ };
+}
+
+test('a decoded source shows the slot its clock names and holds the next it prefetches', () => {
+ const source = decodedSource();
+ assert.equal(framesOf(source).length, 0, 'no list to step through');
+ const at = decodedShownAt(source, 140);
+ assert.deepEqual(at, { nearest: 100, shown: [{ index: 100, weight: 1 }] });
+ assert.equal(decodedShownAt(source, -5), null, 'no slot: nothing shown');
+ assert.equal(decodedShownAt(source, NaN), null);
+ assert.deepEqual(decodedHeld(source, at, 2, 140), [100, 300, 400]);
+ assert.deepEqual(decodedHeld(source, at, 0, 140), [100]);
+ assert.deepEqual(
+ decodedHeld({ slotAt: () => 0 }, at, 3, 140),
+ [100],
+ 'a source with no prefetch holds the shown slot only',
+ );
+});
+
+test("a decoded slot's tiles are the source's images, asked again when deferred", async () => {
+ const image = { width: 256, height: 256 };
+ let defers = 1;
+ const source = decodedSource(({ tile }) => {
+ if (tile.level === 9) return { missing: true };
+ if (defers-- > 0) return { defer: true };
+ return { image };
+ });
+ let frames = 0;
+ let shown = true;
+ const signals = new Set();
+ const provider = decodedProvider(
+ { kind: 'xyz', url: '', maxLevel: 10, tiling: 'webmercator' },
+ 100,
+ source,
+ {
+ laterFrame: async () => {
+ frames += 1;
+ },
+ signals,
+ urgency: () => (shown ? 'shown' : 'prefetch'),
+ },
+ );
+ assert.ok(provider.tilingScheme instanceof Cesium.WebMercatorTilingScheme);
+ assert.equal(provider.maximumLevel, 10);
+ assert.equal(provider.hasAlphaChannel, true);
+ assert.equal(await provider.requestImage(1, 2, 3), image);
+ assert.equal(frames, 1, 'the deferred tile waited a frame');
+ assert.deepEqual(
+ source.asked.map((r) => [r.tile, r.slot, r.urgency]),
+ [
+ [{ x: 1, y: 2, level: 3 }, 100, 'shown'],
+ [{ x: 1, y: 2, level: 3 }, 100, 'shown'],
+ ],
+ );
+ shown = false;
+ await assert.rejects(provider.requestImage(0, 0, 9), MissingTile);
+ assert.equal(source.asked.at(-1).urgency, 'prefetch');
+ assert.equal(signals.size, 0, 'no tile left waiting');
+});
+
+test('a decoded tile answered after its slot was let go is closed, not drawn', async () => {
+ let release;
+ const closed = [];
+ const image = { close: () => closed.push('image') };
+ const source = decodedSource(
+ () => new Promise((resolve) => (release = () => resolve({ image }))),
+ );
+ const signals = new Set();
+ const provider = decodedProvider({ kind: 'single-image' }, 0, source, {
+ laterFrame: async () => {},
+ signals,
+ urgency: () => 'shown',
+ });
+ assert.equal(provider.maximumLevel, 0, 'one image over the rectangle');
+ const pending = provider.requestImage(0, 0, 0);
+ await Promise.resolve();
+ assert.ok(source.asked[0].signal instanceof AbortSignal);
+ for (const controller of signals) controller.abort();
+ release();
+ await assert.rejects(pending);
+ assert.deepEqual(closed, ['image']);
+});
diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js
index 5f73daa482..09554e04c6 100644
--- a/src/render/cesium/ports.js
+++ b/src/render/cesium/ports.js
@@ -49,6 +49,8 @@ const GLOBE_CAPABILITIES = [
'imageHooks',
// Timed imagery: a layer a frame, prefetched unseen (`imagery.js`).
'imageryFrames',
+ // Timed imagery handed over as finished images (`imageryFrames.js`).
+ 'imageryDecoded',
'surfaceIdentity',
'surfaceShading',
// A MapLibre style's vector tiles, painted as imagery (`vectorBase.js`).
diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs
index fc0e40bff2..36602d89a9 100644
--- a/src/render/cesium/ports.test.mjs
+++ b/src/render/cesium/ports.test.mjs
@@ -28,6 +28,7 @@ test('capabilities follow what the scene supports', () => {
'splitSwipe',
'imageHooks',
'imageryFrames',
+ 'imageryDecoded',
'surfaceIdentity',
'surfaceShading',
'vectorBase',
diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js
index 9d2409d9e2..10062c4f67 100644
--- a/src/render/conformance/checks/ports.js
+++ b/src/render/conformance/checks/ports.js
@@ -5425,6 +5425,125 @@ export function portChecks() {
},
{ capability: 'imageryFrames', bareSky: true },
),
+ check(
+ 'globe.imagery.decoded',
+ 'decoded imagery draws the images its source hands over for the slot shown',
+ async (h, r) => {
+ await overAustin(h, r, 200000);
+ const t0 = r.frame.time();
+ const slots = [t0, t0 + 60000, t0 + 120000];
+ const colours = ['#ff0000', '#0000ff', '#00ff00'];
+ const pixels = h.pixels !== false;
+ /** A solid tile of a slot's colour, or a canvas where none is made. */
+ const imageOf = async (slot) => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 16;
+ canvas.height = 16;
+ const g = canvas.getContext('2d');
+ g.fillStyle = colours[slots.indexOf(slot)];
+ g.fillRect(0, 0, 16, 16);
+ return createImageBitmap(canvas);
+ };
+ const asked = [];
+ const source = {
+ kind: 'decoded',
+ slotAt: (ms) => {
+ if (ms < t0 - 30000) return null;
+ let best = slots[0];
+ for (const slot of slots)
+ if (Math.abs(slot - ms) < Math.abs(best - ms)) best = slot;
+ return best;
+ },
+ prefetch: (ms) => slots.filter((slot) => slot > ms),
+ async tile({ tile, slot, signal, urgency }) {
+ asked.push({ slot, urgency });
+ signal.throwIfAborted();
+ // The first ask of each slot is put off: the renderer asks again.
+ if (asked.filter((a) => a.slot === slot).length === 1)
+ return { defer: true };
+ if (tile.level > 0) return { missing: true };
+ return { image: await imageOf(slot) };
+ },
+ };
+ const layer = r.globe.imagery.add({
+ kind: 'single-image',
+ url: PIXEL_PNG,
+ rectangle: {
+ west: AUSTIN.lon - 2,
+ south: AUSTIN.lat - 2,
+ east: AUSTIN.lon + 2,
+ north: AUSTIN.lat + 2,
+ },
+ });
+ const ready = [];
+ layer.on('frameReady', (time) => ready.push(time));
+ const wait = (ms) => new Promise((done) => setTimeout(done, ms));
+ const shows = async (ms, slot, colour, what) => {
+ const before = ready.length;
+ layer.setFrameTime(ms);
+ for (let i = 0; i < 500 && ready.length === before; i++) {
+ await drawn(h, r, 1);
+ await wait(10);
+ }
+ equal(ready.at(-1), slot, `${what}: its slot is ready`);
+ if (!pixels) return;
+ r.frame.renderNow();
+ const s = r.query.project(h.toEcef({ ...AUSTIN, height: 0 }));
+ const image = r.readPixels({
+ crop: {
+ x: Math.round(s.x),
+ y: Math.round(s.y),
+ width: 1,
+ height: 1,
+ },
+ });
+ const [red, green, blue] = image.data;
+ ok(colour(red, green, blue), `${what}: (${red}, ${green}, ${blue})`);
+ };
+ try {
+ throws(
+ () => layer.setFrames({ kind: 'decoded', slotAt: () => null }),
+ 'a decoded source with no tile',
+ );
+ layer.setFrames(source, { clock: 'own', prefetch: 1 });
+ await shows(
+ t0 + 10000,
+ t0,
+ (rr, g, b) => rr > 180 && g < 70 && b < 70,
+ 'the first slot',
+ );
+ if (pixels) {
+ ok(
+ asked.some((a) => a.slot === t0 && a.urgency === 'shown'),
+ 'the slot shown is asked for as shown',
+ );
+ ok(
+ asked.some(
+ (a) => a.slot === t0 + 60000 && a.urgency === 'prefetch',
+ ),
+ 'the next slot is asked for ahead, as a prefetch',
+ );
+ ok(
+ !asked.some((a) => a.slot === t0 + 120000),
+ 'no more slots are held ahead than prefetch allows',
+ );
+ }
+ await shows(
+ t0 + 65000,
+ t0 + 60000,
+ (rr, g, b) => b > 180 && rr < 70 && g < 70,
+ 'the second slot',
+ );
+ ready.length = 0;
+ layer.setFrameTime(t0 - 60000);
+ for (let i = 0; i < 20; i++) await drawn(h, r, 1);
+ deepEqual(ready, [], 'a time with no slot announces nothing');
+ } finally {
+ layer.remove();
+ }
+ },
+ { capability: ['imageryFrames', 'imageryDecoded'], bareSky: true },
+ ),
check(
'globe.withoutImageHooks',
'without imageHooks, a spec with main-thread tile hooks throws',
diff --git a/src/render/contract/common.d.ts b/src/render/contract/common.d.ts
index df585c2484..1ac6413542 100644
--- a/src/render/contract/common.d.ts
+++ b/src/render/contract/common.d.ts
@@ -165,6 +165,8 @@ export type Capability =
| 'splitSwipe'
/** Timed imagery frames with hidden prefetch. */
| 'imageryFrames'
+ /** Timed imagery the application hands over as finished tile images (`decoded`). */
+ | 'imageryDecoded'
/** Wind-relief and similar shading of the globe surface. */
| 'surfaceShading'
/** A version of what surface heights answer against (`globe.surfaceVersion`). */
diff --git a/src/render/contract/globe.d.ts b/src/render/contract/globe.d.ts
index abf63537e9..38516e66e4 100644
--- a/src/render/contract/globe.d.ts
+++ b/src/render/contract/globe.d.ts
@@ -130,17 +130,51 @@ export interface TimedUrl {
url: string;
}
+/**
+ * A tile of a `decoded` source at one slot: its finished image, `missing`
+ * (no tile there; draw the parent's), or `defer` (ask again on a later
+ * frame). The renderer owns the image once answered: it draws it as it is
+ * (its alpha too) and may close it once drawn.
+ */
+export type DecodedTile =
+ { image: ImageBitmap } | { missing: true } | { defer: true };
+
+/** What a `decoded` source is asked for: one tile at one slot. */
+export interface DecodedTileRequest {
+ tile: TileRequest;
+ /** The slot, as `slotAt` or `prefetch` named it. */
+ slot: number;
+ /** Aborted once the renderer no longer wants the tile. */
+ signal: AbortSignal;
+ /** `shown`: the slot the clock shows; `prefetch`: one held ahead. */
+ urgency: 'shown' | 'prefetch';
+}
+
/**
* A timed source: frames as URLs (one template per time), or video tiles
* in segments, each a template whose tiles are videos spanning `start` to
* `end` (epoch ms), a time within shown by its offset into the segment's
* videos. Outside every segment, the nearest segment end is shown.
+ *
+ * `decoded` (`imageryDecoded`): tiles the application makes itself and hands
+ * over as finished images. Its slots are times (epoch ms): `slotAt` names
+ * the slot a time shows (`null`: none, and nothing is drawn), `prefetch` the
+ * slots to hold ahead of it, nearest first. The renderer asks `tile` for the
+ * tiles each held slot draws, in the layer's tiling, and only draws what it
+ * is given. It shows the nearest slot only (`mode` is not read); the
+ * `prefetch` option caps how many of the source's slots it holds ahead.
*/
export type TimedSource =
| { kind: 'frames'; frames: TimedUrl[] }
| {
kind: 'video';
segments: Array<{ url: string; start: number; end: number }>;
+ }
+ | {
+ kind: 'decoded';
+ slotAt(time: number): number | null;
+ prefetch?(time: number): number[];
+ tile(request: DecodedTileRequest): Promise;
};
export interface ImageryLayer {
@@ -176,8 +210,8 @@ export interface ImageryLayer {
/** `imageryFrames`: which time to show, on the `own` clock. */
setFrameTime?(ms: number): void;
/**
- * `imageryFrames`: the frame the layer's clock now shows (by its time)
- * has been drawn. Fires once each time the shown frame changes, never
+ * `imageryFrames`: the frame the layer's clock now shows (by its time;
+ * a `decoded` source's by its slot) has been drawn. Fires once each time the shown frame changes, never
* for frames only prefetched.
*/
on(event: 'frameReady', cb: (time: number) => void): Off;
diff --git a/src/render/contract/index.js b/src/render/contract/index.js
index 2198b6226c..3accf55f71 100644
--- a/src/render/contract/index.js
+++ b/src/render/contract/index.js
@@ -23,6 +23,7 @@ export const CAPABILITIES = Object.freeze([
'imageryOnTiles',
'splitSwipe',
'imageryFrames',
+ 'imageryDecoded',
'surfaceShading',
'surfaceIdentity',
'imageHooks',
diff --git a/src/render/stub/index.js b/src/render/stub/index.js
index 9eb21cfc58..7ef3bcf7c4 100644
--- a/src/render/stub/index.js
+++ b/src/render/stub/index.js
@@ -1574,8 +1574,12 @@ export function createStubRenderer(options = {}) {
if (capabilities.has('imageryFrames')) {
let source = null;
let clockKind = 'scene';
- /** The time the source shows for `ms`: the nearest frame, or within the videos. */
+ /** The time the source shows for `ms`: the nearest frame, within the videos, or a decoded source's slot. */
const shownTime = (ms) => {
+ if (source?.kind === 'decoded') {
+ const slot = Number.isFinite(ms) ? source.slotAt(ms) : null;
+ return Number.isFinite(slot) ? slot : null;
+ }
if (source?.kind === 'video') {
let best = null;
let bestOff = Infinity;
@@ -1609,10 +1613,22 @@ export function createStubRenderer(options = {}) {
deliver(listeners.frameReady, drawnTime);
});
layer.setFrames = (next, opts = {}) => {
+ if (next.kind === 'decoded' && !capabilities.has('imageryDecoded'))
+ throw new TypeError('decoded imagery needs imageryDecoded');
+ if (
+ next.kind === 'decoded' &&
+ (typeof next.slotAt !== 'function' || typeof next.tile !== 'function')
+ )
+ throw new TypeError('a decoded source needs slotAt and tile');
source =
- next.kind === 'video'
- ? { kind: 'video', segments: next.segments.map((s) => ({ ...s })) }
- : { kind: 'frames', frames: next.frames.slice() };
+ next.kind === 'decoded'
+ ? next
+ : next.kind === 'video'
+ ? {
+ kind: 'video',
+ segments: next.segments.map((s) => ({ ...s })),
+ }
+ : { kind: 'frames', frames: next.frames.slice() };
wanted = null;
drawnTime = null;
clockKind = opts.clock ?? 'scene';
diff --git a/src/scenes/interactions.js b/src/scenes/interactions.js
index a7c2d09eef..35d76b10bd 100644
--- a/src/scenes/interactions.js
+++ b/src/scenes/interactions.js
@@ -1,6 +1,7 @@
import { nextTick } from 'vue';
import { isPointerFree } from '../data/inputOwnership.js';
import { inputFor } from '../input/dispatcher.js';
+import { isUnderOtherCard } from '../data/pickRegistry.js';
import { createInteractionSession } from '../director/interactions/session.js';
import { t } from '../i18n/index.js';
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
@@ -119,6 +120,9 @@ export function createSceneInteractions(
session.activate(items);
unsubscribeClick = inputFor(viewer).onClick((event) => {
if (panel?.owner !== owner || !shown() || !available()) return;
+ // Another layer's card or label painted on top takes the click: the item
+ // under it does not act, and the click is not empty space either.
+ if (isUnderOtherCard(event)) return;
// A pack feature is its draw set's item (see dataPacks/presentation.js).
const hit = event.drawHit;
if (!hit) return;
diff --git a/src/scenes/interactionsView.test.mjs b/src/scenes/interactionsView.test.mjs
index 04b1e18262..99cb576766 100644
--- a/src/scenes/interactionsView.test.mjs
+++ b/src/scenes/interactionsView.test.mjs
@@ -10,6 +10,8 @@ import { createPinia } from 'pinia';
import { useSceneInteractionsStore } from '../ui/stores/sceneInteractions.js';
import SceneInteractions from '../ui/views/panels/SceneInteractions.vue';
import { createSceneInteractions } from './interactions.js';
+import { fakeInput } from '../input/testDoubles.mjs';
+import { setClickCardHitTest } from '../data/pickRegistry.js';
const target = (featureId) => ({ packId: 'qa', featureId });
const key = (featureId) => JSON.stringify(['qa', featureId]);
@@ -192,3 +194,39 @@ test("an earlier owner leaves a later owner's panel alone", async (t) => {
await settle();
assert.equal(later.getState().selected, 'fly');
});
+
+// The card or label painted on top takes the click: a pack feature under
+// another layer's card is not selected for its actions.
+test("another layer's card over a pack feature keeps the click", async (t) => {
+ document.body.replaceChildren();
+ const container = document.body.appendChild(document.createElement('div'));
+ const canvas = container.appendChild(document.createElement('canvas'));
+ const pinia = createPinia();
+ const app = createApp(SceneInteractions).use(pinia);
+ app.mount(document.body.appendChild(document.createElement('div')));
+ let picked = null;
+ const viewer = { container, scene: { canvas, pick: () => picked } };
+ const input = fakeInput(viewer);
+ const store = useSceneInteractionsStore(pinia);
+ const interactions = createSceneInteractions(viewer, {
+ execute: async () => true,
+ store,
+ });
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => {
+ setClickCardHitTest(null);
+ interactions.destroy();
+ input.destroy();
+ app.unmount();
+ });
+ const feature = { set: 'qa:points', id: 'point' };
+ interactions.activate(SHOT, new Map([[key('point'), feature]]));
+ await nextTick();
+ picked = { id: feature, primitive: {} };
+ input.tap({ x: 10, y: 10 });
+ assert.deepEqual(store.panel?.outlined ?? [], [], 'covered: not selected');
+ top = null;
+ input.tap({ x: 10, y: 10 });
+ assert.deepEqual(store.panel.outlined, ['card', 'fly']);
+});
diff --git a/src/scenes/project.js b/src/scenes/project.js
index 95397183c7..b4cdf33571 100644
--- a/src/scenes/project.js
+++ b/src/scenes/project.js
@@ -287,6 +287,9 @@ export function normalizeShot(
hud: {
visible: typeof hud.visible === 'boolean' ? hud.visible : true,
variant: typeof hud.variant === 'string' ? hud.variant : 'tactical',
+ // Sonar on beside a layout whose code cannot say so; absent is off
+ // unless the variant names the retired Cyber layout.
+ ...(hud.sonar === true ? { sonar: true } : {}),
},
detection: {
...(typeof detection.allocation === 'string'
diff --git a/src/search/bip39Words.js b/src/search/bip39Words.js
new file mode 100644
index 0000000000..0c8fa29f63
--- /dev/null
+++ b/src/search/bip39Words.js
@@ -0,0 +1,210 @@
+/**
+ * @module search/bip39Words
+ * @description The 2048 words of the BIP39 English list, from which wallet
+ * recovery phrases are made (github.com/bitcoin/bips, bip-0039/english.txt).
+ * Only read to keep a typed phrase from leaving the browser.
+ */
+
+const WORDS = `
+abandon ability able about above absent absorb abstract absurd abuse
+access accident account accuse achieve acid acoustic acquire across
+act action actor actress actual adapt add addict address adjust admit
+adult advance advice aerobic affair afford afraid again age agent
+agree ahead aim air airport aisle alarm album alcohol alert alien all
+alley allow almost alone alpha already also alter always amateur
+amazing among amount amused analyst anchor ancient anger angle angry
+animal ankle announce annual another answer antenna antique anxiety
+any apart apology appear apple approve april arch arctic area arena
+argue arm armed armor army around arrange arrest arrive arrow art
+artefact artist artwork ask aspect assault asset assist assume asthma
+athlete atom attack attend attitude attract auction audit august aunt
+author auto autumn average avocado avoid awake aware away awesome
+awful awkward axis baby bachelor bacon badge bag balance balcony ball
+bamboo banana banner bar barely bargain barrel base basic basket
+battle beach bean beauty because become beef before begin behave
+behind believe below belt bench benefit best betray better between
+beyond bicycle bid bike bind biology bird birth bitter black blade
+blame blanket blast bleak bless blind blood blossom blouse blue blur
+blush board boat body boil bomb bone bonus book boost border boring
+borrow boss bottom bounce box boy bracket brain brand brass brave
+bread breeze brick bridge brief bright bring brisk broccoli broken
+bronze broom brother brown brush bubble buddy budget buffalo build
+bulb bulk bullet bundle bunker burden burger burst bus business busy
+butter buyer buzz cabbage cabin cable cactus cage cake call calm
+camera camp can canal cancel candy cannon canoe canvas canyon capable
+capital captain car carbon card cargo carpet carry cart case cash
+casino castle casual cat catalog catch category cattle caught cause
+caution cave ceiling celery cement census century cereal certain chair
+chalk champion change chaos chapter charge chase chat cheap check
+cheese chef cherry chest chicken chief child chimney choice choose
+chronic chuckle chunk churn cigar cinnamon circle citizen city civil
+claim clap clarify claw clay clean clerk clever click client cliff
+climb clinic clip clock clog close cloth cloud clown club clump
+cluster clutch coach coast coconut code coffee coil coin collect color
+column combine come comfort comic common company concert conduct
+confirm congress connect consider control convince cook cool copper
+copy coral core corn correct cost cotton couch country couple course
+cousin cover coyote crack cradle craft cram crane crash crater crawl
+crazy cream credit creek crew cricket crime crisp critic crop cross
+crouch crowd crucial cruel cruise crumble crunch crush cry crystal
+cube culture cup cupboard curious current curtain curve cushion custom
+cute cycle dad damage damp dance danger daring dash daughter dawn day
+deal debate debris decade december decide decline decorate decrease
+deer defense define defy degree delay deliver demand demise denial
+dentist deny depart depend deposit depth deputy derive describe desert
+design desk despair destroy detail detect develop device devote
+diagram dial diamond diary dice diesel diet differ digital dignity
+dilemma dinner dinosaur direct dirt disagree discover disease dish
+dismiss disorder display distance divert divide divorce dizzy doctor
+document dog doll dolphin domain donate donkey donor door dose double
+dove draft dragon drama drastic draw dream dress drift drill drink
+drip drive drop drum dry duck dumb dune during dust dutch duty dwarf
+dynamic eager eagle early earn earth easily east easy echo ecology
+economy edge edit educate effort egg eight either elbow elder electric
+elegant element elephant elevator elite else embark embody embrace
+emerge emotion employ empower empty enable enact end endless endorse
+enemy energy enforce engage engine enhance enjoy enlist enough enrich
+enroll ensure enter entire entry envelope episode equal equip era
+erase erode erosion error erupt escape essay essence estate eternal
+ethics evidence evil evoke evolve exact example excess exchange excite
+exclude excuse execute exercise exhaust exhibit exile exist exit
+exotic expand expect expire explain expose express extend extra eye
+eyebrow fabric face faculty fade faint faith fall false fame family
+famous fan fancy fantasy farm fashion fat fatal father fatigue fault
+favorite feature february federal fee feed feel female fence festival
+fetch fever few fiber fiction field figure file film filter final find
+fine finger finish fire firm first fiscal fish fit fitness fix flag
+flame flash flat flavor flee flight flip float flock floor flower
+fluid flush fly foam focus fog foil fold follow food foot force forest
+forget fork fortune forum forward fossil foster found fox fragile
+frame frequent fresh friend fringe frog front frost frown frozen fruit
+fuel fun funny furnace fury future gadget gain galaxy gallery game gap
+garage garbage garden garlic garment gas gasp gate gather gauge gaze
+general genius genre gentle genuine gesture ghost giant gift giggle
+ginger giraffe girl give glad glance glare glass glide glimpse globe
+gloom glory glove glow glue goat goddess gold good goose gorilla
+gospel gossip govern gown grab grace grain grant grape grass gravity
+great green grid grief grit grocery group grow grunt guard guess guide
+guilt guitar gun gym habit hair half hammer hamster hand happy harbor
+hard harsh harvest hat have hawk hazard head health heart heavy
+hedgehog height hello helmet help hen hero hidden high hill hint hip
+hire history hobby hockey hold hole holiday hollow home honey hood
+hope horn horror horse hospital host hotel hour hover hub huge human
+humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice
+icon idea identify idle ignore ill illegal illness image imitate
+immense immune impact impose improve impulse inch include income
+increase index indicate indoor industry infant inflict inform inhale
+inherit initial inject injury inmate inner innocent input inquiry
+insane insect inside inspire install intact interest into invest
+invite involve iron island isolate issue item ivory jacket jaguar jar
+jazz jealous jeans jelly jewel job join joke journey joy judge juice
+jump jungle junior junk just kangaroo keen keep ketchup key kick kid
+kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock
+know lab label labor ladder lady lake lamp language laptop large later
+latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn
+leave lecture left leg legal legend leisure lemon lend length lens
+leopard lesson letter level liar liberty library license life lift
+light like limb limit link lion liquid list little live lizard load
+loan lobster local lock logic lonely long loop lottery loud lounge
+love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad
+magic magnet maid mail main major make mammal man manage mandate mango
+mansion manual maple marble march margin marine market marriage mask
+mass master match material math matrix matter maximum maze meadow mean
+measure meat mechanic medal media melody melt member memory mention
+menu mercy merge merit merry mesh message metal method middle midnight
+milk million mimic mind minimum minor minute miracle mirror misery
+miss mistake mix mixed mixture mobile model modify mom moment monitor
+monkey monster month moon moral more morning mosquito mother motion
+motor mountain mouse move movie much muffin mule multiply muscle
+museum mushroom music must mutual myself mystery myth naive name
+napkin narrow nasty nation nature near neck need negative neglect
+neither nephew nerve nest net network neutral never news next nice
+night noble noise nominee noodle normal north nose notable note
+nothing notice novel now nuclear number nurse nut oak obey object
+oblige obscure observe obtain obvious occur ocean october odor off
+offer office often oil okay old olive olympic omit once one onion
+online only open opera opinion oppose option orange orbit orchard
+order ordinary organ orient original orphan ostrich other outdoor
+outer output outside oval oven over own owner oxygen oyster ozone pact
+paddle page pair palace palm panda panel panic panther paper parade
+parent park parrot party pass patch path patient patrol pattern pause
+pave payment peace peanut pear peasant pelican pen penalty pencil
+people pepper perfect permit person pet phone photo phrase physical
+piano picnic picture piece pig pigeon pill pilot pink pioneer pipe
+pistol pitch pizza place planet plastic plate play please pledge pluck
+plug plunge poem poet point polar pole police pond pony pool popular
+portion position possible post potato pottery poverty powder power
+practice praise predict prefer prepare present pretty prevent price
+pride primary print priority prison private prize problem process
+produce profit program project promote proof property prosper protect
+proud provide public pudding pull pulp pulse pumpkin punch pupil puppy
+purchase purity purpose purse push put puzzle pyramid quality quantum
+quarter question quick quit quiz quote rabbit raccoon race rack radar
+radio rail rain raise rally ramp ranch random range rapid rare rate
+rather raven raw razor ready real reason rebel rebuild recall receive
+recipe record recycle reduce reflect reform refuse region regret
+regular reject relax release relief rely remain remember remind remove
+render renew rent reopen repair repeat replace report require rescue
+resemble resist resource response result retire retreat return reunion
+reveal review reward rhythm rib ribbon rice rich ride ridge rifle
+right rigid ring riot ripple risk ritual rival river road roast robot
+robust rocket romance roof rookie room rose rotate rough round route
+royal rubber rude rug rule run runway rural sad saddle sadness safe
+sail salad salmon salon salt salute same sample sand satisfy satoshi
+sauce sausage save say scale scan scare scatter scene scheme school
+science scissors scorpion scout scrap screen script scrub sea search
+season seat second secret section security seed seek segment select
+sell seminar senior sense sentence series service session settle setup
+seven shadow shaft shallow share shed shell sheriff shield shift shine
+ship shiver shock shoe shoot shop short shoulder shove shrimp shrug
+shuffle shy sibling sick side siege sight sign silent silk silly
+silver similar simple since sing siren sister situate six size skate
+sketch ski skill skin skirt skull slab slam sleep slender slice slide
+slight slim slogan slot slow slush small smart smile smoke smooth
+snack snake snap sniff snow soap soccer social sock soda soft solar
+soldier solid solution solve someone song soon sorry sort soul sound
+soup source south space spare spatial spawn speak special speed spell
+spend sphere spice spider spike spin spirit split spoil sponsor spoon
+sport spot spray spread spring spy square squeeze squirrel stable
+stadium staff stage stairs stamp stand start state stay steak steel
+stem step stereo stick still sting stock stomach stone stool story
+stove strategy street strike strong struggle student stuff stumble
+style subject submit subway success such sudden suffer sugar suggest
+suit summer sun sunny sunset super supply supreme sure surface surge
+surprise surround survey suspect sustain swallow swamp swap swarm
+swear sweet swift swim swing switch sword symbol symptom syrup system
+table tackle tag tail talent talk tank tape target task taste tattoo
+taxi teach team tell ten tenant tennis tent term test text thank that
+theme then theory there they thing this thought three thrive throw
+thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue
+title toast tobacco today toddler toe together toilet token tomato
+tomorrow tone tongue tonight tool tooth top topic topple torch tornado
+tortoise toss total tourist toward tower town toy track trade traffic
+tragic train transfer trap trash travel tray treat tree trend trial
+tribe trick trigger trim trip trophy trouble truck true truly trumpet
+trust truth try tube tuition tumble tuna tunnel turkey turn turtle
+twelve twenty twice twin twist two type typical ugly umbrella unable
+unaware uncle uncover under undo unfair unfold unhappy uniform unique
+unit universe unknown unlock until unusual unveil update upgrade
+uphold upon upper upset urban urge usage use used useful useless usual
+utility vacant vacuum vague valid valley valve van vanish vapor
+various vast vault vehicle velvet vendor venture venue verb verify
+version very vessel veteran viable vibrant vicious victory video view
+village vintage violin virtual virus visa visit visual vital vivid
+vocal voice void volcano volume vote voyage wage wagon wait walk wall
+walnut want warfare warm warrior wash wasp waste water wave way wealth
+weapon wear weasel weather web wedding weekend weird welcome west wet
+whale what wheat wheel when where whip whisper wide width wife wild
+will win window wine wing wink winner winter wire wisdom wise wish
+witness wolf woman wonder wood wool word work world worry worth wrap
+wreck wrestle wrist write wrong yard year yellow you young youth zebra
+zero zone zoo
+`;
+
+let words = null;
+
+/** Whether `word` (lower case) is on the list. */
+export function isBip39Word(word) {
+ words ??= new Set(WORDS.split(/\s+/).filter(Boolean));
+ return words.has(word);
+}
diff --git a/src/search/placeSuggestions.js b/src/search/placeSuggestions.js
index 6fa20b11b5..02e37b7bcc 100644
--- a/src/search/placeSuggestions.js
+++ b/src/search/placeSuggestions.js
@@ -1,3 +1,4 @@
+import { isBip39Word } from './bip39Words.js';
import { normalizePhotonFeature, photonSearchUrl } from '../keylessGeocoder.js';
import { parseCoordinateQuery } from './coordinateParser.js';
import {
@@ -14,6 +15,31 @@ export const isCjk = (text) => CJK.test(String(text || ''));
/** The fewest characters a place name is looked up from. */
export const minPlaceChars = (text) => (isCjk(text) ? 2 : 3);
+/**
+ * Words on the BIP39 list that name places and things on a map, or that a
+ * request about one is made of, for telling a list of places or a request
+ * from a recovery phrase.
+ */
+const MAP_WORDS = new Set(
+ (
+ 'airport alley arena bar beach bike boat border bridge bus cabin camp ' +
+ 'canal canyon capital car castle cave city cliff clinic coast coffee ' +
+ 'country cruise dentist desert dune east elevator farm field fire ' +
+ 'flight forest gallery garage garden gym harbor hill hospital hotel ' +
+ 'island jungle kitchen lake library market meadow moon mountain museum ' +
+ 'nation north ocean office opera palace park pizza planet police pond ' +
+ 'pool rail rain ranch region ridge river road rocket route school sea ' +
+ 'ship shop ski snow soccer south space square stadium street subway sun ' +
+ 'swamp taxi tennis tornado tower town traffic train truck tunnel valley ' +
+ 'van vessel village volcano wagon weather west wine zoo ' +
+ // Words a request about a map is made of.
+ 'any area around best cheap city close day dinner early find food ' +
+ 'fresh good hour live local lunch main minute morning near night now ' +
+ 'old open spot that there this time today tomorrow travel trip view ' +
+ 'visit walk weekend what when where world'
+ ).split(' '),
+);
+
/**
* Text that may hold something private, which is never looked up, offered
* as a place or sent anywhere:
@@ -62,10 +88,27 @@ export function onlyNumbersLookPrivate(text) {
// is ("card 4111 …", "phone +1 415 …", "token 12345678").
groups.every((group) => group.length <= 6) &&
groups.join('').length <= 9 &&
+ !/(? (/\d/.test(text) ? 10 : 8);
+
+/**
+ * "Boise ID 83702", "Coeur d'Alene ID 83814": Idaho's code before a ZIP
+ * code, after a town's name (not after "my" or "employee", whose "ID" is an
+ * identity number).
+ */
+const IDAHO_BEFORE_ZIP =
+ /(?
+ ID_OWNERS.test(word.replace(/\p{P}+$/u, ''))
+ ? whole
+ : `${word}${gap}Idaho`,
+ );
}
/** A US ZIP+4 after a state's code or name, as an address writes it. */
const US_ZIP4 = new RegExp(
- String.raw`(?<=(?:^|\s)(?:[a-z]{2}|[a-z]\.[a-z]|Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Mass|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming|Puerto Rico)\.?,?\s)\d{5}-\d{4}\b`,
+ String.raw`(?<=(?:^|\s)(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|PR|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY]|[a-z]\.[a-z]|Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Mass|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming|Puerto Rico)\.?,?\s)\d{5}-\d{4}\b`,
'giu',
);
@@ -119,6 +168,80 @@ function privacyReason(text) {
)
)
return 'other';
+ // An email written around a filter: "john(at)gmail.com",
+ // "john[at]gmail[dot]com", "john at gmail dot com".
+ // Also "john at gmail.com" and a "(dot)" or "[dot]" in any of them.
+ // Spaced letter by letter ("j o h n @ g m a i l . c o m").
+ if (
+ /(?:^|\s)(?:\S\s){3,}@\s?(?:\S\s?){2,}/u.test(line) &&
+ /[^@]@[\p{L}\p{N}-]+\.\p{L}{2,}/u.test(line.replace(/\s+/g, ''))
+ )
+ return 'other';
+ if (
+ /[\p{L}\p{N}._%+-]\s*[([{<]\s*at\s*[)\]}>]\s*[\p{L}\p{N}-]/iu.test(line) ||
+ /(?])\s+\p{L}{2,24}\b/iu.test(
+ line,
+ ) ||
+ /(?]\s*\p{L}{2,24}\b/iu.test(
+ line,
+ ) ||
+ /(?= 2 && (host.includes('::') || colons >= 5)) return 'other';
+ }
+ // An IP address ("10.0.0.1").
+ if (/(? {
+ const bare = token
+ .replace(/^[[(]+|(?<=[^\]),.;])[\]),.;]+$/g, '')
+ .replace(/%\w+$/, '');
+ const colons = (bare.match(/:/g) || []).length;
+ return (
+ /^[0-9a-f:.]+$/i.test(bare) &&
+ colons >= 2 &&
+ (bare.includes('::') || colons >= 5)
+ );
+ })
+ )
+ return 'other';
+ // A wallet's recovery phrase ("abandon ability able …"): twelve words in
+ // a row on the BIP39 list ("can you tell where the most …" is a
+ // question). Too long to be sent for suggestions anyway, it is kept from
+ // the assistant too.
+ // Written with commas, numbered ("1. abandon 2. ability"), joined by
+ // dashes or slashes, or after a few words ("my seed is …"): twelve of
+ // the list's words in a row. The list has many words for places and for
+ // asking about them, and a phrase is drawn at random from all of it:
+ // twelve with four of those ("coffee, bar, hotel, museum, park …", "find
+ // good food open now near this area") are a list or a request, which a
+ // phrase is about once in a hundred.
+ const recent = [];
+ for (const token of line.toLowerCase().split(/[\s,;|/.\-\u2013\u2014]+/)) {
+ // Numbered ("1.", "(1)", "1:", "#1", "[1]") or quoted words; "and"
+ // before the last word joins it.
+ const word = token
+ .replace(/^["'“”„‚«»‹›‘’([{<#]*\d*[)\]:]?["'“”„‚«»‹›‘’([{<]*/, '')
+ .replace(/(?<=[a-z])[^a-z]+$/, '');
+ if (!word || word === 'and') continue;
+ if (!isBip39Word(word)) {
+ recent.length = 0;
+ continue;
+ }
+ recent.push(MAP_WORDS.has(word));
+ if (recent.length > 12) recent.shift();
+ if (recent.length === 12 && recent.filter(Boolean).length < 4)
+ return 'other';
+ }
// Coordinates and grid references are a spot, not a number to keep: only
// text the place search itself reads as coordinates, as typed ("١٢٣٤,
// ٥٦٧٨" folded would read as a spot, but is not one).
@@ -146,7 +269,7 @@ function privacyReason(text) {
.replace(
// After a street word, or before the city ("12, 10115 Berlin");
// "030 12345" alone is a phone number.
- /(?<=\p{L}\.?\s)\d{1,4}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+\p{L}|$)|(?<=^|\s)\d{1,4}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+\p{L})/giu,
+ /(?<=\p{L}\.?\s)[1-9]\d{0,3}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+(?!(?:thanks|thank|thx|please|pls|ok|okay|now|asap|call|text)\b)\p{L}|$)|(?<=^|\s)[1-9]\d{0,3}[a-z]?,?\s+\d{5}(?:-\d{3})?(?=\s+(?!(?:thanks|thank|thx|please|pls|ok|okay|now|asap|call|text)\b)\p{L})/giu,
' ',
)
// Other postcodes after a street's house number and before the city (a
@@ -164,7 +287,7 @@ function privacyReason(text) {
.replace(US_ZIP4, ' x ')
.replace(/\b\d{5}-\d{3}\b/g, ' x ')
.replace(
- /〒\s?\d{3}-\d{4}|\b\d{3}-\d{4}(?=\s*[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])/gu,
+ /〒\s?\d{3}-\d{4}|\b\d{3}-\d{4}(?=\s*[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}])|(?<=[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]\s*)\d{3}-\d{4}\b/gu,
' x ',
)
.replace(/#/g, ' x ')
@@ -176,7 +299,12 @@ function privacyReason(text) {
// An IBAN.
if (/\b[a-z]{2}\d{2}(?:\s?[a-z0-9]){10,}/i.test(line)) return 'other';
if (
- /\b(?:password|passcode|passwd|ssn|pw|pwd|bearer)\b\s*[:=#]?\s*\S/i.test(
+ /\b(?:password|passcode|passwd|pw|pwd)\b\s*[:=#]?\s*\S/i.test(line) ||
+ // "Bearer Island" and "SSN Station" are places: after "bearer" any value
+ // but a capitalised name is a token, and a social security number has
+ // digits.
+ bearerToken(line) ||
+ /\bssn\b(?:\s+(?:is|are|no\.?|number|#|ending|ends?|in|with|last|four|4|digits))*\s*[:=#]?\s*(?:\d|[x*]{2})/i.test(
line,
) ||
// The word for "password" in the interface's languages.
@@ -190,11 +318,23 @@ function privacyReason(text) {
line,
) ||
/\b(?:token|secret|api[ _-]?key|key|pass)\s*[:=]\s*\S/i.test(line) ||
+ // A number on a document or account after its label: "license ABC1234",
+ // "passport X1234567", "plate 7ABC123", "member no. 12345".
+ /\b(?:licen[cs]e|plate|passport|member(?:ship)?|account|acct|policy|ticket|booking|confirmation|ref(?:erence)?)(?:\s+(?:no\.?|number|#|is))*(?:\s*[:=#]\s*|\s+)(?=[a-z0-9-]*\d)[a-z0-9-]{4,}/i.test(
+ line,
+ ) ||
+ // An identity number after "ID" in capitals ("ID AB123"); "Id" and
+ // "id" are words.
+ /\bID(?:\s+(?:no\.?|number|#|is))*(?:\s*[:=#]\s*|\s+)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]{4,}/.test(
+ line,
+ ) ||
/\b(?:my secret is|passphrase|mnemonic|seed phrase|recovery phrase)\b\s*[:=]?\s*\S/i.test(
line,
) ||
// An email spelled out to slip past a filter: "john at example dot com".
- /\b\S+\s+at\s+\S+\s+dot\s+(?:com|net|org|edu|gov|io|co)\b/i.test(line) ||
+ /(? token.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''))
+ .map((token) =>
+ token.replace(/^[^\p{L}\p{N}]+|(?<=[\p{L}\p{N}])[^\p{L}\p{N}]+$/gu, ''),
+ )
.some(
(token) =>
- /^(?:sk[-_]|rk_|pk_live|ghp_|xox[abposr]-)/i.test(token) ||
- /^(?:AIza|eyJ|AKIA)/.test(token) ||
+ /^(?:sk[-_]|rk_|pk_live|ghp_|gho_|ghu_|ghs_|github_pat_|glpat-|hf_|xox[abposr]-)/i.test(
+ token,
+ ) ||
+ /^SG\.[\w-]{8,}\.[\w-]{8,}$/.test(token) ||
+ /^(?:AIza|eyJ)/.test(token) ||
+ /^AKIA[0-9A-Z]{12,}$/.test(token) ||
mayBeSecret(token),
)
)
@@ -224,6 +391,25 @@ function privacyReason(text) {
return longNumber ? 'number' : null;
}
+/**
+ * A value after "bearer" that is not a word a place's name is made of
+ * ("Bearer Island"); after "Authorization:" any value is a token.
+ */
+function bearerToken(line) {
+ if (/\bauthori[sz]ation\s*:\s*bearer\b\s*\S/i.test(line)) return true;
+ for (const match of line.matchAll(/\bbearer\b(\s*[:=#]?\s*)(\S+)/gi)) {
+ const value = match[2].replace(/(?<=[^,.;:!?)])[,.;:!?)]+$/, '');
+ // Only a word after a space may be a name: "Bearer: island" is a token.
+ if (/^\s+$/.test(match[1]) && PLACE_WORDS.test(value)) continue;
+ return true;
+ }
+ return false;
+}
+
+/** Words a place's name is made of, after a label word ("bearer island"). */
+const PLACE_WORDS =
+ /^(?:island|islands|isle|lake|creek|river|point|bay|mountain|mount|hill|hills|valley|station|road|street|lane|avenue|park|beach|falls|springs?|county|city|town|village|plaza|square|mall|center|centre|tower|building|court|bank)$/i;
+
/**
* A code after a label that can only be a code, without a colon ("PIN
* A7B2", "verification code ABCDEF", "otp 7GH2K"): holding a digit, or in
@@ -231,14 +417,59 @@ function privacyReason(text) {
* "GATE CODE LANE", "OTP Bank" and "Auth Code ABCD Street" stay places.
*/
function codeAfterLabel(line) {
+ // Labels that only ever name a code take one in lower case too ("otp
+ // abcdef", "cvv abc", "verification code abcdef"); a capitalised word
+ // after them is a name ("OTP Bank", "MFA Boston").
+ // After a label in lower case, any value is a code ("verification code
+ // Abc"); after one written as a name, only a value that is not one.
+ const coded =
+ /\b((?:otp|2fa|mfa|cvv|cvc|(?:verification|one-time|security|auth|login) code)(?:\s+is)?)\s+([a-z0-9][a-z0-9-]{2,63})(?:(?:\s*[,;]\s*|\s+[-–—]+\s+|\s+)(?:thanks|thank you|thx|ty|cheers|please|pls|ok|now)(?:\s+(?:a lot|so much|very much|again))?)?[\s.,!?]*$/i.exec(
+ line,
+ );
+ if (coded) {
+ const [, label, value] = coded;
+ const labelIsName = /\p{Lu}/u.test(label);
+ // A word a place's name is made of is no code ("security code plaza",
+ // "otp bank"); after the short labels a code in letters is written in
+ // capitals ("otp ABCDEF"), so a lower-case word is a name ("mfa
+ // boston").
+ // A CVV is never a name.
+ if (/^cv[vc]\b/i.test(label)) return true;
+ const shortLabel = /^(?:otp|2fa|mfa)\b/i.test(label);
+ const named =
+ PLACE_WORDS.test(value) || (shortLabel && /^\p{Ll}+$/u.test(value));
+ if (!labelIsName && !named) return true;
+ // After a label written as a name, a value in capitals is a code ("OTP
+ // ABCDEF", "Verification code ABC"), one capitalised a name ("OTP
+ // Bank").
+ if (labelIsName) {
+ if (/^\p{Lu}[\p{Lu}\d-]+$/u.test(value) && !PLACE_WORDS.test(value))
+ return true;
+ if (!/^\p{Lu}(?:\p{Ll}+|\p{Lu}+)$/u.test(value)) return true;
+ }
+ }
+ // A value in mixed case that is no name ("PIN aBcD", "gate code aBcD").
+ const mixed =
+ /\b(?:pin|(?:door|access|gate|alarm|entry) code)(?:\s+is)?\s+([a-z0-9-]{4,64})(?:(?:\s*[,;]\s*|\s+[-–—]+\s+|\s+)(?:thanks|thank you|thx|ty|cheers|please|pls|ok|now)(?:\s+(?:a lot|so much|very much|again))?)?[\s.,!?]*$/i.exec(
+ line,
+ );
+ if (
+ mixed &&
+ /\p{Ll}/u.test(mixed[1]) &&
+ /\p{Lu}/u.test(mixed[1]) &&
+ !/^\p{Lu}\p{Ll}+$/u.test(mixed[1])
+ )
+ return true;
const match =
- /\b((?:pin|cvv|cvc|otp|2fa|mfa|(?:door|access|gate|alarm|entry|security|verification|one-time|auth|login) code)(?:\s+is)?)\s+([a-z0-9][a-z0-9-]{3,})\s*[.!]?\s*$/i.exec(
+ /\b((?:pin|cvv|cvc|otp|2fa|mfa|(?:door|access|gate|alarm|entry|security|verification|one-time|auth|login) code)(?:\s+is)?)\s+([a-z0-9][a-z0-9-]{3,63})(?:(?:\s*[,;]\s*|\s+[-–—]+\s+|\s+)(?:thanks|thank you|thx|ty|cheers|please|pls|ok|now)(?:\s+(?:a lot|so much|very much|again))?)?[\s.,!?]*$/i.exec(
line,
);
if (!match) return false;
const [, label, value] = match;
if (/\d/.test(value)) return true;
- return value === value.toUpperCase() && label !== label.toUpperCase();
+ // A code in capitals ("PIN ABCD", "GATE CODE ABCD"), but not a word a
+ // place's name is made of ("GATE CODE LANE").
+ return value === value.toUpperCase() && !PLACE_WORDS.test(value);
}
/**
@@ -292,6 +523,43 @@ export function resetPlaceSuggestions() {
shared.pending.clear();
}
+/**
+ * Countries that write a house's number before its street ("10 Downing
+ * Street", "12 rue de Rivoli"); elsewhere it follows ("Hauptstraße 12").
+ */
+const NUMBER_FIRST = new Set([
+ 'US',
+ 'CA',
+ 'GB',
+ 'IE',
+ 'AU',
+ 'NZ',
+ 'FR',
+ 'LU',
+ 'MC',
+ 'ZA',
+ 'IN',
+ 'PH',
+ 'SG',
+ 'MY',
+ 'HK',
+ 'TH',
+ 'LK',
+ 'NG',
+ 'GH',
+ 'KE',
+ 'JM',
+ 'TT',
+]);
+
+/** A house's number and street as its country writes them, or ''. */
+export function houseAddress({ houseNumber, street, countryCode }) {
+ if (!houseNumber || !street) return '';
+ return NUMBER_FIRST.has(String(countryCode || 'US').toUpperCase())
+ ? `${houseNumber} ${street}`
+ : `${street} ${houseNumber}`;
+}
+
/** List Photon candidates while typing. The submitted search owns navigation. */
export function createPlaceSuggester({
endpoint,
@@ -308,7 +576,14 @@ export function createPlaceSuggester({
const text = String(query ?? '')
.trim()
.slice(0, MAX_QUERY_CHARS);
- if (!enabled || text.length < minPlaceChars(text) || mayBePrivate(text))
+ // A line longer than a place's name is never sent: a pasted sentence
+ // or phrase is no place, and may be private in ways not read here.
+ if (
+ !enabled ||
+ text.length < minPlaceChars(text) ||
+ text.split(/\s+/).length > suggestMaxWords(text) ||
+ mayBePrivate(text)
+ )
return [];
const language = (globalThis.document?.documentElement?.lang || 'en')
.slice(0, 2)
@@ -384,11 +659,17 @@ export function createPlaceSuggester({
type,
street,
housenumber: houseNumber,
+ locality,
+ district,
} = feature.properties ?? {};
- // A house has no name of its own: its street and number are its
- // name, so two houses on one street stay two places.
- const address =
- street && houseNumber ? `${houseNumber} ${street}` : '';
+ // A house has no name of its own: its street (or, without one, its
+ // locality) and number are its name, written in the country's own
+ // order, so two houses on one street stay two places.
+ const address = houseAddress({
+ houseNumber,
+ street: street || locality || district || city,
+ countryCode,
+ });
const name = normalized.name || address || city || state || country;
if (!name) continue;
const detail = [...new Set([city, state, country])]
diff --git a/src/search/placeSuggestions.test.mjs b/src/search/placeSuggestions.test.mjs
index 7063008116..4df112e6ae 100644
--- a/src/search/placeSuggestions.test.mjs
+++ b/src/search/placeSuggestions.test.mjs
@@ -3,8 +3,10 @@ import test from 'node:test';
import {
citiesInRegion,
createPlaceSuggester,
+ houseAddress,
inExtent,
mayBePrivate,
+ onlyNumbersLookPrivate,
resetPlaceSuggestions,
} from './placeSuggestions.js';
@@ -392,9 +394,11 @@ test('streets named for keys, tokens and codes, and ZIP+4 after a state, are pla
'Access Token Road',
'Api Key Lane',
'GATE CODE LANE',
+ 'meet at Central Park [12:30:00]',
+ '10 Main St 123456 A Block',
+ 'show every plane over london then show every ship near boston please',
'SECURITY CODE PLAZA',
'OTP Bank',
- 'MFA BOSTON',
'Auth Code ABCD Street',
'California 90210-1234',
'Austin Texas 78701-1234',
@@ -402,7 +406,10 @@ test('streets named for keys, tokens and codes, and ZIP+4 after a state, are pla
'12, 10115 Berlin',
])
assert.equal(mayBePrivate(line), false, line);
+ // All in capitals, a name cannot be told from a code: "MFA BOSTON" is
+ // kept back with "OTP ABCDEF".
for (const line of [
+ 'MFA BOSTON',
'gate code: abcd',
'PIN A7B2',
'PIN is A7B2',
@@ -427,3 +434,240 @@ test('the same text asked again while its request is out is sent once', async ()
await Promise.all([service.suggest('Paris'), service.suggest('Paris')]);
assert.equal(sent, 1);
});
+
+test('spelled-out emails, addresses, phrases, codes and short phone numbers stay private', () => {
+ for (const line of [
+ 'john(at)gmail.com',
+ 'john[at]gmail[dot]com',
+ 'john at gmail dot de',
+ '10.0.0.1',
+ 'abandon ability able about above absent absorb abstract absurd abuse access accident',
+ 'Abandon ability able about above absent absorb abstract absurd abuse access accident acid',
+ 'license ABC1234',
+ 'passport X1234567',
+ 'plate 7ABC123',
+ 'otp ABCDEF',
+ 'verification code abcdef',
+ 'cvv abc',
+ 'Bearer abcdef',
+ 'Bearer Abcdefgh',
+ 'Authorization: Bearer Xyz',
+ 'glpat-abcdef123456',
+ 'hf_abcdefghijk',
+ 'SG.abcdefghij.klmnopqrstuv',
+ 'https://x.com/?code=abcdef',
+ 'code 4821',
+ 'garage code 4821',
+ 'lockbox 4821',
+ 'the code to my door is 4821',
+ 'AB 12 34 56 C',
+ 'my id is AB12345',
+ 'ssn ending 1234',
+ 'ssn last four 1234',
+ 'SSN ends in 6789',
+ 'otp ABCDEF, thanks',
+ 'pin AbCd, thanks',
+ 'otp ABCDEF thanks!!',
+ 'verification code ABCDEF thanks a lot',
+ 'otp ABCDEF cheers',
+ 'otp ab12cd - thanks',
+ 'gate code aBcD - thanks,',
+ 'gate code aBcD – thanks',
+ '"abandon ability able about above absent absorb abstract absurd abuse access accident"',
+ '“abandon ability able about above absent absorb abstract absurd abuse access accident”',
+ '«abandon ability able about above absent absorb abstract absurd abuse access accident»',
+ '»abandon ability able about above absent absorb abstract absurd abuse access accident«',
+ 'abandon-ability-able-about-above-absent-absorb-abstract-absurd-abuse-access-accident',
+ '#1 abandon #2 ability #3 able #4 about #5 above #6 absent #7 absorb #8 abstract #9 absurd #10 abuse #11 access #12 accident',
+ '(1) abandon (2) ability (3) able (4) about (5) above (6) absent (7) absorb (8) abstract (9) absurd (10) abuse (11) access (12) accident',
+ 'gate code aBcD - thanks',
+ 'abandon ability able about above absent absorb abstract absurd abuse access accident.',
+ 'abandon, ability, able, about, above, absent, absorb, abstract, absurd, abuse, access, accident',
+ '1. abandon 2. ability 3. able 4. about 5. above 6. absent 7. absorb 8. abstract 9. absurd 10. abuse 11. access 12. accident',
+ 'my seed is abandon ability able about above absent absorb abstract absurd abuse access accident',
+ 'My ID 12345',
+ 'john at gmail .com',
+ 'john at gmail punto com',
+ 'john.doe at example period com',
+ 'j o h n @ g m a i l . c o m',
+ 'ssn is 123456',
+ 'ssn: xxx-xx-1234',
+ 'Bearer: island',
+ 'Bearer=lake',
+ 'OTP ABCDEF',
+ 'CVV ABC',
+ 'Verification code ABC',
+ 'PIN ABCD',
+ 'passport:123456',
+ 'ID:12345',
+ 'abandon please abandon abandon abandon abandon abandon abandon abandon abandon abandon abstract',
+ 'find abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon',
+ 'lockbox number 4821',
+ 'lockbox is 4821',
+ 'ab 12 34 56 c',
+ 'https://[::1]/',
+ 'my, ID 12345',
+ 'ssn 1',
+ 'cvv BANK',
+ 'PIN ABCD thanks',
+ 'OTP ABCDEF now',
+ 'AB123456C',
+ 'ssn 123',
+ 'Jo 12345-6789',
+ 'Joe 1234 12345 thanks',
+ 'Mo 0171 12345',
+ ])
+ assert.equal(mayBePrivate(line), true, line);
+ // A phone's three and four digits are not offered as an address.
+ assert.equal(onlyNumbersLookPrivate('is 555 0100 thanks'), false);
+});
+
+test('places that only looked private are looked up', () => {
+ for (const line of [
+ 'Akiak',
+ 'Bearer Island',
+ 'SSN Station',
+ 'Bearer Island, Canada',
+ 'bearer island',
+ 'Washington DC 20500-0003',
+ '東京都千代田区100-0001',
+ 'Security Code Plaza',
+ 'Idaho Falls',
+ 'meet at 12:30:45',
+ 'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch',
+ 'llanfairpwllgwyngyll',
+ 'Boise ID 83702',
+ 'Boise, ID 83702',
+ 'Hayden ID 83835-1234',
+ 'mfa boston',
+ 'otp bank',
+ 'security code plaza',
+ 'zip code 90210',
+ 'area code 415',
+ 'Settipalle @ K.Bandarlapalle',
+ 'boise ID 83702',
+ "Coeur d'Alene ID 83814",
+ 'meet at West Point tomorrow',
+ 'OTP Bank',
+ 'GATE CODE LANE',
+ // Lists of places, though every word is on the BIP39 list.
+ 'coffee, bar, hotel, museum, park, beach, hospital, school, market, bridge, tower, airport',
+ '1. beach 2. park 3. museum 4. zoo 5. bridge 6. tower 7. market 8. castle 9. island 10. lake 11. river 12. canyon',
+ 'show only bus, train, car, truck, ship, boat traffic over city bridge today',
+ 'museum, gallery, library, palace, square, alley, canal, garden, hill, cave, farm, field',
+ 'find any good cheap fresh food open now near this area today',
+ // Questions for the assistant, however many short words they have.
+ 'can you tell where the most flights are going over texas today',
+ 'are there any storms near florida right now that might cause delays',
+ 'OTP Bank',
+ // A long request is not a recovery phrase.
+ 'show flights over texas near austin with altitude above thirty thousand feet please',
+ 'show fires near austin then show flights above texas with labels please',
+ ])
+ assert.equal(mayBePrivate(line), false, line);
+});
+
+test('a house is named by its number and street in the order its country writes them', async () => {
+ assert.equal(
+ houseAddress({
+ houseNumber: '10',
+ street: 'Downing Street',
+ countryCode: 'gb',
+ }),
+ '10 Downing Street',
+ );
+ assert.equal(
+ houseAddress({
+ houseNumber: '12',
+ street: 'Hauptstraße',
+ countryCode: 'DE',
+ }),
+ 'Hauptstraße 12',
+ );
+ assert.equal(houseAddress({ houseNumber: '12', street: '' }), '');
+ // Without a street, a house's number and its locality name it, so two
+ // houses in one hamlet stay two places, not the city twice.
+ const house = (number) => ({
+ geometry: { type: 'Point', coordinates: [11.2, 47.6] },
+ properties: {
+ housenumber: number,
+ locality: 'Mittenwald Au',
+ city: 'Mittenwald',
+ country: 'Germany',
+ countrycode: 'de',
+ osm_value: 'house',
+ },
+ });
+ const service = createPlaceSuggester({
+ endpoint: 'https://fixture.test/api/',
+ fetchImpl: async () =>
+ Response.json({ features: [house('3'), house('5')] }),
+ });
+ assert.deepEqual(
+ (await service.suggest('Mittenwald Au')).map((place) => place.name),
+ ['Mittenwald Au 3', 'Mittenwald Au 5'],
+ );
+});
+
+test('codes, phones, tokens, emails and addresses in further shapes stay private', () => {
+ for (const line of [
+ // A phone's three and four digits after a name, as a postcode can't be
+ // told from it ("Shibuya 150-0002" is refused for that).
+ 'Alice 555-0100',
+ 'Shibuya 150-0002',
+ `${Array(23).fill('abandon').join(' ')} art`,
+ 'Bearer Abcdefghijklmnopqrstuvwxyz',
+ 'Bearer Island bearer abcdef',
+ 'verification code Abc',
+ 'verification code ABC',
+ 'verification code abc thanks',
+ 'PIN aBcD',
+ 'gate code aBcD',
+ 'john at gmail.com',
+ 'john at gmail (dot) com',
+ 'john at gmail [dot] com',
+ 'john at gmail dot technology',
+ 'passport number 123456',
+ 'passport no. 123456',
+ 'ID AB123',
+ '::1',
+ 'fe80::1',
+ '2001:db8:0:0:0:0:2:1',
+ ])
+ assert.equal(mayBePrivate(line), true, line);
+});
+
+test('a line longer than a place name is never sent for suggestions', async () => {
+ let sent = 0;
+ const service = createPlaceSuggester({
+ endpoint: 'https://fixture.test/api/',
+ fetchImpl: async () => {
+ sent++;
+ return Response.json({ features: [] });
+ },
+ });
+ assert.deepEqual(
+ await service.suggest('one two three four five six seven eight nine'),
+ [],
+ );
+ assert.equal(sent, 0);
+ // An address has more words: as many as the Omnibar reads as a place.
+ await service.suggest('350 Fifth Avenue, New York, NY 10118, United States');
+ assert.equal(sent, 1);
+ await service.suggest('1 2 3 4 5 6 7 8 9 10 11');
+ assert.equal(sent, 1);
+});
+
+test('a long line is read quickly', () => {
+ for (const line of [
+ ...['a-', 'a.', '1-', 'a ', '//[a:'].map((unit) => unit.repeat(10000)),
+ `otp a${'-'.repeat(20000)}!x`,
+ `gate code a${'-'.repeat(20000)}!x`,
+ `${','.repeat(20000)}!x`,
+ `bearer x${','.repeat(20000)}z`,
+ ]) {
+ const started = performance.now();
+ mayBePrivate(line);
+ assert.ok(performance.now() - started < 1000, line.slice(0, 12));
+ }
+});
diff --git a/src/share/legacyShareState.js b/src/share/legacyShareState.js
index e941faeee8..98fae4a75f 100644
--- a/src/share/legacyShareState.js
+++ b/src/share/legacyShareState.js
@@ -34,6 +34,7 @@ export const LEGACY_SHARE_STATE_KEYS = Object.freeze([
'bloomVersion',
'sharpenIntensity',
'hudVariant',
+ 'hudSonar',
'hudVisible',
'detectionMode',
'detectionDensity',
diff --git a/src/share/legacyShareState.test.mjs b/src/share/legacyShareState.test.mjs
index 7f3bac84ab..a511ca1f7d 100644
--- a/src/share/legacyShareState.test.mjs
+++ b/src/share/legacyShareState.test.mjs
@@ -146,6 +146,23 @@ test('links from earlier long-form versions keep their historical meaning', () =
assert.equal(off.layerState.options.flights.models3d, false);
});
+test('Sonar beside the Minimal layout survives the compact form; older links do not name it', () => {
+ const { parsed, state } = assertLegacyRoundTrip(
+ 'v=2&lat=10&lon=20&hud=minimal&hs=1',
+ );
+ assert.equal(parsed.hudSonar, true);
+ assert.equal(state.hudVariant, 'minimal');
+ assert.equal(state.hudSonar, true);
+ // Links made before `hs`: Minimal carries no Sonar, Cyber carries it in
+ // its own code.
+ for (const hud of ['minimal', 'cyber']) {
+ const old = assertLegacyRoundTrip(`v=2&lat=10&lon=20&hud=${hud}`);
+ assert.equal(old.parsed.hudSonar, false);
+ assert.equal(old.state.hudVariant, hud);
+ assert.equal(old.state.hudSonar, false);
+ }
+});
+
test('a tracking selection becomes a thing view and back', () => {
const flights = assertLegacyRoundTrip('v=2&lat=1&lon=2&l=f&lo=f.t.a1b2c3');
assert.deepEqual(flights.state.view.entity, {
@@ -232,6 +249,7 @@ function generatedLegacyHash(random) {
bloomVersion: pick(random, [1, 2]),
sharpenIntensity: int(0, 100),
hudVariant: pick(random, HUD_LAYOUTS),
+ hudSonar: random() < 0.5,
hudVisible: random() < 0.5,
detectionMode: pick(random, ['OFF', 'SPARSE', 'BALANCED', 'DENSE']),
detectionDensity: density,
diff --git a/src/share/viewCodec.js b/src/share/viewCodec.js
index 518156fb67..9a5015964d 100644
--- a/src/share/viewCodec.js
+++ b/src/share/viewCodec.js
@@ -255,6 +255,9 @@ export const SHARE_VIEW_FLAGS = freezeAll([
{ bit: 2, key: 'hudVisible', default: BY_STYLE },
{ bit: 3, key: 'celestialRing', default: BY_STYLE },
{ bit: 4, key: 'scopeEnabled', default: true },
+ // Sonar on beside a HUD layout whose code cannot say so (Minimal). Tactical
+ // with Sonar stays the `cyber` layout code alone.
+ { bit: 5, key: 'hudSonar', default: false },
]);
/**
diff --git a/src/share/viewCodec.test.mjs b/src/share/viewCodec.test.mjs
index aafa5083b2..1a2c87e0c0 100644
--- a/src/share/viewCodec.test.mjs
+++ b/src/share/viewCodec.test.mjs
@@ -348,6 +348,7 @@ test('every registered field round-trips at once', () => {
bloomVersion: 1,
sharpenIntensity: 65,
hudVariant: 'operator',
+ hudSonar: true,
hudVisible: false,
detectionMode: 'SPARSE',
detectionDensity: 100,
@@ -449,6 +450,28 @@ test('links made with a retired HUD layout still decode to its name', () => {
}
});
+test('Sonar beside the Minimal layout is flag bit 5; links made before it keep their meaning', () => {
+ const minimal = { ...createDefaultShareViewState(), hudVariant: 'minimal' };
+ const plain = encodeShareView(minimal);
+ // Off is the default, so a view without Sonar costs nothing for it.
+ assert.equal(encodeShareView({ ...minimal, hudSonar: false }), plain);
+ const withSonar = assertRoundTrip({ ...minimal, hudSonar: true });
+ assert.notEqual(withSonar, plain);
+ const decoded = decodeOk(withSonar).state;
+ assert.equal(decoded.hudVariant, 'minimal');
+ assert.equal(decoded.hudSonar, true);
+ assert.equal(decodeOk(plain).state.hudSonar, false);
+ // Tactical with Sonar is still the Cyber code alone.
+ const cyber = { ...createDefaultShareViewState(), hudVariant: 'cyber' };
+ assert.equal(decodeOk(encodeShareView(cyber)).state.hudSonar, false);
+ // A link made before the bit (thermal, Cyber, Scope off) decodes as it did:
+ // Cyber without the bit, which the app opens as Tactical with Sonar on.
+ const before = decodeOk('ARD-7j4YuxMguBcoUEgQcAOAAQPIASPQAWGa').state;
+ assert.equal(before.hudVariant, 'cyber');
+ assert.equal(before.hudSonar, false);
+ assert.equal(encodeShareView(before), 'ARD-7j4YuxMguBcoUEgQcAOAAQPIASPQAWGa');
+});
+
test('defaults travel as frozen meanings that match today’s app defaults', () => {
const defaults = createDefaultShareViewState();
// When an app default moves, these tests should be updated to document the
@@ -535,6 +558,7 @@ test('the field registry is well formed and permanent', () => {
[2, 'hudVisible', BY_STYLE],
[3, 'celestialRing', BY_STYLE],
[4, 'scopeEnabled', true],
+ [5, 'hudSonar', false],
],
);
// The style-applied defaults are frozen meanings too. If the app's style
@@ -921,7 +945,7 @@ test('unknown fields inside a thing view, codes and bits are skipped too', () =>
thing.textField(20, 'cockpit'); // a future thing field
const writer = new WireWriter();
writer.bytes.push(1);
- writer.sintField(2, 100000).uintField(9, 0b100001); // flag bit 5 unknown
+ writer.sintField(2, 100000).uintField(9, 0b1000001); // flag bit 6 unknown
writer.bytesField(
10,
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
@@ -944,7 +968,7 @@ test('unknown fields inside a thing view, codes and bits are skipped too', () =>
result.unknownFields.map((u) => [u.scope, u.field ?? u.code]),
[
['enum:style', 99],
- ['flags', 32],
+ ['flags', 64],
['layer', 160],
['panel', 12],
['thing', 20],
diff --git a/src/sharelink.celestial.test.mjs b/src/sharelink.celestial.test.mjs
index 6e2cd935c0..aa679c105e 100644
--- a/src/sharelink.celestial.test.mjs
+++ b/src/sharelink.celestial.test.mjs
@@ -158,6 +158,37 @@ test('share-link serialization emits the current celestial state', () => {
assert.equal(new URLSearchParams(window.location.hash.slice(1)).get('cr'), '1');
});
+test('Sonar beside the HUD layout rides as hs only when on, and through the compact link', async () => {
+ // Links made before `hs` name no Sonar.
+ assert.equal(makeManager('#v=2&lat=10&lon=20&hud=minimal').parseInitialHash().hudSonar, false);
+ assert.equal(makeManager('#v=2&lat=10&lon=20&hud=minimal&hs=1').parseInitialHash().hudSonar, true);
+
+ const manager = makeManager();
+ manager.onToggleChange(false, false, { hudVariant: 'minimal', hudSonar: false });
+ assert.equal(manager._buildHashParams().has('hs'), false, 'off writes nothing');
+ assert.equal(sharedState(manager.buildLink()).hudSonar, false);
+ manager.onToggleChange(false, false, { hudVariant: 'minimal', hudSonar: true });
+ assert.equal(manager._buildHashParams().get('hs'), '1');
+ const shared = sharedState(manager.buildLink());
+ assert.equal(shared.hudVariant, 'minimal');
+ assert.equal(shared.hudSonar, true);
+ // Tactical with Sonar is written as the Cyber layout code alone.
+ manager.onToggleChange(false, false, { hudVariant: 'cyber', hudSonar: false });
+ assert.equal(manager._buildHashParams().get('hud'), 'cyber');
+ assert.equal(manager._buildHashParams().has('hs'), false);
+ assert.equal(sharedState(manager.buildLink()).hudVariant, 'cyber');
+ clearTimeout(manager._debounceTimer);
+
+ // The restore hands it to the visual settings beside the layout.
+ const opened = makeManager('#v=2&lat=40&lon=-74&hud=minimal&hs=1');
+ let restored = null;
+ opened._onRestore = (state) => { restored = state; };
+ opened._isNavigationCurrent = () => false;
+ await opened.applyState(opened.parseInitialHash(), { navigationToken: 1 });
+ assert.equal(restored.hudVariant, 'minimal');
+ assert.equal(restored.hudSonar, true);
+});
+
test('generated links are v2 and include deterministic layers, options, style params, and panels', () => {
const manager = makeManager();
const layers = createDefaultLayerState();
diff --git a/src/sharelink.js b/src/sharelink.js
index 063a2792b2..1ddfeeb326 100644
--- a/src/sharelink.js
+++ b/src/sharelink.js
@@ -94,6 +94,8 @@ export class ShareLinkManager {
this._bloomVersion = BLOOM_SCALE_VERSION;
this._sharpenIntensity = 49;
this._hudVariant = 'tactical';
+ // Sonar on beside a layout whose code cannot say so (Minimal); `hs`.
+ this._hudSonar = false;
this._hudVisible = false;
this._detectionMode = 'OFF';
this._detectionDensity = 50;
@@ -260,6 +262,9 @@ export class ShareLinkManager {
bloomVersion: parseOr(params.get('bv'), 1),
sharpenIntensity: parseOr(params.get('si'), 49),
hudVariant: params.get('hud') || 'tactical',
+ // Absent in links made before it, which restore Sonar from `hud=cyber`
+ // alone.
+ hudSonar: params.get('hs') === '1',
hudVisible: params.get('hv') === '1',
detectionMode: restoredDetection.enabled
? restoredDetection.profile
@@ -477,6 +482,7 @@ export class ShareLinkManager {
bloomVersion: visualCurrent ? state.bloomVersion : undefined,
sharpenIntensity: visualCurrent ? state.sharpenIntensity : undefined,
hudVariant: visualCurrent ? state.hudVariant : undefined,
+ hudSonar: visualCurrent ? state.hudSonar : undefined,
hudVisible: visualCurrent ? state.hudVisible : undefined,
detectionMode: visualCurrent ? state.detectionMode : undefined,
detectionDensity: visualCurrent ? state.detectionDensity : undefined,
@@ -627,6 +633,7 @@ export class ShareLinkManager {
this._sharpenIntensity = extras.sharpenIntensity;
if (typeof extras.hudVariant === 'string')
this._hudVariant = extras.hudVariant;
+ if (typeof extras.hudSonar === 'boolean') this._hudSonar = extras.hudSonar;
if (typeof extras.hudVisible === 'boolean')
this._hudVisible = extras.hudVisible;
if (typeof extras.detectionMode === 'string')
@@ -786,6 +793,8 @@ export class ShareLinkManager {
params.set('bv', Math.round(this._bloomVersion).toString());
params.set('si', Math.round(this._sharpenIntensity).toString());
params.set('hud', this._hudVariant);
+ // Only written when on, so a link without Sonar keeps its old form.
+ if (this._hudSonar) params.set('hs', '1');
params.set('hv', this._hudVisible ? '1' : '0');
params.set('dm', this._detectionMode);
params.set('dd', Math.round(this._detectionDensity).toString());
diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js
index f563a827df..59f4599d6b 100644
--- a/src/ui/applicationShell.js
+++ b/src/ui/applicationShell.js
@@ -219,7 +219,6 @@ export class StyleManager extends ShellFacade {
pinia: applicationPinia(),
pickWorld: services.pickWorldFromScreen,
regionalBrief: services.fetchRegionalBrief,
- overlayHit: services.hitTestWorldOverlay,
});
this.mapStackController = mapStackController;
this.placeSearch = placeSearch;
diff --git a/src/ui/cockpitOrbitalFocus.js b/src/ui/cockpitOrbitalFocus.js
index 5b97c34838..a7790ab102 100644
--- a/src/ui/cockpitOrbitalFocus.js
+++ b/src/ui/cockpitOrbitalFocus.js
@@ -10,6 +10,7 @@
*/
import { fromDegrees } from '../geo/ellipsoid.js';
import { inputFor } from '../input/dispatcher.js';
+import { isUnderOtherCard } from '../data/pickRegistry.js';
import { findQuery } from '../render/rendererOf.js';
import { clampOrbitalLook, easeLook } from '../cockpitLook.js';
import { ORBITAL_EARTH_RADIUS_M } from '../cockpitOrbital.js';
@@ -286,7 +287,12 @@ export function routeSceneClick() {
// A viewer with no input (headless tools, partial stubs) has no clicks.
return () => {};
}
- return input.onClick((event) => this.onOrbitalClick(event?.position));
+ return input.onClick((event) => {
+ // Another layer's card or label painted on top takes the click: the site
+ // under it does not focus, and the click does not end a held focus.
+ if (isUnderOtherCard(event)) return;
+ this.onOrbitalClick(event?.position);
+ });
}
/**
diff --git a/src/ui/cockpitOrbitalFocus.test.mjs b/src/ui/cockpitOrbitalFocus.test.mjs
index 836d6e8d99..0677ec1f98 100644
--- a/src/ui/cockpitOrbitalFocus.test.mjs
+++ b/src/ui/cockpitOrbitalFocus.test.mjs
@@ -31,6 +31,7 @@ import CockpitView from './views/CockpitView.vue';
import ContextView from './views/ContextView.vue';
import IntelHudView from './views/IntelHudView.vue';
import { claimPointer, releasePointer } from '../data/inputOwnership.js';
+import { setClickCardHitTest } from '../data/pickRegistry.js';
import { ORBITAL_FOCUS_EASE_TAU_MS } from '../cockpitOrbitalFocus.js';
import { ORBITAL_HOP_MS } from '../cockpitOrbitalSatellites.js';
@@ -648,6 +649,23 @@ test('a click a tool owns is left alone', async (t) => {
assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'kept while drawing');
});
+// The card or label painted on top takes the click: a site under another
+// layer's card does not focus, and a click there does not end a held focus.
+test('another layer\'s card over the orbital view keeps the click', async (t) => {
+ const scene = await inOrbit(t);
+ let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ setClickCardHitTest(() => top);
+ t.after(() => setClickCardHitTest(null));
+ scene.click(SITES.alpha.at);
+ assert.equal(scene.cockpit.orbital.focus ?? null, null, 'covered: no focus');
+ top = null;
+ scene.click(SITES.alpha.at);
+ assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id);
+ top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
+ scene.click(EMPTY_GROUND);
+ assert.equal(scene.cockpit.orbital.focus.key, SITES.alpha.id, 'covered: kept');
+});
+
test('a double-click on a site focuses it and keeps the orbital view', async (t) => {
const scene = await inOrbit(t);
const { cockpit, viewer, handler } = scene;
diff --git a/src/ui/creditLineHeight.js b/src/ui/creditLineHeight.js
new file mode 100644
index 0000000000..700f6c8789
--- /dev/null
+++ b/src/ui/creditLineHeight.js
@@ -0,0 +1,41 @@
+/**
+ * @module ui/creditLineHeight
+ * @description Keeps `--credit-line-height` on the page's root at the
+ * height of the attribution line at the bottom of the screen, so what sits
+ * above it (the HUD's bottom corners) clears it when it wraps onto more
+ * lines. The line is the application's own (`#gev-credits`) or the one a
+ * renderer draws inside `#cesium-credits`.
+ */
+
+const LINES = ['#gev-credits', '#cesium-credits .cesium-widget-credits'];
+
+/**
+ * Follow the attribution line's height in `--credit-line-height`.
+ * @param {Document} [doc]
+ * @returns {() => void} Stops following it and clears the property.
+ */
+export function trackCreditLineHeight(doc = globalThis.document) {
+ const Observer = doc?.defaultView?.ResizeObserver;
+ if (!doc?.documentElement || typeof Observer !== 'function') return () => {};
+ const root = doc.documentElement;
+ const lines = LINES.map((selector) => doc.querySelector(selector)).filter(
+ Boolean,
+ );
+ if (!lines.length) return () => {};
+ const update = () => {
+ const height = Math.max(
+ 0,
+ ...lines.map((line) => line.getBoundingClientRect().height),
+ );
+ if (height > 0)
+ root.style.setProperty('--credit-line-height', `${Math.ceil(height)}px`);
+ else root.style.removeProperty('--credit-line-height');
+ };
+ const observer = new Observer(update);
+ for (const line of lines) observer.observe(line);
+ update();
+ return () => {
+ observer.disconnect();
+ root.style.removeProperty('--credit-line-height');
+ };
+}
diff --git a/src/ui/creditLineHeight.test.mjs b/src/ui/creditLineHeight.test.mjs
new file mode 100644
index 0000000000..6b3def9ba8
--- /dev/null
+++ b/src/ui/creditLineHeight.test.mjs
@@ -0,0 +1,79 @@
+import '../testSupport/registerDom.mjs';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { trackCreditLineHeight } from './creditLineHeight.js';
+
+/** A ResizeObserver the test drives, with each line's height set by hand. */
+function fakeResizing() {
+ const observers = [];
+ const window = document.defaultView;
+ const original = window.ResizeObserver;
+ window.ResizeObserver = class {
+ constructor(callback) {
+ this.callback = callback;
+ this.targets = new Set();
+ observers.push(this);
+ }
+ observe(target) {
+ this.targets.add(target);
+ }
+ disconnect() {
+ this.targets.clear();
+ }
+ };
+ return {
+ resize(element, height) {
+ element.getBoundingClientRect = () => ({ height });
+ for (const observer of observers)
+ if (observer.targets.has(element)) observer.callback([]);
+ },
+ restore() {
+ window.ResizeObserver = original;
+ },
+ };
+}
+
+test("the credit line's height follows it as it wraps, for either renderer's line", () => {
+ const resizing = fakeResizing();
+ try {
+ for (const markup of [
+ '
',
+ '',
+ ]) {
+ document.body.innerHTML = markup;
+ const line = document.querySelector(
+ '#gev-credits, #cesium-credits .cesium-widget-credits',
+ );
+ line.getBoundingClientRect = () => ({ height: 28 });
+ const stop = trackCreditLineHeight(document);
+ const root = document.documentElement.style;
+ assert.equal(root.getPropertyValue('--credit-line-height'), '28px');
+ resizing.resize(line, 66.4);
+ assert.equal(root.getPropertyValue('--credit-line-height'), '67px');
+ // Hidden, it holds no room.
+ resizing.resize(line, 0);
+ assert.equal(root.getPropertyValue('--credit-line-height'), '');
+ resizing.resize(line, 28);
+ stop();
+ assert.equal(root.getPropertyValue('--credit-line-height'), '');
+ }
+ } finally {
+ resizing.restore();
+ document.body.replaceChildren();
+ }
+});
+
+test('without a credit line nothing is followed', () => {
+ const resizing = fakeResizing();
+ try {
+ document.body.replaceChildren();
+ const stop = trackCreditLineHeight(document);
+ assert.equal(
+ document.documentElement.style.getPropertyValue('--credit-line-height'),
+ '',
+ );
+ stop();
+ } finally {
+ resizing.restore();
+ }
+});
diff --git a/src/ui/entityContextBridge.js b/src/ui/entityContextBridge.js
index 927532f496..d431d25225 100644
--- a/src/ui/entityContextBridge.js
+++ b/src/ui/entityContextBridge.js
@@ -1,4 +1,5 @@
import { resolvePickedContext } from '../data/pickedContext.js';
+import { clickCard } from '../data/pickRegistry.js';
import { followedOf, onFollowChanged } from '../data/followed.js';
import { fromDegreesInto } from '../geo/ellipsoid.js';
import { inputFor } from '../input/dispatcher.js';
@@ -45,8 +46,6 @@ const FOLLOWABLE = new Set(['flights', 'military', 'satellites']);
* to the point under the camera without it.
* @param {(lat: number, lon: number) => Promise} [options.regionalBrief]
* The app's regional brief service, for the weather and news Context shows.
- * @param {(x: number, y: number) => object|null} [options.overlayHit]
- * The overlay card under a screen point, if any (a vessel's, a fire's).
* @returns {() => void} disconnects
*/
export function installEntityContext({
@@ -55,7 +54,6 @@ export function installEntityContext({
pinia,
pickWorld,
regionalBrief,
- overlayHit,
}) {
const store = useEntityCardStore(pinia);
const omnibar = useOmnibarStore(pinia);
@@ -318,6 +316,10 @@ export function installEntityContext({
// Cockpit has its own picks, and Context is hidden while it runs. A
// camera drag never selects, even if it ends over something.
if (inCockpit() || !isTrackingSelectionGesture(event.gesture)) return;
+ // A card or label painted on top is its layer's click, read once per
+ // click so every layer agrees: Context names nothing under it and keeps
+ // its own card as it is.
+ if (clickCard(event)) return;
const identity = resolvePickedContext(event.hit, {
dataManager: getDataManager(),
});
@@ -331,14 +333,8 @@ export function installEntityContext({
// A click on open ground, sea or sky lets go of what was selected. A
// click on something else Context cannot describe (a label, a trail)
// leaves the card as it is.
- // Only a clean click lets go, as the layers' own clicks do; a card
- // painted on the overlay (a vessel's, a fire's) is not open map.
- if (
- event.surface &&
- isTrackingClickGesture(event.gesture) &&
- !overlayHit?.(event.screenPosition?.x, event.screenPosition?.y)
- )
- store.clear();
+ // Only a clean click lets go, as the layers' own clicks do.
+ if (event.surface && isTrackingClickGesture(event.gesture)) store.clear();
});
// Layers that select through the context store (GeoJSON sites, fires,
diff --git a/src/ui/entityContextBridge.test.mjs b/src/ui/entityContextBridge.test.mjs
new file mode 100644
index 0000000000..025b23df57
--- /dev/null
+++ b/src/ui/entityContextBridge.test.mjs
@@ -0,0 +1,85 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createPinia } from 'pinia';
+import { installEntityContext } from './entityContextBridge.js';
+import { useEntityCardStore } from './stores/entityCard.js';
+import { fakeInput } from '../input/testDoubles.mjs';
+import {
+ registerPickOwner,
+ setClickCardHitTest,
+ unregisterPickOwner,
+} from '../data/pickRegistry.js';
+
+// The card or label painted on top takes the click: Context names nothing
+// under it, exact or nearby, an acting owner's item or a passive one, and
+// keeps its own card. On open map it names what the click found.
+test('Context names nothing under a card painted on top, and keeps its card', (t) => {
+ const previous = globalThis.matchMedia;
+ globalThis.matchMedia = () => ({ matches: true });
+ t.after(() => {
+ if (previous) globalThis.matchMedia = previous;
+ else delete globalThis.matchMedia;
+ });
+ const fire = { set: 'test-fires:1', id: 'fire:1' };
+ const plane = { set: 'test-planes:1', id: 'plane:1' };
+ const route = { set: 'test-route:1', id: 'route:line' };
+ registerPickOwner('test-fires', (id) => id === fire.id);
+ registerPickOwner('test-planes', (id) => id === plane.id);
+ registerPickOwner('test-route', (id) => id.startsWith('route:'));
+ let cardOnTop = false;
+ // The card on top at a click, as the host answers the pick registry.
+ setClickCardHitTest(() =>
+ cardOnTop ? { sourceId: 'earthquake-card', entryId: 'q' } : null,
+ );
+ t.after(() => {
+ setClickCardHitTest(null);
+ unregisterPickOwner('test-fires');
+ unregisterPickOwner('test-planes');
+ unregisterPickOwner('test-route');
+ });
+ let exact = null;
+ let near = null;
+ const viewer = {
+ scene: {
+ pick: () => (exact ? { id: exact } : null),
+ drillPick: () => (near ? [{ id: near }] : []),
+ },
+ };
+ const input = fakeInput(viewer);
+ const pinia = createPinia();
+ const disconnect = installEntityContext({
+ viewer,
+ getDataManager: () => ({
+ isEnabled: () => true,
+ layers: new Map(),
+ getAll: () => [],
+ }),
+ pinia,
+ });
+ t.after(() => {
+ disconnect();
+ input.destroy();
+ });
+ const store = useEntityCardStore(pinia);
+ const named = [];
+ let clears = 0;
+ store.select = (identity) => named.push(identity.id);
+ store.clear = () => clears++;
+ const tap = (hitExact, hitNear) => {
+ exact = hitExact;
+ near = hitNear;
+ named.length = 0;
+ input.click();
+ return [...named];
+ };
+ assert.deepEqual(tap(null, fire), ['fire:1'], 'open map: a near fire');
+ assert.deepEqual(tap(route, null), ['route:line'], 'open map: a route');
+ cardOnTop = true;
+ assert.deepEqual(tap(null, fire), [], 'under a card: a near fire');
+ assert.deepEqual(tap(fire, fire), [], 'under a card: an exact fire');
+ assert.deepEqual(tap(plane, plane), [], 'under a card: an aircraft');
+ assert.deepEqual(tap(route, null), [], 'under a card: a route');
+ const cleared = clears;
+ tap(null, null);
+ assert.equal(clears, cleared, 'a card over open map is not open map');
+});
diff --git a/src/ui/hudSonarStyle.test.mjs b/src/ui/hudSonarStyle.test.mjs
index 75c7aaa6f9..0892e07480 100644
--- a/src/ui/hudSonarStyle.test.mjs
+++ b/src/ui/hudSonarStyle.test.mjs
@@ -28,6 +28,13 @@ import { setCyberSonarControls } from './cyberSonarControls.js';
import { createPinia } from 'pinia';
import { useDisplayStore } from './stores/display.js';
import { VisualSettings } from './visualSettings.js';
+import { normalizeShot } from '../scenes/project.js';
+import {
+ SCENE_DOCUMENT_VERSION,
+ validateSceneDocument,
+} from '../director/document.js';
+import { decodeShareView, encodeShareView } from '../share/viewCodec.js';
+import { toLegacyShareState } from '../share/legacyShareState.js';
import { STYLES } from './visualPresets.js';
const read = (relative) =>
@@ -140,9 +147,10 @@ test('a share link, scene or saved view naming Cyber opens Tactical with Sonar o
assert.equal(isCyberSonarEnabled(root), true);
});
-test('links and scene shots record Tactical with Sonar as the Cyber code, and only that', (t) => {
- const { owner, root } = styleOwner(t, 'tactical');
- Object.assign(owner.services, {
+/** A styleOwner that can also read its share state and scene shot. */
+function sharingOwner(t, initialVariant) {
+ const fixture = styleOwner(t, initialVariant);
+ Object.assign(fixture.owner.services, {
getDetectionTuning: () => ({ allocationStrategy: 'ELASTIC' }),
getDetectionMode: () => 'OFF',
isScopeMaskEnabled: () => true,
@@ -150,18 +158,94 @@ test('links and scene shots record Tactical with Sonar as the Cyber code, and on
getScopeMaskOpacity: () => 1,
getScopeTerminusOverride: () => null,
});
- owner.readCelestialRing = () => null;
- const shared = () => owner._readShareState().options.hudVariant;
- assert.equal(shared(), 'tactical');
+ fixture.owner.readCelestialRing = () => null;
+ return fixture;
+}
+
+test('links and scene shots record Tactical with Sonar as the Cyber code, and only that', (t) => {
+ const { owner, root } = sharingOwner(t, 'tactical');
+ const shared = () => {
+ const { hudVariant, hudSonar } = owner._readShareState().options;
+ return [hudVariant, hudSonar];
+ };
+ const shot = () => owner.getVisualState().hud;
+ assert.deepEqual(shared(), ['tactical', false]);
+ assert.deepEqual(shot(), { visible: true, variant: 'tactical' });
owner._setCyberSonarEnabled(true);
- assert.equal(shared(), 'cyber');
- // Minimal has no code that carries Sonar; it stays local.
+ // Tactical with Sonar is the Cyber code alone, as older readers expect.
+ assert.deepEqual(shared(), ['cyber', false]);
+ assert.deepEqual(shot(), { visible: true, variant: 'cyber' });
+ // Minimal has no such code, so Sonar is carried beside it.
owner._setHudVariant('minimal');
- assert.equal(shared(), 'minimal');
- owner._setHudVariant('tactical');
- assert.equal(shared(), 'cyber');
+ assert.deepEqual(shared(), ['minimal', true]);
+ assert.deepEqual(shot(), { visible: true, variant: 'minimal', sonar: true });
owner._setCyberSonarEnabled(false);
- assert.equal(shared(), 'tactical');
+ assert.deepEqual(shared(), ['minimal', false]);
+ assert.deepEqual(shot(), { visible: true, variant: 'minimal' });
+ owner._setHudVariant('tactical');
+ assert.deepEqual(shared(), ['tactical', false]);
+ assert.equal(isCyberSonarEnabled(root), false);
+});
+
+test('Minimal with Sonar round-trips through a compact link and a scene shot', async (t) => {
+ const { owner, hud, root } = sharingOwner(t, 'minimal');
+ owner._setCyberSonarEnabled(true);
+ const options = owner._readShareState().options;
+ const shot = normalizeShot(
+ JSON.parse(JSON.stringify({ visual: owner.getVisualState() })),
+ );
+ validateSceneDocument({
+ version: SCENE_DOCUMENT_VERSION,
+ scenes: [{ id: 'scene', title: 'Scene', shots: [shot] }],
+ });
+ const code = encodeShareView({
+ hudVariant: options.hudVariant,
+ hudSonar: options.hudSonar,
+ });
+ const link = decodeShareView(code, { nowMs: Date.now() }).state;
+
+ // The viewer is elsewhere: Tactical, Sonar off.
+ owner._setHudVariant('tactical');
+ owner._setCyberSonarEnabled(false);
+ // The HUD fields of the parsed link (the fixture drives no detection).
+ const { hudVariant, hudSonar } = toLegacyShareState(link);
+ assert.deepEqual([hudVariant, hudSonar], ['minimal', true]);
+ await owner.restoreShareState({ hudVariant, hudSonar });
+ assert.equal(hud.getVariant(), 'minimal');
+ assert.equal(isCyberSonarEnabled(root), true);
+
+ owner._setHudVariant('tactical');
+ owner._setCyberSonarEnabled(false);
+ // The saved shot's HUD, as the editor normalized and validated it.
+ assert.deepEqual(shot.visual.hud, {
+ visible: true,
+ variant: 'minimal',
+ sonar: true,
+ });
+ await owner.applyVisualState({ hud: shot.visual.hud });
+ assert.equal(hud.getVariant(), 'minimal');
+ assert.equal(isCyberSonarEnabled(root), true);
+});
+
+test('a link or scene shot that does not mention Sonar restores as before', async (t) => {
+ const { owner, hud, root } = sharingOwner(t, 'minimal');
+ // Made before Sonar was carried: Minimal turns the viewer's Sonar off...
+ setCyberSonarEnabled(true, root);
+ await owner.restoreShareState({ hudVariant: 'minimal' });
+ assert.equal(isCyberSonarEnabled(root), false);
+ setCyberSonarEnabled(true, root);
+ await owner.applyVisualState({ hud: { variant: 'minimal' } });
+ assert.equal(isCyberSonarEnabled(root), false);
+ // ...and Cyber still opens Tactical with Sonar on.
+ await owner.restoreShareState({ hudVariant: 'cyber', hudSonar: false });
+ assert.equal(hud.getVariant(), 'tactical');
+ assert.equal(isCyberSonarEnabled(root), true);
+ owner._setCyberSonarEnabled(false);
+ await owner.applyVisualState({ hud: { variant: 'cyber' } });
+ assert.equal(isCyberSonarEnabled(root), true);
+ // Sonar beside a layout counts only in a restore, not a layout choice.
+ owner._setCyberSonarEnabled(false);
+ owner._setHudVariant('minimal', { sonar: true });
assert.equal(isCyberSonarEnabled(root), false);
});
@@ -458,8 +542,14 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted,
const anchor = trays.match(
/#cesium-credits \{\s*right: auto;\s*bottom: ([\d.]+)rem;\s*left: 1\.5rem;/,
);
+ // From 1200px, and in the Omnibar layout at every width: a long line
+ // wraps rather than running under the corner row.
const box = trayWide.match(
- /\n #cesium-credits \.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - ([\d.]+)rem\);\s*white-space: normal;/,
+ /\n\s*#cesium-credits \.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - ([\d.]+)rem\);\s*white-space: normal;/,
+ );
+ assert.match(
+ trays,
+ /:has\(#command-dock > #gev-voice-control\)\s*\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*width: max-content;\s*max-width: calc\(100vw - 1\.5rem - 26rem\);/,
);
return anchor && box && [null, anchor[1], box[1]];
})(),
@@ -490,14 +580,22 @@ test('the desktop bottom row: credits on the Power Up baseline, the dock lifted,
trayWide,
/html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*:is\(#cesium-credits, #gev-credits\),\s*html\[dir='rtl'\]\s*body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\):has\(\s*#intel-hud\[data-variant='minimal'\]\.active\s*\)\s*:is\(#cesium-credits, #gev-credits\) \{\s*right: 1\.5rem;\s*left: auto;/,
);
+ // Its box hangs from the anchor's right edge there, and in the Omnibar
+ // layout at every width; never in clean view or recording, where the
+ // anchor stays on the left.
assert.match(
trayWide,
- /#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
+ /body:not\(\.context-docked\):not\(\.ui-clean-view\):not\(\.recording-mode\)\s*#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
);
- // There the readout clears two lines of the row under it.
+ assert.match(
+ trays,
+ /html\[dir='rtl'\]\s*body:not\(\.mobile-shell\)[^{]*:not\(\.recording-mode\):not\(\.context-docked\)[^{]*#cesium-credits\s*\.cesium-widget-credits \{\s*right: 0;\s*left: auto;/,
+ );
+ // There the readout clears the row under it, however many lines it wraps
+ // onto (--credit-line-height).
assert.match(
read('./styles/omnibar-dock.css'),
- /html\[dir='rtl'\] \*\)\s*#intel-hud\[data-variant='tactical'\]\s*\.hud-bottom-right \{\s*bottom: calc\(3\.375rem \+ 1\.5rem\);/,
+ /html\[dir='rtl'\] \*\):not\(\.context-docked\)\s*#intel-hud\[data-variant='tactical'\]\s*\.hud-bottom-right \{\s*bottom: max\(3\.375rem, var\(--omnibar-credits-clear\)\);/,
);
const locale = read('./styles/locale-picker.css');
assert.match(locale, /#corner-actions \{[^}]*inset-inline-end: 0\.9rem;/);
@@ -670,3 +768,20 @@ test('shared panel hooks affect only opted-in rail surfaces without overriding d
/body:is\(\.ui-clean-view, \.recording-mode\)[^{]+\{[^}]*visibility: hidden !important;[^}]*pointer-events: none !important;/,
);
});
+
+test('narrow Omnibar corners clear the World Timeline over the dock', () => {
+ const css = read('./styles/omnibar-dock.css');
+ const timeline = css.match(
+ /#world-timeline \{\s*bottom: calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px\);/,
+ );
+ const height = read('./styles/world-timeline.css').match(
+ /#world-timeline \{[^}]*\n {2}height: (\d+)px;/,
+ );
+ const corners = css.match(
+ /&:has\(#world-timeline\) \{\s*--omnibar-coordinates-bottom: max\(\s*calc\(var\(--omnibar-dock-bottom\) \+ (\d+)px \+ (\d+)px \+ (\d+)px\)/,
+ );
+ assert.ok(timeline && height && corners);
+ assert.equal(Number(corners[1]), Number(timeline[1]));
+ assert.equal(Number(corners[2]), Number(height[1]));
+ assert.ok(Number(corners[3]) >= 6);
+});
diff --git a/src/ui/panelLayoutController.js b/src/ui/panelLayoutController.js
index bd86d7a4b5..4518fcea50 100644
--- a/src/ui/panelLayoutController.js
+++ b/src/ui/panelLayoutController.js
@@ -67,11 +67,26 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [
'#gev-voice-control',
'#world-timeline',
].join(', ');
-/** True when a mutation adds or removes the Stories card (`#hPop`). */
-function movesStoriesCard(record) {
+/** The body class the welcome sets while BROWSE STORIES loads. */
+const OPENING_STORIES = 'first-run-opening-stories';
+/**
+ * True when a mutation can show or hide the Stories card (`#hPop`): the card
+ * itself coming or going, or the welcome that hides it (`#first-run-launcher`,
+ * and the body class it sets while BROWSE STORIES loads) ending.
+ */
+export function movesStoriesCard(record) {
+ if (record.type === 'attributes')
+ return (
+ (record.oldValue || '').split(/\s+/).includes(OPENING_STORIES) !==
+ record.target.classList.contains(OPENING_STORIES)
+ );
for (const list of [record.addedNodes, record.removedNodes])
for (const node of list)
- if (node.id === 'hPop' || node.querySelector?.('#hPop')) return true;
+ if (
+ ['hPop', 'first-run-launcher'].includes(node.id) ||
+ node.querySelector?.('#hPop, #first-run-launcher')
+ )
+ return true;
return false;
}
@@ -276,6 +291,18 @@ export class PanelLayoutController {
subtree: true,
childList: true,
});
+ const welcomeHost = document.querySelector('[data-gev-view="welcome"]');
+ if (welcomeHost)
+ this._storiesCardObserver.observe(welcomeHost, {
+ subtree: true,
+ childList: true,
+ });
+ if (document.body)
+ this._storiesCardObserver.observe(document.body, {
+ attributes: true,
+ attributeFilter: ['class'],
+ attributeOldValue: true,
+ });
this._storiesCardShownHandler = (event) => {
if (event.target?.id === 'hPop') this._scheduleRightPanelLayout();
};
diff --git a/src/ui/panelRails.test.mjs b/src/ui/panelRails.test.mjs
index d284548b7c..416079aec7 100644
--- a/src/ui/panelRails.test.mjs
+++ b/src/ui/panelRails.test.mjs
@@ -878,3 +878,42 @@ test('left rail keeps collapsed panels shown beside Cockpit, still one open', ()
assert.equal(f.stack.classList.contains('layout-exclusive'), false);
assert.equal(f.first.getAttribute('aria-hidden'), undefined);
});
+
+test('the right rail is laid out again when the Stories card can appear or go', async () => {
+ const { movesStoriesCard } = await import('./panelLayoutController.js');
+ const node = (id, inner = null) => ({
+ id,
+ querySelector: (selector) =>
+ inner && selector.split(', ').includes(`#${inner}`) ? {} : null,
+ });
+ const childList = (added = [], removed = []) => ({
+ type: 'childList',
+ addedNodes: added,
+ removedNodes: removed,
+ });
+ const bodyClass = (oldValue, now) => ({
+ type: 'attributes',
+ oldValue,
+ target: { classList: { contains: (name) => now.includes(name) } },
+ });
+ // The card itself, or a wrapper holding it, comes or goes.
+ assert.equal(movesStoriesCard(childList([node('hPop')])), true);
+ assert.equal(movesStoriesCard(childList([], [node('', 'hPop')])), true);
+ // The welcome, which hides the card, is removed.
+ assert.equal(
+ movesStoriesCard(childList([], [node('first-run-launcher')])),
+ true,
+ );
+ // Story playback's own changes do not lay the rail out.
+ assert.equal(movesStoriesCard(childList([node('story-frame')])), false);
+ // Only the welcome's loading class coming or going counts.
+ assert.equal(
+ movesStoriesCard(bodyClass('first-run-opening-stories', ['stories-mode'])),
+ true,
+ );
+ assert.equal(
+ movesStoriesCard(bodyClass('', ['first-run-opening-stories'])),
+ true,
+ );
+ assert.equal(movesStoriesCard(bodyClass('a', ['b'])), false);
+});
diff --git a/src/ui/stores/firstRun.js b/src/ui/stores/firstRun.js
index af90ac2bd2..3f2569aa62 100644
--- a/src/ui/stores/firstRun.js
+++ b/src/ui/stores/firstRun.js
@@ -8,7 +8,7 @@ import { markRaw, shallowRef } from 'vue';
*/
export const useFirstRunStore = defineStore('gev-first-run', () => {
/**
- * `{removed, shown, visible, closing, state, busy, status, description,
+ * `{removed, shown, visible, closing, state, busy, status,
* environmentalTitle, environmentalSub, scrollable}`, or null until the
* launcher is initialized (the card stays hidden).
*/
@@ -19,7 +19,7 @@ export const useFirstRunStore = defineStore('gev-first-run', () => {
launcher.value = next && markRaw(next);
}
- /** `{choose(choice), dismiss(), suppress(wanted) → boolean}`, or null. */
+ /** `{choose(choice), dismiss(), suppress(wanted) → boolean, refreshLayout()}`, or null. */
const controls = shallowRef(null);
/** @param {?object} next The launcher's controls, or null to disconnect. */
diff --git a/src/ui/styles/command-dock-trays.css b/src/ui/styles/command-dock-trays.css
index eb20f444ad..850f7f4e12 100644
--- a/src/ui/styles/command-dock-trays.css
+++ b/src/ui/styles/command-dock-trays.css
@@ -528,9 +528,37 @@ body:not(.ui-clean-view):not(.recording-mode):has(
}
}
+/* Cesium draws the line in an absolutely placed box inside the empty
+ #cesium-credits anchor, so the cap and the wrapping go on that box: from
+ 1200px, and in the Omnibar layout at every width, whose attribution row
+ shares the bottom edge with the corner row (omnibar-dock.css). */
+body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(
+ .ui-clean-view
+ ):not(.recording-mode):where(
+ :has(#gev-omnibar):has(#command-dock > #gev-voice-control)
+ )
+ #cesium-credits
+ .cesium-widget-credits {
+ width: max-content;
+ max-width: calc(100vw - 1.5rem - 26rem);
+ white-space: normal;
+}
+
+/* Right to left that layout puts the row at the bottom right at every
+ width, so the box hangs from the anchor's right edge. */
+html[dir='rtl']
+ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(
+ .ui-clean-view
+ ):not(.recording-mode):not(.context-docked):where(
+ :has(#gev-omnibar):has(#command-dock > #gev-voice-control)
+ )
+ #cesium-credits
+ .cesium-widget-credits {
+ right: 0;
+ left: auto;
+}
+
@media (min-width: 1200px) {
- /* Cesium draws the line in an absolutely placed box inside the empty
- #cesium-credits anchor, so the cap and the wrapping go on that box. */
#cesium-credits .cesium-widget-credits {
width: max-content;
max-width: calc(100vw - 1.5rem - 26rem);
diff --git a/src/ui/styles/first-run.css b/src/ui/styles/first-run.css
index 3e192c082a..f711fd8b9b 100644
--- a/src/ui/styles/first-run.css
+++ b/src/ui/styles/first-run.css
@@ -2,35 +2,38 @@
Compact and non-modal: it gives a new visitor a meaningful starting
choice without blocking manual map interaction or spending API quota. */
#first-run-launcher {
+ --first-run-step-offset: 1.5rem;
position: fixed;
z-index: 175;
- top: 50%;
+ /* Spans the HUD's deco band: its top meets the HUD's top readouts
+ (`top: max(14vh, 136px)` on the tactical HUD) and its bottom meets the
+ bottom readouts. The sections scroll inside, so the heading, the
+ checkbox, the main action and the status line stay reachable. */
+ top: max(14vh, 136px);
+ bottom: auto;
+ max-height: calc(100vh - 4rem);
+ max-height: calc(100dvh - 4rem);
left: 50%;
- width: min(34rem, calc(100vw - 2rem));
- /* Five tiles do not fit a short landscape phone (667 x 390), where the card
- would otherwise render past BOTH ends of the viewport. Cap it to the
- viewport and let the mission list scroll inside — the heading, the checkbox
- and the status line must stay reachable at every height. */
- max-height: calc(100vh - 1.5rem);
- max-height: calc(100dvh - 1.5rem);
+ width: min(54vw, 52rem);
+ min-width: min(40rem, calc(100vw - 2rem));
display: flex;
flex-direction: column;
- padding: 1.15rem;
+ padding: 1.35rem 1.5rem 1.1rem;
overflow: hidden;
color: var(--text-primary);
- background:
- linear-gradient(145deg, rgba(10, 27, 37, 0.97), rgba(7, 13, 22, 0.95)),
- rgba(7, 17, 25, 0.96);
- border: 1px solid rgba(54, 220, 255, 0.42);
- border-radius: 0.65rem;
+ /* The same frosted glass as the side panels, so the card reads as part of
+ the shell rather than a separate dialog. */
+ background: var(--glass-bg);
+ border: 1px solid var(--glass-border);
+ border-radius: var(--panel-radius);
box-shadow:
- 0 1.4rem 4.5rem rgba(0, 0, 0, 0.72),
- 0 0 2.5rem rgba(0, 212, 255, 0.09),
- inset 0 0 0 1px rgba(255, 255, 255, 0.025);
- backdrop-filter: blur(28px) saturate(1.25);
- -webkit-backdrop-filter: blur(28px) saturate(1.25);
+ 0 8px 32px rgba(0, 0, 0, 0.5),
+ 0 0 0 1px rgba(255, 255, 255, 0.03) inset,
+ 0 1px 0 rgba(255, 255, 255, 0.06) inset;
+ backdrop-filter: blur(24px) saturate(1.4);
+ -webkit-backdrop-filter: blur(24px) saturate(1.4);
opacity: 0;
- transform: translate(-50%, calc(-50% + 0.8rem)) scale(0.985);
+ transform: translate(-50%, 0.8rem) scale(0.985);
transition:
opacity 220ms ease,
transform 280ms cubic-bezier(0.2, 0.8, 0.2, 1);
@@ -49,10 +52,27 @@
#first-run-launcher.visible {
opacity: 1;
- transform: translate(-50%, -50%) scale(1);
+ transform: translate(-50%, 0) scale(1);
pointer-events: auto;
}
+/* A light tint over the globe behind the card, with no blur, so the globe
+ stays sharp. Decorative and click-through: the card stays non-modal, so
+ the map underneath still works. */
+.first-run-backdrop {
+ position: fixed;
+ z-index: 174;
+ inset: 0;
+ background: rgba(3, 8, 14, 0.28);
+ opacity: 0;
+ transition: opacity 220ms ease;
+ pointer-events: none;
+}
+
+.first-run-backdrop.visible {
+ opacity: 1;
+}
+
.first-run-scanline {
position: absolute;
inset: 0 0 auto;
@@ -60,10 +80,10 @@
background: linear-gradient(
90deg,
transparent,
- rgba(54, 220, 255, 0.8),
+ rgba(48, 194, 224, 0.8),
transparent
);
- box-shadow: 0 0 1rem rgba(54, 220, 255, 0.45);
+ box-shadow: 0 0 1rem rgba(48, 194, 224, 0.45);
pointer-events: none;
}
@@ -81,7 +101,7 @@
}
.first-run-kicker {
- color: rgba(54, 220, 255, 0.86);
+ color: rgba(48, 194, 224, 0.86);
}
#first-run-launcher h2 {
@@ -102,8 +122,9 @@
.first-run-choices {
display: grid;
- gap: 0.42rem;
- margin-top: 1rem;
+ gap: 1rem;
+ margin-top: 1.1rem;
+ padding-inline-end: 0.2rem;
/* The one part of the card allowed to scroll when the viewport is too short.
min-height:0 is what actually lets this flex child shrink below its content. */
min-height: 0;
@@ -115,94 +136,1405 @@
scrollbar-gutter: stable;
}
-.first-run-choices button {
+.first-run-section {
display: grid;
- grid-template-columns: 1.7rem 1fr 1.3rem;
+ gap: 0.5rem;
+}
+
+/* A numbered rule: label, then a hairline to the edge. */
+.first-run-section-title {
+ display: flex;
align-items: center;
- gap: 0.7rem;
- width: 100%;
- min-height: 3.55rem;
- padding: 0.6rem 0.7rem;
+ gap: 0.6rem;
+ margin: 0;
+ color: rgba(171, 210, 220, 0.6);
+ font-family: var(--font-mono);
+ font-size: 0.56rem;
+ font-weight: 500;
+ letter-spacing: 0.14rem;
+ text-transform: uppercase;
+}
+
+.first-run-section-title::after {
+ content: '';
+ flex: 1;
+ height: 1px;
+ background: rgba(100, 200, 220, 0.16);
+}
+
+.first-run-tag {
+ padding: 0.08rem 0.4rem;
+ color: rgba(48, 194, 224, 0.86);
+ font-family: var(--font-mono);
+ font-size: 0.5rem;
+ font-weight: 500;
+ letter-spacing: 0.08rem;
+ text-transform: uppercase;
+ border: 1px solid rgba(48, 194, 224, 0.38);
+ border-radius: 999px;
+ white-space: nowrap;
+}
+
+.first-run-tag--soon {
+ color: rgba(199, 225, 231, 0.55);
+ border-color: rgba(199, 225, 231, 0.22);
+}
+
+/* Shared tile surface: modes, tiers, missions and link cards. */
+.first-run-mode,
+.first-run-missions button,
+.first-run-link-card {
color: rgba(225, 244, 248, 0.92);
- text-align: start;
background: rgba(29, 69, 81, 0.18);
border: 1px solid rgba(100, 200, 220, 0.18);
- border-radius: 0.42rem;
+ border-radius: 0.5rem;
+}
+
+/* ── 1 · Mode ── */
+.first-run-modes {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 0.6rem;
+}
+
+.first-run-mode {
+ position: relative;
+ display: grid;
+ grid-template-columns: 7.5rem 1fr;
+ gap: 0.85rem;
+ padding: 0.7rem 2.2rem 0.7rem 0.7rem;
+}
+
+.first-run-mode[data-first-run-mode='god'] {
+ background: rgba(25, 151, 178, 0.14);
+ border-color: rgba(48, 194, 224, 0.62);
+ box-shadow: 0 0 1.4rem rgba(0, 212, 255, 0.08);
+}
+
+.first-run-mode[data-first-run-mode='analyst'] {
+ opacity: 0.55;
+}
+
+.first-run-radio {
+ position: absolute;
+ top: 0.7rem;
+ right: 0.7rem;
+ width: 0.85rem;
+ height: 0.85rem;
+ border: 1px solid rgba(199, 225, 231, 0.45);
+ border-radius: 50%;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-radio {
+ border-color: #30c2e0;
+ box-shadow: inset 0 0 0 0.2rem rgba(7, 17, 25, 0.96);
+ background: #30c2e0;
+}
+
+.first-run-mode-body,
+.first-run-link-body {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+ min-width: 0;
+}
+
+.first-run-mode-title {
+ display: flex;
+ align-items: center;
+ gap: 0.45rem;
+ margin: 0;
+}
+
+.first-run-mode-title strong,
+.first-run-link-body strong,
+.first-run-missions strong {
+ font-family: var(--font-mono);
+ font-size: 0.78rem;
+ font-weight: 600;
+ letter-spacing: 0.04rem;
+}
+
+.first-run-mode-copy {
+ margin: 0;
+ color: rgba(215, 231, 235, 0.66);
+ font-size: 0.68rem;
+ line-height: 1.45;
+}
+
+.first-run-mode-points {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.25rem 0.8rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ color: rgba(199, 225, 231, 0.6);
+ font-size: 0.6rem;
+}
+
+.first-run-mode-points li::before {
+ content: '\2022\00a0';
+ color: rgba(48, 194, 224, 0.7);
+}
+
+/* Drawn previews, so the card needs no image assets. */
+.first-run-preview {
+ position: relative;
+ display: grid;
+ place-items: center;
+ min-height: 5rem;
+ overflow: hidden;
+ border: 1px solid rgba(100, 200, 220, 0.16);
+ border-radius: 0.35rem;
+}
+
+.first-run-preview--god {
+ background:
+ repeating-linear-gradient(
+ 0deg,
+ rgba(48, 194, 224, 0.05) 0 1px,
+ transparent 1px 7px
+ ),
+ #050d14;
+}
+
+.first-run-preview--god i {
+ width: 3.4rem;
+ height: 3.4rem;
+ border: 1px solid rgba(48, 194, 224, 0.75);
+ border-radius: 50%;
+}
+
+.first-run-preview--analyst {
+ background:
+ linear-gradient(rgba(199, 225, 231, 0.08), rgba(199, 225, 231, 0.08)) 0.6rem
+ 0.7rem / 55% 0.3rem no-repeat,
+ linear-gradient(rgba(199, 225, 231, 0.06), rgba(199, 225, 231, 0.06)) 0.6rem
+ 1.3rem / 40% 0.3rem no-repeat,
+ #0b141c;
+}
+
+.first-run-preview--analyst i {
+ position: absolute;
+ inset: auto 0.6rem 0.6rem;
+ height: 1.8rem;
+ background: linear-gradient(
+ 90deg,
+ rgba(199, 225, 231, 0.12) 0 18%,
+ transparent 18% 22%,
+ rgba(199, 225, 231, 0.2) 22% 48%,
+ transparent 48% 52%,
+ rgba(199, 225, 231, 0.1) 52% 100%
+ );
+ border-radius: 0.2rem;
+}
+
+.first-run-preview--stories {
+ width: 4.2rem;
+ min-height: 4.2rem;
+ color: rgba(48, 194, 224, 0.8);
+ background:
+ radial-gradient(
+ circle at 30% 20%,
+ rgba(48, 194, 224, 0.18),
+ transparent 60%
+ ),
+ #071520;
+}
+
+/* ── 2 · Performance (a preview: no setting yet) ── */
+
+.first-run-missions small,
+.first-run-link-body small {
+ color: rgba(198, 220, 226, 0.55);
+ font-size: 0.62rem;
+}
+
+/* ── Start with: where ENTER GOD MODE begins ── */
+.first-run-missions {
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 0.45rem;
+}
+
+.first-run-missions button {
+ display: grid;
+ grid-template-columns: 1.1rem 1fr;
+ align-items: start;
+ gap: 0.45rem;
+ width: 100%;
+ min-height: 0;
+ padding: 0.45rem 0.55rem;
+ text-align: start;
cursor: pointer;
transition:
background var(--transition-fast),
- border-color var(--transition-fast),
- transform var(--transition-fast);
+ border-color var(--transition-fast);
}
-.first-run-choices button:hover,
-.first-run-choices button:focus-visible {
+.first-run-missions button > span:nth-child(2) {
+ display: flex;
+ flex-direction: column;
+ gap: 0.15rem;
+ min-width: 0;
+}
+
+.first-run-missions strong {
+ font-size: 0.6rem;
+ letter-spacing: 0.07rem;
+}
+
+.first-run-missions small {
+ font-size: 0.56rem;
+ line-height: 1.3;
+}
+
+.first-run-missions button > .material-symbols-outlined:first-child {
+ color: rgba(85, 223, 245, 0.75);
+ font-size: 1rem;
+}
+
+/* The selected start: what ENTER GOD MODE will run. */
+.first-run-missions button[aria-pressed='true'] {
+ background: rgba(25, 151, 178, 0.18);
+ border-color: rgba(48, 194, 224, 0.75);
+ box-shadow: inset 0 0 0 1px rgba(48, 194, 224, 0.35);
+}
+
+.first-run-missions
+ button[aria-pressed='true']
+ > .material-symbols-outlined:first-child {
+ color: #4bc4d8;
+}
+
+.first-run-missions button:hover,
+.first-run-missions button:focus-visible,
+a.first-run-link-card:hover,
+a.first-run-link-card:focus-visible {
background: rgba(25, 151, 178, 0.16);
- border-color: rgba(54, 220, 255, 0.62);
+ border-color: rgba(48, 194, 224, 0.62);
outline: none;
- transform: translateX(2px);
}
/* aria-disabled, not :disabled — the JS keeps the buttons focusable while a
mission runs so the keyboard is never dumped out of the launcher mid-flight. */
-.first-run-choices button[aria-disabled='true'] {
+.first-run-missions button[aria-disabled='true'],
+.first-run-enter[aria-disabled='true'] {
cursor: wait;
opacity: 0.48;
- transform: none;
pointer-events: none;
}
-.first-run-choices button > .material-symbols-outlined:first-child {
+/* ── Link cards: Stories, source, more ── */
+.first-run-link-card {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.6rem 0.7rem;
+ text-decoration: none;
+}
+
+.first-run-link-body {
+ flex: 1;
+}
+
+.first-run-stories {
+ padding: 0.7rem;
+ background:
+ repeating-linear-gradient(
+ 135deg,
+ rgba(48, 194, 224, 0.035) 0 0.5rem,
+ transparent 0.5rem 1rem
+ ),
+ rgba(29, 69, 81, 0.18);
+ border-color: rgba(48, 194, 224, 0.34);
+}
+
+.first-run-link-row {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 0.6rem;
+}
+
+.first-run-link-card--quiet {
+ border-style: dashed;
+ background: rgba(255, 255, 255, 0.02);
+ transition:
+ background var(--transition-fast),
+ border-color var(--transition-fast);
+}
+
+.first-run-link-badge {
+ display: grid;
+ flex: none;
+ place-items: center;
+ width: 2rem;
+ height: 2rem;
+ color: rgba(48, 194, 224, 0.85);
+ font-family: var(--font-mono);
+ font-size: 0.6rem;
+ border: 1px solid rgba(100, 200, 220, 0.25);
+ border-radius: 0.35rem;
+}
+
+.first-run-link-badge.material-symbols-outlined {
+ font-size: 1.05rem;
+}
+
+.first-run-link-button {
+ flex: none;
+ padding: 0.42rem 0.7rem;
+ color: rgba(225, 244, 248, 0.92);
+ background: transparent;
+ cursor: pointer;
+ font-family: var(--font-mono);
+ font-size: 0.58rem;
+ letter-spacing: 0.1rem;
+ text-decoration: none;
+ white-space: nowrap;
+ border: 1px solid rgba(48, 194, 224, 0.5);
+ border-radius: 0.35rem;
+ transition:
+ background var(--transition-fast),
+ border-color var(--transition-fast);
+}
+
+.first-run-link-button:not([aria-disabled='true']):hover,
+.first-run-link-button:focus-visible {
+ background: rgba(25, 151, 178, 0.2);
+ border-color: #30c2e0;
+ outline: none;
+}
+
+.first-run-link-button[aria-disabled='true'] {
+ color: rgba(199, 225, 231, 0.5);
+ border-color: rgba(199, 225, 231, 0.2);
+ cursor: default;
+}
+
+/* ── The main action ── */
+.first-run-enter {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.62rem 1rem;
+ color: #031018;
+ font-family: var(--font-mono);
+ font-size: 0.66rem;
+ font-weight: 600;
+ letter-spacing: 0.12rem;
+ text-transform: none;
+ background: #30c2e0;
+ border: 1px solid #30c2e0;
+ border-radius: 0.4rem;
+ box-shadow: 0 0 1.4rem rgba(48, 194, 224, 0.25);
+ cursor: pointer;
+ transition:
+ background var(--transition-fast),
+ box-shadow var(--transition-fast);
+}
+
+.first-run-enter .material-symbols-outlined {
+ font-size: 1rem;
+}
+
+.first-run-enter:hover,
+.first-run-enter:focus-visible {
+ background: #6bcde0;
+ box-shadow: 0 0 1.8rem rgba(48, 194, 224, 0.45);
+ outline: 2px solid rgba(48, 194, 224, 0.5);
+ outline-offset: 2px;
+}
+
+/* ── Compact rows: everything below the mode choice stays short, so the card
+ fits its band without scrolling. ── */
+
+/* Start with: chips. The description stays in the accessible name. */
+.first-run-missions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem;
+}
+
+.first-run-missions button {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ width: auto;
+ padding: 0.32rem 0.75rem 0.32rem 0.55rem;
+ border-radius: 999px;
+}
+
+.first-run-missions button > span:nth-child(2) {
+ display: inline;
+}
+
+.first-run-missions small {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+}
+
+.first-run-missions strong {
+ font-size: 0.58rem;
+ white-space: nowrap;
+}
+
+.first-run-missions button > .material-symbols-outlined:first-child {
+ font-size: 0.95rem;
+}
+
+/* Tiers: one line each. */
+
+/* Link cards: one line of copy, smaller badges. */
+.first-run-section {
+ gap: 0.4rem;
+}
+
+.first-run-choices {
+ gap: 0.75rem;
+}
+
+.first-run-link-card,
+.first-run-stories {
+ gap: 0.6rem;
+ padding: 0.42rem 0.6rem;
+}
+
+.first-run-link-body {
+ gap: 0.1rem;
+}
+
+.first-run-link-body strong,
+.first-run-link-body .first-run-mode-title strong {
+ font-size: 0.7rem;
+}
+
+.first-run-link-body .first-run-mode-copy,
+.first-run-link-body small {
+ overflow: hidden;
+ font-size: 0.6rem;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.first-run-link-badge {
+ width: 1.6rem;
+ height: 1.6rem;
+}
+
+.first-run-preview--stories {
+ width: 2.6rem;
+ min-height: 2.6rem;
+}
+
+.first-run-link-button {
+ padding: 0.3rem 0.6rem;
+}
+
+/* More from Halfpixel: one-line link chips. */
+.first-run-link-card--quiet {
+ padding: 0.28rem 0.6rem 0.28rem 0.4rem;
+ border-radius: 999px;
+}
+
+.first-run-link-card--quiet small {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+}
+
+.first-run-link-card--quiet .first-run-link-badge {
+ width: 1.3rem;
+ height: 1.3rem;
+ font-size: 0.5rem;
+ border-radius: 50%;
+}
+
+.first-run-link-card--quiet .first-run-link-body strong {
+ font-size: 0.64rem;
+}
+
+/* Tighter rhythm between sections and in the heading. */
+.first-run-choices {
+ gap: 0.5rem;
+ margin-top: 0.6rem;
+}
+
+.first-run-section {
+ gap: 0.32rem;
+}
+
+.first-run-preview--stories {
+ width: 2.1rem;
+ min-height: 2.1rem;
+}
+
+.first-run-stories .first-run-preview--stories .material-symbols-outlined {
+ font-size: 1.1rem;
+}
+
+#first-run-launcher h2 {
+ margin-top: 0.35rem;
+ font-size: clamp(1.15rem, 2vw, 1.5rem);
+}
+
+#first-run-description {
+ margin-top: 0.2rem;
+ max-width: 40rem;
+}
+
+/* Final trims so the band fits on a 900px-tall window. */
+.first-run-link-card,
+.first-run-stories {
+ padding-block: 0.32rem;
+}
+
+.first-run-link-badge {
+ width: 1.45rem;
+ height: 1.45rem;
+}
+
+.first-run-preview--stories {
+ width: 1.9rem;
+ min-height: 1.9rem;
+}
+
+/* More from Halfpixel: a wrapping row of link chips. */
+.first-run-link-row--chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem;
+}
+
+.first-run-link-row--chips .first-run-link-card {
+ flex: 0 0 auto;
+}
+
+/* The sections take the card's spare height, so the footer sits on its
+ bottom edge. */
+.first-run-choices {
+ flex: 1 1 auto;
+}
+
+/* Start with: taller chips. */
+.first-run-missions button {
+ gap: 0.5rem;
+ padding: 0.55rem 1rem 0.55rem 0.75rem;
+}
+
+.first-run-missions strong {
+ font-size: 0.64rem;
+}
+
+.first-run-missions button > .material-symbols-outlined:first-child {
+ font-size: 1.1rem;
+}
+
+/* A near-square card: as wide as the HUD band is tall, but never so narrow
+ that the start chips wrap. Sections may shrink below their content, so
+ long copy truncates instead of clipping. */
+.first-run-choices,
+.first-run-section {
+ grid-template-columns: minmax(0, 1fr);
+}
+
+#first-run-launcher {
+ width: min(
+ 52rem,
+ calc(100vw - 2rem),
+ max(44rem, calc(100vh - max(14vh, 136px) - max(13.5vh, 7.5rem)))
+ );
+ min-width: 0;
+}
+
+.first-run-preview--god i {
+ display: grid;
+ place-items: center;
+}
+
+.first-run-globe {
+ width: 82%;
+ height: 82%;
+ color: rgba(48, 194, 224, 0.55);
+}
+
+/* The globe's meridians are full circles squeezed sideways; a squeeze that
+ cycles reads as the globe turning. Still until God mode is selected. */
+.first-run-meridians ellipse {
+ transform: scaleX(var(--m));
+ transform-box: fill-box;
+ transform-origin: center;
+ vector-effect: non-scaling-stroke;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-meridians ellipse {
+ animation: first-run-globe-turn 6s linear infinite;
+}
+
+.first-run-mode[data-first-run-mode='god']
+ .first-run-meridians
+ ellipse:nth-child(2) {
+ animation-delay: -1.5s;
+}
+
+.first-run-mode[data-first-run-mode='god']
+ .first-run-meridians
+ ellipse:nth-child(3) {
+ animation-delay: -3s;
+}
+
+.first-run-mode[data-first-run-mode='god']
+ .first-run-meridians
+ ellipse:nth-child(4) {
+ animation-delay: -4.5s;
+}
+
+/* One meridian's width over half a turn: |cos| sampled. */
+@keyframes first-run-globe-turn {
+ 0% {
+ transform: scaleX(1);
+ }
+ 12.5% {
+ transform: scaleX(0.92);
+ }
+ 25% {
+ transform: scaleX(0.71);
+ }
+ 37.5% {
+ transform: scaleX(0.38);
+ }
+ 50% {
+ transform: scaleX(0);
+ }
+ 62.5% {
+ transform: scaleX(0.38);
+ }
+ 75% {
+ transform: scaleX(0.71);
+ }
+ 87.5% {
+ transform: scaleX(0.92);
+ }
+ 100% {
+ transform: scaleX(1);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .first-run-mode[data-first-run-mode='god'] .first-run-meridians ellipse {
+ animation: none;
+ }
+}
+
+/* HUD callouts over the God preview: brackets, an orbit, and two target
+ blips whose leader lines draw out to a label stub, taking turns. They play
+ only while God mode is selected. */
+.first-run-callouts {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ color: rgba(48, 194, 224, 0.6);
+ pointer-events: none;
+}
+
+.first-run-brackets {
+ opacity: 0.45;
+}
+
+.first-run-orbit {
+ opacity: 0.35;
+ stroke-dasharray: 2 5;
+ transform-box: fill-box;
+ transform-origin: center;
+}
+
+.first-run-blip {
+ fill: currentColor;
+ stroke: none;
+}
+
+.first-run-ping {
+ opacity: 0;
+ transform-box: fill-box;
+ transform-origin: center;
+}
+
+.first-run-leader {
+ stroke-dasharray: 1;
+ stroke-dashoffset: 1;
+}
+
+.first-run-label {
+ opacity: 0;
+ stroke-width: 1.4;
+}
+
+.first-run-callout {
+ opacity: 0;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-orbit {
+ animation: first-run-orbit-turn 24s linear infinite;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-callout {
+ animation: first-run-callout-show 6s ease-in-out infinite;
+}
+
+.first-run-mode[data-first-run-mode='god']
+ .first-run-callout
+ .first-run-leader {
+ animation: first-run-leader-draw 6s ease-out infinite;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-callout .first-run-label {
+ animation: first-run-label-show 6s ease-out infinite;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-callout .first-run-ping {
+ animation: first-run-ping 6s ease-out infinite;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-callout--b,
+.first-run-mode[data-first-run-mode='god'] .first-run-callout--b * {
+ animation-delay: -3s;
+}
+
+@keyframes first-run-orbit-turn {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+@keyframes first-run-callout-show {
+ 0%,
+ 45%,
+ 100% {
+ opacity: 0;
+ }
+ 5%,
+ 40% {
+ opacity: 1;
+ }
+}
+
+@keyframes first-run-leader-draw {
+ 0%,
+ 5% {
+ stroke-dashoffset: 1;
+ }
+ 18%,
+ 100% {
+ stroke-dashoffset: 0;
+ }
+}
+
+@keyframes first-run-label-show {
+ 0%,
+ 18% {
+ opacity: 0;
+ }
+ 24%,
+ 100% {
+ opacity: 1;
+ }
+}
+
+@keyframes first-run-ping {
+ 0%,
+ 5% {
+ opacity: 0.9;
+ transform: scale(1);
+ }
+ 25%,
+ 100% {
+ opacity: 0;
+ transform: scale(4);
+ }
+}
+
+/* Reduced motion: the callouts stand still, fully drawn. The parts are
+ named as specifically as their animation rules above, or those would win. */
+@media (prefers-reduced-motion: reduce) {
+ .first-run-mode[data-first-run-mode='god'] .first-run-orbit,
+ .first-run-mode[data-first-run-mode='god'] .first-run-callout,
+ .first-run-mode[data-first-run-mode='god'] .first-run-callout *,
+ .first-run-mode[data-first-run-mode='god']
+ .first-run-callout
+ :is(.first-run-leader, .first-run-label, .first-run-ping) {
+ animation: none;
+ }
+ .first-run-mode[data-first-run-mode='god']
+ .first-run-callout
+ .first-run-ping {
+ opacity: 0;
+ }
+ .first-run-mode[data-first-run-mode='god'] .first-run-callout,
+ .first-run-mode[data-first-run-mode='god'] .first-run-label {
+ opacity: 1;
+ }
+ .first-run-mode[data-first-run-mode='god'] .first-run-leader {
+ stroke-dashoffset: 0;
+ }
+}
+
+/* Callout tooltips: on hover or keyboard focus a leader line grows up from
+ the control, then a HUD label opens out of it. The text describes a chip
+ that shows only its name; it is visual only (see ::after), so the chip's
+ accessible name stays its visible name. */
+#first-run-launcher [data-callout] {
+ position: relative;
+}
+
+#first-run-launcher [data-callout]::before,
+#first-run-launcher [data-callout]::after {
+ position: absolute;
+ z-index: 3;
+ pointer-events: none;
+}
+
+#first-run-launcher [data-callout]::before {
+ content: '';
+ bottom: 100%;
+ inset-inline-start: 1.1rem;
+ width: 1px;
+ height: 0.7rem;
+ background: rgba(48, 194, 224, 0.8);
+ transform: scaleY(0);
+ transform-origin: bottom;
+ transition: transform 140ms ease-out;
+}
+
+#first-run-launcher [data-callout]::after {
+ /* Visual only: the empty alternative keeps the callout out of the link's
+ accessible name. Browsers without alt text for generated content drop the
+ second declaration and fall back to the first. */
+ content: attr(data-callout);
+ content: attr(data-callout) / '';
+ bottom: calc(100% + 0.7rem);
+ inset-inline-start: 0.5rem;
+ padding: 0.28rem 0.5rem;
+ color: rgba(225, 244, 248, 0.95);
+ font-family: var(--font-mono);
+ font-size: 0.56rem;
+ font-weight: 400;
+ letter-spacing: 0.04rem;
+ text-transform: none;
+ /* Long descriptions wrap rather than run past the card on a narrow window. */
+ width: max-content;
+ max-width: min(15rem, var(--first-run-callout-max, 15rem));
+ box-sizing: border-box;
+ white-space: normal;
+ background: rgba(5, 14, 20, 0.94);
+ border: 1px solid rgba(48, 194, 224, 0.5);
+ border-radius: 3px;
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.45);
+ opacity: 0;
+ clip-path: inset(0 100% 0 0);
+ transition:
+ clip-path 200ms 120ms ease-out,
+ opacity 80ms 120ms linear;
+}
+
+#first-run-launcher [data-callout]:hover::before,
+#first-run-launcher [data-callout]:focus-visible::before {
+ transform: scaleY(1);
+}
+
+/* A chip near the far edge opens its callout toward the card instead, so the
+ label is not cut off by the scrolling list (WelcomeView sets the flag). */
+#first-run-launcher [data-callout][data-callout-align='end']::before {
+ inset-inline-start: auto;
+ inset-inline-end: 1.1rem;
+}
+
+#first-run-launcher [data-callout][data-callout-align='end']::after {
+ inset-inline-start: auto;
+ inset-inline-end: 0.5rem;
+}
+
+#first-run-launcher [data-callout]:hover::after,
+#first-run-launcher [data-callout]:focus-visible::after {
+ opacity: 1;
+ clip-path: inset(0);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ #first-run-launcher [data-callout]::before,
+ #first-run-launcher [data-callout]::after {
+ transition: none;
+ }
+}
+
+/* No hover on touch screens: the callouts would only flash on tap. */
+@media (hover: none) {
+ #first-run-launcher [data-callout]::before,
+ #first-run-launcher [data-callout]::after {
+ display: none;
+ }
+}
+
+/* Selection reads in orange: the chosen mode and the chosen start. */
+.first-run-mode[data-first-run-mode='god'],
+.first-run-missions button[aria-pressed='true'] {
+ border-color: rgba(255, 159, 67, 0.85);
+ box-shadow: inset 0 0 0 1px rgba(255, 159, 67, 0.3);
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-radio {
+ border-color: #ff9f43;
+ background: #ff9f43;
+}
+
+/* A mini timeline under the globe: the playhead sweeps the track and the
+ played part lights up behind it. Paused partway while not selected. */
+.first-run-time-track,
+.first-run-time-ticks {
+ opacity: 0.35;
+}
+
+.first-run-time-played {
+ stroke-width: 1.4;
+ transform: scaleX(0.4);
+ transform-box: fill-box;
+ transform-origin: left center;
+}
+
+.first-run-time-head {
+ transform: translateX(27.2px);
+}
+
+.first-run-time-head path {
+ fill: currentColor;
+ stroke: none;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-time-played {
+ animation: first-run-time-played 8s linear infinite;
+}
+
+.first-run-mode[data-first-run-mode='god'] .first-run-time-head {
+ animation: first-run-time-head 8s linear infinite;
+}
+
+@keyframes first-run-time-played {
+ from {
+ transform: scaleX(0);
+ }
+ to {
+ transform: scaleX(1);
+ }
+}
+
+@keyframes first-run-time-head {
+ from {
+ transform: translateX(0);
+ }
+ to {
+ transform: translateX(68px);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .first-run-mode[data-first-run-mode='god'] .first-run-time-played,
+ .first-run-mode[data-first-run-mode='god'] .first-run-time-head {
+ animation: none;
+ }
+}
+
+/* The accent rests dimmed and lights up to full cyan on hover or focus. */
+.first-run-missions button:hover,
+.first-run-missions button:focus-visible,
+a.first-run-link-card:hover,
+a.first-run-link-card:focus-visible {
+ border-color: rgba(54, 220, 255, 0.62);
+}
+
+.first-run-missions button:hover > .material-symbols-outlined:first-child,
+.first-run-missions
+ button:focus-visible
+ > .material-symbols-outlined:first-child,
+a.first-run-link-card:hover .first-run-link-badge,
+a.first-run-link-card:focus-visible .first-run-link-badge {
color: #55dff5;
+}
+
+.first-run-link-button:not([aria-disabled='true']):hover,
+.first-run-link-button:focus-visible {
+ color: #e1f4f8;
+ border-color: #36dcff;
+}
+
+.first-run-enter:hover,
+.first-run-enter:focus-visible {
+ background: #36dcff;
+ border-color: #36dcff;
+ box-shadow: 0 0 1.4rem rgba(54, 220, 255, 0.35);
+ outline-color: rgba(54, 220, 255, 0.5);
+}
+
+#first-run-launcher [data-callout]:hover::before,
+#first-run-launcher [data-callout]:focus-visible::before {
+ background: rgba(54, 220, 255, 0.85);
+}
+
+#first-run-launcher [data-callout]:hover::after,
+#first-run-launcher [data-callout]:focus-visible::after {
+ border-color: rgba(54, 220, 255, 0.55);
+}
+
+/* A selected chip keeps its orange border on hover. */
+.first-run-missions button[aria-pressed='true']:hover,
+.first-run-missions button[aria-pressed='true']:focus-visible {
+ border-color: rgba(255, 159, 67, 0.85);
+}
+
+/* ── Steps ── */
+.first-run-header {
+ position: relative;
+}
+
+.first-run-dots {
+ position: absolute;
+ left: 50%;
+ display: flex;
+ gap: 0.4rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ transform: translateX(-50%);
+}
+
+/* The dots sit centred over the row, outside its flow, so the kicker and
+ Skip each keep to their own half: a long locale wraps instead of running
+ under the dots. (At 620px and below the dots join the flow.) */
+@media (min-width: 621px) {
+ .first-run-kicker,
+ .first-run-dismiss {
+ max-width: calc(50% - 2.4rem);
+ }
+}
+
+.first-run-dots li {
+ width: 0.45rem;
+ height: 0.45rem;
+ background: rgba(199, 225, 231, 0.18);
+ border-radius: 999px;
+ transition:
+ width 220ms ease,
+ background 220ms ease;
+}
+
+.first-run-dots li.done {
+ background: rgba(48, 194, 224, 0.45);
+}
+
+.first-run-dots li.on {
+ width: 1.4rem;
+ background: #30c2e0;
+}
+
+.first-run-step {
+ display: grid;
+ gap: 0.9rem;
+ align-content: start;
+}
+
+/* Steps slide sideways: forward to the left, back to the right. */
+.first-run-step-forward-enter-active,
+.first-run-step-forward-leave-active,
+.first-run-step-back-enter-active,
+.first-run-step-back-leave-active {
+ transition:
+ opacity 180ms ease,
+ transform 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+
+.first-run-step-forward-enter-from,
+.first-run-step-back-leave-to {
+ opacity: 0;
+ transform: translateX(var(--first-run-step-offset));
+}
+
+.first-run-step-forward-leave-to,
+.first-run-step-back-enter-from {
+ opacity: 0;
+ transform: translateX(calc(-1 * var(--first-run-step-offset)));
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .first-run-step-forward-enter-from,
+ .first-run-step-forward-leave-to,
+ .first-run-step-back-enter-from,
+ .first-run-step-back-leave-to {
+ transform: none;
+ }
+}
+
+/* Step 1: the mode tiles get the room the other sections used to take. */
+.first-run-step .first-run-modes .first-run-mode {
+ grid-template-columns: 9.5rem 1fr;
+ padding-block: 0.9rem;
+}
+
+.first-run-step .first-run-preview--god,
+.first-run-step .first-run-preview--analyst {
+ min-height: 9rem;
+}
+
+.first-run-step .first-run-mode-copy {
+ font-size: 0.74rem;
+}
+
+/* Step 2: the start options as tiles, descriptions shown. */
+.first-run-missions--tiles {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 0.6rem;
+}
+
+.first-run-missions--tiles button {
+ display: grid;
+ grid-template-columns: 1.6rem 1fr;
+ align-items: start;
+ gap: 0.7rem;
+ padding: 0.9rem 1rem;
+ border-radius: 0.5rem;
+}
+
+.first-run-missions--tiles button:last-child:nth-child(odd) {
+ /* An odd last tile takes the whole row, so three tiles read as a balanced
+ pair plus the default, not as a gap. One column on a phone already. */
+ grid-column: 1 / -1;
+}
+
+.first-run-missions--tiles button > span:nth-child(2) {
+ display: flex;
+ flex-direction: column;
+ gap: 0.3rem;
+}
+
+.first-run-missions--tiles strong {
+ font-size: 0.72rem;
+ white-space: normal;
+ overflow-wrap: anywhere;
+}
+
+.first-run-missions--tiles small {
+ position: static;
+ width: auto;
+ height: auto;
+ overflow: visible;
+ clip-path: none;
+ white-space: normal;
+ font-size: 0.66rem;
+ line-height: 1.4;
+}
+
+.first-run-missions--tiles button > .material-symbols-outlined:first-child {
font-size: 1.35rem;
}
-.first-run-choices button > span:nth-child(2) {
+/* Step 3: three tips, each with a small looping sketch. */
+.first-run-tips {
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 0.6rem;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.first-run-tip {
display: flex;
flex-direction: column;
- gap: 0.15rem;
+ gap: 0.35rem;
+ padding: 0.85rem;
+ background: rgba(29, 69, 81, 0.18);
+ border: 1px solid rgba(100, 200, 220, 0.18);
+ border-radius: 0.5rem;
}
-.first-run-choices strong {
+.first-run-tip strong {
font-family: var(--font-mono);
- font-size: 0.72rem;
- font-weight: 600;
- letter-spacing: 0.08rem;
+ font-size: 0.7rem;
+ letter-spacing: 0.05rem;
}
-.first-run-choices small {
- color: rgba(198, 220, 226, 0.55);
- font-size: 0.66rem;
+.first-run-tip small {
+ color: rgba(198, 220, 226, 0.6);
+ font-size: 0.64rem;
+ line-height: 1.4;
}
-.first-run-arrow {
- color: rgba(54, 220, 255, 0.4);
- font-size: 1rem;
- transition:
- transform var(--transition-fast),
- color var(--transition-fast);
+.first-run-tip-art {
+ position: relative;
+ display: grid;
+ place-items: center;
+ height: 3.2rem;
+ margin-bottom: 0.2rem;
+ color: rgba(48, 194, 224, 0.85);
+ background: #050d14;
+ border: 1px solid rgba(100, 200, 220, 0.14);
+ border-radius: 0.35rem;
}
-.first-run-choices button:hover .first-run-arrow,
-.first-run-choices button:focus-visible .first-run-arrow {
- color: rgba(54, 220, 255, 0.9);
- transform: translateX(2px);
+.first-run-tip-art .material-symbols-outlined {
+ font-size: 1.4rem;
}
-/* Ordered after the shared button rule rather than shouting !important at it. */
-.first-run-choices button.first-run-explore {
- background: rgba(255, 255, 255, 0.025);
+/* Search: a caret blinks after the glass. */
+.first-run-tip-caret {
+ position: absolute;
+ left: calc(50% + 1rem);
+ width: 1px;
+ height: 0.9rem;
+ background: currentColor;
+ animation: first-run-caret 1s steps(1) infinite;
+}
+
+/* Layers: a dot switches on and off beside the stack. */
+.first-run-tip-dot {
+ position: absolute;
+ left: calc(50% + 1rem);
+ top: calc(50% - 0.6rem);
+ width: 0.4rem;
+ height: 0.4rem;
+ background: #ff9f43;
+ border-radius: 50%;
+ animation: first-run-dot 2.4s ease-in-out infinite;
+}
+
+/* Click: a ring ripples out from the target. */
+.first-run-tip-ring {
+ position: absolute;
+ width: 1.2rem;
+ height: 1.2rem;
+ border: 1px solid currentColor;
+ border-radius: 50%;
+ animation: first-run-ring 1.8s ease-out infinite;
+}
+
+@keyframes first-run-caret {
+ 50% {
+ opacity: 0;
+ }
+}
+
+@keyframes first-run-dot {
+ 0%,
+ 40% {
+ opacity: 0.15;
+ transform: scale(0.7);
+ }
+ 50%,
+ 90% {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+@keyframes first-run-ring {
+ from {
+ opacity: 0.9;
+ transform: scale(0.6);
+ }
+ to {
+ opacity: 0;
+ transform: scale(2.4);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .first-run-tip-caret,
+ .first-run-tip-dot,
+ .first-run-tip-ring {
+ animation: none;
+ }
+}
+
+/* Footer: Back sits before the main action. */
+.first-run-back {
+ padding: 0.5rem 0.9rem;
+ color: rgba(199, 225, 231, 0.75);
+ font-family: var(--font-mono);
+ font-size: 0.62rem;
+ letter-spacing: 0.12rem;
+ background: none;
+ border: 1px solid rgba(199, 225, 231, 0.2);
+ border-radius: 0.4rem;
+ cursor: pointer;
+}
+
+.first-run-back:hover,
+.first-run-back:focus-visible {
+ color: #e1f4f8;
+ border-color: rgba(54, 220, 255, 0.6);
+}
+
+/* Each step is short, so the card fits its content: its top stays on the
+ HUD band, and it may grow at most to the band's bottom. */
+#first-run-launcher {
+ bottom: auto;
+ max-height: calc(100vh - max(14vh, 136px) - max(13.5vh, 7.5rem));
+ max-height: calc(100dvh - max(14vh, 136px) - max(13.5vh, 7.5rem));
+}
+
+.first-run-choices {
+ flex: 0 1 auto;
+}
+
+.first-run-step .first-run-modes .first-run-mode {
+ grid-template-columns: 8rem 1fr;
+}
+
+.first-run-mode-title {
+ flex-wrap: wrap;
+ row-gap: 0.25rem;
+}
+
+/* One footer row: checkbox, status line, main action. */
+.first-run-footer .first-run-note {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ margin: 0;
+ display: -webkit-box;
+ overflow: hidden;
+ font-size: 0.56rem;
+ line-height: 1.35;
+ text-align: center;
+ text-transform: none;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+}
+
+.first-run-footer .first-run-enter {
+ padding: 0.5rem 0.9rem;
}
.first-run-footer {
- margin-top: 0.85rem;
+ margin-top: 0.55rem;
+ padding-top: 0.55rem;
+ border-top: 1px solid rgba(100, 200, 220, 0.14);
font-size: 0.48rem;
letter-spacing: 0.055rem;
}
.first-run-dismiss {
position: relative;
- padding: 0 0 0 0.75rem;
+ padding: 0;
+ padding-inline-start: 0.75rem;
border: 0;
background: none;
color: inherit;
@@ -212,7 +1544,7 @@
cursor: pointer;
}
-/* A 44px touch target drawn outside the layout, so the footer row keeps the
+/* A 44px touch target drawn outside the layout, so the header row keeps the
height of its one line of text; a 44px button box would nearly treble it. */
.first-run-dismiss::before {
content: '';
@@ -226,7 +1558,7 @@
.first-run-dismiss:hover,
.first-run-dismiss:focus-visible {
- color: rgba(54, 220, 255, 0.86);
+ color: rgba(48, 194, 224, 0.86);
}
.first-run-dismiss-touch {
@@ -258,7 +1590,7 @@
width: 0.82rem;
height: 0.82rem;
margin: 0;
- accent-color: #36dcff;
+ accent-color: #30c2e0;
cursor: pointer;
}
@@ -270,7 +1602,7 @@
and reserves its height — otherwise the card resizes as it speaks. */
.first-run-note {
min-height: 1.1rem;
- margin-top: 0.5rem;
+ margin-top: 0.35rem;
color: rgba(199, 225, 231, 0.62);
font-family: var(--font-mono);
font-size: 0.62rem;
@@ -278,7 +1610,7 @@
}
#first-run-launcher[data-state='loading'] .first-run-note {
- color: rgba(54, 220, 255, 0.85);
+ color: rgba(48, 194, 224, 0.85);
}
/* Every surface that claims the screen hides the launcher. This list is the CSS
@@ -293,10 +1625,22 @@ body.scene-playback-mode #first-run-launcher {
display: none;
}
+body.ui-clean-view .first-run-backdrop,
+body.recording-mode .first-run-backdrop,
+body.cockpit-mode .first-run-backdrop,
+body.scene-playback-mode .first-run-backdrop {
+ display: none;
+}
+
@media (max-width: 620px) {
#first-run-launcher {
top: auto;
bottom: 5.8rem;
+ width: calc(100vw - 2rem);
+ min-width: 0;
+ /* Sits above the dock, so it may only use the height above it. */
+ max-height: calc(100vh - 6.55rem);
+ max-height: calc(100dvh - 6.55rem);
padding: 0.9rem;
transform: translate(-50%, 0.8rem) scale(0.985);
}
@@ -304,9 +1648,9 @@ body.scene-playback-mode #first-run-launcher {
#first-run-launcher.visible {
transform: translate(-50%, 0) scale(1);
}
- /* Five tiles have to clear the dock on a 375 x 812 phone, so the rows
- tighten. The dismiss button stays: it is the only way to close the card
- without choosing a mission on a phone, which has no ESC key. */
+ /* The card has to clear the dock on a 375 x 812 phone, so the sections
+ stack into one column and scroll. The dismiss button stays: it is the only
+ way to close the card without choosing on a phone, which has no ESC key. */
#first-run-launcher h2 {
margin-top: 0.45rem;
}
@@ -317,24 +1661,59 @@ body.scene-playback-mode #first-run-launcher {
.first-run-choices {
margin-top: 0.75rem;
}
- .first-run-choices button {
- min-height: 3rem;
- padding: 0.45rem 0.6rem;
+ .first-run-modes,
+ .first-run-link-row {
+ grid-template-columns: minmax(0, 1fr);
}
- .first-run-choices small {
- font-size: 0.62rem;
+ .first-run-missions {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ /* A phone has no room for drawn previews: the choices that work come
+ first. */
+ .first-run-mode {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ .first-run-preview {
+ display: none;
+ }
+ .first-run-footer {
+ flex-wrap: wrap;
+ }
+ .first-run-enter {
+ flex: 1 0 100%;
+ justify-content: center;
+ white-space: nowrap;
+ }
+ /* A status line (a mission that could not open) takes its own row above
+ the buttons instead of a sliver beside the checkbox and BACK. */
+ .first-run-footer .first-run-note:not(:empty) {
+ flex: 1 0 100%;
+ order: -1;
}
}
/* Short viewports — landscape phones, small laptop windows. The chrome tightens
- so the mission list keeps a usable share of the height. The intro line STAYS:
- it is the only copy that says what this thing is, and with four tiles it
- fits. (It was dropped here while there were five; the tile that went is
- exactly why it can come back.) */
+ so the sections keep a usable share of the height. The intro line STAYS: it
+ is the only copy that says what this thing is. */
@media (max-height: 620px) {
+ /* The height cap and bottom edge come from the shell rules at the end of
+ this file; the tighter padding (and the mobile shell's top) stay here. */
#first-run-launcher {
+ top: 0.75rem;
padding: 0.75rem 0.85rem;
}
+ /* As on a phone: no drawn previews, so the choices that work stay within
+ reach. */
+ .first-run-mode {
+ grid-template-columns: minmax(0, 1fr);
+ padding-block: 0.5rem;
+ }
+ .first-run-mode-points {
+ display: none;
+ }
+ .first-run-preview {
+ display: none;
+ }
#first-run-launcher h2 {
margin-top: 0.3rem;
font-size: 1.1rem;
@@ -346,16 +1725,10 @@ body.scene-playback-mode #first-run-launcher {
}
.first-run-choices {
margin-top: 0.55rem;
+ gap: 0.7rem;
}
- .first-run-choices button {
- min-height: 2.7rem;
- padding: 0.36rem 0.6rem;
- }
- .first-run-choices strong {
- font-size: 0.68rem;
- }
- .first-run-choices small {
- font-size: 0.6rem;
+ .first-run-missions button {
+ padding: 0.36rem 0.5rem;
}
.first-run-footer {
margin-top: 0.5rem;
@@ -404,8 +1777,12 @@ body.scene-playback-mode #first-run-launcher {
@media (prefers-reduced-motion: reduce) {
#first-run-launcher,
- .first-run-choices button,
- .first-run-arrow {
+ .first-run-backdrop,
+ .first-run-back,
+ .first-run-missions button,
+ .first-run-link-card,
+ .first-run-link-button,
+ .first-run-enter {
transition: none;
}
/* Scrolling a tile into view must not animate either. */
@@ -413,3 +1790,90 @@ body.scene-playback-mode #first-run-launcher {
scroll-behavior: auto;
}
}
+
+/* Centred on the screen, top to bottom as well as side to side, at its own
+ height (capped so its sections still scroll on short screens). */
+body:not(.mobile-shell) #first-run-launcher {
+ top: 50%;
+ bottom: auto;
+ max-height: calc(100vh - 4rem);
+ max-height: calc(100dvh - 4rem);
+ transform: translate(-50%, calc(-50% + 0.8rem)) scale(0.985);
+}
+
+body:not(.mobile-shell) #first-run-launcher.visible {
+ transform: translate(-50%, -50%) scale(1);
+}
+
+@media (max-width: 620px) {
+ .first-run-dots {
+ position: static;
+ transform: none;
+ }
+ .first-run-tips,
+ .first-run-missions--tiles {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ .first-run-step .first-run-modes .first-run-mode {
+ grid-template-columns: minmax(0, 1fr);
+ }
+}
+
+@media (max-height: 620px) {
+ .first-run-step .first-run-modes .first-run-mode {
+ grid-template-columns: minmax(0, 1fr);
+ padding-block: 0.5rem;
+ }
+ .first-run-missions--tiles {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+ body.mobile-shell #first-run-launcher {
+ bottom: 5.8rem;
+ max-height: calc(100vh - 6.55rem);
+ max-height: calc(100dvh - 6.55rem);
+ }
+}
+.first-run-back[aria-disabled='true'] {
+ opacity: 0.5;
+ cursor: wait;
+}
+@media (prefers-reduced-motion: reduce) {
+ .first-run-dots li {
+ transition: none;
+ }
+}
+[dir='rtl'] #first-run-launcher {
+ --first-run-step-offset: -1.5rem;
+}
+[dir='rtl'] .first-run-enter .material-symbols-outlined {
+ transform: scaleX(-1);
+}
+[dir='rtl'] #first-run-launcher [data-callout]::after {
+ clip-path: inset(0 0 0 100%);
+}
+
+[dir='rtl'] #first-run-launcher [data-callout]:hover::after,
+[dir='rtl'] #first-run-launcher [data-callout]:focus-visible::after {
+ clip-path: inset(0);
+}
+
+.first-run-step-announcement {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip-path: inset(50%);
+ white-space: nowrap;
+ border: 0;
+}
+/* The Stories announcement waits behind onboarding without consuming its
+ unseen state: from startup while the card is pending, through its reveal,
+ until it is removed (not shown this session, or dismissed). It also stays
+ hidden while BROWSE STORIES is loading Stories. */
+body:has(#first-run-launcher) #gev-stories #hPop,
+body.first-run-opening-stories #gev-stories #hPop {
+ visibility: hidden;
+ pointer-events: none;
+}
diff --git a/src/ui/styles/omnibar-dock.css b/src/ui/styles/omnibar-dock.css
index 480227e014..e9faafcdb2 100644
--- a/src/ui/styles/omnibar-dock.css
+++ b/src/ui/styles/omnibar-dock.css
@@ -5,8 +5,13 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(
:has(#gev-omnibar):has(#command-dock > #gev-voice-control)
) {
--omnibar-dock-width: clamp(400px, 32vw, 460px);
- --omnibar-dock-bottom: 74px;
- --omnibar-coordinates-bottom: 4.25rem;
+ /* Clear of the attribution line under it, however many lines it wraps
+ onto (--credit-line-height, src/ui/creditLineHeight.js). */
+ --omnibar-credits-clear: calc(1rem + var(--credit-line-height, 28px) + 6px);
+ /* The dock, and the World Timeline and narrow corners placed from it,
+ rise over a line wrapped taller than its usual one or two lines. */
+ --omnibar-dock-bottom: max(74px, calc(var(--omnibar-credits-clear) + 2px));
+ --omnibar-coordinates-bottom: max(4.25rem, var(--omnibar-credits-clear));
--world-timeline-lift: 0px;
#intel-hud:is([data-variant='tactical'], [data-variant='minimal'])
@@ -320,24 +325,61 @@ body:not(.mobile-shell):not(.cockpit-mode):not(.scene-playback-mode):not(
display: none;
}
- /* Align the plain credits with Power Up. */
+ /* Align the plain credits with Power Up. The line wraps at every width
+ rather than running under the corner row (Power Up and the language
+ picker), whose side it stays clear of. */
:is(#cesium-credits, #gev-credits),
&:has(#intel-hud[data-variant='minimal'].active)
:is(#cesium-credits, #gev-credits) {
bottom: 1rem;
}
+ #gev-credits {
+ width: max-content !important;
+ max-width: calc(100vw - 1.5rem - 26rem);
+ white-space: normal;
+ }
+ /* Right to left the corner row is at the bottom left, so the line takes
+ the bottom right at every width. Expanded Context places it itself. */
+ &:where(html[dir='rtl'] *):not(.context-docked) {
+ :is(#cesium-credits, #gev-credits),
+ &:has(#intel-hud[data-variant='minimal'].active)
+ :is(#cesium-credits, #gev-credits) {
+ right: 1.5rem;
+ left: auto;
+ text-align: right;
+ }
+ }
/* 8px above the bottom-right corner row (Power Up and the language picker:
32px tall, 14px up), as outside the Omnibar layout. */
#intel-hud[data-variant='tactical'] .hud-bottom-right {
bottom: 3.375rem;
}
- /* Right to left the attribution row takes the bottom right: the readout
- clears two lines of it (rail-split.css). */
- @media (min-width: 1200px) {
- &:where(html[dir='rtl'] *)
+ /* Right to left the attribution line is under the readout, which clears
+ it however many lines it wraps onto. */
+ &:where(html[dir='rtl'] *):not(.context-docked)
+ #intel-hud[data-variant='tactical']
+ .hud-bottom-right {
+ bottom: max(3.375rem, var(--omnibar-credits-clear));
+ }
+ /* Narrower than the two corners and the dock between them, the corners
+ rise above the dock. */
+ @media (max-width: 1119px) {
+ --omnibar-coordinates-bottom: max(
+ calc(var(--omnibar-dock-bottom) + 56px + 10px),
+ var(--omnibar-credits-clear)
+ );
+ /* And above the World Timeline (42px tall) over the dock. */
+ &:has(#world-timeline) {
+ --omnibar-coordinates-bottom: max(
+ calc(var(--omnibar-dock-bottom) + 66px + 42px + 10px),
+ var(--omnibar-credits-clear)
+ );
+ }
+ #intel-hud[data-variant='tactical'] .hud-bottom-right,
+ &:where(html[dir='rtl'] *):not(.context-docked)
#intel-hud[data-variant='tactical']
.hud-bottom-right {
- bottom: calc(3.375rem + 1.5rem);
+ bottom: var(--omnibar-coordinates-bottom);
}
}
#intel-hud:is([data-variant='tactical'], [data-variant='minimal'])
diff --git a/src/ui/styles/rtl.css b/src/ui/styles/rtl.css
index 91cf97e950..2d0c20ee3e 100644
--- a/src/ui/styles/rtl.css
+++ b/src/ui/styles/rtl.css
@@ -125,16 +125,10 @@ html[dir='rtl'] #command-dock :is(#location-bar, #control-panel) .dock-pin-btn {
}
/* The right rail sits on the left: its expand/collapse arrows point the
- other way, and the start window's "go" arrows point along the reading
- direction. */
-html[dir='rtl'] #right-context-rail .panel-collapse-btn,
-html[dir='rtl'] .first-run-arrow {
+ other way. (The first-run card flips its own arrow in first-run.css.) */
+html[dir='rtl'] #right-context-rail .panel-collapse-btn {
transform: scaleX(-1);
}
-html[dir='rtl'] .first-run-choices button:hover .first-run-arrow,
-html[dir='rtl'] .first-run-choices button:focus-visible .first-run-arrow {
- transform: translateX(-2px) scaleX(-1);
-}
/* The cockpit is an aircraft panel, not page chrome: its windows keep their
physical sides, so the data-layer stack goes back to the left edge instead
diff --git a/src/ui/surfaceKeyboard.js b/src/ui/surfaceKeyboard.js
index 887ae1eb31..e3b5a2c843 100644
--- a/src/ui/surfaceKeyboard.js
+++ b/src/ui/surfaceKeyboard.js
@@ -9,6 +9,10 @@
* @param {() => boolean} options.isActive Whether this surface may handle input now.
* @param {() => void} options.onEscape Caller-owned dismissal action.
* @param {() => HTMLElement} [options.fallbackFocus] Return target if the opener is gone.
+ * @param {boolean} [options.claimOutsideFocus=true] Tab from a control outside
+ * the surface moves into it. False leaves Tab to the page then, for a
+ * surface that does not hold the keyboard (focus that has nowhere to be,
+ * on the page body, still moves in).
* @returns {{activate: Function, deactivate: Function, destroy: Function}}
*/
export function createSurfaceKeyboard({
@@ -17,6 +21,7 @@ export function createSurfaceKeyboard({
isActive,
onEscape,
fallbackFocus,
+ claimOutsideFocus = true,
}) {
let active = false;
let destroyed = false;
@@ -54,6 +59,11 @@ export function createSurfaceKeyboard({
// Allow native scrolling when cycling to an off-screen control in a short
// surface. Initial focus and return focus use the caller's separate policy.
if (!root.contains(focused)) {
+ const lost =
+ !focused ||
+ focused === documentRef.body ||
+ focused === documentRef.documentElement;
+ if (!claimOutsideFocus && !lost) return;
event.preventDefault();
(event.shiftKey ? last : first).focus();
} else if (event.shiftKey && focused === first) {
diff --git a/src/ui/surfaceKeyboard.test.mjs b/src/ui/surfaceKeyboard.test.mjs
index d9b8388cf1..51a6b8238a 100644
--- a/src/ui/surfaceKeyboard.test.mjs
+++ b/src/ui/surfaceKeyboard.test.mjs
@@ -2,7 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createSurfaceKeyboard } from './surfaceKeyboard.js';
-function fixture() {
+function fixture({ claimOutsideFocus } = {}) {
const listeners = new Set();
const documentRef = {
activeElement: null,
@@ -54,6 +54,7 @@ function fixture() {
isActive: () => visible,
onEscape: () => onEscape(),
fallbackFocus: () => fallback,
+ claimOutsideFocus,
});
opener.focus();
const event = (key, extra = {}) => ({
@@ -134,6 +135,23 @@ test('Tab enters from outside in either direction and wraps only at an edge', ()
);
});
+test('a surface that does not claim outside focus leaves Tab to the page', () => {
+ const f = fixture({ claimOutsideFocus: false });
+ f.controller.activate();
+ // From a control outside (the search bar), Tab follows the page.
+ f.opener.focus();
+ assert.equal(f.send('Tab').defaultPrevented, false);
+ assert.equal(f.send('Tab', { shiftKey: true }).defaultPrevented, false);
+ assert.equal(f.documentRef.activeElement, f.opener);
+ // Focus with nowhere to be still moves in, and wraps inside as before.
+ f.documentRef.activeElement = null;
+ assert.equal(f.send('Tab').defaultPrevented, true);
+ assert.equal(f.documentRef.activeElement, f.first);
+ f.last.focus();
+ f.send('Tab');
+ assert.equal(f.documentRef.activeElement, f.first);
+});
+
test('Tab uses current controls and skips hidden/disabled nodes without changing native middle movement', () => {
const f = fixture();
f.controller.activate();
diff --git a/src/ui/views/WelcomeView.vue b/src/ui/views/WelcomeView.vue
index c4c52fb1ea..395facfb4e 100644
--- a/src/ui/views/WelcomeView.vue
+++ b/src/ui/views/WelcomeView.vue
@@ -1,22 +1,142 @@
-
+
+
- {{ t('Choose your first view') }}
-
- {{ launcher?.description ?? DESCRIPTION }}
+ {{ t(TITLES[step - 1]) }}
+ {{ t(TITLES[step - 1]) }}
+ {{ t(LEADS[step - 1]) }}
-
- {{ launcher?.status ?? FIRST_RUN_TIP }}
+
diff --git a/src/ui/visualSettings.js b/src/ui/visualSettings.js
index e9ad998d50..1e2efbf6c0 100644
--- a/src/ui/visualSettings.js
+++ b/src/ui/visualSettings.js
@@ -73,6 +73,7 @@ export class VisualSettings {
bloomVersion,
sharpenIntensity,
hudVariant,
+ hudSonar,
hudVisible,
detectionMode,
detectionDensity,
@@ -122,7 +123,8 @@ export class VisualSettings {
this._setSharpenIntensity(sharpenIntensity, { syncShare: false });
if (typeof bloom === 'boolean') this._setBloomEnabled(bloom);
if (typeof sharpen === 'boolean') this._setSharpenEnabled(sharpen);
- if (hudVariant) this._setHudVariant(hudVariant, { restore: true });
+ if (hudVariant)
+ this._setHudVariant(hudVariant, { restore: true, sonar: hudSonar });
if (typeof hudVisible === 'boolean') {
this.hud.setMode(hudVisible ? 'on' : 'off');
this._updateHudButtonState();
@@ -719,15 +721,21 @@ export class VisualSettings {
/**
* @param {string} variantName Layout, or the removed `cyber` layout.
- * @param {{restore?: boolean}} [options] A share link, scene or saved view
- * is authoritative for Sonar too: it is on only when the state names
- * Cyber. Other callers leave Sonar as the viewer set it.
+ * @param {{restore?: boolean, sonar?: boolean}} [options] A share link,
+ * scene or saved view is authoritative for Sonar too: it is on only when
+ * the state names Cyber or says `sonar: true`, so a state that does not
+ * mention Sonar turns it off unless it names Cyber. Other callers leave
+ * Sonar as the viewer set it.
*/
- _setHudVariant(variantName, { restore = false } = {}) {
+ _setHudVariant(
+ variantName,
+ { restore = false, sonar: sonarOn = false } = {},
+ ) {
if (!variantName) return;
// Cyber was removed; its sonar became a visual style. A state that names
// Cyber opens in Tactical with Sonar on.
- const sonar = isLegacySonarHudLayout(variantName);
+ const sonar =
+ isLegacySonarHudLayout(variantName) || (restore && sonarOn === true);
if (sonar || (restore && isCyberSonarEnabled()))
this._setCyberSonarEnabled(sonar);
this.hud.setVariant(variantName);
@@ -761,8 +769,8 @@ export class VisualSettings {
/**
* The HUD layout a share link or scene shot records. Tactical with Sonar on
- * is written as the retired Cyber code, which restores exactly that; Minimal
- * has no such code, so its Sonar stays local.
+ * is written as the retired Cyber code, which restores exactly that and
+ * which older readers understand too.
*/
_sharedHudVariant() {
const variant = this.hud.getVariant();
@@ -771,6 +779,17 @@ export class VisualSettings {
: variant;
}
+ /**
+ * Whether a share link or scene shot records Sonar on beside its layout:
+ * only when the layout code does not already say so (Minimal with Sonar),
+ * so a state with Tactical and Sonar stays the Cyber code alone.
+ */
+ _sharedHudSonar() {
+ return (
+ isCyberSonarEnabled() && !isLegacySonarHudLayout(this._sharedHudVariant())
+ );
+ }
+
_setCyberSonarSetting(name, value) {
const settings = readCyberSonarSettings();
if (!Object.hasOwn(settings, name)) return settings;
@@ -919,6 +938,7 @@ export class VisualSettings {
bloomVersion: BLOOM_SCALE_VERSION,
sharpenIntensity: this._sharpenPct,
hudVariant: this._sharedHudVariant(),
+ hudSonar: this._sharedHudSonar(),
hudVisible: this.hud.visible,
detectionMode: detection.mode,
detectionDensity: detection.densityPct,
@@ -1237,6 +1257,9 @@ export class VisualSettings {
hud: {
visible: this.hud.visible,
variant: this._sharedHudVariant(),
+ // Written only when on beside a layout that cannot say it, so a shot
+ // without Sonar or with Tactical and Sonar reads in older builds.
+ ...(this._sharedHudSonar() ? { sonar: true } : {}),
},
detection: {
mode: getDetectionMode(),
@@ -1284,7 +1307,10 @@ export class VisualSettings {
const hudState = state.hud || {};
if (hudState.variant) {
- this._setHudVariant(hudState.variant, { restore: true });
+ this._setHudVariant(hudState.variant, {
+ restore: true,
+ sonar: hudState.sonar,
+ });
}
if (typeof hudState.visible === 'boolean') {
this.hud.setMode(hudState.visible ? 'on' : 'off');
diff --git a/src/ui/wildlifeSightingCard.test.mjs b/src/ui/wildlifeSightingCard.test.mjs
index 731897a6a2..e38a6c4852 100644
--- a/src/ui/wildlifeSightingCard.test.mjs
+++ b/src/ui/wildlifeSightingCard.test.mjs
@@ -128,8 +128,10 @@ function fixture(
now: () => NOW,
overlayHost: {
setEntries: (id, entries) => overlays.set(id, entries),
- hitTest: (_x, _y, { sourceId }) =>
- hit?.sourceId === sourceId ? hit : null,
+ // As the host does: unfiltered, the topmost entry; filtered, only
+ // an entry of that source.
+ hitTest: (_x, _y, { sourceId } = {}) =>
+ hit && (!sourceId || hit.sourceId === sourceId) ? hit : null,
},
input: () => ({
onClick(fn) {
@@ -138,6 +140,8 @@ function fixture(
},
}),
focus: { requestWorldFocus: (value) => flights.push(value) },
+ // The card on top at a click, as the registry answers from the host.
+ picking: { clickCard: () => hit },
},
parts: {
rendering: { refreshSelection() {}, requestRender() {} },
diff --git a/src/voice/analystAccessors.test.mjs b/src/voice/analystAccessors.test.mjs
index 05d9cd9735..ff50cba6cb 100644
--- a/src/voice/analystAccessors.test.mjs
+++ b/src/voice/analystAccessors.test.mjs
@@ -194,7 +194,6 @@ test('cyclones flatten the storm position and stay empty while off', async () =>
ownsPickId: () => false,
getDiagnostics: () => ({}),
}),
- hitTestOverlay: () => null,
});
const viewer = {
scene: { canvas: new EventTarget(), pick: () => null },
diff --git a/src/worldFocus.js b/src/worldFocus.js
index af50b2f30b..8cecfa955b 100644
--- a/src/worldFocus.js
+++ b/src/worldFocus.js
@@ -18,6 +18,10 @@ export const WORLD_FOCUS_FRAMING = Object.freeze({
// A stopped train's one fly-to, and the frame a moving train is followed
// in (src/layers/rail/follow.js): the train and the track either side.
train: Object.freeze({ radiusM: 200, rangeM: 2500, pitchDeg: -35 }),
+ // A clicked quake's magnitude label: its disc (2^M km in radius, so about
+ // 6 km at M2.5 and 64 km at M6) and the ground around it. A larger quake
+ // passes its own radius and range (never less than these).
+ earthquake: Object.freeze({ radiusM: 20000, rangeM: 220000, pitchDeg: -45 }),
'sighting-area': Object.freeze({
radiusM: 11000,
rangeM: 60000,
@@ -85,7 +89,8 @@ export function routeWorldFocusRequest(event, runExplicitFocus, fly) {
* `keepView` (a click on it) keeps the camera's distance and angle: the eye
* moves, on a straight path, to where it sees the target in the centre with
* the view it has now (`keptViewFrom`). Any other is framed by its kind
- * (`WORLD_FOCUS_FRAMING`).
+ * (`WORLD_FOCUS_FRAMING`); a target's own `rangeM`, past the framed radius,
+ * stands the camera off that far instead (a target larger than its kind).
*/
export function flyToWorldTarget(viewer, target = {}) {
const camera = findCamera(viewer);
@@ -112,13 +117,25 @@ export function flyToWorldTarget(viewer, target = {}) {
target.durationSec > 0
? target.durationSec
: WORLD_CLICK_FOCUS_DURATION_SEC;
+ // A target may ask for a wider sphere than its kind's framing (a large
+ // quake's disc), never a narrower one.
+ const atLeast = (value, floor) =>
+ Number.isFinite(value) && value > floor ? value : floor;
camera.flyToBounds(
- { center: target.position, radius: framing.radiusM },
+ {
+ center: target.position,
+ radius: atLeast(target.radiusM, framing.radiusM),
+ },
{
offset: {
heading,
pitch: toRadians(framing.pitchDeg),
- range: framing.rangeM,
+ // A target's own range past the framed radius replaces the kind's.
+ range:
+ Number.isFinite(target.rangeM) &&
+ target.rangeM > atLeast(target.radiusM, framing.radiusM)
+ ? target.rangeM
+ : framing.rangeM,
},
durationS: duration,
easing: 'cubicInOut',
diff --git a/src/worldFocus.test.mjs b/src/worldFocus.test.mjs
index 2f90c5b6f9..f266610cc0 100644
--- a/src/worldFocus.test.mjs
+++ b/src/worldFocus.test.mjs
@@ -206,9 +206,52 @@ test('fires frame wider than vessels — a fire is read by its surroundings', ()
);
});
+// A large quake's disc does not fit the earthquake framing, so the target
+// asks for more room; it never gets less than the framing.
+test('a target can widen its framing sphere, never narrow it', () => {
+ const fly = (extra) => {
+ const camera = stubCamera();
+ flyToWorldTarget(bindFakeCesiumCamera({ camera }), {
+ kind: 'earthquake',
+ id: 'earthquake:us1',
+ position: POSITION,
+ ...extra,
+ });
+ return camera.calls.flights[0];
+ };
+ const m72 = fly({ radiusM: 147000, rangeM: 514000 });
+ assert.equal(m72.sphere.radius, 147000);
+ assert.equal(m72.options.offset.range, 514000);
+ const m3 = fly({ radiusM: 8000 });
+ assert.equal(m3.sphere.radius, WORLD_FOCUS_FRAMING.earthquake.radiusM);
+ assert.equal(m3.options.offset.range, WORLD_FOCUS_FRAMING.earthquake.rangeM);
+ const bad = fly({ radiusM: NaN, rangeM: -1 });
+ assert.equal(bad.options.offset.range, WORLD_FOCUS_FRAMING.earthquake.rangeM);
+});
+
+test("a target's own range stands the camera off that far, past the framed radius", () => {
+ const range = (rangeM) => {
+ const camera = stubCamera();
+ flyToWorldTarget(bindFakeCesiumCamera({ camera }), {
+ kind: 'fire',
+ id: 'fire-1',
+ position: POSITION,
+ rangeM,
+ });
+ const { sphere, options } = camera.calls.flights[0];
+ assert.equal(sphere.radius, WORLD_FOCUS_FRAMING.fire.radiusM);
+ return options.offset.range;
+ };
+ assert.equal(range(24_000), 24_000);
+ // Inside the framed sphere, or not a number: the kind's own range.
+ for (const value of [WORLD_FOCUS_FRAMING.fire.radiusM, 0, -5, NaN, '9000'])
+ assert.equal(range(value), WORLD_FOCUS_FRAMING.fire.rangeM);
+});
+
test('every framing is a real oblique standoff, not a nadir or an inside-out sphere', () => {
const kinds = Object.keys(WORLD_FOCUS_FRAMING);
assert.deepEqual(kinds.sort(), [
+ 'earthquake',
'fire',
'sighting',
'sighting-area',
@@ -232,8 +275,10 @@ test('every framing is a real oblique standoff, not a nadir or an inside-out sph
framing.rangeM > framing.radiusM,
`${kind}: range ${framing.rangeM} must stand off outside radius ${framing.radiusM}`,
);
- // An obscured sighting frames its entire 0.2° privacy cell.
- const maximumRange = kind === 'sighting-area' ? 60000 : 10000;
+ // An obscured sighting frames its entire 0.2° privacy cell, and a quake
+ // its disc, up to 128 km across at M6.
+ const maximumRange =
+ { 'sighting-area': 60000, earthquake: 250000 }[kind] ?? 10000;
assert.ok(
framing.rangeM <= maximumRange,
`${kind}: range must fit its surface extent, got ${framing.rangeM}`,