Merge pull request #1826 from bilawalsidhu/manjunath/space-missions-layer

Make Space Missions an ordinary layer with its own panel
This commit is contained in:
Sameh Khamis authored and GitHub committed 2026-11-18 16:16:01 -08:00
commit 46e831620e
104 files changed
+4156 -1981

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
- Space Missions moves out of the Context panel into its own right-rail panel,
with its own tab on phones, and becomes an ordinary layer. It no longer
switches other layers off or refuses them while it runs, and Context leaves
it and Satellites alone, so it runs beside Contacts in either order
(Contacts no longer switches Satellites off). On desktop, opening Context or
Space Missions collapses the other. Mission labels on the globe are
clickable and select their mission, even where they sit over aircraft or
ships, and picking a mission on the globe opens the panel. The Data Layers
row gets previous and next mission controls. Share links keep the panel
open or closed (a short link made from an older long link, which does not
mention the panel, is two bytes longer), voice can open it, and Cockpit
folds it away like the other map panels. An explicit user or voice
Satellites off request made after Space Missions was switched on ends it
and keeps Satellites off afterwards; scene, story, preset and other
programmatic Satellites changes leave Space Missions running
(manjunath22466, samehkhamis, #1826).
+53 -54
View File
@@ -935,10 +935,10 @@ the header narrows every list. Expanded, Context becomes a full-height
column at the right edge (the left edge right to left) and the map credits
stop short of it.
The Contacts and Space Missions modes and the Radio strip stay in the
panel's main tab, below the card. When Contacts follows the aircraft the
card shows, its list sits inside the card. Turning Radio or Launches on
opens Context. The Properties tab holds the Labels and 3D aircraft
The Contacts mode and the Radio strip stay in the panel's main tab, below
the card. When Contacts follows the aircraft the card shows, its list sits
inside the card. Turning Radio on opens Context. Space Missions is not part
of Context: turning it on opens its own Space Missions panel. The Properties tab holds the Labels and 3D aircraft
settings from Visual while a layer they act on is on.
Context does its reading only while its panel is open. Weather and news
@@ -2861,13 +2861,23 @@ them.
## Context coordination
Context controls own Contacts/Space Missions state, entry and exit transactions,
layer snapshots and restoration. The application supplies the existing manager,
Context controls own Contacts state, entry and exit transactions, layer
snapshots and restoration. Space Missions is an ordinary layer outside this
owner: the launches layer keeps its own Satellites dependency
(`src/layers/launches/satelliteIntents.js`), and `SpaceMissionsControls`
(`src/ui/spaceMissionsControls.js`) connects it to its panel and store. The application supplies the existing manager,
installations search and camera/panel actions. Tab listeners and pending
presentation work stop during disposal; layer restoration retains its existing
compensation and latest-intent rules. Clear Selected Layers shares this owner,
so an older restore cannot replay over a newer Clear action.
Contacts leaves Satellites on. Contacts is being removed, so no new Contacts
behavior is added here. Only an explicit user or voice Satellites OFF requested
after Space Missions ON ends Space Missions. A scene, story, preset or other
programmatic Satellites OFF leaves Space Missions running: an automatic change
must not undo the user’s explicit choice, and the mission lifecycle remains
independent of Satellites.
## Camera panel ownership
CCTV controls receive the existing camera port and explicit application actions.
@@ -2884,7 +2894,7 @@ The panel opens when a camera becomes active and collapses when the layer is
switched off, from its own switch or anywhere else. The panel chrome applies
the collapse, so a panel the desktop accordion only folded has its saved and
shared state closed too. Clear selected data layers and Context isolation
(Contacts, Space Missions) switch the layer off without the user asking: the
(Contacts) switch the layer off without the user asking: the
panel and its share preference stay as they are, and the layer comes back to an
open panel. Only the switch-off isolation makes counts (`suspendsLayer`, true
while `_clearLayersOutsideContextMode` switches the layer off): the user
@@ -3356,8 +3366,7 @@ and military aircraft and vessels share this rule; fine pointers stay exact.
Manually opening Context with a tracked civilian or military aircraft enters
the existing Contacts mode when Context is off. Contacts adopts that aircraft
without restarting its tracking; an active or entering Space Missions mode is
left alone. Programmatic sheet changes and closing the tab do not activate a mode.
without restarting its tracking. Programmatic sheet changes and closing the tab do not activate a mode.
Sheets borrow panels. Opening one expands its panels without persisting them or
claiming a user choice, and share links keep reporting each borrowed panel's
@@ -3840,9 +3849,9 @@ they do not reduce the materialized entity count or establish an FPS gain.
- Display controls and shader-parameter sliders show keyboard focus in both
the map panel and Cockpit Display. Arrow keys retain native range adjustment.
The enabled CCTV camera dropdown shows keyboard focus as well.
- Tab reaches both Contacts and Space Missions in sequence in every Context
state. Left/Right arrows also switch them; the focused tab has a distinct ring
even when selected.
- Tab reaches the Contacts control in Context and the separate Space Missions
rail button when launches are enabled. Both keep a visible focus ring when
active.
- Keyboard focus on a Space Missions roster item uses the same temporary globe
rotation and mission-marker highlight as pointer hover. Focus alone does not
select the mission; Enter or Space performs selection. Keyboard and pointer
@@ -4546,16 +4555,10 @@ a number`, exactly `(0,0,0)` returns undefined, and a near-center value such
> cannot slip through by not matching the older spelling. CCTV's
> `selectedCameraId` is the one recorded keep: it raises a monitor plane and
> never writes `viewer.trackedEntity` or the camera.
> (4) An **isolating Context mode is exited before a shot's layers apply**.
> Space Missions refuses every enable outside its replay bundle, so with it
> left dirty all five recipes were refused (or, for Orbital Watch, composed
> over a replay they never declared). The verdict is read off the shared guard
> (`contextLayerEnableBlockReason`), not a mode name, so a future isolating
> mode is covered — the probe id `SCENE_EXCLUSIVITY_PROBE_LAYER_ID` is
> reserved by a test against the real layer registry. The exit itself is the
> ordinary `setContextMode('off')` exact-restore path and is deliberately NOT
> abortable: leaving the mode IS the restore to the operator's pre-mode state,
> and tearing that transaction in half would strand Context. A refused
> (4) Playback leaves every Context mode alone. No mode isolates the globe
> any more (Space Missions is an ordinary layer), so the former exit of an
> isolating mode before a shot's layers apply, and its probe layer id, were
> removed with it. A refused
> `setEnabled` is surfaced in the status line and a `shot_layers_refused`
> telemetry event instead of being reported as success. **Mixed accepted /
> refused layers are reported honestly, not rolled back** — a shot whose
@@ -4876,10 +4879,10 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
> selected manager-owned data layers, including an active Context choice,
> while retaining visual, HUD, map, and panel settings. A disabled layer may
> still release camera work that it owns through its normal teardown.
> Direct Data Layers entry into Space Missions excludes the new mission ON
> intent from its pre-entry snapshot. Its OFF control therefore leaves Space
> Missions off and restores Satellites to their exact pre-entry visibility
> and parameter state.
> Space Missions is an ordinary layer and opens no Context session. Its OFF
> control leaves Space Missions off and restores Satellites to their
> pre-mission visibility and parameter state, keeping an explicit Satellites
> action taken while it ran.
> The title and loading logos use a blue 10 px outer-eye stroke with a
> translucent slate fill, while the globe-and-cage gaze travels up to 34 SVG
> units toward the pointer for clearer feedback at the compact title size.
@@ -4887,11 +4890,12 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with
> clock goes live and the camera flies to the view the app started from (the
> host's `homeView`, else its `startView`, else the whole planet), letting go
> of whatever it follows as Reset Globe does (`returnToStart()`).
> - **Context, Cockpit, and Radio interaction contract:** explicit Contacts,
> Space Missions, and successful Cockpit actions reveal the Context panel, while
> restoration and replay preserve its prior collapsed state. Contacts uses the
> dedicated right-side chooser; the underlying Global Context coordinator is
> registered for lifecycle and restoration but is not duplicated in Data Layers.
> - **Context, Cockpit, and Radio interaction contract:** explicit Contacts and
> Radio actions and successful Cockpit actions can reveal Context. Contacts
> uses the dedicated right-side chooser. Space Missions has its own rail
> button and panel while launches are enabled.
> Mission teardown clears the selection shown in the panel before restoring
> the Satellites layer, so a failed restore leaves no stale mission details.
> Inside Cockpit, the focused summary card is titled Contact in both visible
> copy and its accessible control labels.
> The top-center Cockpit vision cycle is the fixed, duplicate-free sequence
@@ -5585,9 +5589,10 @@ activeCameraCardEnabled: true })` may publish it through the retained
> pitch/heading instruments, altitude/speed tapes, and the signal window.
> Topline vision and exit controls retain the highest in-cockpit layer.
> - **Space Missions dependency shutdown:** disabling a mission dependency or
> leaving the mode closes mission context and restores the exact pre-entry
> Satellite enabled state and presentation parameters. Restored parameters
> never re-show primitives while the Satellite layer is disabled.
> 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.
> - **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`
@@ -5628,17 +5633,13 @@ activeCameraCardEnabled: true })` may publish it through the retained
> only for the synchronous selection window, history survives same-layer
> reselection, and NEXT availability uses the same UNKNOWN-cohort gate as the
> navigation action. Contacts entry does not wait for unrelated serialized
> layer teardown; Space Missions waits for every incompatible live/current
> layer to settle off before replay data starts. A rejected teardown keeps
> that layer authoritatively enabled, restores any siblings already stopped,
> and aborts replay entry; the isolation
> guard remains active until Rocket Launches finishes enabling. Manually enabling
> layer teardown. (Space Missions isolation, which waited for incompatible
> layers to settle off, was later removed: Space Missions is now an ordinary
> layer.) Manually enabling
> another Data Layer is additive in both an active mode and the neutral shell:
> it does not exit Context, and the added layer joins the pre-entry snapshot
> when the session is eventually restored. Manually disabling a required mode
> dependency still exits and restores that union.
> While Space Missions is active, direct incompatible enables are refused
> before initialization or polling and explain that the mode must be exited.
> User entry alone owns the pre-entry snapshot; programmatic dependencies do
> not replace it, and rapid re-entry snapshots the pending settled restore
> target rather than partial manager state.
@@ -5694,10 +5695,8 @@ activeCameraCardEnabled: true })` may publish it through the retained
> enabled-layer set and every runtime parameter it changes, then clears
> unrelated active Data Layers. Mode switches, required-dependency disables, direct
> disable, and teardown restore that pre-entry state before control leaves
> Context. Directly switching between Flights and Space Missions remains
> supported without losing the original snapshot. Contacts waits for the
> dependency releases it owns before restoring that snapshot, so the first
> Space Missions selection completes without a stale teardown superseding it.
> Context. Contacts waits for the dependency releases it owns before
> restoring that snapshot.
> - **Space Mission horizon occlusion:** mission dots and hover reticles apply
> their surface-anchor horizon state before Cesium draws or picks the frame,
> while shared-host labels use the same hidden-globe horizon contract. Rear-side
@@ -6419,9 +6418,9 @@ start where the label would round to 10.0 km, so a 9.96 km route displays as
**Keys needed: none.** Directions works on a keyless boot, and the layer is off
until the operator turns it on.
**Context behavior.** Directions is not a Context layer: neither Contacts nor
Space Missions reads it, depends on it, or lists it as a companion. It is
therefore one of the layers an exclusive Context mode switches off on entry
**Context behavior.** Directions is not a Context layer: Contacts does not
read it, depend on it, or list it as a companion. It is therefore one of the
layers the exclusive Contacts mode switches off on entry
(`_clearLayersOutsideContextMode`) and restores on exit, like every other
non-participating layer — the route and both endpoints are cleared with it, and
placing them again is the way back. Cockpit does not touch the layer either,
@@ -6747,8 +6746,8 @@ Required empty or unexercised checks fail acceptance. The passing final line is
cannot claim full acceptance.
**Lifecycle and proxy.** Contacts temporarily disables Transit and restores its
prior state on exit; Space Missions refuses enablement while isolating replay
data. Cockpit does not need Contacts and does not independently enable Transit.
prior state on exit; Space Missions, an ordinary layer, leaves Transit as it
is. Cockpit does not need Contacts and does not independently enable Transit.
The proxy fetches registered URLs only, validates redirect origins, bounds
responses and decoding, caches successful snapshots, and backs off after failed
refreshes. A 304 confirms contact without appending history. Missing vehicles
@@ -7328,14 +7327,14 @@ silently demoting every later lookup for the session.
### Context / Contacts coordinator (July 2026)
- The internal Context coordinator is available in every visual style. Its dedicated right-side `CONTEXT` chooser exposes the neutral shell; the coordinator is not duplicated in Data Layers and does not enable a live-data dependency until a mode is selected.
- The expanded `CONTEXT` view offers mutually exclusive `CONTACTS` and `SPACE MISSIONS` modes. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled; selecting `SPACE MISSIONS` enables the recent-launch layer and its Satellite dependency. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies.
- The expanded `CONTEXT` view offers the `CONTACTS` mode. Selecting `CONTACTS` enables the context-owned Flights, Military Flights, AIS Vessels, and Mapped Installations dependencies only when they are not already user-enabled. Space Missions is not a Context mode: it is the ordinary recent-launch layer with its own panel, and it runs beside Contacts. `CONTACTS` cycles the nearest supported contact of whatever type is selected. Satellites are deliberately excluded from those Awareness cohorts and keep their own tracking UX. Selecting the active mode again returns to the neutral chooser and releases only mode-owned dependencies.
- If a civilian or military aircraft is already tracked when `CONTACTS` becomes operational, that source-owned track is adopted as the Context subject before nearest-contact autofocus. Context rechecks the tracker after its dependencies settle, so a newer selection wins, while an explicit clear during activation prevents fallback from silently selecting a replacement. Cockpit entry remains unavailable until that Context transaction has settled, so its camera takeover cannot clear Cesium tracking before adoption. Adoption does not recreate tracking or transfer camera ownership; it initializes the normal 250 km ring, history, proximity results, and Cockpit Previous/Next state for the original aircraft. With no tracked aircraft, an AIS vessel already selected (the vessel layer's `getSelectedInfo()`) becomes the subject, at activation and again when a deferred dependency settles, exactly as a vessel selected while `CONTACTS` is on; no nearest flight is picked and the camera is not moved.
- `SEARCH NEARBY SITES` retains the bounded OSM results and makes one user-initiated, view-biased Google Maps Places text search for “military installation.” Google results are source-stamped, deduplicated against OSM by rounded location/name, and remain mapped context rather than operational claims. If Places is unavailable or the API is not enabled for the supplied key, OSM context remains available. A view across the antimeridian is searched around its own centre, with a radius from its real width.
- The Context header holds only its title and collapse control. It no longer carries a Radio shortcut or a compact Radio player: Radio is the `RADIO` section inside the panel, with its own disclosure and the single `ENABLE` power control. Cockpit keeps its own compact Radio utility.
- 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 replay-isolated: Rocket Launches and Satellites are the only Data Layers permitted while the mode is active. Direct UI and voice entry capture the same pre-entry snapshot; internal dependency and restoration enables do not create a user-owned Context session. Entry waits for incompatible layers to shut down, direct incompatible enables are blocked before lifecycle work, and the entry gate remains active through the complete Rocket Launches enable. That enable includes the first mission-index load: an HTTP error, timeout, network failure or malformed payload before any index has loaded fails the enable, so Context rolls back to the pre-entry layers instead of committing an empty, isolating mode; 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 enters, and a refresh failure after an index loaded keeps its records and the mode. Exiting cancels the layer's own camera flights but never one navigation started. A newer same-target ON request takes ownership of the pending entry without releasing its isolation snapshot, including when it arrives while the prior request is awaiting the adoption guard. A caller abort, resource cancellation, newer OFF, or layer teardown waits for exact manager settlement and restores that snapshot without resurrecting Rocket Launches. If an abort lands after only part of a restore settles, Context completes the same exact target without the stale caller signal and then replays newer explicit layer intent. Dedicated Voice Context cancellation reports a stable cancelled result plus the current Context state; generic layer visibility additionally exposes manager phase, reason, successor, and lifecycle details. Once an exact voice visibility intent commits, a newer voice turn cannot relabel it as cancelled while Context settlement completes; pre-commit aborts remain cancellable and final lifecycle mismatches remain failures. Clear Selected Layers reserves its complete captured OFF set before sequential teardown; a newer absolute request of any origin supersedes only its layer reservation and remains authoritative. A rejected layer teardown retains the truthful enabled state, rolls already-stopped siblings back to the captured pre-entry set, and aborts replay; rapid exit/re-entry serializes the full Satellite enabled-state and parameter restore before a new snapshot is taken. Contacts remains additive and restores user-enabled layers normally.
- 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.
- 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.
@@ -7492,8 +7491,8 @@ 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 selects the unified right-side Context panel's Space Missions mode and enables the required satellite layer. 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 either Context or the left Data Layers rail 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. Selecting a mission isolates its launch-to-orbit transfer and dashed satellite orbit, fills that same panel with navigation/details, 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; its text is non-interactive shared-host presentation. 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,Line truncated
When no mission is selected, the Context 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.
- **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 valLine truncated
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.
Close selected-pad views add one static 500 m-radius cyan launch-zone ring with a low-opacity translucent fill over the sampled photoreal launch-site surface. The single scene primitive is created only for the visible selected site and is otherwise dormant. It appears during Focus, sufficiently close manual zoom, and the replay countdown, but is suppressed above 120 km camera altitude, beyond 180 km direct camera-to-pad range, for unselected missions, and whenever Space Missions is inactive. Focus establishes a launch-site-centered camera transform once; subsequent manual heading and pitch changes remain centered on that site without an automated per-frame correction. Surface mission markers and labels use an additional conservative globe-limb margin before the exact ellipsoid occluder boundary, preventing near-horizon visibility from alternating between frames.
+1
View File
@@ -282,6 +282,7 @@ reserved: a decoder ignores that entry, as for collapsed 0.
| 8 | `global-context-panel` | `g` | collapsed |
| 9 | `pp-toggles` | `p` | collapsed |
| 10 | `param-slider-panel` | `m` | expanded |
| 11 | `space-missions-panel` | `n` | collapsed |
### Style parameters (field 27)
+7
View File
@@ -297,6 +297,9 @@
"src/ui/contextControls.js",
"src/ui/contextControls.test.mjs",
"src/ui/contextLayerChanges.js",
"src/ui/spaceMissionsControls.js",
"src/ui/spaceMissionsControls.test.mjs",
"src/ui/stores/spaceMissions.js",
"src/ui/contextPresentation.js",
"src/ui/contextSession.js",
"src/ui/contextSubscriptions.js",
@@ -521,6 +524,10 @@
"src/layers/launches/source.test.mjs",
"src/layers/launches/ingestion.test.mjs",
"src/layers/launches/failedEntry.test.mjs",
"src/layers/launches/labelClick.test.mjs",
"src/layers/launches/missionCycler.test.mjs",
"src/layers/launches/satelliteIntents.js",
"src/layers/launches/satelliteIntents.test.mjs",
"src/layers/installations/lifecycle.js",
"src/layers/installations/viewport.js",
"src/layers/installations/controls.js",
+9
View File
@@ -130,6 +130,7 @@
"src/ui/radioTunerModel.js",
"src/ui/views/panels/MissionDetail.vue",
"src/ui/views/panels/MissionRoster.vue",
"src/ui/views/panels/SpaceMissionsPanel.vue",
"src/ui/views/panels/AwarenessPanel.vue",
"src/ui/views/panels/AwarenessNames.vue",
"src/ui/views/DisplayControlsView.vue",
@@ -163,6 +164,7 @@
"src/ui/stores/cctv.js",
"src/ui/stores/radio.js",
"src/ui/stores/context.js",
"src/ui/stores/spaceMissions.js",
"src/ui/stores/cockpit.js",
"src/ui/stores/locale.js",
"src/ui/stores/providerSettings.js",
@@ -1449,6 +1451,7 @@
"src/ui/contextSession.js",
"src/ui/contextSubscriptions.js",
"src/ui/contextTransactions.js",
"src/ui/spaceMissionsControls.js",
"src/ui/displayControls.js",
"src/ui/effects.js",
"src/ui/frameRateMonitor.js",
@@ -1577,6 +1580,7 @@
"src/ui/stores/cctv.js",
"src/ui/stores/radio.js",
"src/ui/stores/context.js",
"src/ui/stores/spaceMissions.js",
"src/ui/stores/cockpit.js",
"src/ui/stores/locale.js",
"src/ui/stores/providerSettings.js",
@@ -2875,6 +2879,7 @@
"src/data/entityRecords.js",
"src/render/cesium/follow.js",
"src/layers/launches/ingestion.js",
"src/layers/launches/satelliteIntents.js",
"src/layers/launches/launchPad.js",
"src/layers/launches/lifecycle.js",
"src/layers/launches/model.js",
@@ -4534,6 +4539,7 @@
"src/layers/launches/controls.js",
"src/layers/launches/index.js",
"src/layers/launches/ingestion.js",
"src/layers/launches/satelliteIntents.js",
"src/layers/launches/launchPad.js",
"src/layers/launches/lifecycle.js",
"src/layers/launches/model.js",
@@ -4765,6 +4771,7 @@
"src/ui/contextSession.js",
"src/ui/contextSubscriptions.js",
"src/ui/contextTransactions.js",
"src/ui/spaceMissionsControls.js",
"src/ui/displayControls.js",
"src/ui/effects.js",
"src/ui/frameRateMonitor.js",
@@ -5327,6 +5334,7 @@
"src/ui/stores/cctv.js",
"src/ui/stores/radio.js",
"src/ui/stores/context.js",
"src/ui/stores/spaceMissions.js",
"src/ui/stores/cockpit.js",
"src/ui/stores/locale.js",
"src/ui/stores/providerSettings.js",
@@ -5815,6 +5823,7 @@
"src/layers/launches/controls.js",
"src/layers/launches/index.js",
"src/layers/launches/ingestion.js",
"src/layers/launches/satelliteIntents.js",
"src/layers/launches/launchPad.js",
"src/layers/launches/lifecycle.js",
"src/layers/launches/model.js",
+108 -290
View File
@@ -193,41 +193,74 @@ try {
});
const contactMissionHandoff = await page.evaluate(async () => {
const { styleManager, dataManager } = window.__godsEyeView;
// Launch Library is not contacted: the layer's own work is stubbed so the
// check covers only how Space Missions sits beside Context.
const stubMissions = (rocketEntry) => {
const original = {
initialized: rocketEntry.initialized,
lifecycleState: rocketEntry.lifecycleState,
init: rocketEntry.module.init,
enable: rocketEntry.module.enable,
update: rocketEntry.module.update,
disable: rocketEntry.module.disable,
};
rocketEntry.initialized = true;
rocketEntry.module.init = async () => true;
rocketEntry.module.enable = async () => true;
rocketEntry.module.update = async () => true;
rocketEntry.module.disable = async () => true;
return () => {
rocketEntry.initialized = original.initialized;
rocketEntry.lifecycleState = original.lifecycleState;
rocketEntry.module.init = original.init;
rocketEntry.module.enable = original.enable;
rocketEntry.module.update = original.update;
rocketEntry.module.disable = original.disable;
};
};
const originalShowToast = styleManager._showToast;
const toasts = [];
styleManager._showToast = (message) => { toasts.push(String(message)); };
const restoreMissions = stubMissions(dataManager.layers.get('rocket-launches'));
try {
if (styleManager._contextControls._contextMode) await styleManager._contextControls._selectContextMode(null);
const contactsResult = await styleManager._contextControls._selectContextMode('flights');
const missionResult = await styleManager._contextControls._selectContextMode('space-missions');
const switched = {
const missionResult = await dataManager.setEnabled('rocket-launches', true, { origin: 'user' });
await styleManager._waitForContextLayerSettlement();
const together = {
contactsResult,
missionResult,
mode: styleManager._contextControls._contextMode,
missionsEnabled: dataManager.isEnabled('rocket-launches'),
toasts: [...toasts],
};
const missionOff = await dataManager.setEnabled('rocket-launches', false, { origin: 'user' });
await styleManager._waitForContextLayerSettlement();
const modeAfterMissions = styleManager._contextControls._contextMode;
const exitResult = await styleManager._contextControls._selectContextMode(null);
return {
...switched,
...together,
missionOff,
modeAfterMissions,
exitResult,
modeAfterExit: styleManager._contextControls._contextMode,
missionsOffAfterExit: !dataManager.isEffectivelyEnabled('rocket-launches'),
};
} finally {
restoreMissions();
styleManager._showToast = originalShowToast;
}
});
check(
'Contacts hands off to Space Missions on the first request without a failure toast',
'Space Missions runs beside Contacts, and switching it off leaves Contacts on',
contactMissionHandoff.contactsResult === true
&& contactMissionHandoff.missionResult === true
&& contactMissionHandoff.mode === 'space-missions'
&& contactMissionHandoff.mode === 'flights'
&& contactMissionHandoff.missionsEnabled
&& contactMissionHandoff.toasts?.length === 0
&& contactMissionHandoff.missionOff === true
&& contactMissionHandoff.modeAfterMissions === 'flights'
&& contactMissionHandoff.exitResult === true
&& contactMissionHandoff.modeAfterExit === null
&& contactMissionHandoff.missionsOffAfterExit,
&& contactMissionHandoff.modeAfterExit === null,
JSON.stringify(contactMissionHandoff),
);
const cancelledMissionEntry = await page.evaluate(async () => {
@@ -330,7 +363,7 @@ try {
}
});
check(
'cancelled direct Space Missions entry restores its exact isolated sibling state',
'a cancelled Space Missions start leaves its sibling layer on and opens no Context session',
cancelledMissionEntry.exercised
&& cancelledMissionEntry.transitionResult === false
&& !cancelledMissionEntry.timedOut
@@ -341,214 +374,45 @@ try {
JSON.stringify(cancelledMissionEntry),
);
check(
'successful Space Missions cancellation rollback stays silent',
'a cancelled Space Missions start stays silent',
cancelledMissionEntry.exercised && cancelledMissionEntry.toasts?.length === 0,
JSON.stringify(cancelledMissionEntry.toasts || []),
);
const replacementMissionEntry = await page.evaluate(async () => {
const styleManager = window.__godsEyeView.styleManager;
const dataManager = window.__godsEyeView.dataManager;
const rocketEntry = dataManager.layers.get('rocket-launches');
if (!rocketEntry || dataManager.isEffectivelyEnabled('rocket-launches')) {
return { exercised: false, reason: 'Space Missions was not in a clean OFF state' };
}
const siblingId = 'qa-cockpit-replacement-sibling';
window.__gevQaRegisterLayer(dataManager, {
id: siblingId,
name: 'QA replacement sibling',
icon: 'science',
source: 'QA',
updateInterval: -1,
async init() { return true; },
async enable() { return true; },
async update() { return true; },
async disable() { return true; },
async destroy() {},
getStats() { return { count: 1, status: 'live' }; },
});
await dataManager.setEnabled(siblingId, true, { origin: 'programmatic' });
const original = {
siblingInitialized: dataManager.layers.get(siblingId)?.initialized,
initialized: rocketEntry.initialized,
lifecycleState: rocketEntry.lifecycleState,
init: rocketEntry.module.init,
enable: rocketEntry.module.enable,
update: rocketEntry.module.update,
disable: rocketEntry.module.disable,
showToast: styleManager._showToast,
};
let firstUpdate = true;
let releaseUpdate;
let markUpdateStarted;
const updateStarted = new Promise((resolve) => { markUpdateStarted = resolve; });
const updateGate = new Promise((resolve) => { releaseUpdate = resolve; });
const toasts = [];
rocketEntry.initialized = true;
rocketEntry.module.enable = async () => true;
rocketEntry.module.update = async () => {
if (!firstUpdate) return true;
firstUpdate = false;
markUpdateStarted();
await updateGate;
return true;
};
rocketEntry.module.disable = async () => true;
styleManager._showToast = (message) => { toasts.push(String(message)); };
try {
const entry = styleManager._contextControls._selectContextMode('space-missions');
await updateStarted;
const replacement = dataManager.setEnabled('rocket-launches', true, { origin: 'programmatic' });
releaseUpdate();
const [entryResult, replacementResult] = await Promise.all([entry, replacement]);
const committed = {
entryResult,
replacementResult,
mode: styleManager._contextControls._contextMode,
entering: styleManager._contextControls._contextModeEntering,
snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot),
siblingIsolated: !dataManager.isEffectivelyEnabled(siblingId),
missionEnabled: dataManager.isEnabled('rocket-launches'),
missionEffective: dataManager.isEffectivelyEnabled('rocket-launches'),
toasts: [...toasts],
};
const exitResult = await styleManager._contextControls._selectContextMode(null);
return {
exercised: true,
...committed,
exitResult,
siblingRestored: dataManager.isEnabled(siblingId),
missionRestoredOff: !dataManager.isEffectivelyEnabled('rocket-launches'),
};
} finally {
styleManager._showToast = original.showToast;
rocketEntry.module.init = original.init;
rocketEntry.module.enable = original.enable;
rocketEntry.module.update = original.update;
rocketEntry.module.disable = original.disable;
rocketEntry.initialized = original.initialized;
rocketEntry.lifecycleState = original.lifecycleState;
await dataManager.setEnabled(siblingId, false, { origin: 'programmatic' });
await window.__gevQaUnregisterLayer(dataManager, siblingId);
}
});
check(
'right-rail Space Missions adopts a newer authoritative ON without stale restoration',
replacementMissionEntry.exercised
&& replacementMissionEntry.entryResult === true
&& replacementMissionEntry.replacementResult === true
&& replacementMissionEntry.mode === 'space-missions'
&& replacementMissionEntry.entering === null
&& replacementMissionEntry.snapshotRetained
&& replacementMissionEntry.siblingIsolated
&& replacementMissionEntry.missionEnabled
&& replacementMissionEntry.missionEffective
&& replacementMissionEntry.toasts?.length === 0
&& replacementMissionEntry.exitResult === true
&& replacementMissionEntry.siblingRestored
&& replacementMissionEntry.missionRestoredOff,
JSON.stringify(replacementMissionEntry),
);
const supersededMissionEntry = await page.evaluate(async () => {
const styleManager = window.__godsEyeView.styleManager;
const dataManager = window.__godsEyeView.dataManager;
const rocketEntry = dataManager.layers.get('rocket-launches');
if (!rocketEntry || dataManager.isEffectivelyEnabled('rocket-launches')) {
return { exercised: false, reason: 'Space Missions was not in a clean OFF state' };
}
const siblingId = 'qa-cockpit-superseded-sibling';
window.__gevQaRegisterLayer(dataManager, {
id: siblingId,
name: 'QA superseded sibling',
icon: 'science',
source: 'QA',
updateInterval: -1,
async init() { return true; },
async enable() { return true; },
async update() { return true; },
async disable() { return true; },
async destroy() {},
getStats() { return { count: 1, status: 'live' }; },
});
await dataManager.setEnabled(siblingId, true, { origin: 'programmatic' });
const original = {
initialized: rocketEntry.initialized,
lifecycleState: rocketEntry.lifecycleState,
init: rocketEntry.module.init,
enable: rocketEntry.module.enable,
update: rocketEntry.module.update,
disable: rocketEntry.module.disable,
showToast: styleManager._showToast,
};
let releaseUpdate;
let markUpdateStarted;
const updateStarted = new Promise((resolve) => { markUpdateStarted = resolve; });
const updateGate = new Promise((resolve) => { releaseUpdate = resolve; });
const toasts = [];
rocketEntry.initialized = true;
rocketEntry.module.enable = async () => true;
rocketEntry.module.update = async () => {
markUpdateStarted();
await updateGate;
return true;
};
rocketEntry.module.disable = async () => true;
styleManager._showToast = (message) => { toasts.push(String(message)); };
try {
const entry = styleManager._runUserFacingContextAction(
(notificationToken) => styleManager._contextControls._selectContextMode(
'space-missions',
{ notificationToken },
),
'Space Missions could not complete the requested transition; try again',
);
await updateStarted;
const supersedingOff = dataManager.setEnabled('rocket-launches', false, {
origin: 'programmatic',
});
releaseUpdate();
const [entryResult, offResult] = await Promise.all([entry, supersedingOff]);
return {
exercised: true,
entryResult,
offResult,
mode: styleManager._contextControls._contextMode,
entering: styleManager._contextControls._contextModeEntering,
snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot),
siblingRestored: dataManager.isEnabled(siblingId),
missionEffective: dataManager.isEffectivelyEnabled('rocket-launches'),
toasts,
};
} finally {
styleManager._showToast = original.showToast;
rocketEntry.module.init = original.init;
rocketEntry.module.enable = original.enable;
rocketEntry.module.update = original.update;
rocketEntry.module.disable = original.disable;
rocketEntry.initialized = original.initialized;
rocketEntry.lifecycleState = original.lifecycleState;
await dataManager.setEnabled(siblingId, false, { origin: 'programmatic' });
await window.__gevQaUnregisterLayer(dataManager, siblingId);
}
});
check(
'right-rail Space Missions superseded by OFF restores exactly without a failure toast',
supersededMissionEntry.exercised
&& supersededMissionEntry.entryResult === null
&& supersededMissionEntry.mode === null
&& supersededMissionEntry.entering === null
&& !supersededMissionEntry.snapshotRetained
&& supersededMissionEntry.siblingRestored
&& !supersededMissionEntry.missionEffective
&& supersededMissionEntry.toasts?.length === 0,
JSON.stringify(supersededMissionEntry),
);
const voiceMissionEntry = await page.evaluate(async () => {
const ordinaryMissionLayer = await page.evaluate(async () => {
const { dataManager, styleManager } = window.__godsEyeView;
const siblingId = '__qa_voice_context_sibling__';
const rocketEntry = dataManager.layers.get('rocket-launches');
if (!rocketEntry || dataManager.isEffectivelyEnabled('rocket-launches')) {
return { exercised: false, reason: 'Space Missions was not in a clean OFF state' };
}
// Launch Library is not contacted: the layer's own work is stubbed so the
// check covers only how Space Missions sits beside Context.
const stubMissions = (rocketEntry) => {
const original = {
initialized: rocketEntry.initialized,
lifecycleState: rocketEntry.lifecycleState,
init: rocketEntry.module.init,
enable: rocketEntry.module.enable,
update: rocketEntry.module.update,
disable: rocketEntry.module.disable,
};
rocketEntry.initialized = true;
rocketEntry.module.init = async () => true;
rocketEntry.module.enable = async () => true;
rocketEntry.module.update = async () => true;
rocketEntry.module.disable = async () => true;
return () => {
rocketEntry.initialized = original.initialized;
rocketEntry.lifecycleState = original.lifecycleState;
rocketEntry.module.init = original.init;
rocketEntry.module.enable = original.enable;
rocketEntry.module.update = original.update;
rocketEntry.module.disable = original.disable;
};
};
const siblingId = '__qa_space_missions_sibling__';
window.__gevQaRegisterLayer(dataManager, {
id: siblingId,
name: 'QA voice Context sibling',
name: 'QA Space Missions sibling',
icon: 'science',
source: 'QA',
updateInterval: -1,
@@ -559,94 +423,48 @@ try {
async destroy() {},
getStats() { return { count: 1, status: 'live' }; },
});
const original = {
initialized: rocketEntry.initialized,
lifecycleState: rocketEntry.lifecycleState,
init: rocketEntry.module.init,
enable: rocketEntry.module.enable,
update: rocketEntry.module.update,
disable: rocketEntry.module.disable,
};
const siblingLayerEntry = dataManager.layers.get(siblingId);
siblingLayerEntry.initialized = true;
await dataManager.setEnabled(siblingId, true, { origin: 'programmatic' });
rocketEntry.initialized = true;
rocketEntry.module.init = async () => true;
rocketEntry.module.enable = async () => true;
rocketEntry.module.update = async () => true;
rocketEntry.module.disable = async () => true;
const restoreMissions = stubMissions(rocketEntry);
try {
const voiceOn = await dataManager.setEnabled('rocket-launches', true, { origin: 'voice' });
await new Promise((resolve) => setTimeout(resolve, 80));
const voiceState = {
voiceOn,
mode: styleManager._contextControls._contextMode,
entering: styleManager._contextControls._contextModeEntering,
snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot),
siblingIsolated: !dataManager.isEffectivelyEnabled(siblingId),
};
const snapshotBeforeOff = [...(styleManager._contextControls._contextSessionSnapshot?.enabledLayerIds || [])];
const voiceOff = await dataManager.setEnabled('rocket-launches', false, { origin: 'voice' });
const reactionCountAfterOff = styleManager._contextControls._contextLayerReactionPromises.size;
await styleManager._waitForContextLayerSettlement();
const restoredSiblingEntry = dataManager.layers.get(siblingId);
const voiceExit = {
voiceOff,
snapshotBeforeOff,
reactionCountAfterOff,
mode: styleManager._contextControls._contextMode,
entering: styleManager._contextControls._contextModeEntering,
snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot),
siblingRestored: dataManager.isEffectivelyEnabled(siblingId),
siblingEnabled: restoredSiblingEntry?.enabled,
siblingLifecycle: restoredSiblingEntry?.lifecycleState,
restoreActive: Boolean(styleManager._contextControls._contextRestoreState),
};
await dataManager.setEnabled('rocket-launches', true, { origin: 'programmatic' });
await new Promise((resolve) => setTimeout(resolve, 40));
const internalState = {
mode: styleManager._contextControls._contextMode,
entering: styleManager._contextControls._contextModeEntering,
snapshotRetained: Boolean(styleManager._contextControls._contextSessionSnapshot),
missionEnabled: dataManager.isEffectivelyEnabled('rocket-launches'),
};
await dataManager.setEnabled('rocket-launches', false, { origin: 'programmatic' });
return { exercised: true, voiceState, voiceExit, internalState };
const results = {};
for (const origin of ['user', 'voice', 'programmatic']) {
const on = await dataManager.setEnabled('rocket-launches', true, { origin });
await styleManager._waitForContextLayerSettlement();
const during = {
on,
mode: styleManager._contextControls._contextMode,
snapshot: Boolean(styleManager._contextControls._contextSessionSnapshot),
siblingOn: dataManager.isEffectivelyEnabled(siblingId),
};
const off = await dataManager.setEnabled('rocket-launches', false, { origin });
await styleManager._waitForContextLayerSettlement();
results[origin] = {
...during,
off,
siblingOnAfter: dataManager.isEffectivelyEnabled(siblingId),
snapshotAfter: Boolean(styleManager._contextControls._contextSessionSnapshot),
};
}
return { exercised: true, results };
} finally {
rocketEntry.module.init = original.init;
rocketEntry.module.enable = original.enable;
rocketEntry.module.update = original.update;
rocketEntry.module.disable = original.disable;
rocketEntry.initialized = original.initialized;
rocketEntry.lifecycleState = original.lifecycleState;
restoreMissions();
await dataManager.setEnabled(siblingId, false, { origin: 'programmatic' });
siblingLayerEntry.initialized = original.siblingInitialized;
await window.__gevQaUnregisterLayer(dataManager, siblingId);
}
});
check(
'voice Space Missions uses the same Context snapshot and exact-restore transaction as UI entry',
voiceMissionEntry.exercised
&& voiceMissionEntry.voiceState?.voiceOn
&& voiceMissionEntry.voiceState.mode === 'space-missions'
&& voiceMissionEntry.voiceState.entering === null
&& voiceMissionEntry.voiceState.snapshotRetained
&& voiceMissionEntry.voiceState.siblingIsolated
&& voiceMissionEntry.voiceExit?.voiceOff
&& voiceMissionEntry.voiceExit.mode === null
&& voiceMissionEntry.voiceExit.entering === null
&& !voiceMissionEntry.voiceExit.snapshotRetained
&& voiceMissionEntry.voiceExit.siblingRestored,
JSON.stringify(voiceMissionEntry),
);
check(
'internal programmatic Space Missions activation does not create a user Context session',
voiceMissionEntry.internalState?.missionEnabled
&& voiceMissionEntry.internalState.mode === null
&& voiceMissionEntry.internalState.entering === null
&& !voiceMissionEntry.internalState.snapshotRetained,
JSON.stringify(voiceMissionEntry),
'Space Missions is an ordinary layer: no Context session, no isolation, from any origin',
ordinaryMissionLayer.exercised
&& Object.values(ordinaryMissionLayer.results || {}).length === 3
&& Object.values(ordinaryMissionLayer.results).every((entry) =>
entry.on === true
&& entry.mode === null
&& !entry.snapshot
&& entry.siblingOn
&& entry.off === true
&& entry.siblingOnAfter
&& !entry.snapshotAfter),
JSON.stringify(ordinaryMissionLayer),
);
await page.evaluate(() => window.__godsEyeView.dataManager.setEnabled(
'flights',
+2 -2
View File
@@ -307,8 +307,8 @@ const MUTATIONS = [
{
defect: 'a cancelled globe flight fails the whole mission',
file: 'module',
from: ' .catch(() => null);',
to: ' .catch(() => { throw new Error("flight failed"); });',
from: ' .catch(() => null)\n : null;',
to: ' .catch(() => { throw new Error("flight failed"); })\n : null;',
},
{
defect: 'Explore manually quietly runs a mission instead of nothing',
+12 -2
View File
@@ -662,8 +662,18 @@ async function main() {
await open(page, { query: "?welcome=1", errorSink: consoleErrors });
await pick(page, 'space-missions');
state = await appState(page);
record('SPACE MISSIONS activates its context mode', state.contextMode === 'space-missions',
`contextMode=${state.contextMode}`);
const missions = await page.evaluate(() => {
const panel = document.getElementById('space-missions-panel');
return {
layerOn: window.__godsEyeView.dataManager.isEffectivelyEnabled('rocket-launches'),
panelOpen: !!panel && !panel.hidden && !panel.classList.contains('collapsed'),
};
});
record('SPACE MISSIONS switches its layer on without a Context mode',
missions.layerOn && state.contextMode == null,
`layerOn=${missions.layerOn} contextMode=${state.contextMode}`);
record('SPACE MISSIONS opens its own panel', missions.panelOpen,
`panelOpen=${missions.panelOpen}`);
shots.push(await shoot(page, 'mission-space-missions'));
});
+9 -11
View File
@@ -845,7 +845,7 @@ async function main() {
params: {},
};
let failureUsed = false;
const entryLayerId = mode === 'flights' ? 'military-awareness' : 'rocket-launches';
const entryLayerId = 'military-awareness';
dataManager.setEnabled = async (layerId, shouldEnable) => {
const failsIsolation = phase === 'isolation' && layerId === 'local-datacenters' && !shouldEnable;
const failsActivation = phase === 'activation' && layerId === entryLayerId && shouldEnable;
@@ -872,7 +872,6 @@ async function main() {
priorLayerRestored: enabled.has('local-datacenters'),
entryEnabled: enabled.has(entryLayerId),
flightsButtonDisabled: document.getElementById('global-context-flights-btn').disabled,
missionsButtonDisabled: document.getElementById('global-context-missions-btn').disabled,
message: document.getElementById('toast').textContent,
};
};
@@ -893,7 +892,7 @@ async function main() {
}
};
const contextFailures = [];
for (const mode of ['flights', 'space-missions']) {
for (const mode of ['flights']) {
for (const phase of ['isolation', 'activation']) {
for (const outcome of ['false', 'reject']) {
contextFailures.push(await runContextFailure(mode, phase, outcome));
@@ -902,7 +901,7 @@ async function main() {
}
const directEntryFailures = [];
for (const layerId of ['military-awareness', 'rocket-launches']) {
for (const layerId of ['military-awareness']) {
for (const outcome of ['false', 'reject']) {
enabled.clear();
enabled.add('local-datacenters');
@@ -971,7 +970,7 @@ async function main() {
styleManager._showToast = originalShowToast;
const directActivationFailures = [];
for (const layerId of ['military-awareness', 'rocket-launches']) {
for (const layerId of ['military-awareness']) {
enabled.clear();
styleManager._contextControls._contextMode = null;
styleManager._contextControls._contextSessionSnapshot = {
@@ -1001,7 +1000,7 @@ async function main() {
}
const directActivationRollbackFailures = [];
for (const layerId of ['military-awareness', 'rocket-launches']) {
for (const layerId of ['military-awareness']) {
enabled.clear();
styleManager._contextControls._contextMode = null;
styleManager._contextControls._contextSessionSnapshot = {
@@ -1211,7 +1210,7 @@ async function main() {
check(
'user-facing chip, real Context entry rollback, and installation Search failures settle safely',
userFacingFailures.semanticFalseMessage === 'Radio could not stop cleanly'
&& userFacingFailures.contextFailures.length === 8
&& userFacingFailures.contextFailures.length === 4
&& userFacingFailures.contextFailures.every((failure) => (
failure.result === false
&& failure.visibleMode === null
@@ -1219,10 +1218,9 @@ async function main() {
&& failure.priorLayerRestored
&& !failure.entryEnabled
&& !failure.flightsButtonDisabled
&& !failure.missionsButtonDisabled
&& failure.message.includes('QA transition failed')
))
&& userFacingFailures.directEntryFailures.length === 4
&& userFacingFailures.directEntryFailures.length === 2
&& userFacingFailures.directEntryFailures.every((failure) => (
failure.reason.includes('could not start')
&& failure.retryReason === null
@@ -1233,14 +1231,14 @@ async function main() {
&& failure.priorLayerRestored
&& !failure.modeChanging
))
&& userFacingFailures.directActivationFailures.length === 2
&& userFacingFailures.directActivationFailures.length === 1
&& userFacingFailures.directActivationFailures.every((failure) => (
failure.mode === null
&& failure.snapshotCleared
&& failure.priorLayerRestored
&& failure.failedLayerDisabled
))
&& userFacingFailures.directActivationRollbackFailures.length === 2
&& userFacingFailures.directActivationRollbackFailures.length === 1
&& userFacingFailures.directActivationRollbackFailures.every((failure) => (
failure.toastMessages.length === 1
&& failure.toastMessages[0] === `${failure.layerId} could not start cleanly`
+17 -17
View File
@@ -1980,16 +1980,19 @@ try {
await wait(12_000);
check('leaving Contacts restores Transit', await isOn());
// SPACE MISSIONS
await page.evaluate(() =>
window.__godsEyeView.dataManager.setEnabled('transit', false, {
origin: 'user',
}),
);
await wait(2_000);
await page.click('#global-context-missions-btn');
// SPACE MISSIONS: an ordinary layer. It neither refuses nor puts away
// Transit, so a Transit switched on while it runs stays on after it ends.
const setMissions = (enabled) =>
page.evaluate(
(on) =>
window.__godsEyeView.dataManager.setEnabled('rocket-launches', on, {
origin: 'user',
}),
enabled,
);
await setMissions(true);
await wait(20_000);
const blocked = await page.evaluate(async () => {
const beside = await page.evaluate(async () => {
const settled = await window.__godsEyeView.dataManager.setEnabled(
'transit',
true,
@@ -2001,16 +2004,13 @@ try {
};
});
check(
'Space Missions refuses to enable Transit while it isolates replay data',
blocked.enabled === false,
JSON.stringify(blocked),
'Transit can be switched on while Space Missions runs',
beside.settled !== false && beside.enabled === true,
JSON.stringify(beside),
);
await page.click('#global-context-missions-btn');
await setMissions(false);
await wait(12_000);
check(
'leaving Space Missions leaves Transit off, as it was on entry',
(await isOn()) === false,
);
check('switching Space Missions off leaves Transit on', await isOn());
check(
'no uncaught page errors',
+5 -3
View File
@@ -680,6 +680,7 @@ test('fresh Cockpit entry temporarily collapses map panels and exit restores the
'scene-panel',
'pp-toggles',
'global-context-panel',
'space-missions-panel',
'radio-panel',
]) {
assert.match(
@@ -1261,14 +1262,15 @@ test('Global Context uses its dedicated right rail without a duplicate Data Laye
);
assert.match(html, /id="global-context-panel"/);
assert.match(html, /id="global-context-flights-btn"/);
assert.match(html, /id="global-context-missions-btn"/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
assert.match(html, /id="space-missions-panel"/);
});
test('Global Context standby describes both chooser modes', () => {
test('Global Context standby describes Contacts', () => {
const match = html.match(/<div id="context-mode-standby"[\s\S]*?<\/div>/);
assert.ok(match, 'Global Context standby is missing');
assert.match(match[0], /CONTACTS — nearest planes · vessels · sites/);
assert.match(match[0], /SPACE MISSIONS — launches &amp; orbital assets/);
assert.doesNotMatch(match[0], /SPACE MISSIONS/);
});
test('cockpit briefing cycle control keeps its state as the accessible name', () => {
+19 -106
View File
@@ -1,5 +1,3 @@
import { msg } from './i18n/marker.js';
const CONTEXT_DEPENDENCIES = Object.freeze({
flights: new Set([
'military-awareness',
@@ -8,15 +6,18 @@ const CONTEXT_DEPENDENCIES = Object.freeze({
'ais-live-vessels',
'military-installations',
]),
'space-missions': new Set(['rocket-launches', 'satellites']),
});
const CONTEXT_COMPANIONS = new Set(['radio']);
/** The Space Missions refusal, with the blocked layer's name as {layer}. */
export const SPACE_MISSIONS_LAYER_BLOCK_REASON = msg(
'Space Missions isolates replay data. Exit the mode to enable {layer}.',
);
const [BLOCK_REASON_PREFIX, BLOCK_REASON_SUFFIX] =
SPACE_MISSIONS_LAYER_BLOCK_REASON.split('{layer}');
/**
* Layers Context never touches: Space Missions and the Satellites layer it
* depends on. Contacts neither switches them off on entry nor restores them
* on exit, so they run beside it in either order and keep their own state
* (the mission controller owns the Satellites dependency).
*/
export const CONTEXT_INDEPENDENT_LAYER_IDS = Object.freeze([
'rocket-launches',
'satellites',
]);
/** Return whether an origin represents a direct user choice on this route. */
export function isExplicitUserIntentOrigin(origin, layerId = null) {
return origin === 'user' || origin === 'voice';
@@ -27,7 +28,8 @@ export function recordContextRestoreExplicitChange({ restoreState, change }) {
if (
!restoreState?.enabledLayerIds ||
change?.type !== 'visibility' ||
!isExplicitUserIntentOrigin(change.origin, change.layerId)
!isExplicitUserIntentOrigin(change.origin, change.layerId) ||
CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId)
)
return false;
if (!restoreState.explicitLayerStates)
@@ -121,10 +123,7 @@ export async function settleUserFacingContextAction({
* one into `userAdded` makes exit restoration re-enable the mode layer the
* user just turned off.
*/
export const CONTEXT_ENTRY_LAYER_IDS = Object.freeze([
'military-awareness',
'rocket-launches',
]);
export const CONTEXT_ENTRY_LAYER_IDS = Object.freeze(['military-awareness']);
/**
* Leave a Context transaction: publish the settled coordination flag, then
@@ -193,7 +192,8 @@ export function shouldExitContextForLayerChange({
change?.type !== 'visibility' ||
!isExplicitUserIntentOrigin(change.origin, change.layerId) ||
change.layerId === 'military-awareness' ||
CONTEXT_COMPANIONS.has(change.layerId)
CONTEXT_COMPANIONS.has(change.layerId) ||
CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId)
) {
return false;
}
@@ -215,6 +215,7 @@ export function contextAllowedLayerIds(contextMode) {
return new Set([
...(CONTEXT_DEPENDENCIES[contextMode] || ['military-awareness']),
...CONTEXT_COMPANIONS,
...CONTEXT_INDEPENDENT_LAYER_IDS,
]);
}
@@ -235,21 +236,6 @@ export function shouldCaptureContextSession(change) {
);
}
/**
* Return whether one explicit mission intent superseded an in-flight Clear All
* reservation and therefore needs deferred Context adoption.
*/
export function shouldDeferContextEntryDuringClear({ change, clearInFlight }) {
return Boolean(
clearInFlight &&
change?.type === 'visibility-requested' &&
change.layerId === 'rocket-launches' &&
change.enabled === true &&
isExplicitUserIntentOrigin(change.origin, change.layerId) &&
Number.isInteger(change.intentEpoch),
);
}
/**
* Bookkeep a user-owned layer change against the active Context session so
* exit restoration can honor layers the user added mid-session. Two rules
@@ -273,7 +259,8 @@ export function recordContextSessionUserChange({
if (
!snapshot?.userAdded ||
change?.type !== 'visibility' ||
!isExplicitUserIntentOrigin(change.origin, change.layerId)
!isExplicitUserIntentOrigin(change.origin, change.layerId) ||
CONTEXT_INDEPENDENT_LAYER_IDS.includes(change.layerId)
) {
return false;
}
@@ -319,83 +306,10 @@ export function contextSnapshotLayerIds(
) {
const snapshot = new Set(restoringLayerIds || currentEnabledLayerIds || []);
for (const layerId of excludeLayerIds || []) snapshot.delete(layerId);
for (const layerId of CONTEXT_INDEPENDENT_LAYER_IDS) snapshot.delete(layerId);
return snapshot;
}
/**
* Block layers that would mix unrelated live/current data into Space Missions.
* The manager calls this before lifecycle work so a refused layer never starts.
* @param {object} input Current mode and requested visibility transition.
* @param {string|null} input.contextMode Active Context mode.
* @param {object|null} input.change Requested visibility transition.
* @param {string|null} [input.layerName] User-facing layer name.
* @returns {string|null} Honest user-facing refusal reason, or null when allowed.
*/
export function contextLayerEnableBlockReason({
contextMode,
change,
layerName = null,
}) {
if (
contextMode !== 'space-missions' ||
change?.enabled !== true ||
contextAllowedLayerIds('space-missions').has(change.layerId)
) {
return null;
}
const label = String(layerName || change.layerId || 'that layer');
return SPACE_MISSIONS_LAYER_BLOCK_REASON.replace('{layer}', label);
}
/**
* The layer name from a Space Missions refusal, so the UI can rebuild the
* sentence in its language.
* @param {string} reason
* @returns {{layer: string}|null} The blocked layer's name, or null when the
* reason is not a Space Missions refusal.
*/
export function parseContextLayerBlockReason(reason) {
if (
typeof reason !== 'string' ||
!reason.startsWith(BLOCK_REASON_PREFIX) ||
!reason.endsWith(BLOCK_REASON_SUFFIX) ||
reason.length <= BLOCK_REASON_PREFIX.length + BLOCK_REASON_SUFFIX.length
)
return null;
return {
layer: reason.slice(
BLOCK_REASON_PREFIX.length,
reason.length - BLOCK_REASON_SUFFIX.length,
),
};
}
/**
* Resolve who owns a cancelled direct Space Missions entry. A newer ON keeps
* the entry shell reserved for its replacement transaction; every other
* cancellation must roll back the isolated pre-entry session.
*
* @param {object} input Cancellation and current manager intent state.
* @param {object|null} input.change Manager visibility notification.
* @returns {'ignore'|'replacement'|'restore'} Cancellation disposition.
*/
export function spaceMissionEntryCancellationDisposition({ change }) {
if (
change?.type !== 'visibility-cancelled' ||
change.layerId !== 'rocket-launches' ||
change.enabled !== true
)
return 'ignore';
if (
change.cancellationReason === 'superseded' &&
Number.isInteger(change.successorIntentEpoch) &&
change.successorIntentEpoch > change.intentEpoch &&
change.successorEnabled === true
)
return 'replacement';
return 'restore';
}
/**
* Merge the pre-entry layer snapshot with layers the user enabled during the
* Context session so both survive restoration.
@@ -510,7 +424,6 @@ export function subjectEntryAllowed({
*/
export const CONTEXT_MODE_VOICE_NAMES = Object.freeze({
flights: 'contacts',
'space-missions': 'space-missions',
});
/**
+63 -111
View File
@@ -5,7 +5,6 @@ import {
orbitEntryAllowed,
cockpitEntryAllowed,
contextAllowedLayerIds,
contextLayerEnableBlockReason,
contextRestoreLayerIds,
isExplicitUserIntentOrigin,
mergeContextTransitionErrors,
@@ -17,9 +16,7 @@ import {
settleContextIntentReplay,
settleUserFacingContextAction,
shouldCaptureContextSession,
shouldDeferContextEntryDuringClear,
shouldExitContextForLayerChange,
spaceMissionEntryCancellationDisposition,
} from './contextModePolicy.js';
test('Context transition errors preserve primary identity and aggregate failed layers', () => {
@@ -119,11 +116,6 @@ test('user-enabled layers are additive and do not exit Context', () => {
globalContextEnabled: true,
change: userEnable('earthquakes'),
}), false);
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
globalContextEnabled: false,
change: userEnable('traffic'),
}), false);
assert.equal(shouldExitContextForLayerChange({
contextMode: null,
globalContextEnabled: true,
@@ -133,48 +125,16 @@ test('user-enabled layers are additive and do not exit Context', () => {
test('programmatic Context dependencies and direct mode setup remain allowed', () => {
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
contextMode: 'flights',
globalContextEnabled: true,
change: { ...userEnable('satellites'), origin: 'programmatic' },
change: { ...userEnable('military'), enabled: false, origin: 'programmatic' },
}), false);
});
test('Space Missions cancellation retains only a newer authoritative ON entry', () => {
const cancelledEntry = {
type: 'visibility-cancelled',
layerId: 'rocket-launches',
enabled: true,
intentEpoch: 8,
cancellationReason: 'superseded',
successorIntentEpoch: 9,
successorEnabled: true,
successorOrigin: 'programmatic',
};
assert.equal(spaceMissionEntryCancellationDisposition({
change: cancelledEntry,
}), 'replacement');
assert.equal(spaceMissionEntryCancellationDisposition({
change: { ...cancelledEntry, successorEnabled: false },
}), 'restore', 'a newer OFF releases the entry shell');
assert.equal(spaceMissionEntryCancellationDisposition({
change: {
...cancelledEntry,
cancellationReason: 'caller-abort',
successorIntentEpoch: undefined,
successorEnabled: undefined,
},
}), 'restore', 'caller abort at the same epoch restores the isolated session');
assert.equal(spaceMissionEntryCancellationDisposition({
change: { ...cancelledEntry, enabled: false },
currentIntentEpoch: 9,
effectivelyEnabled: true,
}), 'ignore');
});
test('only explicit user-owned shell enables capture a Context restoration snapshot', () => {
const userMissionEnable = {
type: 'visibility-requested',
layerId: 'rocket-launches',
layerId: 'military-awareness',
enabled: true,
origin: 'user',
};
@@ -186,40 +146,25 @@ test('only explicit user-owned shell enables capture a Context restoration snaps
assert.equal(shouldCaptureContextSession({ ...userMissionEnable, origin: 'context-restore' }), false);
assert.equal(shouldCaptureContextSession({ ...userMissionEnable, enabled: false }), false);
assert.equal(shouldCaptureContextSession({ ...userMissionEnable, layerId: 'satellites' }), false);
assert.equal(
shouldCaptureContextSession({ ...userMissionEnable, layerId: 'rocket-launches' }),
false,
'Space Missions is an ordinary layer, not a Context entry',
);
});
test('voice dependency OFF exits Space Missions like the equivalent UI action', () => {
test('voice dependency OFF exits Contacts like the equivalent UI action', () => {
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
contextMode: 'flights',
globalContextEnabled: false,
change: { type: 'visibility', layerId: 'satellites', enabled: false, origin: 'voice' },
change: { type: 'visibility', layerId: 'flights', enabled: false, origin: 'voice' },
}), true);
});
test('only a newer explicit mission request is deferred during Clear All', () => {
const change = {
type: 'visibility-requested',
layerId: 'rocket-launches',
enabled: true,
origin: 'voice',
intentEpoch: 12,
};
assert.equal(shouldDeferContextEntryDuringClear({ change, clearInFlight: true }), true);
assert.equal(shouldDeferContextEntryDuringClear({ change, clearInFlight: false }), false);
assert.equal(shouldDeferContextEntryDuringClear({
change: { ...change, origin: 'programmatic' },
clearInFlight: true,
}), false);
assert.equal(shouldDeferContextEntryDuringClear({
change: { ...change, enabled: false },
clearInFlight: true,
}), false);
});
test('a rapid re-entry snapshots the settled restore target, not partial manager state', () => {
assert.deepEqual(
[...contextSnapshotLayerIds(
new Set(['rocket-launches', 'earthquakes']),
new Set(['cctv', 'earthquakes']),
new Set(['flights', 'traffic']),
)],
['flights', 'traffic'],
@@ -230,31 +175,15 @@ test('a rapid re-entry snapshots the settled restore target, not partial manager
);
assert.deepEqual(
[...contextSnapshotLayerIds(
new Set(['rocket-launches', 'satellites']),
new Set(['military-awareness', 'cctv']),
null,
['rocket-launches'],
['military-awareness'],
)],
['satellites'],
['cctv'],
'the synchronous entry intent is not part of the pre-entry snapshot',
);
});
test('Space Missions blocks unrelated layer enables before replay data can mix', () => {
const change = { layerId: 'flights', enabled: true, origin: 'user' };
assert.match(
contextLayerEnableBlockReason({ contextMode: 'space-missions', change, layerName: 'Live Flights' }),
/Exit the mode to enable Live Flights/,
);
assert.equal(contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { ...change, layerId: 'satellites' },
}), null);
assert.equal(contextLayerEnableBlockReason({
contextMode: 'flights',
change,
}), null, 'live cockpit keeps additive user layers');
});
test('the Global Context shell and layers selected while Context is off remain allowed', () => {
assert.equal(shouldExitContextForLayerChange({
contextMode: null,
@@ -275,14 +204,38 @@ test('manually disabling a mode dependency exits that Context bundle', () => {
change: { ...userEnable('military'), enabled: false },
}), true);
assert.equal(shouldExitContextForLayerChange({
contextMode: 'space-missions',
contextMode: 'flights',
globalContextEnabled: false,
change: { ...userEnable('satellites'), enabled: false },
}), true);
}), false, 'Satellites is not a Contacts dependency');
});
test('Context never isolates, snapshots, restores or bookkeeps Space Missions and Satellites', () => {
for (const layerId of ['rocket-launches', 'satellites']) {
assert.equal(contextAllowedLayerIds('flights').has(layerId), true);
const snapshot = { userAdded: new Set(), userRemoved: new Set() };
for (const enabled of [true, false]) {
assert.equal(recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', origin: 'user', layerId, enabled },
effectiveContextMode: 'flights',
}), false);
const restoreState = { enabledLayerIds: new Set() };
assert.equal(recordContextRestoreExplicitChange({
restoreState,
change: { type: 'visibility', origin: 'user', layerId, enabled },
}), false);
}
assert.equal(snapshot.userAdded.size + snapshot.userRemoved.size, 0);
}
assert.deepEqual(
[...contextSnapshotLayerIds(new Set(['rocket-launches', 'satellites', 'cctv']))],
['cctv'],
);
});
test('Radio remains an independent companion across Context transitions', () => {
for (const contextMode of ['flights', 'space-missions']) {
for (const contextMode of ['flights', null]) {
for (const enabled of [true, false]) {
assert.equal(shouldExitContextForLayerChange({
contextMode,
@@ -292,21 +245,17 @@ test('Radio remains an independent companion across Context transitions', () =>
}
assert.equal(contextAllowedLayerIds(contextMode).has('radio'), true);
}
assert.equal(contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { type: 'visibility', origin: 'user', layerId: 'radio', enabled: true },
layerName: 'Radio',
}), null);
});
test('each Context mode exposes only its shell and dependencies', () => {
assert.deepEqual(
[...contextAllowedLayerIds(null)],
['military-awareness', 'radio'],
['military-awareness', 'radio', 'rocket-launches', 'satellites'],
);
assert.deepEqual(
[...contextAllowedLayerIds('space-missions')],
['rocket-launches', 'satellites', 'radio'],
['military-awareness', 'radio', 'rocket-launches', 'satellites'],
'Space Missions is not a Context mode',
);
});
@@ -332,7 +281,7 @@ test('Context restoration honors an explicit companion disable', () => {
});
test('the latest explicit Radio state wins across a Context session', () => {
for (const effectiveContextMode of [null, 'flights', 'space-missions']) {
for (const effectiveContextMode of [null, 'flights']) {
for (const origin of ['user', 'voice']) {
const snapshot = { userAdded: new Set(), userRemoved: new Set() };
const record = (enabled) => recordContextSessionUserChange({
@@ -368,7 +317,7 @@ test('only direct UI and voice origins count as explicit Context intent', () =>
assert.equal(recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', origin, layerId: 'radio', enabled: true },
effectiveContextMode: 'space-missions',
effectiveContextMode: 'flights',
}), false);
assert.equal(snapshot.userAdded.size, 0);
}
@@ -526,16 +475,8 @@ test('the teardown guard re-publishes on the way out, so a mid-flight exit is no
test('the session-starting entry layer is never bookkept as user-added (chip ON→OFF restores exactly)', () => {
const snapshot = { enabledLayerIds: new Set(['flights', 'ais-live-vessels']), userAdded: new Set() };
// The exact left-panel regression: the rockets enable event lands while the
// mode is still being entered (or even null); it must not survive its own exit.
for (const effectiveContextMode of ['space-missions', null]) {
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'rocket-launches', enabled: true, origin: 'user' },
effectiveContextMode,
});
assert.equal(snapshot.userAdded.has('rocket-launches'), false);
}
// The entry layer's enable event lands while the mode is still being
// entered; it must not survive its own exit.
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'military-awareness', enabled: true, origin: 'user' },
@@ -559,10 +500,21 @@ test('mid-session user additions are recorded, removed on disable, and judged ag
// A dependency of the mode being ENTERED is not a user addition.
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'satellites', enabled: true, origin: 'user' },
effectiveContextMode: 'space-missions',
change: { type: 'visibility', layerId: 'military', enabled: true, origin: 'user' },
effectiveContextMode: 'flights',
});
assert.equal(snapshot.userAdded.has('satellites'), false);
assert.equal(snapshot.userAdded.has('military'), false);
// Space Missions is not Context's: it is never bookkept.
recordContextSessionUserChange({
snapshot,
change: { type: 'visibility', layerId: 'rocket-launches', enabled: true, origin: 'user' },
effectiveContextMode: 'flights',
});
assert.equal(
snapshot.userAdded.has('rocket-launches'),
false,
'Space Missions is not Context state',
);
// Disabling a recorded addition removes it before any exit restore reads it.
recordContextSessionUserChange({
snapshot,
+38 -36
View File
@@ -13,10 +13,7 @@ const radioControlsSource = readRadioSource(new URL('./ui/radioControls.js', imp
// - session bookkeeping ran AFTER the exit early-return, so the compensating
// userAdded.delete never ran on the left-panel chip exit and restoration
// resurrected the mission layer the user just disabled;
// - the effective mode was read AFTER the entering flag was cleared, so the
// entry layer's own enable event was judged against a null mode;
// - a failed Space Missions START from the chip route cleared siblings with
// no rollback;
// - a failed direct Contacts START cleared siblings with no rollback;
// - the right-rail entry ignored the activation result entirely.
import { test } from 'node:test';
import assert from 'node:assert/strict';
@@ -33,25 +30,20 @@ test('context handler: session bookkeeping runs before the exit early-return', (
assert.ok(record < exit, 'bookkeeping must precede the exit check');
});
test('context handler: effective mode is read before the entering flag is cleared', () => {
const effective = handler.indexOf('this._contextModeEntering || this._contextMode');
const clear = handler.indexOf('this._contextModeEntering = null');
assert.ok(effective > 0, 'effective-mode read present');
assert.ok(clear > 0, 'entering-flag clear present');
assert.ok(effective < clear, 'effective mode must be captured first');
test('Space Missions is an ordinary layer the Context handler never enters', () => {
assert.doesNotMatch(handler, /'space-missions'/);
assert.doesNotMatch(handler, /_contextModeEntering = /);
const attach = connectContextManager.toString();
assert.doesNotMatch(attach, /rocket-launches|space-missions/);
});
test('cancelled Space Missions entry resolves ownership before settled bookkeeping', () => {
test('a cancelled visibility request returns before settled bookkeeping', () => {
const cancelled = handler.indexOf("change?.type === 'visibility-cancelled'");
const bookkeeping = handler.indexOf('recordContextSessionUserChange(');
assert.ok(cancelled > 0, 'cancellation branch present');
assert.ok(cancelled < bookkeeping, 'cancellation returns before settled session bookkeeping');
const branch = handler.slice(cancelled, handler.indexOf("change?.type === 'visibility-blocked'"));
assert.match(branch, /spaceMissionEntryCancellationDisposition\(\{/);
assert.match(branch, /cancellationDisposition === 'replacement'[\s\S]*?_contextModeEntering = 'space-missions'[\s\S]*?entryIntent\.intentEpoch === change\.intentEpoch[\s\S]*?_contextModeReplacementIntent = \{[\s\S]*?intentEpoch: change\.successorIntentEpoch/);
assert.match(branch, /cancellationDisposition === 'restore'[\s\S]*?_contextModeEntering = null/);
assert.match(branch, /_restoreContextSessionAfterLayerSettles\(/);
assert.match(branch, /return;/);
assert.match(branch, /this\._syncContextModeButtons\(\);\s*return;/);
});
test('direct Context entry captures on the synchronous request boundary', () => {
@@ -60,18 +52,29 @@ test('direct Context entry captures on the synchronous request boundary', () =>
attach,
/subscribeVisibilityRequests\(\(change\) => \{[\s\S]*?shouldCaptureContextSession\(change\)/,
);
assert.match(
attach,
/_captureContextSessionSnapshot\(\{\s*excludeLayerIds:\s*\[change\.layerId\],?\s*\}\)/,
);
});
test('Clear All defers a newer explicit mission guard until its batch settles', () => {
const attach = connectContextManager.toString();
assert.match(attach, /shouldDeferContextEntryDuringClear\(\{/);
assert.match(attach, /_contextModeDeferredEntryIntent = \{/);
assert.match(attach, /await this\._clearSelectedLayersManagerPromise/);
assert.match(attach, /await this\._clearLayersOutsideContextMode\(entryMode/);
test('only a direct Contacts entry request snapshots the layers', () => {
let request;
const controls = new ContextControls({
elements: {},
installations: {},
actions: { getCockpit: () => null },
});
const captures = [];
controls._captureContextSessionSnapshot = (options) => captures.push(options);
controls._syncContextModeButtons = () => {};
controls.connect({
subscribe: () => () => {},
subscribeVisibilityRequests(listener) {
request = listener;
return () => {};
},
});
for (const layerId of ['rocket-launches', 'military-awareness'])
request({ type: 'visibility-requested', layerId, enabled: true, origin: 'user', intentEpoch: 1 });
controls.stop();
assert.deepEqual(captures, [{ excludeLayerIds: ['military-awareness'] }]);
});
test('context restore replays explicit companion intent after the stale restore queue drains', () => {
@@ -91,7 +94,7 @@ test('context restore settles the Contacts coordinator before dependency fanout'
assert.ok(settle > 0, 'Contacts coordinator settlement is present');
assert.ok(coordinatorOff > settle, 'Contacts OFF is awaited');
assert.ok(fanout > coordinatorOff, 'snapshot fanout starts after Contacts settles');
assert.match(restore, /excludeLayerIds: settleContactsCoordinator[\s\S]*?contactsCoordinatorId/);
assert.match(restore, /excludeLayerIds: \[[\s\S]*?CONTEXT_INDEPENDENT_LAYER_IDS[\s\S]*?settleContactsCoordinator \? \[contactsCoordinatorId\]/);
});
test('Clear All during the Contacts settle stops the snapshot coming back', () => {
@@ -116,7 +119,7 @@ test('context handler: either failed direct Context-shell start rolls the sessio
handler.indexOf("change?.type === 'visibility-failed'"),
handler.indexOf("change?.type === 'visibility-will-change'"),
);
assert.match(failedBranch, /\['military-awareness', 'rocket-launches'\]\.includes\(change\.layerId\)/);
assert.match(failedBranch, /change\.layerId === 'military-awareness' &&/);
assert.match(
failedBranch,
/_restoreContextSessionAfterLayerSettles\(\s*change\.layerId,\s*\{\s*notificationToken,?\s*\},?\s*\)/,
@@ -154,14 +157,14 @@ test('wrapped visibility blocks leave the accessible toast to the wrapper token
test('every user-facing Context exit route settles through the failure surface', () => {
const initPanel = _initGlobalContextPanel.toString();
assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 3);
assert.equal((initPanel.match(/void this\._runUserFacingContextAction/g) || []).length, 2);
assert.doesNotMatch(initPanel, /falseIsFailure:\s*false/);
assert.doesNotMatch(initPanel, /void this\._selectContextMode/);
const deactivationCalls = [...handler.matchAll(
/void this\._trackContextLayerReaction\(\s*this\._runUserFacingContextAction\(\(notificationToken\) =>\s*this\._deactivateContextForLayerChange\(\{ notificationToken \}\),?\s*\),?\s*\)/g,
)];
assert.equal(deactivationCalls.length, 4, 'dependency and primary layer exits share the caught restore path');
assert.equal(deactivationCalls.length, 3, 'dependency and primary layer exits share the caught restore path');
assert.doesNotMatch(handler, /void this\._deactivateContextForLayerChange\(\)/);
});
@@ -193,10 +196,7 @@ test('right-rail context entry is transactional: activation result gates the mod
const failureBlock = select.slice(activation);
assert.match(failureBlock, /activated = await activationIntent\.promise/);
assert.match(failureBlock, /catch \(error\) \{\s*activationError = error;/);
assert.match(failureBlock, /_contextModeReplacementIntent\?\.generation === generation/);
assert.match(failureBlock, /await this\._dataManager\._waitForVisibilityIntent\?\.\(/);
assert.match(failureBlock, /outcome\?\.intentEpoch === replacementIntent\.intentEpoch[\s\S]*?outcome\.succeeded === true/);
assert.match(failureBlock, /outcome\?\.cancellationReason === 'superseded'[\s\S]*?outcome\.successorEnabled === true[\s\S]*?outcome\.successorIntentEpoch > replacementIntent\.intentEpoch/);
assert.match(failureBlock, /activationError\s*\|\|\s*activated === false\s*\|\|\s*!this\._dataManager\.isEnabled\(entryLayerId\)/);
assert.match(failureBlock, /cancelledAndSettled\s*=\s*terminalIntentOutcome\?\.succeeded === false/);
assert.match(failureBlock, /\['caller-abort', 'resource-abort', 'superseded'\]/);
@@ -216,9 +216,11 @@ test('Context entry awaits isolation and direct shell routes isolate in the visi
// rests on Context OFF; the honesty lives in the REPORT, not in a racy
// attempt to put the prior mode back (see the note above
// _restoreContextSessionAfterLayerSettles).
const capture = select.indexOf('this._captureContextSessionSnapshot(');
assert.ok(capture > 0, 'Context snapshot capture is missing');
const crossMode = select.slice(
select.indexOf('const crossModeSwitch = Boolean('),
select.indexOf('this._captureContextSessionSnapshot();'),
capture,
);
assert.ok(crossMode, 'cross-mode teardown block is missing');
assert.doesNotMatch(crossMode, /if \(signal\?\.aborted\)[\s\S]*?await this\._restoreContextSession/);
@@ -242,10 +244,10 @@ test('Context entry awaits isolation and direct shell routes isolate in the visi
assert.match(ContextControls.prototype.stop.toString(), /this\._contextModeGeneration\+\+/);
const guard = connectContextManager.toString();
assert.match(guard, /\['military-awareness', 'rocket-launches'\]\.includes\(change\.layerId\)/);
assert.match(guard, /change\.layerId !== 'military-awareness'/);
assert.match(guard, /const notificationToken\s*=\s*change\.notificationToken\s*\|\|\s*Symbol\('direct-context-shell-entry'\)/);
assert.match(guard, /this\._userFacingContextNotificationTokens\.add\(notificationToken\)/);
assert.match(guard, /await this\._clearLayersOutsideContextMode\(entryMode,\s*\{\s*notificationToken,?\s*\}\)/);
assert.match(guard, /await this\._clearLayersOutsideContextMode\(null,\s*\{\s*notificationToken,?\s*\}\)/);
assert.match(
guard,
/await this\._restoreContextSession\(\{\s*excludeLayerIds: \[change\.layerId\],\s*notificationToken,\s*\}\)/,
+39 -44
View File
@@ -2,7 +2,9 @@ import { renderApplicationHtml } from './testSupport/applicationHtml.mjs';
import { readStylesheet } from './testSupport/readStylesheet.mjs';
import { _selectContextMode } from './ui/contextTransactions.js';
import { _initGlobalContextPanel } from './ui/contextBindings.js';
import { ContextControls } from './ui/contextControls.js';
import { clearSelectedLayers } from './ui/contextActions.js';
import { PANEL_RAIL_ITEMS } from './ui/panelRailCatalog.js';
import { readFileSync as readRadioSource } from 'node:fs';
const radioBindings = readRadioSource(
new URL('./ui/radioBindings.js', import.meta.url),
@@ -21,43 +23,24 @@ const html = await renderApplicationHtml(
);
const css = readStylesheet(new URL('../style.css', import.meta.url));
test('Contacts and Space Missions both participate in the ordinary Tab sequence', () => {
for (const id of [
'global-context-flights-btn',
'global-context-missions-btn',
]) {
const button = html.match(
new RegExp(`<button id="${id}"[\\s\\S]*?</button>`),
);
assert.ok(button, `${id} is missing`);
assert.match(button[0], /role="tab"/);
assert.match(button[0], /tabindex="0"/);
}
// The view keeps both tabs' tabindex static and never disables them; the
// transition itself is covered over happy-dom in ui/contextPanel.test.mjs.
for (const id of [
'global-context-flights-btn',
'global-context-missions-btn',
]) {
const tag = contextView.match(new RegExp(`<button id="${id}"[^>]*>`))?.[0];
assert.ok(tag, `${id} is missing from the view`);
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
}
test('Contacts stays in the keyboard sequence and Space Missions owns its rail item', () => {
const button = html.match(
/<button id="global-context-flights-btn"[\s\S]*?<\/button>/,
)?.[0];
assert.ok(button, 'Contacts control is missing');
assert.match(button, /role="tab"/);
assert.match(button, /tabindex="0"/);
const tag = contextView.match(/<button id="global-context-flights-btn"[^>]*>/)?.[0];
assert.ok(tag, 'Contacts control is missing from the view');
assert.doesNotMatch(tag, /:tabindex|:disabled|\sdisabled/);
assert.doesNotMatch(html, /id="global-context-missions-btn"/);
assert.match(html, /id="space-missions-panel"[^>]*data-panel-id="space-missions-panel"/);
assert.equal(PANEL_RAIL_ITEMS['space-missions-panel'].icon, 'rocket_launch');
});
test('Context activation and Clear All never native-disable tabs and guard repeated clicks', () => {
const init = _initGlobalContextPanel.toString();
const select = _selectContextMode.toString();
const clear = clearSelectedLayers.toString();
assert.equal(
(
init.match(
/if \(\s*this\.destroyed\s*\|\|\s*this\._contextModeChanging\s*\|\|\s*this\._clearSelectedLayersPromise\s*\)\s*return;/g,
) || []
).length,
2,
);
assert.doesNotMatch(
select,
/_globalContext(?:Flights|Missions)Btn\.disabled\s*=\s*true/,
@@ -68,17 +51,29 @@ test('Context activation and Clear All never native-disable tabs and guard repea
);
});
test('Context tablist retains Left, Right, Home, and End keyboard navigation', () => {
const initSource = _initGlobalContextPanel.toString();
assert.match(initSource, /event\.key === 'ArrowRight'/);
assert.match(initSource, /event\.key === 'ArrowLeft'/);
assert.match(initSource, /event\.key === 'Home'/);
assert.match(initSource, /event\.key === 'End'/);
assert.match(
initSource,
/contextTabs\[nextIndex\]\.focus\(\{ preventScroll: true \}\)/,
);
assert.match(initSource, /contextTabs\[nextIndex\]\.click\(\)/);
test('a Contacts click while Context is busy is ignored', () => {
const button = new EventTarget();
const controls = new ContextControls({
elements: { _globalContextFlightsBtn: button },
installations: {},
actions: { getCockpit: () => null, claimVisualAuthority() {} },
});
const runs = [];
controls._runUserFacingContextAction = (operation) => {
runs.push(operation);
return Promise.resolve(false);
};
const click = () => button.dispatchEvent(new Event('click'));
controls._contextModeChanging = true;
click();
controls._contextModeChanging = false;
controls._clearSelectedLayersPromise = Promise.resolve();
click();
assert.equal(runs.length, 0, 'a transition or Clear All in flight drops it');
controls._clearSelectedLayersPromise = null;
click();
assert.equal(runs.length, 1, 'an idle panel takes the click');
controls.stop();
});
test('Context tabs draw a visible keyboard-focus outline including active tabs', () => {
@@ -102,7 +97,6 @@ test('Context tabs draw a visible keyboard-focus outline including active tabs',
});
test('Context async action buttons remain focused while busy', () => {
const init = _initGlobalContextPanel.toString();
const radio = radioBindings.slice(
radioBindings.indexOf('const toggleRadio = async (trigger) => {'),
radioBindings.indexOf('this._storeToken = this.store?.connect?.('),
@@ -113,6 +107,7 @@ test('Context async action buttons remain focused while busy', () => {
);
const clear = clearSelectedLayers.toString();
const init = _initGlobalContextPanel.toString();
assert.match(init, /if \(this\._installationsSearchBusy\) return;/);
assert.doesNotMatch(init, /\.disabled\s*=\s*true/);
const search = contextView.match(
+38
View File
@@ -1827,6 +1827,44 @@ export class LayerLifecycle {
await entry.toggleChain.catch(() => {});
}
/**
* Wait until a layer's lifecycle queue is idle, following any request that
* joins it while waiting, but no longer than `timeoutMs` or `signal` allows.
* @param {string} layerId Layer id.
* @param {{signal?: AbortSignal, timeoutMs?: number}} [options]
* @returns {Promise<boolean>} true once idle; false on timeout or abort.
*/
async waitForLayerIdle(layerId, { signal, timeoutMs = 30000 } = {}) {
const entry = this.layers.get(layerId);
if (!entry) return true;
if (signal?.aborted) return false;
let timer = null;
let onAbort = null;
const givenUp = new Promise((resolve) => {
timer = setTimeout(() => resolve(false), timeoutMs);
onAbort = () => resolve(false);
signal?.addEventListener('abort', onAbort, { once: true });
});
try {
let pending;
do {
pending = entry.toggleChain;
const idle = await Promise.race([
pending.then(
() => true,
() => true,
),
givenUp,
]);
if (!idle) return false;
} while (pending !== entry.toggleChain);
return true;
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
}
}
_reserveLayerParamsIntent(layerId, params, origin = 'programmatic') {
const entry = this.layers.get(layerId);
if (
+45 -8
View File
@@ -1503,6 +1503,43 @@ test('waitForLayerSettled defers reconciliation until the captured queue complet
await mgr.destroyAll();
});
test('waitForLayerIdle follows queued requests and gives up at its bound', async () => {
const mgr = new DataLayerManager({});
const gates = [];
const layer = makeSlowLayer('satellites', { updateInterval: 0 });
layer.module.enable = () => new Promise((resolve) => { gates.push(resolve); });
mgr.register(layer.module);
assert.equal(await mgr.waitForLayerIdle('satellites'), true, 'idle at once');
assert.equal(await mgr.waitForLayerIdle('unknown-layer'), true);
const first = mgr.setEnabled('satellites', true);
while (!gates.length) await new Promise((resolve) => setTimeout(resolve, 1));
let idle = null;
const waiting = mgr.waitForLayerIdle('satellites', { timeoutMs: 1000 })
.then((value) => { idle = value; });
// A request that joins the queue while waiting is waited for too.
const second = mgr.setEnabled('satellites', false);
gates[0]();
await Promise.all([first, second, waiting]);
assert.equal(idle, true);
// A queue that never drains returns false at the deadline or on abort.
const hung = mgr.setEnabled('satellites', true);
assert.equal(await mgr.waitForLayerIdle('satellites', { timeoutMs: 20 }), false);
const controller = new AbortController();
const aborted = mgr.waitForLayerIdle('satellites', { signal: controller.signal });
controller.abort();
assert.equal(await aborted, false);
assert.equal(
await mgr.waitForLayerIdle('satellites', { signal: controller.signal }),
false,
'an already aborted signal returns at once',
);
for (const release of gates) release();
await hung;
await mgr.destroyAll();
});
test('programmatic Context enables neither create nor replace a restoration snapshot', async () => {
const mgr = new DataLayerManager({});
const missions = makeSlowLayer('rocket-launches', { updateInterval: 0 });
@@ -1854,10 +1891,10 @@ test('pre-transition subscribers capture the exact enabled set before user chang
test('absolute Context entry intent is excluded from its own pre-entry restore snapshot', async () => {
const mgr = new DataLayerManager({});
const missions = makeSlowLayer('rocket-launches', { updateInterval: 0 });
const satellites = makeSlowLayer('satellites', { updateInterval: 0 });
mgr.register(missions.module);
mgr.register(satellites.module);
const contacts = makeSlowLayer('military-awareness', { updateInterval: 0 });
const flights = makeSlowLayer('flights', { updateInterval: 0 });
mgr.register(contacts.module);
mgr.register(flights.module);
let snapshot = null;
mgr.subscribe((change) => {
if (shouldCaptureContextSession(change)) {
@@ -1869,13 +1906,13 @@ test('absolute Context entry intent is excluded from its own pre-entry restore s
}
});
await mgr.setEnabled('rocket-launches', true, { origin: 'user' });
await mgr.setEnabled('military-awareness', true, { origin: 'user' });
assert.deepEqual([...snapshot], []);
await mgr.setEnabled('rocket-launches', false, { origin: 'user' });
await mgr.setEnabled('military-awareness', false, { origin: 'user' });
await mgr.restoreEnabledLayerIds(snapshot, { origin: 'context-restore' });
assert.equal(mgr.isEnabled('rocket-launches'), false);
assert.equal(mgr.isEnabled('satellites'), false);
assert.equal(mgr.isEnabled('military-awareness'), false);
assert.equal(mgr.isEnabled('flights'), false);
await mgr.destroyAll();
});
+22 -14
View File
@@ -53,11 +53,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 two
* Context missions, exactly as the visible Contacts /
* Space Missions tabs do it. 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 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, SESSION the camera. Never persisted by anything.
* NOT TOUCHED detection mode + density. The reasonable-defaults
* landing owns the DENSE/75 start, and Contacts owns
@@ -75,9 +76,10 @@ 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 two Context missions deliberately reuse `styleManager.setContextMode`, the
* same facade the visible tabs and voice use, so Contacts detection ownership,
* layer isolation and rollback stay in exactly one place.
* 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.
*/
/** @type {Readonly<Record<string, object>>} */
@@ -88,8 +90,10 @@ export const FIRST_RUN_MISSIONS = Object.freeze({
busyKey: msg('Starting live contacts…'),
}),
'space-missions': Object.freeze({
kind: 'context',
contextMode: 'space-missions',
// 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.
kind: 'layer',
layerIds: Object.freeze(['rocket-launches']),
busyKey: msg('Opening space missions…'),
}),
environmental: Object.freeze({
@@ -265,9 +269,13 @@ export async function runFirstRunChoice(
// 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.
const flight = Promise.resolve()
.then(() => flyToGlobe())
.catch(() => null);
// Layer missions keep the camera where it is.
const flight =
mission.kind === 'globe'
? Promise.resolve()
.then(() => flyToGlobe())
.catch(() => null)
: null;
const outcomes = await Promise.all(
mission.layerIds.map(async (layerId) => {
try {
@@ -469,7 +477,7 @@ export function initFirstRunExperience({
// 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 / Space Missions tabs do.
// Contacts tab does.
styleManager.setPanelCollapsed?.('global-context-panel', false, {
explicit: true,
});
+36 -17
View File
@@ -549,7 +549,7 @@ function missionSpy({
calls.contextModes.push(mode);
return contextOk
? { ok: true, mode }
: { ok: false, failedLayerIds: ['rocket-launches'] };
: { ok: false, failedLayerIds: ['military-awareness'] };
},
setLayerEnabled: async (layerId) => {
calls.layerIds.push(layerId);
@@ -582,19 +582,32 @@ test('the menu is the four owner-ordered missions', () => {
);
});
test('Live Contacts and Space Missions go through the one setContextMode facade', async () => {
for (const [choice, mode] of [
['contacts', 'contacts'],
['space-missions', 'space-missions'],
]) {
const spy = missionSpy();
const outcome = await runFirstRunChoice(choice, spy.deps);
assert.equal(outcome.ok, true);
assert.deepEqual(spy.calls.contextModes, [mode]);
// 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);
}
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);
});
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');
const refused = missionSpy({ layerResult: () => false });
const failed = await runFirstRunChoice('space-missions', refused.deps);
assert.equal(failed.ok, false);
assert.deepEqual(failed.failedLayerIds, ['rocket-launches']);
});
test('Environmental enables BOTH its feeds and pulls out to the globe', async () => {
@@ -682,9 +695,9 @@ test('Explore manually touches nothing at all, and an unknown choice is inert',
test('a failed Context mission reports the layers the facade named', async () => {
const spy = missionSpy({ contextOk: false });
const outcome = await runFirstRunChoice('space-missions', spy.deps);
const outcome = await runFirstRunChoice('contacts', spy.deps);
assert.equal(outcome.ok, false);
assert.deepEqual(outcome.result.failedLayerIds, ['rocket-launches']);
assert.deepEqual(outcome.result.failedLayerIds, ['military-awareness']);
});
test('the fires/quakes tile name is switchable from one constant', () => {
@@ -736,7 +749,8 @@ 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
// missions — the globe missions open no panel at all.
// 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,
@@ -1033,6 +1047,11 @@ test('the voice TOOL SCHEMA matches the pinned contract — the mission mapping
delete camera.pitchDeg;
camera.direction.description =
'Required for pan/tilt/rotate; orbit/rotate_globe default right.';
// The Space Missions panel is a later, separate set_panel_open target.
const panels = legacyTools.find((tool) => tool.name === 'set_panel_open')
.parameters.properties.panelId;
assert.ok(panels.enum.includes('space-missions-panel'));
panels.enum = panels.enum.filter((id) => id !== 'space-missions-panel');
const block = JSON.stringify(legacyTools);
// Re-derived for the voice layer manifest (generated layer enums, alias and
// field hints), point-and-ask's pointer/referent arguments and the prompt
-5
View File
@@ -260,7 +260,6 @@
"Running {index}/{total}: {scene} / {shot}": "جارٍ التشغيل {index} من {total}: {scene} / {shot}",
"Scene run complete": "اكتمل تشغيل المشهد",
"Error: {message}": "خطأ: {message}",
"Could not exit {mode} — scene layers may be refused": "تعذّر الخروج من {mode} — قد تُرفض طبقات المشهد",
"REMOVE": "إزالة",
"Remove {title} from this app's saved keys": "إزالة {title} من مفاتيح هذا التطبيق المحفوظة",
"Needs {envVars} — add it in Provider Settings": "يحتاج إلى {envVars} — أضفه في «إعدادات المزوّدين»",
@@ -610,7 +609,6 @@
"Space Missions": "المهام الفضائية",
"{mode} could not start because another layer did not stop cleanly": "تعذّر بدء {mode} لأن طبقة أخرى لم تتوقف بشكل سليم",
"Contacts could not complete the requested transition; try again": "تعذّر على وضع «الأهداف» إكمال الانتقال المطلوب؛ أعد المحاولة",
"Space Missions could not complete the requested transition; try again": "تعذّر على وضع «المهام الفضائية» إكمال الانتقال المطلوب؛ أعد المحاولة",
"Nearby installations could not be refreshed; try again": "تعذّر تحديث المنشآت القريبة؛ أعد المحاولة",
"Context could not restore every layer; try again": "تعذّر على السياق استعادة كل الطبقات؛ أعد المحاولة",
"Zoom in to search mapped installations": "قرّب الخريطة للبحث في المنشآت المرسومة",
@@ -626,8 +624,6 @@
"CCTV layer unavailable": "طبقة CCTV غير متاحة",
"MAP": "خريطة",
"CONTACTS — nearest planes · vessels · sites": "الأهداف — أقرب الطائرات · السفن · المواقع",
"SPACE MISSIONS — launches & orbital assets": "المهام الفضائية — عمليات الإطلاق والأصول المدارية",
"Space Missions cancellation could not restore the previous layer state": "تعذّرت استعادة حالة الطبقة السابقة عند إلغاء وضع المهام الفضائية",
"Collapse Cockpit display options": "طي خيارات عرض القمرة",
"Collapse Cockpit Radio controls": "طي عناصر تحكم الراديو في القمرة",
"SYNC": "مزامنة",
@@ -1132,7 +1128,6 @@
"Could not place the shape: {error}": "تعذّر وضع الشكل: {error}",
"Board cleared.": "تم مسح اللوحة.",
"{label} · Detailed outline unavailable": "{label} · المخطط التفصيلي غير متاح",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "وضع المهام الفضائية يعزل بيانات إعادة العرض. اخرج من الوضع لتفعيل طبقة «{layer}».",
"Data attribution": "إسناد البيانات",
"Data provided by:": "البيانات مقدَّمة من:",
"Light aircraft": "طائرة خفيفة",
-5
View File
@@ -452,7 +452,6 @@
"Camera unavailable — exit cockpit first": "Kamera nicht verfügbar: zuerst Cockpit verlassen",
"No shots to run": "Keine Aufnahmen zum Abspielen",
"Project exported": "Projekt exportiert",
"Could not exit {mode} — scene layers may be refused": "{mode} konnte nicht beendet werden: Szenenebenen werden eventuell abgelehnt",
"Running {index}/{total}: {scene} / {shot}": "Läuft {index}/{total}: {scene} / {shot}",
"Scene run complete": "Szenenlauf abgeschlossen",
"Global Flights Radar": "Globales Flugradar",
@@ -466,7 +465,6 @@
"VISUAL PRESETS": "VISUELLE PRESETS",
"LOCATION": "STANDORT",
"CONTACTS — nearest planes · vessels · sites": "KONTAKTE: nächstgelegene Flugzeuge · Schiffe · Standorte",
"SPACE MISSIONS — launches & orbital assets": "RAUMMISSIONEN: Starts & Orbit-Objekte",
"LIVE SIGNALS": "LIVE-SIGNALE",
"Contacts could not complete the requested transition; try again": "Kontakte konnten den gewünschten Wechsel nicht abschließen; erneut versuchen",
"CCTV layer unavailable": "CCTV-Ebene nicht verfügbar",
@@ -637,10 +635,8 @@
"other": "{count} Datenebenen ausgeschaltet"
},
"Selected data layers could not be cleared": "Ausgewählte Datenebenen konnten nicht ausgeschaltet werden",
"Space Missions could not complete the requested transition; try again": "Raummissionen konnten den gewünschten Wechsel nicht abschließen; erneut versuchen",
"Nearby installations refreshed": "Anlagen in der Nähe aktualisiert",
"Nearby installations could not be refreshed; try again": "Anlagen in der Nähe konnten nicht aktualisiert werden; erneut versuchen",
"Space Missions cancellation could not restore the previous layer state": "Abbruch der Raummissionen konnte den vorherigen Ebenenstatus nicht wiederherstellen",
"That layer is unavailable in the current Context mode": "Diese Ebene ist im aktuellen Kontextmodus nicht verfügbar",
"{layerId} could not {action} cleanly": "{layerId} konnte nicht sauber {action}",
"start": "starten",
@@ -1067,7 +1063,6 @@
"Could not place the shape: {error}": "Form konnte nicht platziert werden: {error}",
"Board cleared.": "Zeichenfläche geleert.",
"{label} · Detailed outline unavailable": "{label} · Detaillierter Umriss nicht verfügbar",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Der Modus Raummissionen isoliert Replay-Daten. Modus verlassen, um {layer} zu aktivieren.",
"Data attribution": "Datenquellen",
"Data provided by:": "Daten bereitgestellt von:",
"Light aircraft": "Leichtflugzeug",
-5
View File
@@ -470,7 +470,6 @@
"Space Missions": "Misiones espaciales",
"{mode} could not start because another layer did not stop cleanly": "{mode} no pudo iniciarse porque otra capa no se detuvo correctamente",
"Contacts could not complete the requested transition; try again": "Contactos no pudo completar la transición solicitada; inténtalo de nuevo",
"Space Missions could not complete the requested transition; try again": "Misiones espaciales no pudo completar la transición solicitada; inténtalo de nuevo",
"Nearby installations could not be refreshed; try again": "No se pudieron actualizar las instalaciones cercanas; inténtalo de nuevo",
"Context could not restore every layer; try again": "Contexto no pudo restaurar todas las capas; inténtalo de nuevo",
"Zoom in to search mapped installations": "Acércate para buscar instalaciones mapeadas",
@@ -486,8 +485,6 @@
"CCTV layer unavailable": "Capa de CCTV no disponible",
"MAP": "MAPA",
"CONTACTS — nearest planes · vessels · sites": "CONTACTOS — aeronaves · buques · sitios más cercanos",
"SPACE MISSIONS — launches & orbital assets": "MISIONES ESPACIALES — lanzamientos y activos orbitales",
"Space Missions cancellation could not restore the previous layer state": "La cancelación de Misiones espaciales no pudo restaurar el estado previo de las capas",
"Collapse Cockpit display options": "Contraer las opciones de visualización de la cabina",
"Collapse Cockpit Radio controls": "Contraer los controles de Radio de la cabina",
"SYNC": "SINCR.",
@@ -1022,7 +1019,6 @@
"Running {index}/{total}: {scene} / {shot}": "Ejecutando {index}/{total}: {scene} / {shot}",
"Scene run complete": "Ejecución de escenas completada",
"Error: {message}": "Error: {message}",
"Could not exit {mode} — scene layers may be refused": "No se pudo salir de {mode} — las capas de la escena pueden rechazarse",
"REMOVE": "ELIMINAR",
"Remove {title} from this app's saved keys": "Elimina {title} de las claves guardadas de esta app",
"Needs {envVars} — add it in Provider Settings": "Necesita {envVars} — se añade en Ajustes de proveedores",
@@ -2613,7 +2609,6 @@
"Importing project": "Importando proyecto",
"Camera move interrupted": "Movimiento de cámara interrumpido",
"Scene media timed out": "El contenido multimedia de la escena agotó el tiempo de espera",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "El modo Misiones espaciales aísla los datos de repetición. Sal del modo para activar {layer}.",
"Tilted view": "Vista inclinada",
"Straight-down view": "Vista cenital",
"North up": "Norte arriba",
-5
View File
@@ -129,7 +129,6 @@
"Loading the keyless globe...": "Chargement du globe sans clé…",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles indisponible ({detail}). Chargement du globe sans clé…",
"Initializing systems...": "Initialisation des systèmes…",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Le mode Missions spatiales isole les données de rejeu. Quittez-le pour activer {layer}.",
"Data attribution": "Attribution des données",
"Data provided by:": "Données fournies par :",
"Close data attribution": "Fermer l'attribution des données",
@@ -1550,7 +1549,6 @@
"Import failed: {error}": "Échec de l'importation : {error}",
"Import failed (could not read JSON file)": "Échec de l'importation (fichier JSON illisible)",
"Layers refused: {layers}": "Couches refusées : {layers}",
"Could not exit {mode} — scene layers may be refused": "Impossible de quitter {mode} — les couches de la scène peuvent être refusées",
"Camera move interrupted": "Mouvement de caméra interrompu",
"Scene media timed out": "Délai dépassé pour les médias de la scène",
"Action complete": "Action terminée",
@@ -1690,7 +1688,6 @@
"VISUAL PRESETS": "PRÉRÉGLAGES VISUELS",
"LOCATION": "LIEU",
"CONTACTS — nearest planes · vessels · sites": "CONTACTS — avions, navires et sites les plus proches",
"SPACE MISSIONS — launches & orbital assets": "MISSIONS SPATIALES — lancements et objets orbitaux",
"LIVE SIGNALS": "SIGNAUX EN DIRECT",
"Contacts could not complete the requested transition; try again": "Les contacts n'ont pas pu effectuer la transition demandée ; réessayez",
"CCTV layer unavailable": "Couche CCTV indisponible",
@@ -1917,10 +1914,8 @@
"other": "{count} couches de données effacées"
},
"Selected data layers could not be cleared": "Impossible d'effacer les couches de données sélectionnées",
"Space Missions could not complete the requested transition; try again": "Les missions spatiales n'ont pas pu effectuer la transition demandée ; réessayez",
"Nearby installations refreshed": "Installations proches actualisées",
"Nearby installations could not be refreshed; try again": "Impossible d'actualiser les installations proches ; réessayez",
"Space Missions cancellation could not restore the previous layer state": "L'annulation des missions spatiales n'a pas pu restaurer l'état précédent des couches",
"That layer is unavailable in the current Context mode": "Cette couche est indisponible dans le mode Contexte actuel",
"{layerId} could not {action} cleanly": "{layerId} n'a pas pu {action} proprement",
"start": "démarrer",
-5
View File
@@ -38,7 +38,6 @@
"Loading the keyless globe...": "טוען גלובוס ללא מפתח...",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles אינם זמינים ({detail}). טוען גלובוס ללא מפתח...",
"Initializing systems...": "מאתחל מערכות...",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "מצב משימות החלל מבודד את נתוני ההצגה החוזרת. צא מהמצב כדי להפעיל את {layer}.",
"Data attribution": "ייחוס נתונים",
"Data provided by:": "הנתונים מסופקים על ידי:",
"Close data attribution": "סגירת ייחוס הנתונים",
@@ -1434,7 +1433,6 @@
"Import failed: {error}": "הייבוא נכשל: {error}",
"Import failed (could not read JSON file)": "הייבוא נכשל (לא ניתן לקרוא קובץ JSON)",
"Layers refused: {layers}": "שכבות שנדחו: {layers}",
"Could not exit {mode} — scene layers may be refused": "לא ניתן לצאת מ-{mode} — ייתכן ששכבות הסצנה יידחו",
"Camera move interrupted": "תנועת המצלמה הופסקה",
"Scene media timed out": "מדיית הסצנה חרגה מהזמן הקצוב",
"Action complete": "הפעולה הושלמה",
@@ -1756,10 +1754,8 @@
"other": "נוקו {count} שכבות נתונים"
},
"Selected data layers could not be cleared": "שכבות הנתונים הנבחרות לא נוקו",
"Space Missions could not complete the requested transition; try again": "משימות החלל לא השלימו את המעבר המבוקש; נסה שוב",
"Nearby installations refreshed": "המתקנים הסמוכים התרעננו",
"Nearby installations could not be refreshed; try again": "לא ניתן לרענן את המתקנים הסמוכים; נסה שוב",
"Space Missions cancellation could not restore the previous layer state": "ביטול משימות החלל לא שיחזר את מצב השכבה הקודם",
"That layer is unavailable in the current Context mode": "השכבה הזאת אינה זמינה במצב ההקשר הנוכחי",
"{layerId} could not {action} cleanly": "{layerId} — הפעולה {action} לא הסתיימה כראוי",
"start": "התחלה",
@@ -2335,7 +2331,6 @@
"SPACE MISSIONS": "משימות חלל",
"SELECT CONTEXT": "בחירת ההקשר",
"CONTACTS — nearest planes · vessels · sites": "מגעים — המטוסים הקרובים · אוניות · אתרים",
"SPACE MISSIONS — launches & orbital assets": "משימות חלל — שיגורים ונכסים במסלול",
"Contact Context actions": "פעולות הקשר של מגעים",
"SEARCH NEARBY SITES": "חיפוש אתרים סמוכים",
"Reclassify tracked contact as TR-3B": "סיווג מחדש של המגע הנעקב כ-TR-3B",
-5
View File
@@ -129,7 +129,6 @@
"Loading the keyless globe...": "Caricamento del globo senza chiave...",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles non disponibile ({detail}). Caricamento del globo senza chiave...",
"Initializing systems...": "Inizializzazione dei sistemi...",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "La modalità Missioni spaziali isola i dati del replay. Esci dalla modalità per attivare {layer}.",
"Data attribution": "Attribuzione dei dati",
"Data provided by:": "Dati forniti da:",
"Close data attribution": "Chiudi le attribuzioni dei dati",
@@ -1550,7 +1549,6 @@
"Import failed: {error}": "Importazione non riuscita: {error}",
"Import failed (could not read JSON file)": "Importazione non riuscita (impossibile leggere il file JSON)",
"Layers refused: {layers}": "Livelli rifiutati: {layers}",
"Could not exit {mode} — scene layers may be refused": "Impossibile uscire da {mode}: i livelli della scena potrebbero essere rifiutati",
"Camera move interrupted": "Movimento della camera interrotto",
"Scene media timed out": "I contenuti della scena sono andati in timeout",
"Action complete": "Azione completata",
@@ -1690,7 +1688,6 @@
"VISUAL PRESETS": "PRESET VISIVI",
"LOCATION": "POSIZIONE",
"CONTACTS — nearest planes · vessels · sites": "CONTATTI — aerei · navi · siti più vicini",
"SPACE MISSIONS — launches & orbital assets": "MISSIONI SPAZIALI — lanci e asset orbitali",
"LIVE SIGNALS": "SEGNALI LIVE",
"Contacts could not complete the requested transition; try again": "Impossibile completare la transizione richiesta per Contatti; riprova",
"CCTV layer unavailable": "Livello CCTV non disponibile",
@@ -1917,10 +1914,8 @@
"other": "Disattivati {count} livelli dati"
},
"Selected data layers could not be cleared": "Impossibile disattivare i livelli dati selezionati",
"Space Missions could not complete the requested transition; try again": "Impossibile completare la transizione richiesta per Missioni spaziali; riprova",
"Nearby installations refreshed": "Installazioni vicine aggiornate",
"Nearby installations could not be refreshed; try again": "Impossibile aggiornare le installazioni vicine; riprova",
"Space Missions cancellation could not restore the previous layer state": "L'annullamento di Missioni spaziali non ha potuto ripristinare lo stato precedente dei livelli",
"That layer is unavailable in the current Context mode": "Quel livello non è disponibile nella modalità Contesto attuale",
"{layerId} could not {action} cleanly": "{layerId} non ha potuto {action} correttamente",
"start": "avviarsi",
-5
View File
@@ -113,7 +113,6 @@
"Loading the keyless globe...": "キー不要の地球儀を読み込み中…",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tilesを利用できません({detail})。キー不要の地球儀を読み込み中…",
"Initializing systems...": "システムを初期化中…",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "宇宙ミッションはリプレイデータを分離しています。{layer}を有効にするには、このモードを終了してください。",
"Data attribution": "データの出典",
"Data provided by:": "データ提供:",
"Close data attribution": "データ出典を閉じる",
@@ -1500,7 +1499,6 @@
"Import failed: {error}": "インポートに失敗しました:{error}",
"Import failed (could not read JSON file)": "インポートに失敗しました(JSONファイルを読み取れませんでした)",
"Layers refused: {layers}": "拒否されたレイヤー:{layers}",
"Could not exit {mode} — scene layers may be refused": "{mode}を終了できませんでした。シーンのレイヤーが拒否される可能性があります",
"Camera move interrupted": "カメラの移動が中断されました",
"Scene media timed out": "シーンのメディアがタイムアウトしました",
"Action complete": "操作が完了しました",
@@ -1634,7 +1632,6 @@
"VISUAL PRESETS": "ビジュアルプリセット",
"LOCATION": "位置",
"CONTACTS — nearest planes · vessels · sites": "コンタクト:最寄りの航空機 · 船舶 · 施設",
"SPACE MISSIONS — launches & orbital assets": "宇宙ミッション:打ち上げと軌道上の宇宙機",
"LIVE SIGNALS": "ライブシグナル",
"Contacts could not complete the requested transition; try again": "コンタクトが要求された切り替えを完了できませんでした。もう一度お試しください",
"CCTV layer unavailable": "CCTVレイヤーを利用できません",
@@ -1845,10 +1842,8 @@
"other": "データレイヤーを{count}件解除しました"
},
"Selected data layers could not be cleared": "選択中のデータレイヤーを解除できませんでした",
"Space Missions could not complete the requested transition; try again": "宇宙ミッションが要求された切り替えを完了できませんでした。もう一度お試しください",
"Nearby installations refreshed": "周辺施設を更新しました",
"Nearby installations could not be refreshed; try again": "周辺施設を更新できませんでした。もう一度お試しください",
"Space Missions cancellation could not restore the previous layer state": "宇宙ミッションのキャンセル時に、以前のレイヤー状態を復元できませんでした",
"That layer is unavailable in the current Context mode": "そのレイヤーは現在のコンテキストモードでは利用できません",
"{layerId} could not {action} cleanly": "{layerId}を正常に{action}できませんでした",
"start": "開始",
-5
View File
@@ -129,7 +129,6 @@
"Loading the keyless globe...": "Carregando o globo sem chave...",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles indisponível ({detail}). Carregando o globo sem chave...",
"Initializing systems...": "Inicializando sistemas...",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "O modo Missões espaciais isola os dados da reprise. Saia do modo para ativar {layer}.",
"Data attribution": "Atribuição de dados",
"Data provided by:": "Dados fornecidos por:",
"Close data attribution": "Fechar atribuição de dados",
@@ -1550,7 +1549,6 @@
"Import failed: {error}": "Falha na importação: {error}",
"Import failed (could not read JSON file)": "Falha na importação (não foi possível ler o arquivo JSON)",
"Layers refused: {layers}": "Camadas recusadas: {layers}",
"Could not exit {mode} — scene layers may be refused": "Não foi possível sair de {mode} — as camadas da cena podem ser recusadas",
"Camera move interrupted": "Movimento de câmera interrompido",
"Scene media timed out": "A mídia da cena excedeu o tempo limite",
"Action complete": "Ação concluída",
@@ -1690,7 +1688,6 @@
"VISUAL PRESETS": "PREDEF. VISUAIS",
"LOCATION": "LOCAL",
"CONTACTS — nearest planes · vessels · sites": "CONTATOS — aviões · embarcações · locais mais próximos",
"SPACE MISSIONS — launches & orbital assets": "MISSÕES ESPACIAIS — lançamentos e ativos orbitais",
"LIVE SIGNALS": "SINAIS AO VIVO",
"Contacts could not complete the requested transition; try again": "Contatos: não foi possível concluir a transição solicitada; tente novamente",
"CCTV layer unavailable": "Camada de CCTV indisponível",
@@ -1917,10 +1914,8 @@
"other": "{count} camadas de dados limpas"
},
"Selected data layers could not be cleared": "Não foi possível limpar as camadas de dados selecionadas",
"Space Missions could not complete the requested transition; try again": "Missões espaciais: não foi possível concluir a transição solicitada; tente novamente",
"Nearby installations refreshed": "Instalações próximas atualizadas",
"Nearby installations could not be refreshed; try again": "Não foi possível atualizar as instalações próximas; tente novamente",
"Space Missions cancellation could not restore the previous layer state": "O cancelamento de Missões espaciais não conseguiu restaurar o estado anterior das camadas",
"That layer is unavailable in the current Context mode": "Essa camada não está disponível no modo de contexto atual",
"{layerId} could not {action} cleanly": "Não foi possível {action} {layerId} corretamente",
"start": "iniciar",
-5
View File
@@ -431,7 +431,6 @@
"Error: {message}": "Ошибка: {message}",
"Project exported": "Проект экспортирован",
"Ready": "Готово",
"Could not exit {mode} — scene layers may be refused": "Не удалось выйти из режима {mode} — слои сцены могут быть отклонены",
"Loaded: {scene} / {shot}": "Загружено: {scene} / {shot}",
"Global Flights Radar": "Глобальный радар рейсов",
"Orbital Watch": "Орбитальный дозор",
@@ -455,7 +454,6 @@
"DISPLAY": "ЭКРАН",
"CONTACT": "КОНТАКТ",
"CONTACTS — nearest planes · vessels · sites": "КОНТАКТЫ — ближайшие самолёты · суда · объекты",
"SPACE MISSIONS — launches & orbital assets": "КОСМИЧЕСКИЕ МИССИИ — пуски и орбитальные аппараты",
"LIVE SIGNALS": "СИГНАЛЫ ОНЛАЙН",
"MAP SOURCE": "ИСТОЧНИК КАРТЫ",
"Map source": "Источник карты",
@@ -643,11 +641,9 @@
"Nearby installations refreshed": "Ближайшие объекты обновлены",
"Nearby installations could not be refreshed; try again": "Не удалось обновить ближайшие объекты; попробуйте снова",
"Contacts could not complete the requested transition; try again": "Не удалось переключить режим «Контакты»; попробуйте снова",
"Space Missions could not complete the requested transition; try again": "Не удалось переключить режим «Космические миссии»; попробуйте снова",
"{layerId} could not {action} cleanly": "Не удалось корректно {action} слой {layerId}",
"start": "запустить",
"stop": "остановить",
"Space Missions cancellation could not restore the previous layer state": "Не удалось восстановить прежнее состояние слоёв после отмены космических миссий",
"That layer is unavailable in the current Context mode": "Этот слой недоступен в текущем режиме контекста",
"{mode} could not start because another layer did not stop cleanly": "Не удалось запустить режим «{mode}»: другой слой не остановился корректно",
"Space Missions": "Космические миссии",
@@ -2665,7 +2661,6 @@
"Importing project": "Импорт проекта",
"Camera move interrupted": "Перелёт камеры прерван",
"Scene media timed out": "Истекло время ожидания медиа сцены",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Режим «Космические миссии» изолирует данные воспроизведения. Выйдите из режима, чтобы включить слой «{layer}».",
"Tilted view": "Вид с наклоном",
"Straight-down view": "Вид сверху",
"North up": "Север вверху",
-5
View File
@@ -418,7 +418,6 @@
"Camera unavailable — exit cockpit first": "Kameran är otillgänglig – lämna cockpit först",
"No shots to run": "Inga tagningar att köra",
"Project exported": "Projektet har exporterats",
"Could not exit {mode} — scene layers may be refused": "Kunde inte lämna {mode} – scenens lager kan nekas",
"Running {index}/{total}: {scene} / {shot}": "Kör {index}/{total}: {scene} / {shot}",
"Scene run complete": "Scenkörningen är klar",
"Global Flights Radar": "Global flygradar",
@@ -432,7 +431,6 @@
"VISUAL PRESETS": "VISUELLA FÖRVAL",
"LOCATION": "PLATS",
"CONTACTS — nearest planes · vessels · sites": "KONTAKTER – närmaste flygplan · fartyg · platser",
"SPACE MISSIONS — launches & orbital assets": "RYMDUPPDRAG – uppskjutningar och objekt i omloppsbana",
"LIVE SIGNALS": "LIVESIGNALER",
"Contacts could not complete the requested transition; try again": "Läget ”Kontakter” kunde inte slutföra övergången – försök igen",
"CCTV layer unavailable": "CCTV-lagret är otillgängligt",
@@ -591,10 +589,8 @@
"other": "Stängde av {count} datalager"
},
"Selected data layers could not be cleared": "De valda datalagren kunde inte stängas av",
"Space Missions could not complete the requested transition; try again": "Läget ”Rymduppdrag” kunde inte slutföra övergången – försök igen",
"Nearby installations refreshed": "Anläggningar i närheten har uppdaterats",
"Nearby installations could not be refreshed; try again": "Det gick inte att uppdatera anläggningar i närheten – försök igen",
"Space Missions cancellation could not restore the previous layer state": "Lagrens tidigare läge kunde inte återställas när ”Rymduppdrag” avbröts",
"That layer is unavailable in the current Context mode": "Lagret är otillgängligt i det aktuella läget ”Kontext”",
"{layerId} could not {action} cleanly": "{layerId} kunde inte {action} korrekt",
"start": "startas",
@@ -983,7 +979,6 @@
"Could not place the shape: {error}": "Kunde inte placera formen: {error}",
"Board cleared.": "Ritytan rensad.",
"{label} · Detailed outline unavailable": "{label} · Detaljerad kontur otillgänglig",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Läget ”Rymduppdrag” isolerar uppspelningsdata. Lämna läget för att aktivera {layer}.",
"Data attribution": "Datakällor",
"Data provided by:": "Data från:",
"Light aircraft": "Lätt flygplan",
-5
View File
@@ -137,7 +137,6 @@
"Loading the keyless globe...": "Завантаження глобуса без ключа...",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles недоступні ({detail}). Завантаження глобуса без ключа...",
"Initializing systems...": "Ініціалізація систем...",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "Режим «Космічні місії» ізолює дані відтворення. Вийдіть із режиму, щоб увімкнути шар «{layer}».",
"Data attribution": "Джерела даних",
"Data provided by:": "Дані надали:",
"Close data attribution": "Закрити відомості про джерела даних",
@@ -1574,7 +1573,6 @@
"Import failed: {error}": "Помилка імпорту: {error}",
"Import failed (could not read JSON file)": "Помилка імпорту (не вдалося прочитати файл JSON)",
"Layers refused: {layers}": "Шари відхилено: {layers}",
"Could not exit {mode} — scene layers may be refused": "Не вдалося вийти з {mode} — шари сцени може бути відхилено",
"Camera move interrupted": "Переліт камери перервано",
"Scene media timed out": "Минув час очікування медіа сцени",
"Action complete": "Дію виконано",
@@ -1717,7 +1715,6 @@
"VISUAL PRESETS": "ВІЗУАЛЬНІ ПРЕСЕТИ",
"LOCATION": "РОЗТАШУВАННЯ",
"CONTACTS — nearest planes · vessels · sites": "КОНТАКТИ — найближчі літаки · судна · обʼєкти",
"SPACE MISSIONS — launches & orbital assets": "КОСМІЧНІ МІСІЇ — запуски та орбітальні апарати",
"LIVE SIGNALS": "СИГНАЛИ ОНЛАЙН",
"Contacts could not complete the requested transition; try again": "Режим «Контакти» не зміг завершити запитаний перехід; спробуйте ще раз",
"CCTV layer unavailable": "Шар CCTV недоступний",
@@ -1952,10 +1949,8 @@
"other": "Очищено {count} шару даних"
},
"Selected data layers could not be cleared": "Не вдалося очистити вибрані шари даних",
"Space Missions could not complete the requested transition; try again": "Режим «Космічні місії» не зміг завершити запитаний перехід; спробуйте ще раз",
"Nearby installations refreshed": "Найближчі обʼєкти оновлено",
"Nearby installations could not be refreshed; try again": "Не вдалося оновити найближчі обʼєкти; спробуйте ще раз",
"Space Missions cancellation could not restore the previous layer state": "Скасування режиму «Космічні місії» не відновило попередній стан шарів",
"That layer is unavailable in the current Context mode": "Цей шар недоступний у поточному режимі контексту",
"{layerId} could not {action} cleanly": "{layerId}: не вдалося коректно {action}",
"start": "запустити",
-5
View File
@@ -113,7 +113,6 @@
"Loading the keyless globe...": "正在加载免密钥地球…",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles 不可用({detail})。正在加载免密钥地球…",
"Initializing systems...": "正在初始化系统…",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "太空任务模式会隔离回放数据。退出该模式后才能启用“{layer}”。",
"Data attribution": "数据来源说明",
"Data provided by:": "数据提供方:",
"Close data attribution": "关闭数据来源说明",
@@ -1475,7 +1474,6 @@
"Import failed: {error}": "导入失败:{error}",
"Import failed (could not read JSON file)": "导入失败(无法读取 JSON 文件)",
"Layers refused: {layers}": "被拒绝的图层:{layers}",
"Could not exit {mode} — scene layers may be refused": "无法退出 {mode}——场景图层可能被拒绝",
"Camera move interrupted": "相机移动被中断",
"Scene media timed out": "场景媒体播放超时",
"Action complete": "动作已完成",
@@ -1609,7 +1607,6 @@
"VISUAL PRESETS": "视觉预设",
"LOCATION": "位置",
"CONTACTS — nearest planes · vessels · sites": "目标:最近的飞机 · 船舶 · 设施",
"SPACE MISSIONS — launches & orbital assets": "太空任务:发射与在轨资产",
"LIVE SIGNALS": "实时信号",
"CCTV layer unavailable": "CCTV 图层不可用",
"Link copied!": "链接已复制!",
@@ -1821,10 +1818,8 @@
},
"Selected data layers could not be cleared": "无法清除已选数据图层",
"Contacts could not complete the requested transition; try again": "目标未能完成所请求的切换,请重试",
"Space Missions could not complete the requested transition; try again": "太空任务未能完成所请求的切换,请重试",
"Nearby installations refreshed": "附近设施已刷新",
"Nearby installations could not be refreshed; try again": "无法刷新附近设施,请重试",
"Space Missions cancellation could not restore the previous layer state": "取消太空任务后无法恢复先前的图层状态",
"That layer is unavailable in the current Context mode": "该图层在当前态势模式下不可用",
"{layerId} could not {action} cleanly": "{layerId} 未能正常{action}",
"start": "启动",
-5
View File
@@ -113,7 +113,6 @@
"Loading the keyless globe...": "正在加載免密鑰地球…",
"Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles 不可用({detail})。正在加載免密鑰地球…",
"Initializing systems...": "正在初始化系統…",
"Space Missions isolates replay data. Exit the mode to enable {layer}.": "太空任務模式會隔離回放數據。退出該模式後才能啟用“{layer}”。",
"Data attribution": "數據來源說明",
"Data provided by:": "數據提供方:",
"Close data attribution": "關閉數據來源說明",
@@ -1475,7 +1474,6 @@
"Import failed: {error}": "導入失敗:{error}",
"Import failed (could not read JSON file)": "導入失敗(無法讀取 JSON 文件)",
"Layers refused: {layers}": "被拒絕的圖層:{layers}",
"Could not exit {mode} — scene layers may be refused": "無法退出 {mode}——場景圖層可能被拒絕",
"Camera move interrupted": "相機移動被中斷",
"Scene media timed out": "場景媒體播放超時",
"Action complete": "動作已完成",
@@ -1609,7 +1607,6 @@
"VISUAL PRESETS": "視覺預設",
"LOCATION": "位置",
"CONTACTS — nearest planes · vessels · sites": "目標:最近的飛機 · 船舶 · 設施",
"SPACE MISSIONS — launches & orbital assets": "太空任務:發射與在軌資產",
"LIVE SIGNALS": "實時信號",
"CCTV layer unavailable": "CCTV 圖層不可用",
"Link copied!": "鏈接已複製!",
@@ -1821,10 +1818,8 @@
},
"Selected data layers could not be cleared": "無法清除已選數據圖層",
"Contacts could not complete the requested transition; try again": "目標未能完成所請求的切換,請重試",
"Space Missions could not complete the requested transition; try again": "太空任務未能完成所請求的切換,請重試",
"Nearby installations refreshed": "附近設施已刷新",
"Nearby installations could not be refreshed; try again": "無法刷新附近設施,請重試",
"Space Missions cancellation could not restore the previous layer state": "取消太空任務後無法恢復先前的圖層狀態",
"That layer is unavailable in the current Context mode": "該圖層在當前態勢模式下不可用",
"{layerId} could not {action} cleanly": "{layerId} 未能正常{action}",
"start": "啟動",
+21 -1
View File
@@ -190,6 +190,9 @@ function topHitOf(hit, foreign) {
* @typedef {object} InputDispatcher
* @property {(fn: (event: ClickEvent) => void) => () => void} onClick
* 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.
* @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
@@ -267,6 +270,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
const queryOf = () => givenQuery ?? findQuery(viewer);
/** @type {Array<{fn: Function}>} */
const clickSubscribers = [];
const overlayClicks = new Set();
/** @type {Record<string, Array<{fn: Function, lease: object|null}>>} */
const pointerSubscribers = Object.fromEntries(
POINTER_TYPES.map((type) => [type, []]),
@@ -333,6 +337,15 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
xy(ev.position),
ev.gesture ?? { travelPx: 0, durationMs: 0 },
);
if (ambient) {
for (const handle of [...overlayClicks]) {
try {
if (handle(event) === true) return;
} catch (error) {
console.error('Pointer input handler failed', error);
}
}
}
run(pointerSubscribers.click, ambient, event);
if (ambient) run(clickSubscribers, true, event);
},
@@ -357,6 +370,12 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
return subscribe(clickSubscribers, { fn, lease: null });
},
onOverlayClick(fn) {
if (destroyed) return () => {};
overlayClicks.add(fn);
return () => overlayClicks.delete(fn);
},
onPointer(type, fn, { lease = null } = {}) {
const list = pointerSubscribers[type];
if (!list) throw new TypeError(`Unknown pointer event: ${type}`);
@@ -395,7 +414,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
subscriberCount() {
return POINTER_TYPES.reduce(
(sum, type) => sum + pointerSubscribers[type].length,
clickSubscribers.length,
clickSubscribers.length + overlayClicks.size,
);
},
@@ -404,6 +423,7 @@ function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
destroyed = true;
if (dispatchers.get(viewer) === self) dispatchers.delete(viewer);
clickSubscribers.length = 0;
overlayClicks.clear();
for (const type of POINTER_TYPES) pointerSubscribers[type].length = 0;
for (const off of offPort) off();
bridge.off();
+31
View File
@@ -129,6 +129,37 @@ test('a click nobody reads is never picked', (t) => {
assert.equal(h.calls.pick, 0);
});
test('a painted overlay can claim a click before its underlying owner', (t) => {
registerPickOwner('satellites', (id) => id === '25544');
t.after(() => unregisterPickOwner('satellites'));
const h = harness({ pick: () => ({ id: '25544' }) });
t.after(() => h.input.destroy());
const clicks = [];
h.input.onClick((event) => clicks.push(event.ownerId));
const offOverlay = h.input.onOverlayClick(({ screenPosition }) => {
if (screenPosition.x !== 10) return false;
clicks.push('mission label');
return true;
});
h.input.onPointer('click', () => clicks.push('ambient pointer'));
h.click();
assert.deepEqual(clicks, ['mission label']);
assert.equal(h.calls.pick, 0);
h.click(11, 10);
offOverlay();
h.click();
assert.deepEqual(clicks, [
'mission label',
'ambient pointer',
'satellites',
'ambient pointer',
'satellites',
]);
});
test('the gesture carries summed travel and press time', (t) => {
const h = harness();
t.after(() => h.input.destroy());
+106 -1
View File
@@ -1,4 +1,35 @@
import { formatNumber, t } from '../../i18n/index.js';
export function createControls({ state: layerState, services, parts, source }) {
let unsubscribeRowControls = null;
function cycleMission(step) {
const entries = layerState._missionRosterView?.entries;
if (!layerState._enabled || !entries?.length) return;
const index = entries.findIndex(
({ id }) => id === layerState._selectedLaunchId,
);
const next =
index < 0
? step > 0
? 0
: entries.length - 1
: (index + step + entries.length) % entries.length;
parts.panel.selectMissionAt(entries[next].index);
// Stepped from the Data Layers row: the panel opens, as for a globe pick.
const id = layerState._selectedLaunchId;
for (const listener of [...(layerState._globePickListeners || [])]) {
try {
listener(id);
} catch (error) {
console.warn(
'[Data:RocketLaunches] mission step listener failed',
error,
);
}
}
}
const methods = {
id: 'rocket-launches',
@@ -10,6 +41,67 @@ export function createControls({ state: layerState, services, parts, source }) {
updateInterval: 300000,
getRowControls() {
const entries = layerState._missionRosterView?.entries;
if (!layerState._enabled || !entries?.length) return null;
const index = entries.findIndex(
({ id }) => id === layerState._selectedLaunchId,
);
const disabled = entries.length === 1 && index >= 0;
return {
info:
index < 0
? t('SELECT A MISSION TO INSPECT')
: `${formatNumber(index + 1)} / ${formatNumber(entries.length)} · ${entries[index].label}`,
chips: [
{
id: 'previous-mission',
label: t('Previous mission'),
icon: 'chevron_left',
action: true,
disabled,
onClick: () => cycleMission(-1),
},
{
id: 'next-mission',
label: t('Next mission'),
icon: 'chevron_right',
action: true,
disabled,
onClick: () => cycleMission(1),
},
],
};
},
setRowControlsListener(listener) {
unsubscribeRowControls?.();
unsubscribeRowControls = null;
if (!listener) return;
let previousRoster;
let previousSelection;
unsubscribeRowControls = parts.panel.subscribePanel(({ roster }) => {
// Replay and telemetry can update without changing the roster or pick.
const selection = layerState._selectedLaunchId;
if (roster === previousRoster && selection === previousSelection)
return;
previousRoster = roster;
previousSelection = selection;
listener();
});
},
/**
* Hear each mission picked on the globe (a marker or its label), after
* it is selected. The app reveals the Space Missions panel for it.
* @param {(launchId: string) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribeGlobePick(listener) {
layerState._globePickListeners.add(listener);
return () => layerState._globePickListeners.delete(listener);
},
/** Release only Space Mission camera ownership, preserving layer and selection state. */
releaseCameraOwnership() {
// Navigation takes the camera; a failed entry must not restore the old view.
@@ -54,19 +146,32 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* Why a start failed, for the person: the mission index never loaded.
* Null when the failure is not the index's (the app then names it).
* @returns {?string}
*/
enableFailureMessage() {
return layerState._lastError && layerState._lastUpdate == null
? t(
'Space Missions unavailable: the mission index could not load. Try again later.',
)
: null;
},
getStats() {
return {
count: layerState._count,
orbitMatches: layerState._orbitMatches,
lastUpdate: layerState._lastUpdate,
error: layerState._lastError,
errorAt: layerState._lastErrorAt,
stale: layerState._stale,
};
},
attachDataManager(dataManager) {
layerState._dataManager = dataManager;
parts.satelliteIntents.connect(dataManager);
},
};
+285 -47
View File
@@ -4,12 +4,12 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { DataLayerManager } from '../../data/manager.js';
import { ContextControls } from '../../ui/contextControls.js';
import { spaceMissionsIndexFailure } from '../../ui/contextActions.js';
import { createLaunchSource } from './source.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createPolicyHelpers } from './policyHelpers.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createPanel } from './panel.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
@@ -98,7 +98,7 @@ function fakeCamera() {
return camera;
}
async function fixture(t) {
async function fixture(t, { beforeConnect } = {}) {
const upstream = { status: 429, results: [launchRecord] };
const source = createLaunchSource({
async fetchImpl(url) {
@@ -191,6 +191,7 @@ async function fixture(t) {
parts.panel = createPanel(context);
parts.replay = createReplay(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
const missions = Object.assign(
@@ -206,6 +207,7 @@ async function fixture(t) {
manager.register(plainLayer('earthquakes', 'Earthquakes (24h)'));
manager.register(plainLayer('satellites', 'Satellites'));
manager.register(plainLayer('wind', 'Wind'));
manager.register(plainLayer('military-awareness', 'Global Context'));
manager.register(missions);
missions.attachDataManager(manager);
@@ -224,12 +226,19 @@ async function fixture(t) {
setPanelCollapsed: noop,
},
});
beforeConnect?.(manager);
controls.connect(manager);
t.after(async () => {
controls.stop();
controls.disconnect();
for (const id of ['rocket-launches', 'satellites', 'earthquakes', 'wind'])
for (const id of [
'rocket-launches',
'satellites',
'earthquakes',
'wind',
'military-awareness',
])
await manager.setEnabled(id, false);
await missions.destroy(viewer);
});
@@ -257,46 +266,37 @@ async function fixture(t) {
state,
camera,
rosters,
panel: parts.panel,
enabledIds,
view,
settle,
};
}
const entries = {
direct: (f) =>
f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
'Context-panel': async (f) =>
(
await f.controls.setContextMode('space-missions', {
claimVisualAuthority: false,
})
).ok,
};
test('a Space Missions start that gets HTTP 429 rolls back and leaves other layers alone', async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
const before = f.view();
for (const [path, enter] of Object.entries(entries))
test(`a ${path} Space Missions entry that gets HTTP 429 rolls back instead of isolating`, async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
const before = f.view();
const entered = await enter(f);
await f.settle();
assert.equal(entered, false, 'a failed mission index fails the enable');
assert.deepEqual(f.enabledIds(), ['earthquakes']);
assert.equal(f.controls.getContextModeState().mode, null);
assert.equal(f.controls.getContextModeState().active, false);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'an unrelated layer is not blocked after the failed entry',
);
const entered = await f.manager.setEnabled('rocket-launches', true, {
origin: 'user',
});
await f.settle();
assert.equal(entered, false, 'a failed mission index fails the enable');
assert.deepEqual(f.enabledIds(), ['earthquakes']);
assert.equal(f.controls.getContextModeState().mode, null);
assert.equal(f.controls.getContextModeState().active, false);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'an unrelated layer is not blocked after the failed entry',
);
});
// Holds the /api/launches reply until the returned release is called.
function holdReply(f) {
@@ -410,7 +410,12 @@ test('the roster reports a failed mission index instead of loading forever', asy
await f.settle();
assert.equal(f.rosters.slice(loadingFrom).includes(null), true);
assert.equal(f.rosters.at(-1).entries.length, 1);
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(
f.controls.getContextModeState().mode,
null,
'not a Context mode',
);
});
test('a valid empty mission index is a successful entry', async (t) => {
@@ -422,7 +427,7 @@ test('a valid empty mission index is a successful entry', async (t) => {
true,
);
await f.settle();
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(
f.rosters.at(-1).empty,
'NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW',
@@ -430,7 +435,236 @@ test('a valid empty mission index is a successful entry', async (t) => {
assert.ok(f.camera.flights > 0, 'a successful entry frames the globe');
});
test('a refresh failure after a loaded index keeps the mode and its records', async (t) => {
for (const phase of ['while starting', 'after start']) {
test(`Space Missions runs beside Contacts and a later Satellites OFF ends it (${phase})`, async (t) => {
const gate = Promise.withResolvers();
const guardReached = Promise.withResolvers();
const f = await fixture(t, {
beforeConnect(manager) {
if (phase !== 'while starting') return;
manager.addVisibilityGuard(async ({ layerId, enabled }) => {
if (layerId !== 'rocket-launches' || !enabled) return;
guardReached.resolve();
await gate.promise;
});
},
});
f.upstream.status = 200;
await f.manager.setEnabled('satellites', true, { origin: 'user' });
assert.equal(await f.controls._selectContextMode('flights'), true);
await f.settle();
assert.deepEqual(
f.enabledIds(),
['military-awareness', 'satellites'],
'Contacts leaves Satellites alone',
);
const launch = f.manager.setEnabled('rocket-launches', true, {
origin: 'user',
});
try {
if (phase === 'while starting') {
await guardReached.promise;
} else {
assert.equal(await launch, true);
assert.deepEqual(f.enabledIds(), [
'military-awareness',
'rocket-launches',
'satellites',
]);
}
assert.equal(
f.controls.getContextModeState().mode,
'flights',
'starting Space Missions leaves Contacts on',
);
assert.equal(
await f.manager.setEnabled('satellites', false, { origin: 'voice' }),
true,
);
} finally {
gate.resolve();
}
assert.equal(await launch, phase === 'after start');
await f.missions.waitForSatelliteIntents?.();
await f.settle();
assert.deepEqual(f.enabledIds(), ['military-awareness']);
assert.equal(f.controls.getContextModeState().mode, 'flights');
});
}
test('Contacts started and ended while Space Missions runs leaves it and Satellites alone', 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();
const missionParams = f.manager.getLayerParams('satellites');
assert.equal(missionParams.showPoints, false, 'the mission display applied');
assert.equal(await f.controls._selectContextMode('flights'), true);
await f.settle();
assert.deepEqual(f.enabledIds(), [
'military-awareness',
'rocket-launches',
'satellites',
]);
assert.equal(await f.controls._selectContextMode(null), true);
await f.settle();
assert.deepEqual(f.enabledIds(), ['rocket-launches', 'satellites']);
assert.deepEqual(f.manager.getLayerParams('satellites'), missionParams);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(f.enabledIds(), []);
const after = f.manager.getLayerParams('satellites');
assert.notEqual(after.showPoints, false, 'Satellites shows its points again');
assert.notEqual(after.showOrbits, false, 'and its orbits');
});
test('a Satellites OFF requested before Space Missions entry does not cancel it', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('satellites', true, { origin: 'user' });
const satellites = f.manager.layers.get('satellites').module;
const disable = satellites.disable;
const gate = Promise.withResolvers();
const disabling = Promise.withResolvers();
satellites.disable = async () => {
disabling.resolve();
await gate.promise;
};
let entry;
try {
const off = f.manager.setEnabled('satellites', false, { origin: 'user' });
await disabling.promise;
// The entry is requested while the earlier OFF is still settling.
entry = f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
gate.resolve();
assert.equal(await off, true);
} finally {
gate.resolve();
satellites.disable = disable;
}
assert.equal(await entry, true, 'the later entry is not cancelled');
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), true);
// Leaving keeps the earlier Satellites OFF.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
assert.equal(f.manager.isEnabled('rocket-launches'), false);
});
test('Space Missions is an ordinary layer: it neither isolates nor opens a Context session', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.deepEqual(f.enabledIds(), [
'earthquakes',
'rocket-launches',
'satellites',
]);
assert.equal(f.controls._contextSessionSnapshot, null);
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'other layers are not refused while Space Missions is on',
);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(
f.enabledIds(),
['earthquakes', 'wind'],
'Space Missions gives back only the Satellites it turned on',
);
});
test('a Satellites enable that never settles still lets mission disable complete', 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 {
// A programmatic Satellites restart whose enable hangs.
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
const exit = f.manager.setEnabled('rocket-launches', false, {
origin: 'user',
});
const outcome = await Promise.race([
exit.then(() => 'settled'),
new Promise((resolve) => setTimeout(() => resolve('hung'), 2000)),
]);
assert.equal(
outcome,
'settled',
'the mission disable does not wait forever',
);
assert.equal(f.missions.getAnalystRecords().length, 0);
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
});
test('a failed Satellites restore still clears the selected mission panel', 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();
assert.equal(f.manager.isEnabled('satellites'), true);
let panelView;
const unsubscribe = f.panel.subscribePanel((view) => {
panelView = view;
});
const satellites = f.manager.layers.get('satellites').module;
const disable = satellites.disable;
try {
f.state._selectedLaunchId = f.state._launches[0].id;
f.panel.renderMissionPanel();
assert.ok(panelView.mission);
satellites.disable = () => {
throw new Error('injected Satellites restore failure');
};
assert.equal(
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' }),
false,
);
const { enabled, uncertain } =
f.manager.getLayerLifecycleState('rocket-launches');
assert.equal(enabled, true);
assert.equal(uncertain, true);
assert.equal(panelView.mission, null);
} finally {
satellites.disable = disable;
unsubscribe();
}
});
test('a refresh failure after a loaded index keeps the layer and its records', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
@@ -442,12 +676,11 @@ test('a refresh failure after a loaded index keeps the mode and its records', as
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.missions.getStats().count, 1);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.equal(f.rosters.at(-1).entries.length, 1);
// Leaving a loaded mode does not restore the pre-entry view.
// Leaving after a loaded index does not restore the pre-entry view.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(f.view(), framed);
@@ -475,11 +708,9 @@ test('a failed first load tells the user the mission index is unavailable', asyn
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
await f.controls.setContextMode('space-missions', {
claimVisualAuthority: false,
});
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
assert.equal(f.controls.getContextModeState().mode, null, 'rolled back');
assert.equal(f.manager.isEnabled('rocket-launches'), false, 'rolled back');
assert.ok(
f.toasts.some((message) => /mission index/i.test(message)),
`visible feedback names the failure, got ${JSON.stringify(f.toasts)}`,
@@ -504,10 +735,17 @@ test('navigation taking the camera keeps a mission flight it asked to preserve',
assert.equal(f.camera.flight, other);
});
test("an earlier attempt's index error is not blamed for a later failure", async (t) => {
test('a refresh error after a loaded index is not blamed on the index', async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
assert.match(spaceMissionsIndexFailure(f.manager), /mission index/);
assert.equal(spaceMissionsIndexFailure(f.manager, Date.now() + 1), null);
assert.match(f.missions.enableFailureMessage(), /mission index/);
f.upstream.status = 200;
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
f.upstream.status = 429;
await f.missions.update();
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.equal(f.missions.enableFailureMessage(), null);
});
+3
View File
@@ -1,5 +1,6 @@
import { createPolicyHelpers } from './policyHelpers.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createOrbitRendering } from './orbitRendering.js';
import { createOverlays } from './overlays.js';
import { createSelection } from './selection.js';
@@ -24,6 +25,7 @@ export function createRocketLaunchesLayer({ services, source }) {
const context = { state, services, parts, source };
parts.policyHelpers = createPolicyHelpers(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.orbitRendering = createOrbitRendering(context);
parts.overlays = createOverlays(context);
parts.selection = createSelection(context);
@@ -45,6 +47,7 @@ export function createRocketLaunchesLayer({ services, source }) {
parts.panel.commands,
{
subscribePanel: parts.panel.subscribePanel,
waitForSatelliteIntents: parts.satelliteIntents.settled,
subscribeReplayOverlay: parts.overlays.subscribeReplayOverlay,
satelliteParamsForSpaceMissions:
parts.policyHelpers.satelliteParamsForSpaceMissions,
+55 -22
View File
@@ -1,5 +1,15 @@
import { MAX_POST_TLE_RETRIES, POST_TLE_RETRY_DELAY_MS } from './policy.js';
/**
* Let pending Satellites work finish, including requests that join it while
* waiting, so the mission dependency cannot overtake it. Bounded: a
* Satellites change that never settles cannot hold missions forever.
*/
async function waitForSatelliteVisibility(manager, { signal, timeoutMs }) {
if (typeof manager.waitForLayerIdle !== 'function') return true;
return manager.waitForLayerIdle('satellites', { signal, timeoutMs });
}
export function createIngestion({
state: layerState,
services,
@@ -97,28 +107,39 @@ export function createIngestion({
}
async function captureSatelliteDependency() {
if (!layerState._dataManager || layerState._satelliteStateBeforeMission)
const manager = layerState._dataManager;
if (!manager || layerState._satelliteStateBeforeMission) 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.
const idle = await waitForSatelliteVisibility(manager, {
signal: layerState._sourceController?.signal,
timeoutMs: layerState.satelliteSettleTimeoutMs,
});
if (token !== layerState._lifecycleToken) return;
if (!idle && layerState._enabled)
throw new Error(
'Space Missions could not start: the satellites layer did not settle',
);
if (
!layerState._enabled ||
(manager.layers?.has('rocket-launches') &&
!manager.isEffectivelyEnabled('rocket-launches'))
)
return;
layerState._satelliteStateBeforeMission = {
// Effective visibility: a user enable still mid-activation is intent ON —
// capturing settled false would restore the user's enable away on exit.
enabled:
layerState._dataManager.isEffectivelyEnabled?.('satellites') ??
layerState._dataManager.isEnabled('satellites'),
enabled: manager.isEnabled('satellites'),
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
layerState._dataManager.getLayerParams('satellites'),
manager.getLayerParams('satellites'),
),
};
layerState._dataManager.setLayerParams(
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsForSpaceMissions(
layerState._satelliteStateBeforeMission.params,
),
);
const token = layerState._lifecycleToken;
const activation = Promise.resolve(
layerState._dataManager.setEnabled('satellites', true),
);
const activation = Promise.resolve(manager.setEnabled('satellites', true));
layerState._satelliteActivationPromise = activation;
try {
const activated = await activation;
@@ -128,8 +149,7 @@ export function createIngestion({
if (
token === layerState._lifecycleToken &&
layerState._enabled &&
(activated === false ||
!layerState._dataManager.isEnabled('satellites'))
(activated === false || !manager.isEnabled('satellites'))
) {
throw new Error(
'Space Missions requires the satellites layer, which failed to start',
@@ -146,21 +166,35 @@ export function createIngestion({
}
async function restoreSatelliteDependency() {
const manager = layerState._dataManager;
const snapshot = layerState._satelliteStateBeforeMission;
if (!snapshot || !layerState._dataManager) return;
if (!snapshot || !manager) return;
// Keep the snapshot available until any explicit Satellites action settles.
const token = layerState._lifecycleToken;
const idle = await waitForSatelliteVisibility(manager, {
timeoutMs: layerState.satelliteSettleTimeoutMs,
});
if (
token !== layerState._lifecycleToken ||
layerState._satelliteStateBeforeMission !== snapshot
)
return;
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
layerState._dataManager.setLayerParams(
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsAfterSpaceMissions(snapshot.params),
);
const restored = await layerState._dataManager.setEnabled(
'satellites',
snapshot.enabled,
);
// 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',
);
const restored = await manager.setEnabled('satellites', snapshot.enabled);
if (
restored === false ||
layerState._dataManager.isEnabled('satellites') !== snapshot.enabled
manager.isEnabled('satellites') !== snapshot.enabled
) {
throw new Error('Space Missions could not restore the satellites layer');
}
@@ -230,7 +264,6 @@ export function createIngestion({
} catch (error) {
if (layerState._enabled && token === layerState._lifecycleToken) {
layerState._lastError = error.message;
layerState._lastErrorAt = Date.now();
console.warn('[Data:RocketLaunches] Fetch error:', error);
// No index yet: fail the enable so Context rolls back.
// After a loaded index, a failed refresh keeps its records.
+7 -1
View File
@@ -8,6 +8,7 @@ import { createLaunchSource } from './source.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { layerFeedState } from '../../data/feedState.js';
@@ -147,6 +148,7 @@ async function fixture({ legacySource = false } = {}) {
const context = { state, services, parts, source };
parts.model = createModel(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
const current = () => {
@@ -326,7 +328,11 @@ test('destroy followed by actual init starts a clean instance with owned handler
assert.equal(typeof f.state._inputSubscription, 'function');
await f.destroy();
assert.equal(f.state._inputSubscription, null);
assert.equal(input.subscriberCount(), before - 2, 'click and hover');
assert.equal(
input.subscriberCount(),
before - 3,
'label click, point click and hover',
);
assert.equal(f.attachedSets(), 0);
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
+221
View File
@@ -0,0 +1,221 @@
// Clicks on painted mission labels, routed through the real input dispatcher.
import test from 'node:test';
import assert from 'node:assert/strict';
import { Event } from 'cesium';
import { createLifecycle } from './lifecycle.js';
import { createState } from './state.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.js';
import {
FAKE_EVENT_TYPES,
FakeScreenSpaceEventHandler,
fakeInput,
} from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
const noop = () => {};
/** Parts whose every method is a no-op unless given. */
function stub(methods = {}) {
return new Proxy(methods, {
get: (target, key) => (key in target ? target[key] : noop),
});
}
function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
const stock = new FakeScreenSpaceEventHandler();
stock.setInputAction(noop, FAKE_EVENT_TYPES.LEFT_CLICK);
const viewer = bindFakeCesiumCamera({
isDestroyed: () => false,
screenSpaceEventHandler: stock,
camera: {
moveStart: new Event(),
moveEnd: new Event(),
pickEllipsoid: () => null,
},
scene: {
canvas: { style: { cursor: '' } },
screenSpaceCameraController: { enableInputs: true },
pick: () => undefined,
drillPick: () => [],
},
});
const pointer = fakeInput(viewer);
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
hitTestWorldOverlay: () => overlayHit,
},
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
};
const state = createState({ services });
const focused = [];
const restoreFailure = { error: null };
const parts = {
panel: stub(),
overlays: stub(),
replay: stub(),
launchPad: stub(),
orbitRendering: stub(),
selection: stub({
setSelectedMission: (id) => focused.push(id),
}),
satelliteIntents: stub(),
ingestion: stub({
async restoreSatelliteDependency() {
if (restoreFailure.error) throw restoreFailure.error;
},
}),
rendering: stub({
missionsShown: () => true,
missionHitsAt: () => [],
launchIdFromPicks: () => geometryLaunchId,
launchMarkerAt: () => null,
}),
};
const lifecycle = createLifecycle({
state,
services,
parts,
source: {},
}).methods;
lifecycle.init(viewer);
state._enabled = true;
state._launches = [{ id: 'L1' }, { id: 'L2' }];
// Another layer's ambient click handler, as aircraft or the cockpit has.
const ambient = [];
const offAmbient = pointer.input.onClick((event) => ambient.push(event));
t.after(async () => {
restoreFailure.error = null;
offAmbient();
await lifecycle.destroy(viewer);
pointer.input.destroy();
});
return {
focused,
ambient,
state,
lifecycle,
viewer,
input: pointer.input,
restoreFailure,
setHit(hit) {
overlayHit = hit;
},
click: () => pointer.tap({ x: 40, y: 30 }),
};
}
const label = (
entryId,
sourceId = ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
) => ({
sourceId,
entryId,
});
test('a mission label click focuses its launch and stops the click there', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
r.click();
assert.deepEqual(r.focused, ['L2']);
assert.equal(r.ambient.length, 0, 'the layers beneath do not see it');
r.setHit(label('launch:L1', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID));
r.click();
assert.deepEqual(r.focused, ['L2', 'L1'], 'the selected label routes too');
});
test('a mission picked on the globe is announced, after it is selected', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const picks = [];
r.state._globePickListeners.add((id) => picks.push([id, [...r.focused]]));
r.click();
assert.deepEqual(picks, [['L2', ['L2']]], 'the label pick is announced');
r.setHit(null);
r.click();
assert.equal(picks.length, 1, 'a click on nothing announces nothing');
});
test('a throwing globe-pick listener does not stop the pick', (t) => {
const r = rig(t, { overlayHit: label('launch:L1') });
const warn = console.warn;
console.warn = noop;
t.after(() => {
console.warn = warn;
});
const heard = [];
r.state._globePickListeners.add(() => {
throw new Error('listener failure');
});
r.state._globePickListeners.add((id) => heard.push(id));
r.click();
assert.deepEqual(r.focused, ['L1']);
assert.deepEqual(heard, ['L1']);
assert.equal(r.ambient.length, 0);
});
test('a mission label for an unknown launch falls through to other layers', (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');
});
test("another layer's label keeps the click above mission geometry", (t) => {
// An aircraft label painted over a mission path.
const r = rig(t, {
overlayHit: { sourceId: 'aircraft-labels', entryId: 'launch:L1' },
geometryLaunchId: 'L1',
});
r.click();
assert.deepEqual(r.focused, [], 'the mission under the label is not picked');
assert.equal(r.ambient.length, 1, "the label's owner gets the click");
// With no label there, the same click picks the mission geometry.
r.setHit(null);
r.click();
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') });
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
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, []);
assert.equal(r.ambient.length, 1, 'the cockpit click handler gets it');
});
test('destroy releases the click handlers when the Satellites restore fails', async (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const before = r.input.subscriberCount();
r.restoreFailure.error = new Error('injected Satellites restore failure');
await assert.rejects(r.lifecycle.destroy(r.viewer), /injected/);
assert.equal(r.state._inputSubscription, null);
// The rest of teardown still ran before the failure was reported.
assert.equal(r.state._viewer, null, 'the viewer is released');
assert.deepEqual(r.state._launches, [], 'the records are dropped');
assert.equal(r.state._dataManager, null, 'the manager is released');
assert.ok(r.input.subscriberCount() < before, 'the handlers unsubscribed');
r.click();
assert.deepEqual(r.focused, [], 'a later label click reaches no mission');
assert.equal(r.ambient.length, 1);
});
+76 -15
View File
@@ -2,6 +2,10 @@ import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -150,6 +154,22 @@ 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 &&
hit?.sourceId !== ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID
)
return null;
return hit.entryId.startsWith('launch:') ? hit.entryId.slice(7) : null;
}
export function createLifecycle({
state: layerState,
services,
@@ -157,6 +177,25 @@ export function createLifecycle({
source,
}) {
const { holdContinuousRender, releaseContinuousRender } = services.render;
const overlayAt = (position) =>
services.overlays?.hitTestWorldOverlay?.(position?.x, position?.y);
const missionsShown = () =>
layerState._enabled && parts.rendering.missionsShown();
const focusLaunch = (id) => {
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);
for (const listener of [...layerState._globePickListeners]) {
try {
listener(launch.id);
} catch (error) {
console.warn('[Data:RocketLaunches] globe pick listener failed', error);
}
}
return true;
};
let hover = null;
// While on, the launches loaded span the time from the first to the last,
// each one a mark labelled with its mission's name (the launch's where it
@@ -204,25 +243,38 @@ export function createLifecycle({
layerState._orbitMatches = 0;
parts.overlays.clearMissionOverlaySources();
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;
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));
});
const unsubscribeClick = input.onClick((event) => {
if (!layerState._enabled || !parts.rendering.missionsShown()) return;
// The click's pick position (CSS px), as the click picked it.
const launchId = parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
);
if (!launchId) return;
parts.selection.setSelectedMission(launchId);
parts.selection.focusMission(
layerState._launches.find((launch) => launch.id === launchId),
if (!missionsShown() || overlayClicks.has(event)) return;
focusLaunch(
parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
),
);
});
hover = createLaunchHover({
viewer,
enabled: () => layerState._enabled && parts.rendering.missionsShown(),
launchAt: parts.rendering.launchMarkerAt,
enabled: missionsShown,
launchAt(position) {
const hit = overlayAt(position);
return hit
? Boolean(markerLaunchId(hit))
: parts.rendering.launchMarkerAt(position);
},
});
const unsubscribeHover = input.onPointer('move', hover.move);
layerState._inputSubscription = () => {
unsubscribeLabelClick();
unsubscribeClick();
unsubscribeHover();
};
@@ -321,8 +373,8 @@ export function createLifecycle({
parts.overlays.hideReplayVehicleOverlay();
layerState._selectedLaunchId = null;
parts.overlays.clearMissionOverlaySources();
await parts.ingestion.restoreSatelliteDependency();
parts.panel.renderMissionPanel();
await parts.ingestion.restoreSatelliteDependency();
layerState.coverageChanged();
},
@@ -336,14 +388,22 @@ export function createLifecycle({
layerState._enabled = false;
layerState._lifecycleToken++;
layerState._updateDirty = false;
await parts.ingestion.restoreSatelliteDependency();
// A failed Satellites restore still tears everything else down; the
// failure is reported once teardown is complete.
let restoreError = null;
try {
await parts.ingestion.restoreSatelliteDependency();
} catch (error) {
restoreError = error;
}
layerState._inputSubscription?.();
layerState._inputSubscription = null;
parts.satelliteIntents.connect(null);
parts.panel.clearMissionRosterHover();
parts.replay.stopMissionReplay();
layerState._cameraReleased = true;
parts.selection.stopMissionZoomAnchor();
parts.ingestion.clearPostTleRetry();
layerState._inputSubscription?.();
layerState._inputSubscription = null;
if (layerState._declutterHandler) layerState._declutterHandler();
layerState._declutterHandler = null;
parts.launchPad.destroyLaunchPadZonePrimitive();
@@ -370,6 +430,7 @@ export function createLifecycle({
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
layerState._dataManager = null;
if (restoreError) throw restoreError;
},
};
+179
View File
@@ -0,0 +1,179 @@
// The Data Layers row's previous/next mission controls, and the Satellites
// restore an explicit Satellites action takes over.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
const roster = (...ids) => ({
entries: ids.map((id, index) => ({ id, index, label: `Mission ${id}` })),
});
function rig({ ids = ['A', 'B', 'C'], selected = null, enabled = true } = {}) {
const panelListeners = new Set();
const state = {
_enabled: enabled,
_selectedLaunchId: selected,
_missionRosterView: ids ? roster(...ids) : null,
};
const parts = {
panel: {
selectMissionAt(index) {
state._selectedLaunchId = state._missionRosterView.entries[index].id;
},
subscribePanel(listener) {
panelListeners.add(listener);
return () => panelListeners.delete(listener);
},
},
};
const { methods } = createControls({ state, services: {}, parts });
return {
state,
methods,
chip: (id) => methods.getRowControls().chips.find((c) => c.id === id),
publish: (view) => {
for (const listener of [...panelListeners]) listener(view);
},
listenerCount: () => panelListeners.size,
};
}
test('next and previous wrap around the roster', () => {
const r = rig({ selected: 'C' });
r.chip('next-mission').onClick();
assert.equal(
r.state._selectedLaunchId,
'A',
'next after the last is the first',
);
r.chip('previous-mission').onClick();
assert.equal(
r.state._selectedLaunchId,
'C',
'previous before the first is the last',
);
r.chip('previous-mission').onClick();
assert.equal(r.state._selectedLaunchId, 'B');
assert.match(r.methods.getRowControls().info, /^2 \/ 3 · Mission B$/);
});
test('with nothing selected, next picks the first mission and previous the last', () => {
const next = rig();
next.chip('next-mission').onClick();
assert.equal(next.state._selectedLaunchId, 'A');
const previous = rig();
previous.chip('previous-mission').onClick();
assert.equal(previous.state._selectedLaunchId, 'C');
});
test('the controls disable only when the one mission is already selected', () => {
const only = rig({ ids: ['A'], selected: 'A' });
assert.equal(only.chip('next-mission').disabled, true);
assert.equal(only.chip('previous-mission').disabled, true);
// One mission, not yet picked: the controls can still select it.
const unpicked = rig({ ids: ['A'] });
assert.equal(unpicked.chip('next-mission').disabled, false);
unpicked.chip('next-mission').onClick();
assert.equal(unpicked.state._selectedLaunchId, 'A');
assert.equal(rig({ selected: 'B' }).chip('next-mission').disabled, false);
});
test('there are no controls while the layer is off or the roster is empty', () => {
assert.equal(rig({ enabled: false }).methods.getRowControls(), null);
assert.equal(rig({ ids: [] }).methods.getRowControls(), null);
assert.equal(rig({ ids: null }).methods.getRowControls(), null);
// A stale click after the layer stops selects nothing.
const r = rig({ selected: 'A' });
const next = r.chip('next-mission');
r.state._enabled = false;
next.onClick();
assert.equal(r.state._selectedLaunchId, 'A');
});
test('the row listener fires only when the roster or the selection changes', () => {
const r = rig();
let calls = 0;
r.methods.setRowControlsListener(() => calls++);
const view = r.state._missionRosterView;
r.publish({ roster: view });
assert.equal(calls, 1, 'the first view is a change');
r.publish({ roster: view });
assert.equal(calls, 1, 'a replay or telemetry update is not');
r.state._selectedLaunchId = 'B';
r.publish({ roster: view });
assert.equal(calls, 2, 'a new selection is');
r.publish({ roster: roster('A', 'B') });
assert.equal(calls, 3, 'a new roster is');
// A new listener replaces the old one; null removes it.
let replaced = 0;
r.methods.setRowControlsListener(() => replaced++);
assert.equal(r.listenerCount(), 1);
r.methods.setRowControlsListener(null);
assert.equal(r.listenerCount(), 0);
r.publish({ roster: roster('C') });
assert.equal(calls, 3);
assert.equal(replaced, 0);
});
function satelliteRig({ enabledBefore }) {
const calls = [];
let satellitesOn = true;
const manager = {
layers: new Map([['satellites', { toggleChain: null }]]),
waitForLayerIdle: async () => true,
isEnabled: () => satellitesOn,
isEffectivelyEnabled: (id) =>
id === 'satellites' ? satellitesOn : id === 'rocket-launches',
setLayerParams: (id, params) => calls.push(['params', id, params]),
async setEnabled(id, enabled) {
calls.push(['enabled', id, enabled]);
satellitesOn = enabled;
return true;
},
};
const state = {
_dataManager: manager,
_satelliteStateBeforeMission: {
enabled: enabledBefore,
params: { mode: 'before' },
},
_satelliteActivationPromise: null,
};
const parts = {
policyHelpers: { satelliteParamsAfterSpaceMissions: (params) => params },
};
const ingestion = createIngestion({ state, services: {}, parts, source: {} });
parts.satelliteIntents = createSatelliteIntents({ state });
const { methods } = createControls({ state, services: {}, parts });
return { state, calls, ingestion, methods, intents: parts.satelliteIntents };
}
test('an accepted Satellites action keeps its visibility through mission exit', async () => {
const r = satelliteRig({ enabledBefore: false });
// The person turns Satellites on themselves while the missions are on.
r.intents.handleVisibility({
type: 'visibility',
layerId: 'satellites',
enabled: true,
origin: 'user',
});
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(
r.calls,
[['params', 'satellites', { mode: 'before' }]],
'the parameters come back, the visibility is left alone',
);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
test('without a Satellites action the exit restores the pre-mission visibility', async () => {
const r = satelliteRig({ enabledBefore: false });
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [
['params', 'satellites', { mode: 'before' }],
['enabled', 'satellites', false],
]);
});
+1 -1
View File
@@ -135,7 +135,7 @@ export function createOverlays({ state: layerState, services, parts, source }) {
protected: selected,
paintLane: selected ? 'selected' : 'ambient-label',
collisionGroup: 'ambient-label',
interactive: false,
interactive: true,
distanceScale: {
near: 1000,
nearValue: 1.08,
+3
View File
@@ -2,6 +2,9 @@ import { TWO_PI, toRadians } from '../../geo/vector.js';
export const WINDOW_DAYS = 30;
/** Longest Space Missions waits for pending Satellites work to settle. */
export const SATELLITE_SETTLE_TIMEOUT_MS = 30000;
export const ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID = 'rocket-missions';
export const ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID =
+2
View File
@@ -336,6 +336,8 @@ export function createReplay({ state: layerState, services, parts, source }) {
// The chase camera moves on the frame loop; without one, no replay.
const frame = findFrame(layerState._viewer);
if (!layerState._viewer || !launch || !track || !frame) return false;
// Not while the layer is going off.
if (!layerState._enabled) return false;
if (layerState._replayCameraLaunchId === launchId) {
stopMissionReplay();
return false;
+126
View File
@@ -0,0 +1,126 @@
/**
* Space Missions owns its Satellites dependency. While the layer is on or
* starting, an explicit Satellites action from the person (a Data Layers
* click, a voice command) wins over the dependency:
* - the mission teardown leaves Satellites as that action set it, and
* - a Satellites OFF asked for after the newest Space Missions ON ends Space
* Missions, which cannot replay without it.
* Whether an OFF ends the missions depends on which of the two was asked for
* first, not on which settles first, so request order is recorded when each
* intent is published.
*/
const ORDERED_REQUEST_LAYER_IDS = new Set(['rocket-launches', 'satellites']);
const LAYER_ID = 'rocket-launches';
function isExplicitOrigin(origin) {
return origin === 'user' || origin === 'voice';
}
export function createSatelliteIntents({ state: layerState }) {
const requestOrder = new Map();
let sequence = 0;
let unsubscribe = null;
/** The Space Missions stop a Satellites OFF started, while it runs. */
let pendingStop = null;
/**
* Whether an accepted Satellites OFF was requested after the newest Space
* Missions ON. An OFF asked for before the entry belongs to the view the
* entry started from, so the entry it races with is kept. Without request
* records the OFF is treated as the newer action.
*/
function offFollowsMissionsEntry(change) {
const satellites = requestOrder.get('satellites');
const missions = requestOrder.get(LAYER_ID);
if (satellites?.intentEpoch !== change.intentEpoch || !missions?.enabled)
return true;
return satellites.sequence > missions.sequence;
}
function recordRequest(change) {
if (!ORDERED_REQUEST_LAYER_IDS.has(change?.layerId)) return;
requestOrder.set(change.layerId, {
enabled: change.enabled,
intentEpoch: change.intentEpoch,
sequence: ++sequence,
});
}
/**
* Hand an explicit Satellites action its visibility while Space Missions is
* on or starting.
* @returns {Promise<boolean>|boolean} Whether Space Missions was asked to stop.
*/
function handleVisibility(change) {
const manager = layerState._dataManager;
if (
!manager ||
change?.type !== 'visibility' ||
change.layerId !== 'satellites' ||
!isExplicitOrigin(change.origin)
)
return false;
const missionsRequested = manager.isEffectivelyEnabled(LAYER_ID);
if (!missionsRequested && !layerState._satelliteStateBeforeMission)
return false;
// A newer Satellites request is queued; it will report for itself.
if (manager.isEffectivelyEnabled('satellites') !== change.enabled)
return false;
// The person's choice survives the mission teardown.
const previous = layerState._satelliteStateBeforeMission;
if (previous) previous.restoreVisibility = false;
if (
change.enabled ||
!missionsRequested ||
!offFollowsMissionsEntry(change)
)
return false;
const stop = Promise.resolve(
manager.setEnabled(LAYER_ID, false, { origin: change.origin }),
)
.then(() => true)
.catch((error) => {
console.warn(
'[Data:RocketLaunches] Satellites OFF could not stop Space Missions',
error,
);
return false;
})
.finally(() => {
if (pendingStop === stop) pendingStop = null;
});
pendingStop = stop;
return stop;
}
/** Settle once a Satellites OFF has finished stopping Space Missions. */
function settled() {
return pendingStop ?? Promise.resolve(false);
}
/** Follow the manager the layer is attached to; null detaches. */
function connect(manager) {
unsubscribe?.();
unsubscribe = null;
requestOrder.clear();
if (!manager) return;
const unsubscribeRequests =
manager.subscribeVisibilityRequests?.(recordRequest) ?? null;
const unsubscribeChanges =
manager.subscribe?.((change) => {
void handleVisibility(change);
}) ?? null;
unsubscribe = () => {
unsubscribeRequests?.();
unsubscribeChanges?.();
};
}
return {
connect,
settled,
handleVisibility,
recordRequest,
offFollowsMissionsEntry,
};
}
@@ -0,0 +1,167 @@
// An explicit Satellites action while Space Missions is on or starting.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSatelliteIntents } from './satelliteIntents.js';
/** A manager whose effective and settled state can differ. */
function rig({ effective, snapshot = { enabled: false } } = {}) {
const calls = [];
const listeners = { requests: new Set(), changes: new Set() };
const manager = {
isEffectivelyEnabled: (id) => Boolean(effective[id]),
async setEnabled(id, enabled, options) {
calls.push([id, enabled, options?.origin]);
return true;
},
subscribeVisibilityRequests(listener) {
listeners.requests.add(listener);
return () => listeners.requests.delete(listener);
},
subscribe(listener) {
listeners.changes.add(listener);
return () => listeners.changes.delete(listener);
},
};
const state = {
_dataManager: manager,
_satelliteStateBeforeMission: snapshot,
};
const intents = createSatelliteIntents({ state });
intents.connect(manager);
const request = (layerId, enabled, intentEpoch) => {
for (const listener of listeners.requests)
listener({
type: 'visibility-requested',
layerId,
enabled,
intentEpoch,
});
};
const settle = (change) => {
for (const listener of listeners.changes) listener(change);
};
return { calls, intents, listeners, manager, state, request, settle };
}
const satellitesOff = {
type: 'visibility',
layerId: 'satellites',
enabled: false,
origin: 'user',
intentEpoch: 7,
};
test('a Satellites OFF asked for after the mission start ends Space Missions', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.request('rocket-launches', true, 3);
r.request('satellites', false, 7);
r.settle(satellitesOff);
assert.equal(await r.intents.settled(), true);
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
false,
'the teardown leaves Satellites as the person set it',
);
});
test('a Satellites OFF asked for before the mission start leaves the start alone', () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.request('satellites', false, 7);
r.request('rocket-launches', true, 3);
r.settle(satellitesOff);
assert.deepEqual(r.calls, []);
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
});
test('a Satellites OFF without request records is treated as the newer action', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
assert.equal(await r.intents.handleVisibility(satellitesOff), true);
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
});
test('a superseded Satellites event is left to the newer request', () => {
// A newer Satellites ON is queued, but this OFF has already settled.
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
assert.equal(r.intents.handleVisibility(satellitesOff), false);
assert.deepEqual(r.calls, []);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
undefined,
);
});
test('a Satellites ON while the missions are on is kept through their exit', () => {
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
assert.equal(
r.intents.handleVisibility({ ...satellitesOff, enabled: true }),
false,
);
assert.deepEqual(r.calls, []);
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
});
test('only direct user and voice Satellites actions count', () => {
// Settled: a scene, story, preset or other programmatic Satellites OFF
// neither ends Space Missions nor survives its teardown.
for (const origin of [
'programmatic',
'context-restore',
'dependency',
'scene',
'tool',
]) {
const r = rig({
effective: { satellites: false, 'rocket-launches': true },
});
assert.equal(
r.intents.handleVisibility({ ...satellitesOff, origin }),
false,
);
assert.deepEqual(r.calls, []);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
undefined,
);
}
const voice = rig({
effective: { satellites: false, 'rocket-launches': true },
});
voice.settle({ ...satellitesOff, origin: 'voice' });
assert.deepEqual(voice.calls, [['rocket-launches', false, 'voice']]);
});
test('with Space Missions off, a Satellites action is not its business', () => {
const r = rig({ effective: { satellites: false }, snapshot: null });
assert.equal(r.intents.handleVisibility(satellitesOff), false);
assert.deepEqual(r.calls, []);
});
test('reconnecting and detaching release each manager subscription', () => {
const r = rig({ effective: {} });
assert.equal(r.listeners.requests.size, 1);
assert.equal(r.listeners.changes.size, 1);
r.intents.connect(r.manager);
assert.equal(r.listeners.requests.size, 1, 'no duplicate subscription');
assert.equal(r.listeners.changes.size, 1);
r.intents.connect(null);
assert.equal(r.listeners.requests.size, 0);
assert.equal(r.listeners.changes.size, 0);
});
test('a failed stop is reported, not thrown', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.manager.setEnabled = async () => {
throw new Error('injected stop failure');
};
const warn = console.warn;
const warnings = [];
console.warn = (...args) => warnings.push(args);
try {
assert.equal(await r.intents.handleVisibility(satellitesOff), false);
} finally {
console.warn = warn;
}
assert.equal(warnings.length, 1);
assert.equal(await r.intents.settled(), false, 'nothing left pending');
});
+5 -2
View File
@@ -66,6 +66,9 @@ export function createSelection({
}
function setSelectedMission(launchId, isolate = true) {
// Once the layer is going off (its Satellites restore may still be
// running) a roster click selects nothing and moves no camera.
if (launchId && !layerState._enabled) return;
if (launchId) parts.panel.clearMissionRosterHover();
if (
layerState._replayCameraLaunchId &&
@@ -118,7 +121,7 @@ export function createSelection({
}
function focusMission(launch) {
if (!layerState._viewer || !launch) return;
if (!layerState._viewer || !launch || !layerState._enabled) return;
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
const camera = cameraOf(layerState._viewer);
@@ -163,7 +166,7 @@ export function createSelection({
}
function focusLaunchSite(launch) {
if (!layerState._viewer || !launch) return;
if (!layerState._viewer || !launch || !layerState._enabled) return;
parts.replay.stopMissionReplay();
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
+5 -2
View File
@@ -1,4 +1,5 @@
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
import { SATELLITE_SETTLE_TIMEOUT_MS } from './policy.js';
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
@@ -20,8 +21,6 @@ export function createState({ services }) {
state._lastError = null;
state._lastErrorAt = null;
state._entryCameraView = null;
state._entryLandedView = null;
@@ -53,6 +52,9 @@ export function createState({ services }) {
state._lifecycleToken = 0;
/** Bound on waiting for pending Satellites work around a mission. */
state.satelliteSettleTimeoutMs = SATELLITE_SETTLE_TIMEOUT_MS;
state._enabled = false;
state._selectedLaunchId = null;
@@ -68,6 +70,7 @@ export function createState({ services }) {
state._missionPanelSignature = null;
state._missionPanelListeners = new Set();
state._globePickListeners = new Set();
state._missionRosterView = null;
+1 -1
View File
@@ -157,7 +157,7 @@ test('the edited existing tools changed exactly as intended', () => {
const panel = byName.get('set_panel_open');
assert.deepEqual(
panel.parameters.properties.panelId.enum,
['data-panel', 'location-bar', 'control-panel', 'cctv-panel', 'radio-panel', 'scene-panel', 'utilities-panel', 'pp-toggles', 'global-context-panel', 'weather-panel', 'recent-imagery-panel', 'voice-settings', 'voice-preview', 'provider-settings'],
['data-panel', 'location-bar', 'control-panel', 'cctv-panel', 'radio-panel', 'scene-panel', 'utilities-panel', 'pp-toggles', 'global-context-panel', 'space-missions-panel', 'weather-panel', 'recent-imagery-panel', 'voice-settings', 'voice-preview', 'provider-settings'],
);
assert.deepEqual(panel.parameters.required, ['panelId', 'open']);
+2 -6
View File
@@ -1,8 +1,4 @@
const GLOBAL_CONTEXT_EXPLICIT_ACTIONS = new Set([
'contacts',
'space-missions',
'cockpit',
]);
const GLOBAL_CONTEXT_EXPLICIT_ACTIONS = new Set(['contacts', 'cockpit']);
/**
* Decide whether a completed action should reveal the Global Context panel.
@@ -14,7 +10,7 @@ const GLOBAL_CONTEXT_EXPLICIT_ACTIONS = new Set([
* explicit Cockpit action still reveals the context that supports that track.
*
* @param {object} input Action outcome and coordination state.
* @param {'contacts'|'space-missions'|'cockpit'|string} input.action Completed action.
* @param {'contacts'|'cockpit'|string} input.action Completed action.
* @param {boolean} input.explicitUserAction Whether the user directly requested it.
* @param {boolean} input.succeeded Whether the requested transition completed.
* @param {boolean} [input.restoring=false] Whether saved/session state is being restored.
+10 -8
View File
@@ -23,8 +23,8 @@ test('desktop side rails hide collapsed panels in every HUD layout, never on pho
assert.match(css, /#left-panel-stack\.layout-exclusive > \[data-panel-id\]\.collapsed \{/);
});
test('explicit Contacts, Space Missions, and Cockpit actions expand Global Context after success', () => {
for (const action of ['contacts', 'space-missions', 'cockpit']) {
test('explicit Contacts and Cockpit actions expand Global Context after success', () => {
for (const action of ['contacts', 'cockpit']) {
assert.equal(shouldExpandGlobalContextPanel({
action,
explicitUserAction: true,
@@ -51,7 +51,7 @@ test('restoration and programmatic replay preserve the saved Global Context coll
succeeded: true,
}), false);
assert.equal(shouldExpandGlobalContextPanel({
action: 'space-missions',
action: 'contacts',
explicitUserAction: true,
succeeded: true,
restoring: true,
@@ -64,9 +64,11 @@ test('failed or unrelated actions never expand Global Context', () => {
explicitUserAction: true,
succeeded: false,
}), false, 'a failed transition must preserve the prior panel state for rollback');
assert.equal(shouldExpandGlobalContextPanel({
action: 'search-nearby',
explicitUserAction: true,
succeeded: true,
}), false);
for (const action of ['search-nearby', 'space-missions']) {
assert.equal(shouldExpandGlobalContextPanel({
action,
explicitUserAction: true,
succeeded: true,
}), false);
}
});
+6 -66
View File
@@ -36,7 +36,7 @@ import {
displayShotTitle,
getSceneAppendRecipeById,
} from './recipes.js';
import { sceneLayerPlan, sceneRequiresContextModeExit } from './scenePolicy.js';
import { sceneLayerPlan } from './scenePolicy.js';
import { t, tn, msg, onLocaleChange } from '../i18n/index.js';
import { createSceneDataPacks } from './dataPacks/controller.js';
import { createSceneInteractions } from './interactions.js';
@@ -1819,7 +1819,7 @@ export class SceneDirector {
const layerResult = await this._applyLayerStates(
staleStates,
this._loadToken(generation, controller.signal, seekGeneration),
{ stopOnRefusal: true, exitContextMode: false },
{ stopOnRefusal: true },
);
if (this._loadAbort === controller) this._loadAbort = null;
if (this._seekAbort === controller) this._seekAbort = null;
@@ -2632,13 +2632,9 @@ export class SceneDirector {
* Only layers the shot declares are touched — see src/scenes/scenePolicy.js
* for why undeclared layers are left alone.
*
* Two things this pass owes the operator:
* - An isolating Context mode is left FIRST. Space Missions refuses every
* unrelated enable, so a shot applied inside it composes a scene nobody
* authored (see _exitIsolatingContextMode).
* - A refused layer is reported. setEnabled() answers false when a guard
* vetoes the transition; swallowing that answer is how playback came to
* claim success over a scene it never assembled.
* A refused layer is reported. setEnabled() answers false when a guard
* vetoes the transition; swallowing that answer is how playback came to
* claim success over a scene it never assembled.
*
* The token's signal is handed to every transition, so a stop or a newer
* request cancels the layer that is CURRENTLY moving rather than only the
@@ -2659,22 +2655,13 @@ export class SceneDirector {
async _applyLayerStates(
targetStates,
token = null,
{ stopOnRefusal = false, exitContextMode = true } = {},
{ stopOnRefusal = false } = {},
) {
const applied = [];
const refused = [];
const abort = () => ({ applied, refused, cancelled: true });
if (token?.cancelled) return abort();
// Deliberately NOT aborted: leaving an isolating mode IS the restore to
// the operator's pre-mode state, which is exactly where a stopped scene
// should come to rest. Tearing that transaction in half would strand
// Context, so it completes and cancellation is honoured immediately after.
if (exitContextMode) {
await this._exitIsolatingContextMode();
if (token?.cancelled) return abort();
}
const signal = token?.signal;
const registered = new Set(
this.dataManager.getAll().map((layer) => layer.id),
@@ -2802,53 +2789,6 @@ export class SceneDirector {
return this._releaseAbort.signal;
}
/**
* Leave a Context mode that isolates the globe, before a shot's layers land.
*
* Space Missions is the shipped case. It is a destructive-exclusive mode: a
* guard refuses every enable outside its own replay bundle, so a recipe that
* declares flights/satellites/earthquakes/traffic gets all four refused —
* and Orbital Watch, whose satellites the guard does permit, would still
* play over the mode's rocket-launches replay it never declared. Either way
* the shot is not the composition it describes.
*
* The old full-registry reconcile dismantled the mode by accident, as part
* of forcing every undeclared layer off. Declaring the exit is the honest
* version of that: the decision is read off the policy guard itself, so a
* future isolating mode is covered without being named here.
*
* @returns {Promise<boolean>} Whether a mode was exited.
*/
async _exitIsolatingContextMode() {
// Older/headless style managers may predate the Context facade.
if (typeof this.styleManager?.getContextModeState !== 'function')
return false;
if (typeof this.styleManager?.setContextMode !== 'function') return false;
const state = this.styleManager.getContextModeState() || {};
// A mode still being entered already owns the guard, so it counts.
const mode = state.entering || state.mode || null;
if (!sceneRequiresContextModeExit(mode)) return false;
const result = await this.styleManager.setContextMode('off');
if (result && result.ok === false) {
console.warn(
`[Scenes] Could not exit ${mode}:`,
result.error || 'unknown reason',
);
this._updateStatus(() =>
t('Could not exit {mode} — scene layers may be refused', { mode }),
);
this._logEvent('context_mode_exit_failed', {
mode,
error: result.error || null,
});
return false;
}
this._logEvent('context_mode_exited', { mode });
return true;
}
/**
* Use the authored sampler only for explicit moves; ordinary shots keep their
* existing flights. A resumed shot (`fromProgress` > 0) continues along the
+4 -56
View File
@@ -332,7 +332,7 @@ test('same-shot seeking rolls back earlier layers and preserves Context, clock a
await dataManager.setEnabled('flights', false);
await dataManager.setEnabled('traffic', false);
await dataManager.setEnabled('satellites', false);
styleManager.contextMode = 'space-missions';
styleManager.contextMode = 'flights';
styleManager.contextExits.length = 0;
refuse = (id) => id === 'traffic';
dataManager.setEnabledCalls.length = 0;
@@ -349,7 +349,7 @@ test('same-shot seeking rolls back earlier layers and preserves Context, clock a
assert.equal(enabled.get('flights'), false, 'first stale layer stays disabled');
assert.equal(enabled.get('traffic'), false, 'refused second layer stays disabled');
assert.equal(enabled.get('satellites'), false, 'later stale layer is never written');
assert.equal(styleManager.contextMode, 'space-missions');
assert.equal(styleManager.contextMode, 'flights');
assert.deepEqual(styleManager.contextExits, []);
assert.equal(viewer.views.length, viewsBefore, 'camera stays at the pre-seek pose');
assert.equal(styleManager.visualCalls.length, visualCalls, 'do not rebuild the shot');
@@ -966,8 +966,6 @@ const REGISTERED = [
'telegeography-submarine-cables', 'local-firms',
];
/** Layers Space Missions permits while it isolates the globe (contextModePolicy). */
const SPACE_MISSIONS_ALLOWED = new Set(['rocket-launches', 'satellites', 'radio']);
const PROJECT_FIXTURE = {
version: 3,
@@ -1089,7 +1087,7 @@ function fakeDataManager({ registered = REGISTERED, refuse = () => false } = {})
}
/** Style manager double covering the camera, visual, and Context facades. */
function fakeStyleManager({ contextMode = null, exitFails = false } = {}) {
function fakeStyleManager({ contextMode = null } = {}) {
const manager = {
contextMode,
contextExits: [],
@@ -1107,7 +1105,6 @@ function fakeStyleManager({ contextMode = null, exitFails = false } = {}) {
getContextModeState: () => ({ mode: manager.contextMode, entering: null }),
async setContextMode(mode) {
manager.contextExits.push(mode);
if (exitFails) return { ok: false, error: 'transition did not complete' };
manager.contextMode = null;
return { ok: true };
},
@@ -1429,56 +1426,7 @@ test('a shot captured while tracking never re-establishes tracking on playback',
}
});
test('a dirty Space Missions state is exited before a recipe applies its layers', async () => {
// Space Missions refuses every enable outside its own replay bundle. The old
// full-registry walk dismantled it by accident; the sparse policy never does,
// so all four Flights Radar enables were refused and reported as success.
const style = { contextMode: 'space-missions' };
const holder = {};
const data = {
refuse: (id, on) => on
&& holder.styleManager?.contextMode === 'space-missions'
&& !SPACE_MISSIONS_ALLOWED.has(id),
};
const { director, styleManager, dataManager, restore } = makeDirector({ style, data });
holder.styleManager = styleManager;
try {
const result = await director._applyLayerStates(recipeLayers('flights-radar'));
assert.deepEqual(styleManager.contextExits, ['off']);
assert.equal(styleManager.contextMode, null);
assert.deepEqual(result.refused, []);
assert.ok(result.applied.includes('flights'));
assert.deepEqual(
dataManager.setEnabledCalls.filter((call) => call.enabled).map((call) => call.id),
['flights'],
);
} finally {
restore();
}
});
test('Orbital Watch does not compose over a Space Missions replay', async () => {
// Orbital Watch declares satellites, which the guard permits — so nothing is
// refused and a refusal-only check would pass while rocket-launches stayed
// on screen. Playback leaves an isolating mode whether or not it refuses.
const { director, styleManager, dataManager, restore } = makeDirector({
style: { contextMode: 'space-missions' },
});
try {
await director._applyLayerStates(recipeLayers('orbital-watch'));
assert.deepEqual(styleManager.contextExits, ['off']);
assert.equal(
dataManager.setEnabledCalls.some((call) => call.id === 'rocket-launches'),
false,
'the recipe never declares rocket-launches; exiting the mode is what clears it',
);
} finally {
restore();
}
});
test('a non-isolating context mode is left alone', async () => {
test('playback leaves every Context mode alone', async () => {
for (const contextMode of [null, 'flights']) {
const { director, styleManager, restore } = makeDirector({ style: { contextMode } });
try {
-42
View File
@@ -18,8 +18,6 @@
// registry (director._captureLayerStates), so those shots declare all sixteen
// keys and still reconcile in full.
import { contextLayerEnableBlockReason } from '../contextModePolicy.js';
/**
* Layer params that re-establish a tracked contact — and with it a SECOND
* writer on the camera.
@@ -91,46 +89,6 @@ export function stripSceneTrackingParams(params) {
return Object.keys(kept).length ? kept : undefined;
}
/**
* Reserved layer id used ONLY to interrogate a Context mode's enable guard.
*
* The probe asks "would this mode refuse a layer it has no opinion about?" —
* so it must name a layer that can never exist. The double-underscore form is
* outside the kebab-case convention every real layer id follows, and
* scenePolicy.test.mjs asserts no registered layer claims it, so the reservation
* is enforced rather than assumed.
* @constant {string}
*/
export const SCENE_EXCLUSIVITY_PROBE_LAYER_ID = '__scene-exclusivity-probe__';
/**
* Whether an active Context mode must be exited before a shot's layers can be
* applied.
*
* Space Missions is the shipped case: it isolates replay data, so its guard
* (contextLayerEnableBlockReason) refuses every enable outside its own bundle.
* A recipe declaring only flights/satellites/earthquakes/traffic would have
* those enables refused outright — and Orbital Watch, whose satellites the
* guard does permit, would still play over the mode's rocket-launches replay
* it never declared. Either way the shot is not the composition it describes.
*
* The verdict is read off the guard itself rather than a mode name: a mode
* that refuses an arbitrary unrelated layer is by definition isolating, so a
* future isolating mode is covered the day its branch is added to the policy.
*
* @param {string|null} contextMode Active (or entering) Context mode.
* @returns {boolean} Whether playback must leave the mode first.
*/
export function sceneRequiresContextModeExit(contextMode) {
if (!contextMode) return false;
return (
contextLayerEnableBlockReason({
contextMode,
change: { layerId: SCENE_EXCLUSIVITY_PROBE_LAYER_ID, enabled: true },
}) !== null
);
}
/**
* Build the ordered layer reconcile plan for one shot.
*
-28
View File
@@ -4,12 +4,10 @@ import fs from 'node:fs';
import test from 'node:test';
import {
SCENE_EXCLUSIVITY_PROBE_LAYER_ID,
SCENE_KEPT_SELECTION_PARAM_KEYS,
SCENE_SELECTION_PARAM_PATTERN,
SCENE_TRACKING_PARAM_KEYS,
sceneLayerPlan,
sceneRequiresContextModeExit,
stripSceneTrackingParams,
} from './scenePolicy.js';
import { SCENE_RECIPES } from './recipes.js';
@@ -177,32 +175,6 @@ test('the family pattern catches selection names the old sweep would have missed
}
});
test('the exclusivity probe id is reserved — no real layer may claim it', () => {
// The probe asks a mode "would you refuse a layer you have no opinion
// about?". If a real layer ever took this id, the probe would be asking
// about a layer the mode DOES have an opinion on, and an isolating mode
// could read as non-isolating.
for (const entry of LAYER_STATE_REGISTRY) {
assert.notEqual(entry.id, SCENE_EXCLUSIVITY_PROBE_LAYER_ID);
}
assert.equal(REGISTERED.has(SCENE_EXCLUSIVITY_PROBE_LAYER_ID), false);
// Every real id is kebab-case; the sentinel deliberately is not.
for (const entry of LAYER_STATE_REGISTRY) {
assert.match(entry.id, /^[a-z][a-z0-9-]*$/, `${entry.id} breaks the layer-id convention`);
}
assert.doesNotMatch(SCENE_EXCLUSIVITY_PROBE_LAYER_ID, /^[a-z][a-z0-9-]*$/);
});
test('an isolating context mode must be exited before a shot applies', () => {
// Read off the shared guard, not a mode name: Space Missions refuses every
// enable outside its replay bundle, so a shot applied inside it is not the
// composition it describes.
assert.equal(sceneRequiresContextModeExit('space-missions'), true);
assert.equal(sceneRequiresContextModeExit('flights'), false);
assert.equal(sceneRequiresContextModeExit(null), false);
assert.equal(sceneRequiresContextModeExit(undefined), false);
});
test('shipped recipes touch only their four declared layers', () => {
for (const recipe of SCENE_RECIPES) {
const declared = Object.entries(recipe.layers || {})
+4 -3
View File
@@ -88,11 +88,12 @@ function assertLegacyRoundTrip(hash) {
return { parsed, state, encoded };
}
test('the HAL example survives the round trip and shrinks to 39 characters', () => {
test('the HAL example survives the round trip and shrinks to 42 characters', () => {
const { parsed, state, encoded } = assertLegacyRoundTrip(HAL_EXAMPLE_HASH);
assert.equal(HAL_EXAMPLE_HASH.length, 302);
assert.equal(encoded.length, 39);
assert.equal(encoded, 'ARCg-SQYrah3ILAJKB4wO1IEAIQAEGIBNMgBC1o');
// Its long form predates the Space Missions panel: that entry says nothing.
assert.equal(encoded.length, 42);
assert.equal(encoded, 'ARCg-SQYrah3ILAJKB4wO1IEAIQAEGIDNLAByAELpA');
assert.equal(parsed.roll, 360);
assert.equal(state.roll, 0);
assert.deepEqual(state.layerState.enabledLayerIds, [
+7
View File
@@ -191,6 +191,13 @@ export const SHARE_VIEW_PANELS = freezeAll([
pinnable: false,
collapsed: false,
},
{
number: 11,
id: 'space-missions-panel',
token: 'n',
pinnable: false,
collapsed: true,
},
]);
const PANEL_BY_NUMBER = new Map(SHARE_VIEW_PANELS.map((p) => [p.number, p]));
const PANEL_BY_ID = new Map(SHARE_VIEW_PANELS.map((p) => [p.id, p]));
+39 -2
View File
@@ -708,6 +708,43 @@ test('panels: only differences from the frozen layout are written', () => {
);
});
test('panels: the Space Missions panel round-trips, and older links keep its default', () => {
const open = {
specs: [{ id: 'space-missions-panel', collapsed: false, pinned: null }],
};
const hash = assertRoundTrip({ panelState: open });
const specs = decodeOk(hash).state.panelState.specs;
assert.deepEqual(
specs.find((spec) => spec.id === 'space-missions-panel'),
{ id: 'space-missions-panel', collapsed: false, pinned: null },
);
// A link that names only an older panel reads Space Missions as collapsed.
const older = decodeOk(
encodeShareView({
panelState: {
specs: [{ id: 'cctv-panel', collapsed: false, pinned: null }],
},
}),
).state.panelState;
assert.equal(
older.specs.some((spec) => spec.id === 'space-missions-panel'),
false,
'an older link has no opinion about the panel',
);
const panel = SHARE_VIEW_PANELS.find((p) => p.id === 'space-missions-panel');
assert.equal(panel.collapsed, true);
assert.equal(
new Set(SHARE_VIEW_PANELS.map((p) => p.token)).size,
SHARE_VIEW_PANELS.length,
'panel tokens are unique',
);
assert.equal(
new Set(SHARE_VIEW_PANELS.map((p) => p.number)).size,
SHARE_VIEW_PANELS.length,
'panel numbers are unique',
);
});
test('a place view opens at its camera; a thing view also names what to follow', () => {
const place = decodeOk(encodeShareView({ lat: 1, lon: 2 })).state;
assert.deepEqual(place.view, { kind: 'place' });
@@ -889,7 +926,7 @@ test('unknown fields inside a thing view, codes and bits are skipped too', () =>
10,
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
); // layer 160
writer.bytesField(12, new WireWriter().varint(11 * 16 + 4 + 1).finish()); // panel 11
writer.bytesField(12, new WireWriter().varint(12 * 16 + 4 + 1).finish()); // panel 12
writer.uintField(14, 99); // style code 99
writer.bytesField(13, thing.finish());
const result = decodeOk(hashOf(writer.finish()));
@@ -909,7 +946,7 @@ test('unknown fields inside a thing view, codes and bits are skipped too', () =>
['enum:style', 99],
['flags', 32],
['layer', 160],
['panel', 11],
['panel', 12],
['thing', 20],
],
);
+23 -11
View File
@@ -246,6 +246,24 @@ test('a collapsed Street Level panel survives the share-link round trip', () =>
] });
});
test('an open Space Missions panel survives the share-link round trip', () => {
const manager = makeManager();
manager.setPanelStateProvider(() => ({ specs: [
{ id: 'global-context-panel', collapsed: true },
{ id: 'space-missions-panel', collapsed: false },
] }));
clearTimeout(manager._debounceTimer);
manager._updateHash();
const params = new URLSearchParams(window.location.hash.slice(1));
assert.equal(params.get('ui'), 'g.c.1_n.c.0');
const restored = makeManager(`#v=2&lat=10&lon=20&ui=${params.get('ui')}`)
.parseInitialHash();
assert.deepEqual(restored.panelState, { specs: [
{ id: 'global-context-panel', collapsed: true, pinned: null },
{ id: 'space-missions-panel', collapsed: false, pinned: null },
] });
});
test('camera-only, partial, and malformed panel shares remain valid incoming state', () => {
const cameraOnly = makeManager('#lat=10&lon=20').parseInitialHash();
assert.ok(cameraOnly);
@@ -596,17 +614,11 @@ test('explicit Context transitions claim the visual restore lane before transiti
assert.match(uiSource, /claimVisualAuthority: \(\) =>\s*this\.shareLinkManager\?\.claimRestoreLane\?\.\('visual'\)/);
const contextPanel = _initGlobalContextPanel.toString();
for (const [start, end, label] of [
["this.listen(this._globalContextFlightsBtn, 'click'", "this.listen(this._globalContextMissionsBtn, 'click'", 'Contacts tab'],
["this.listen(this._globalContextMissionsBtn, 'click'", 'CONTEXT_PANEL_END', 'Space Missions tab'],
]) {
const startIndex = contextPanel.indexOf(start);
const endIndex = end === 'CONTEXT_PANEL_END'
? contextPanel.length
: contextPanel.indexOf(end, startIndex + start.length);
assert.ok(startIndex >= 0 && endIndex > startIndex, `${label} route is missing`);
assertContextClaimsBefore(contextPanel.slice(startIndex, endIndex), 'this._selectContextMode(', label);
}
const contacts = contextPanel.slice(
contextPanel.indexOf("this.listen(this._globalContextFlightsBtn, 'click'"),
contextPanel.indexOf("this.listen(this._installationsSearchBtn, 'click'"),
);
assertContextClaimsBefore(contacts, 'this._selectContextMode(', 'Contacts tab');
// The voice/tool facade validates the mode first, then transitions.
const facade = setContextMode.toString();
+25 -17
View File
@@ -62,6 +62,8 @@ import { applyLocaleChoice } from './localePicker.js';
import { PanelNavigation } from './panelNavigation.js';
import { applicationPinia, createUiRuntime } from './vueRuntime.js';
import { useContextStore } from './stores/context.js';
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
import { SpaceMissionsControls } from './spaceMissionsControls.js';
import { useMissionReplayStore } from './stores/missionReplay.js';
import { useCelestialRingStore } from './stores/celestialRing.js';
import { icrfToFixedAxes } from '../sky/icrf.js';
@@ -326,6 +328,7 @@ export class StyleManager extends ShellFacade {
readControls: () => ({
hud: this.hud,
_contextControls: this._contextControls,
_spaceMissionsControls: this._spaceMissionsControls,
_cctvControls: this._cctvControls,
_radioControls: this._radioControls,
_streetLevelControls: this._streetLevelControls,
@@ -689,6 +692,7 @@ export class StyleManager extends ShellFacade {
this._initStreetLevelPanel();
this._initWildlifeSightingCard();
this._initGlobalContextPanel();
this._initSpaceMissionsPanel();
this._initLocationBar();
this._initMobileShell();
this._initShareButton();
@@ -1025,17 +1029,12 @@ export class StyleManager extends ShellFacade {
}
_initGlobalContextPanel() {
const {
radioLayer,
militaryInstallationsLayer,
militaryAwarenessLayer,
rocketLaunchesLayer,
} = this.services;
const { radioLayer, militaryInstallationsLayer, militaryAwarenessLayer } =
this.services;
const contextStore = useContextStore(applicationPinia());
this._contextControls = new ContextControls({
elements: {
_globalContextFlightsBtn: this._globalContextFlightsBtn,
_globalContextMissionsBtn: this._globalContextMissionsBtn,
_installationsSearchBtn: this._installationsSearchBtn,
},
installations: militaryInstallationsLayer,
@@ -1071,13 +1070,24 @@ export class StyleManager extends ShellFacade {
militaryAwarenessLayer?.subscribeDirectionOverlay?.((view) =>
awarenessDirectionStore.publish(view),
);
}
_initSpaceMissionsPanel() {
const { rocketLaunchesLayer } = this.services;
// The Space Missions layer publishes its roster and selected mission.
contextStore.connectMissions(rocketLaunchesLayer);
this._missionsPanelUnsubscribe?.();
contextStore.publishMissions(null);
this._missionsPanelUnsubscribe = rocketLaunchesLayer?.subscribePanel?.(
(view) => contextStore.publishMissions(view),
);
this._spaceMissionsControls?.destroy();
this._spaceMissionsControls = new SpaceMissionsControls({
layer: rocketLaunchesLayer,
store: useSpaceMissionsStore(applicationPinia()),
actions: {
setPanelCollapsed: (...args) => this.setPanelCollapsed(...args),
isCockpitActive: () => Boolean(this.cockpitView?.active),
// After the panel has rendered as shown: the phone shell will not
// open the Missions sheet over a hidden panel.
revealPanel: () =>
nextTick(() => this.revealPanel('space-missions-panel')),
},
});
// And its replay vehicle overlay, which the scene chrome renders.
const missionReplayStore = useMissionReplayStore(applicationPinia());
this._missionReplayUnsubscribe?.();
@@ -1955,16 +1965,14 @@ export class StyleManager extends ShellFacade {
this._awarenessDirectionUnsubscribe?.();
this._awarenessDirectionUnsubscribe = null;
useAwarenessDirectionStore(applicationPinia()).publish(null);
this._missionsPanelUnsubscribe?.();
this._missionsPanelUnsubscribe = null;
this._spaceMissionsControls?.destroy();
this._spaceMissionsControls = null;
this._missionReplayUnsubscribe?.();
this._missionReplayUnsubscribe = null;
useMissionReplayStore(applicationPinia()).publish(null);
const contextStore = useContextStore(applicationPinia());
contextStore.connectAwareness(null);
contextStore.publishAwareness(null);
contextStore.connectMissions(null);
contextStore.publishMissions(null);
this._cockpitCoordinator.stop();
this._visualSettings.stop();
this.shareLinkManager?.destroy();
+1 -17
View File
@@ -4,19 +4,6 @@ import {
contextModeWord,
} from '../contextModePolicy.js';
/** Why a Space Missions entry failed: its mission index never loaded, and
* the error is no older than `since` (an earlier attempt's is not the cause). */
export function spaceMissionsIndexFailure(dataManager, since = 0) {
const stats = dataManager?.layers
?.get('rocket-launches')
?.module?.getStats?.();
return stats?.error && stats.lastUpdate == null && stats.errorAt >= since
? t(
'Space Missions unavailable: the mission index could not load. Try again later.',
)
: null;
}
export async function _runUserFacingContextAction(
operation,
message = t('Context could not restore every layer; try again'),
@@ -71,7 +58,6 @@ export function getContextModeState() {
changing: Boolean(this._contextModeChanging),
entering: this._contextModeEntering || null,
canContact: !this._contextMode || this._contextMode === 'flights',
canMission: !this._contextMode || this._contextMode === 'space-missions',
snapshotCaptured: Boolean(this._contextSessionSnapshot),
};
}
@@ -127,7 +113,7 @@ export async function setContextMode(
};
}
const canonical = mode === 'contacts' ? 'flights' : mode;
if (!['flights', 'space-missions'].includes(canonical)) {
if (canonical !== 'flights') {
return {
ok: false,
action: 'set_context_mode',
@@ -222,8 +208,6 @@ export function clearSelectedLayers() {
this._contextModeChanging = true;
this._contextMode = null;
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._contextSessionSnapshot = null;
this._contextRestoreState = null;
this._preservePanelStateDuringLayerClear = true;
-54
View File
@@ -1,28 +1,8 @@
import { t } from '../i18n/index.js';
import { spaceMissionsIndexFailure } from './contextActions.js';
import { translateStatusMessage } from './statusText.js';
import { shouldExpandGlobalContextPanel } from '../rightRailPolicy.js';
export function _initGlobalContextPanel() {
const contextTabs = [
this._globalContextFlightsBtn,
this._globalContextMissionsBtn,
].filter(Boolean);
contextTabs.forEach((tab, index) =>
this.listen(tab, 'keydown', (event) => {
let nextIndex = null;
if (event.key === 'ArrowRight')
nextIndex = (index + 1) % contextTabs.length;
else if (event.key === 'ArrowLeft')
nextIndex = (index - 1 + contextTabs.length) % contextTabs.length;
else if (event.key === 'Home') nextIndex = 0;
else if (event.key === 'End') nextIndex = contextTabs.length - 1;
if (nextIndex === null) return;
event.preventDefault();
contextTabs[nextIndex].focus({ preventScroll: true });
contextTabs[nextIndex].click();
}),
);
this.listen(this._globalContextFlightsBtn, 'click', () => {
if (
this.destroyed ||
@@ -51,40 +31,6 @@ export function _initGlobalContextPanel() {
});
});
});
this.listen(this._globalContextMissionsBtn, 'click', () => {
if (
this.destroyed ||
this._contextModeChanging ||
this._clearSelectedLayersPromise
)
return;
const nextMode =
this._contextMode === 'space-missions' ? null : 'space-missions';
this._claimContextVisualAuthority();
const startedAt = Date.now();
void this._runUserFacingContextAction(
(notificationToken) =>
this._selectContextMode(nextMode, { notificationToken }),
() =>
(nextMode && spaceMissionsIndexFailure(this._dataManager, startedAt)) ||
t(
'Space Missions could not complete the requested transition; try again',
),
).then((succeeded) => {
if (
!this.destroyed &&
nextMode &&
shouldExpandGlobalContextPanel({
action: 'space-missions',
explicitUserAction: true,
succeeded: succeeded === true,
})
)
this.actions.setPanelCollapsed('global-context-panel', false, {
explicit: true,
});
});
});
this.listen(this._installationsSearchBtn, 'click', () => {
if (
this.destroyed ||
-3
View File
@@ -44,9 +44,6 @@ export class ContextControls {
this._contextModeChanging = false;
this._contextModeGeneration = 0;
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._contextModeDeferredEntryIntent = null;
this._contextSessionSnapshot = null;
this._contextRestoreState = null;
this._contextLayerReactionPromises = new Set();
-1
View File
@@ -48,7 +48,6 @@ test('Context starts with an explicit idle snapshot', (t) => {
changing: false,
entering: null,
canContact: true,
canMission: true,
snapshotCaptured: false,
});
});
+4 -51
View File
@@ -2,10 +2,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { setLocale } from '../i18n/index.js';
import {
contextLayerEnableBlockReason,
parseContextLayerBlockReason,
} from '../contextModePolicy.js';
import {
_handleContextLayerChange,
localizeVisibilityBlockReason,
@@ -18,7 +14,7 @@ function fakeShell() {
_userFacingContextNotificationTokens: new Set(),
_contextSessionSnapshot: null,
_contextModeChanging: false,
_contextMode: 'space-missions',
_contextMode: null,
_contextModeEntering: null,
_syncContextModeButtons() {},
showToast(message) {
@@ -28,41 +24,19 @@ function fakeShell() {
};
}
const ENGLISH_GUARD =
'Space Missions isolates replay data. Exit the mode to enable Live Flights.';
test.afterEach(() => setLocale('en'));
test('the guard reason is English data and parses back to its layer name', () => {
const reason = contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { layerId: 'flights', enabled: true, origin: 'user' },
layerName: 'Live Flights',
});
assert.equal(reason, ENGLISH_GUARD);
assert.deepEqual(parseContextLayerBlockReason(reason), {
layer: 'Live Flights',
});
assert.equal(parseContextLayerBlockReason('Data source unavailable'), null);
assert.equal(
parseContextLayerBlockReason(
'Space Missions isolates replay data. Exit the mode to enable .',
),
null,
);
});
test('en: the toast shows the reason unchanged', () => {
setLocale('en');
const shell = fakeShell();
_handleContextLayerChange.call(shell, {
type: 'visibility-blocked',
layerId: 'flights',
layerId: 'street-level',
enabled: true,
origin: 'user',
reason: ENGLISH_GUARD,
reason: 'Data source unavailable',
});
assert.deepEqual(shell.toasts, [ENGLISH_GUARD]);
assert.deepEqual(shell.toasts, ['Data source unavailable']);
assert.equal(
localizeVisibilityBlockReason('Overpass returned HTTP 503'),
'Overpass returned HTTP 503',
@@ -70,27 +44,6 @@ test('en: the toast shows the reason unchanged', () => {
});
for (const locale of ['es', 'ru']) {
test(`${locale}: the Space Missions block toast is localized with the layer name`, () => {
setLocale(locale);
const reason = contextLayerEnableBlockReason({
contextMode: 'space-missions',
change: { layerId: 'flights', enabled: true, origin: 'user' },
layerName: 'Live Flights',
});
const shell = fakeShell();
_handleContextLayerChange.call(shell, {
type: 'visibility-blocked',
layerId: 'flights',
enabled: true,
origin: 'user',
reason,
});
assert.equal(shell.toasts.length, 1);
assert.notEqual(shell.toasts[0], ENGLISH_GUARD, 'toast must be localized');
assert.doesNotMatch(shell.toasts[0], /Space Missions isolates/);
assert.doesNotMatch(shell.toasts[0], /Live Flights/);
});
test(`${locale}: a known lifecycle reason is looked up in the catalog`, () => {
setLocale(locale);
const shell = fakeShell();
+21 -109
View File
@@ -1,28 +1,16 @@
import { t, translateKnown } from '../i18n/index.js';
import {
SPACE_MISSIONS_LAYER_BLOCK_REASON,
isExplicitUserIntentOrigin,
parseContextLayerBlockReason,
recordContextRestoreExplicitChange,
recordContextSessionUserChange,
shouldExitContextForLayerChange,
spaceMissionEntryCancellationDisposition,
} from '../contextModePolicy.js';
import { localizeLayerName } from './layerNames.js';
import { spaceMissionsIndexFailure } from './contextActions.js';
/**
* A blocked-visibility reason in the UI language. Reasons stay English (voice
* and tools read them): the Space Missions refusal is rebuilt with the layer
* name localized, a known sentence is looked up, anything else passes.
* and tools read them): a known sentence is looked up, anything else passes.
*/
export function localizeVisibilityBlockReason(reason) {
if (typeof reason !== 'string' || !reason) return reason;
const blocked = parseContextLayerBlockReason(reason);
if (blocked)
return t(SPACE_MISSIONS_LAYER_BLOCK_REASON, {
layer: localizeLayerName(blocked.layer),
});
return translateKnown(reason);
}
@@ -40,74 +28,12 @@ export function _handleContextLayerChange(change) {
this.actions.refreshRadio();
}
if (change?.type === 'visibility-transition') return;
// The effective mode must be read BEFORE the entering flag is cleared:
// the entry layer's own enable event is the one that clears it, and the
// session bookkeeping below needs to know a mode was being entered.
// A mode still being entered counts for the session bookkeeping below.
const effectiveContextMode = this._contextModeEntering || this._contextMode;
if (change?.type === 'visibility-cancelled') {
const cancellationDisposition = spaceMissionEntryCancellationDisposition({
change,
});
if (
this._contextModeDeferredEntryIntent?.layerId === change.layerId &&
this._contextModeDeferredEntryIntent.intentEpoch === change.intentEpoch
) {
if (cancellationDisposition !== 'replacement') {
this._contextModeDeferredEntryIntent = null;
}
}
if (cancellationDisposition === 'replacement') {
this._contextModeEntering = 'space-missions';
const entryIntent = this._contextModeEntryIntent;
if (
entryIntent?.generation === this._contextModeGeneration &&
entryIntent.layerId === change.layerId &&
entryIntent.intentEpoch === change.intentEpoch
) {
this._contextModeReplacementIntent = {
generation: entryIntent.generation,
layerId: change.layerId,
intentEpoch: change.successorIntentEpoch,
};
}
} else if (cancellationDisposition === 'restore') {
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
if (this._contextSessionSnapshot && !this._contextModeChanging) {
this._contextMode = null;
void this._trackContextLayerReaction(
this._runUserFacingContextAction(
async (notificationToken) => {
await this._restoreContextSessionAfterLayerSettles(
change.layerId,
{
notificationToken,
},
);
return true;
},
'Space Missions cancellation could not restore the previous layer state', // i18n-ignore: English message; the toast shows localizedMessage
{
localizedMessage: t(
'Space Missions cancellation could not restore the previous layer state',
),
},
),
);
}
}
this._syncContextModeButtons();
return;
}
if (
change?.layerId === 'rocket-launches' &&
['visibility', 'visibility-blocked', 'visibility-failed'].includes(
change.type,
)
) {
this._contextModeEntering = null;
}
if (change?.type === 'visibility-blocked') {
if (
!this._userFacingContextNotificationTokens.has(change.notificationToken)
@@ -121,10 +47,13 @@ export function _handleContextLayerChange(change) {
return;
}
if (change?.type === 'visibility-failed') {
// A layer may name why its own start failed (Space Missions: the
// mission index never loaded).
const failureMessage =
(change.layerId === 'rocket-launches' &&
change.enabled &&
spaceMissionsIndexFailure(this._dataManager)) ||
(change.enabled &&
this._dataManager?.layers
?.get(change.layerId)
?.module?.enableFailureMessage?.()) ||
t('{layerId} could not {action} cleanly', {
layerId: change.layerId,
action: change.enabled ? t('start') : t('stop'),
@@ -134,7 +63,7 @@ export function _handleContextLayerChange(change) {
// notification for this queue to settle, then reconcile the complete
// snapshot, including an uncertain failed shell.
const needsDeferredShellRestore =
['military-awareness', 'rocket-launches'].includes(change.layerId) &&
change.layerId === 'military-awareness' &&
change.enabled &&
this._contextSessionSnapshot &&
!this._contextModeChanging;
@@ -212,26 +141,6 @@ export function _handleContextLayerChange(change) {
),
);
}
} else if (change.layerId === 'rocket-launches') {
const ownsContextEntry =
isExplicitUserIntentOrigin(change.origin, change.layerId) ||
this._contextMode === 'space-missions' ||
effectiveContextMode === 'space-missions';
if (!ownsContextEntry) return;
this._contextMode = change.enabled
? 'space-missions'
: this._contextMode === 'space-missions'
? null
: this._contextMode;
if (change.enabled) {
this._syncContextModeButtons();
} else if (this._contextSessionSnapshot) {
void this._trackContextLayerReaction(
this._runUserFacingContextAction((notificationToken) =>
this._deactivateContextForLayerChange({ notificationToken }),
),
);
}
} else if (
this._contextMode === 'flights' &&
[
@@ -254,23 +163,26 @@ export function _handleContextLayerChange(change) {
change.enabled &&
change.origin === 'user' &&
!this.cockpitView?.active &&
(change.layerId === 'radio' || change.layerId === 'rocket-launches')
change.layerId === 'radio'
) {
// Context's panel shows its main tab for them (ContextView listens).
globalThis.dispatchEvent?.(new Event('gev:context-show-view'));
this.actions.setPanelCollapsed('global-context-panel', false, {
explicit: true,
});
if (change.layerId === 'radio')
this.actions.setPanelCollapsed('radio-panel', false, { explicit: true });
this.actions.setPanelCollapsed('radio-panel', false, { explicit: true });
}
finishContextLayerChange(this);
}
/** The checks every settled layer change ends with. */
function finishContextLayerChange(controls) {
// Turning off the layer the view rides ends it; every other layer may be
// turned on or off freely during a session.
const riddenLayerId = this.cockpitView?.active
? this.cockpitView.readSubjectLayerId?.()
const riddenLayerId = controls.cockpitView?.active
? controls.cockpitView.readSubjectLayerId?.()
: null;
if (riddenLayerId && !this._dataManager?.isEnabled(riddenLayerId)) {
this.cockpitView.exit({ restoreTracking: false });
if (riddenLayerId && !controls._dataManager?.isEnabled(riddenLayerId)) {
controls.cockpitView.exit({ restoreTracking: false });
}
this._syncContextModeButtons();
controls._syncContextModeButtons();
}
+22 -43
View File
@@ -22,7 +22,6 @@ function fixture(t) {
const controls = new ContextControls({
elements: {
_globalContextFlightsBtn: $('global-context-flights-btn'),
_globalContextMissionsBtn: $('global-context-missions-btn'),
_installationsSearchBtn: $('installations-search-btn'),
},
installations: {},
@@ -58,61 +57,41 @@ test('before ContextControls renders, the switch shows its initial markup', (t)
'ui-panel panel-collapsible collapsed ui-panel--collapsed',
);
assert.equal(panel.hasAttribute('data-context-mode'), false);
for (const id of [
'global-context-flights-btn',
'global-context-missions-btn',
]) {
const tab = $(id);
assert.equal(tab.className, 'context-mode-button');
assert.equal(tab.getAttribute('aria-selected'), 'false');
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.hasAttribute('aria-busy'), false);
}
const tab = $('global-context-flights-btn');
assert.equal(tab.className, 'context-mode-button');
assert.equal(tab.getAttribute('aria-selected'), 'false');
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.hasAttribute('aria-busy'), false);
assert.equal($('context-mode-standby').hidden, false);
assert.equal($('context-flights-view').hidden, true);
assert.equal($('context-missions-view').hidden, true);
assert.equal($('global-context-missions-btn'), null);
assert.equal($('context-missions-view'), null);
assert.equal($('installations-search-btn').hasAttribute('aria-busy'), false);
});
test('a transition keeps focus and Tab on both tabs until it settles', async (t) => {
test('a Contacts transition keeps the tab focusable until it settles', async (t) => {
const { $, controls, sync } = fixture(t);
const contacts = $('global-context-flights-btn');
const missions = $('global-context-missions-btn');
missions.focus();
contacts.focus();
controls._contextModeChanging = true;
await sync();
assert.equal(
document.activeElement === missions,
true,
'busy render keeps focus',
);
for (const tab of [contacts, missions]) {
assert.equal(tab.disabled, false);
assert.equal(tab.getAttribute('tabindex'), '0');
assert.equal(tab.getAttribute('aria-disabled'), 'true');
assert.equal(tab.getAttribute('aria-busy'), 'true');
}
assert.equal(document.activeElement, contacts);
assert.equal(contacts.disabled, false);
assert.equal(contacts.getAttribute('tabindex'), '0');
assert.equal(contacts.getAttribute('aria-disabled'), 'true');
assert.equal(contacts.getAttribute('aria-busy'), 'true');
controls._contextModeChanging = false;
controls._contextMode = 'space-missions';
controls._contextMode = 'flights';
await sync();
assert.equal(
document.activeElement === missions,
true,
'settled render keeps focus',
);
for (const tab of [contacts, missions]) {
assert.equal(tab.disabled, false);
assert.equal(tab.getAttribute('aria-disabled'), 'false');
assert.equal(tab.getAttribute('aria-busy'), 'false');
}
assert.equal(missions.classList.contains('active'), true);
assert.equal(missions.getAttribute('aria-selected'), 'true');
assert.equal(contacts.classList.contains('active'), false);
assert.equal(contacts.getAttribute('aria-selected'), 'false');
assert.equal(document.activeElement, contacts);
assert.equal(contacts.disabled, false);
assert.equal(contacts.getAttribute('aria-disabled'), 'false');
assert.equal(contacts.getAttribute('aria-busy'), 'false');
assert.equal(contacts.classList.contains('active'), true);
assert.equal(contacts.getAttribute('aria-selected'), 'true');
assert.equal($('context-mode-standby').hidden, true);
assert.equal($('context-flights-view').hidden, true);
assert.equal($('context-missions-view').hidden, false);
assert.equal($('context-flights-view').hidden, false);
});
test('the panel carries the mode beside the classes its chrome writes', async (t) => {
+1 -8
View File
@@ -12,17 +12,10 @@ export function _syncContextModeButtons() {
export function _presentContext() {
if (this.destroyed) return;
const flightsActive = this._contextMode === 'flights';
const missionsActive = this._contextMode === 'space-missions';
// Both Context choices stay in the ordinary Tab sequence and are never
// native-disabled. Arrow keys still provide tablist navigation, but must
// not be the only way to reach Space Missions from the keyboard. Semantic
// busy state keeps them perceivable while synchronous click guards prevent
// a second transition.
this.publish({
mode: this._contextMode || 'none',
enabled: flightsActive || missionsActive,
enabled: flightsActive,
flightsActive,
missionsActive,
busy: Boolean(this._contextModeChanging),
installationsBusy: this._installationsSearchBusy,
});
+8 -4
View File
@@ -1,4 +1,5 @@
import {
CONTEXT_INDEPENDENT_LAYER_IDS,
contextRestoreLayerIds,
contextSnapshotLayerIds,
mergeContextTransitionErrors,
@@ -24,7 +25,8 @@ export async function _waitForContextLayerSettlement() {
export function _captureContextSessionSnapshot({ excludeLayerIds = [] } = {}) {
if (!this._dataManager || this._contextSessionSnapshot) return;
const params = {};
for (const layerId of ['military-awareness', 'satellites']) {
// Satellites is not Context's: the mission controller owns its parameters.
for (const layerId of ['military-awareness']) {
const value = this._dataManager.getLayerParams(layerId);
if (value) params[layerId] = value;
}
@@ -93,9 +95,11 @@ export async function _restoreContextSession({
restoreState.enabledLayerIds,
{
origin: 'context-restore',
excludeLayerIds: settleContactsCoordinator
? [...excludeLayerIds, contactsCoordinatorId]
: excludeLayerIds,
excludeLayerIds: [
...excludeLayerIds,
...CONTEXT_INDEPENDENT_LAYER_IDS,
...(settleContactsCoordinator ? [contactsCoordinatorId] : []),
],
notificationToken,
...(restoreSignal ? { signal: restoreSignal } : {}),
},
+38 -104
View File
@@ -1,11 +1,8 @@
import { t } from '../i18n/index.js';
import {
contextLayerEnableBlockReason,
isExplicitUserIntentOrigin,
runWithContextModeChanging,
settleContextModeChange,
shouldCaptureContextSession,
shouldDeferContextEntryDuringClear,
} from '../contextModePolicy.js';
export function connectContextManager(manager) {
@@ -28,31 +25,6 @@ export function connectContextManager(manager) {
this._captureContextSessionSnapshot({
excludeLayerIds: [change.layerId],
});
if (
shouldDeferContextEntryDuringClear({
change,
clearInFlight: Boolean(this._clearSelectedLayersPromise),
})
) {
this._contextModeDeferredEntryIntent = {
layerId: change.layerId,
intentEpoch: change.intentEpoch,
origin: change.origin,
};
this._contextModeEntering = 'space-missions';
this._syncContextModeButtons();
}
} else if (
change?.layerId === 'rocket-launches' &&
change.enabled === false &&
isExplicitUserIntentOrigin(change.origin, change.layerId)
) {
this._contextModeDeferredEntryIntent = null;
if (this._clearSelectedLayersPromise) {
this._contextSessionSnapshot = null;
this._contextModeEntering = null;
this._syncContextModeButtons();
}
}
});
}
@@ -60,88 +32,50 @@ export function connectContextManager(manager) {
this._dataManagerVisibilityGuardUnsubscribe =
this._dataManager.addVisibilityGuard(async (change) => {
if (this.destroyed) return null;
const layerName =
this._dataManager?.layers?.get(change.layerId)?.module?.name ||
change.layerId;
const reason = contextLayerEnableBlockReason({
contextMode: this._contextModeEntering || this._contextMode,
change,
layerName,
});
if (reason) return reason;
// A direct Contacts start (the coordinator layer itself, not the
// Context chooser) isolates its dependencies like the chooser does.
if (
change.enabled &&
['military-awareness', 'rocket-launches'].includes(change.layerId) &&
shouldCaptureContextSession(change) &&
(!this._contextModeChanging ||
(change.layerId === 'rocket-launches' &&
this._contextModeDeferredEntryIntent?.intentEpoch ===
change.intentEpoch))
) {
const entryMode =
change.layerId === 'rocket-launches' ? 'space-missions' : null;
const deferredClearEntry =
this._contextModeDeferredEntryIntent?.intentEpoch ===
change.intentEpoch;
// A deferred entry owns the state after Clear settles. Restoring
// Clear's transient busy flag here would leave Context stuck.
const priorChanging = deferredClearEntry
? false
: this._contextModeChanging;
const notificationToken =
change.notificationToken || Symbol('direct-context-shell-entry');
const ownsNotificationToken = !change.notificationToken;
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.add(notificationToken);
}
this._contextModeEntering = entryMode;
this._contextModeChanging = true;
!change.enabled ||
change.layerId !== 'military-awareness' ||
!shouldCaptureContextSession(change) ||
this._contextModeChanging
)
return null;
const notificationToken =
change.notificationToken || Symbol('direct-context-shell-entry');
const ownsNotificationToken = !change.notificationToken;
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.add(notificationToken);
}
this._contextModeEntering = null;
this._contextModeChanging = true;
try {
await this._clearLayersOutsideContextMode(null, {
notificationToken,
});
if (this.destroyed) return false;
} catch (error) {
console.warn(`[Context] ${change.layerId} isolation failed`, error);
try {
if (deferredClearEntry) {
await this._clearSelectedLayersManagerPromise;
if (this.destroyed) return false;
if (
this._contextModeDeferredEntryIntent?.intentEpoch !==
change.intentEpoch
)
return false;
this._contextModeDeferredEntryIntent = null;
}
await this._clearLayersOutsideContextMode(entryMode, {
await this._restoreContextSession({
excludeLayerIds: [change.layerId],
notificationToken,
});
if (this.destroyed) return false;
} catch (error) {
this._contextModeEntering = null;
console.warn(`[Context] ${change.layerId} isolation failed`, error);
try {
await this._restoreContextSession({
excludeLayerIds: [change.layerId],
notificationToken,
});
} catch (restoreError) {
console.warn(
`[Context] ${change.layerId} rollback failed`,
restoreError,
);
}
return t(
'{mode} could not start because another layer did not stop cleanly',
{
mode:
entryMode === 'space-missions'
? t('Space Missions')
: t('Context'),
},
} catch (restoreError) {
console.warn(
`[Context] ${change.layerId} rollback failed`,
restoreError,
);
} finally {
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.delete(
notificationToken,
);
}
if (!this.destroyed) settleContextModeChange(this, priorChanging);
}
return t(
'{mode} could not start because another layer did not stop cleanly',
{ mode: t('Context') },
);
} finally {
if (ownsNotificationToken) {
this._userFacingContextNotificationTokens.delete(notificationToken);
}
if (!this.destroyed) settleContextModeChange(this, false);
}
return null;
});
+2 -62
View File
@@ -13,8 +13,6 @@ export async function _selectContextMode(
const generation = ++this._contextModeGeneration;
const isCurrent = () =>
!this.destroyed && generation === this._contextModeGeneration;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._contextModeChanging = true;
this._syncContextModeButtons();
try {
@@ -47,9 +45,6 @@ export async function _selectContextMode(
this._captureContextSessionSnapshot();
this._contextMode = mode;
this._syncContextModeButtons();
// Replay isolation must settle before Space Missions starts. Contacts
// keeps its non-dependency teardown in the background so slow source
// shutdown does not delay cockpit entry.
try {
await this._clearLayersOutsideContextMode(mode, {
notificationToken,
@@ -82,13 +77,8 @@ export async function _selectContextMode(
// Entry is one transaction: isolation succeeded above, so a failed mode
// activation must roll the cleared layers back instead of stranding the
// user in a half-entered mode with an orphaned snapshot.
const entryLayerId =
mode === 'flights' ? 'military-awareness' : 'rocket-launches';
if (mode === 'flights') {
this._dataManager.setLayerParams('military-awareness', {
passive: false,
});
}
const entryLayerId = 'military-awareness';
this._dataManager.setLayerParams(entryLayerId, { passive: false });
let activated = false;
let activationError = null;
let activationIntent = null;
@@ -99,11 +89,6 @@ export async function _selectContextMode(
true,
{ notificationToken, ...(signal ? { signal } : {}) },
);
this._contextModeEntryIntent = {
generation,
layerId: entryLayerId,
intentEpoch: activationIntent.intentEpoch,
};
activated = await activationIntent.promise;
terminalIntentOutcome =
await this._dataManager._waitForVisibilityIntent?.(
@@ -114,46 +99,6 @@ export async function _selectContextMode(
activationError = error;
}
if (!isCurrent()) return false;
let replacementIntent =
mode === 'space-missions' &&
this._contextModeReplacementIntent?.generation === generation &&
this._contextModeReplacementIntent.layerId === entryLayerId
? this._contextModeReplacementIntent
: null;
while (replacementIntent) {
const outcome = await this._dataManager._waitForVisibilityIntent?.(
entryLayerId,
replacementIntent.intentEpoch,
);
terminalIntentOutcome = outcome;
if (!isCurrent()) return false;
const replacementOwnsMode =
outcome?.intentEpoch === replacementIntent.intentEpoch &&
outcome.enabled === true &&
outcome.succeeded === true;
if (replacementOwnsMode) {
this._contextModeEntering = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._syncContextModeButtons();
return true;
}
const successorEpoch =
outcome?.cancellationReason === 'superseded' &&
outcome.successorEnabled === true &&
Number.isInteger(outcome.successorIntentEpoch) &&
outcome.successorIntentEpoch > replacementIntent.intentEpoch
? outcome.successorIntentEpoch
: null;
replacementIntent =
successorEpoch === null
? null
: {
generation,
layerId: entryLayerId,
intentEpoch: successorEpoch,
};
}
if (
activationError ||
activated === false ||
@@ -182,8 +127,6 @@ export async function _selectContextMode(
);
}
this._contextMode = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
this._syncContextModeButtons();
try {
await this._restoreContextSession({
@@ -205,7 +148,6 @@ export async function _selectContextMode(
// while callers still require literal `true` before expanding Context.
return cancelledAndSettled ? null : false;
}
this._contextModeEntryIntent = null;
return true;
} finally {
if (isCurrent()) {
@@ -221,8 +163,6 @@ export async function _deactivateContextForLayerChange({
this._contextModeGeneration += 1;
this._contextModeChanging = true;
this._contextMode = null;
this._contextModeEntryIntent = null;
this._contextModeReplacementIntent = null;
// A layer turned off ends Contacts but not the Cockpit: the view ends only
// when the layer it rides goes off (see _handleContextLayerChange).
this._syncContextModeButtons();
+5
View File
@@ -50,6 +50,9 @@ export class LayerBindings {
get _contextControls() {
return this.readControls()._contextControls;
}
get _spaceMissionsControls() {
return this.readControls()._spaceMissionsControls;
}
get _cctvControls() {
return this.readControls()._cctvControls;
}
@@ -254,6 +257,7 @@ export class LayerBindings {
this._dataManagerUnsubscribe = null;
}
this._contextControls.connect(this._dataManager);
this._spaceMissionsControls?.connect(this._dataManager);
if (typeof this._dataManager?.subscribe === 'function') {
this._dataManagerUnsubscribe = this._dataManager.subscribe((change) => {
this._feedback._loadingFeedbackEvent = change;
@@ -319,6 +323,7 @@ export class LayerBindings {
this._directionsShellModule?.attachShellServices?.(null);
this._directionsShellModule = null;
this._dataManager = null;
this._spaceMissionsControls?.connect(null);
this._connectWeatherCamera();
}
}
+6 -6
View File
@@ -6,14 +6,14 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createPinia } from 'pinia';
import { createApp, h, nextTick } from 'vue';
import { useContextStore } from './stores/context.js';
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
import MissionDetail from './views/panels/MissionDetail.vue';
import MissionRoster from './views/panels/MissionRoster.vue';
function fixture(t) {
document.body.replaceChildren();
const scroller = document.body.appendChild(document.createElement('div'));
scroller.className = 'global-context-panel-inner';
scroller.className = 'space-missions-panel-inner';
const host = scroller.appendChild(document.createElement('div'));
const pinia = createPinia();
const app = createApp({
@@ -21,13 +21,13 @@ function fixture(t) {
}).use(pinia);
app.mount(host);
t.after(() => app.unmount());
const store = useContextStore(pinia);
const store = useSpaceMissionsStore(pinia);
const calls = [];
const record =
(name) =>
(...args) =>
calls.push([name, ...args]);
store.connectMissions({
store.connect({
selectMissionAt: record('select'),
selectPreviousMission: record('previous'),
selectNextMission: record('next'),
@@ -44,7 +44,7 @@ function fixture(t) {
});
const $ = (selector) => document.querySelector(selector);
const publish = async (view) => {
store.publishMissions(view);
store.publish(view);
await nextTick();
await nextTick();
};
@@ -325,7 +325,7 @@ test('the replay controls follow the layer and call its commands', async (t) =>
]);
});
test('each newly presented selection returns the Context panel to the top', async (t) => {
test('each newly presented selection returns the Space Missions panel to the top', async (t) => {
const { publish, scroller } = fixture(t);
scroller.scrollTop = 120;
await publish({ roster: null, mission: mission({ scrollRequest: 4 }) });
+23 -2
View File
@@ -30,6 +30,7 @@ export const MOBILE_SHEET_PANELS = Object.freeze({
layers: Object.freeze(['data-panel']),
cameras: Object.freeze(['cctv-panel', 'street-level-panel']),
context: Object.freeze(['global-context-panel']),
missions: Object.freeze(['space-missions-panel']),
search: Object.freeze(['location-bar']),
more: Object.freeze(['control-panel', 'pp-toggles']),
});
@@ -38,6 +39,11 @@ export const MOBILE_TABS = Object.freeze([
Object.freeze({ sheet: 'layers', label: msg('Layers'), icon: 'layers' }),
Object.freeze({ sheet: 'cameras', label: msg('Cameras'), icon: 'videocam' }),
Object.freeze({ sheet: 'context', label: msg('Context'), icon: 'radar' }),
Object.freeze({
sheet: 'missions',
label: msg('Space Missions'),
icon: 'rocket_launch',
}),
Object.freeze({ sheet: 'search', label: msg('Search'), icon: 'search' }),
Object.freeze({ sheet: 'more', label: msg('More'), icon: 'more_horiz' }),
]);
@@ -142,6 +148,7 @@ export function initMobileShell({
.map(element)
.filter(Boolean);
const dock = element('command-dock');
const missionsPanel = element('space-missions-panel');
const shown = (node) =>
node && globalThis.getComputedStyle?.(node).display !== 'none';
@@ -254,7 +261,9 @@ export function initMobileShell({
const setSheet = (requested) => {
swipe = null;
if (!body.classList.contains(MOBILE_SHELL_CLASS)) return;
const sheet = sheetBlocked(body) ? null : requested;
const unavailableMissions =
requested === 'missions' && missionsPanel?.hidden;
const sheet = sheetBlocked(body) || unavailableMissions ? null : requested;
const previous = currentSheetOf(body);
if (previous === sheet) return;
if (!previous) {
@@ -487,9 +496,21 @@ export function initMobileShell({
if (typeof MutationObserverImpl === 'function') {
const observer = new MutationObserverImpl(() => {
if (currentSheetOf(body) && sheetBlocked(body)) setSheet(null);
const sheet = currentSheetOf(body);
if (!sheet) return;
if (sheet === 'missions' && missionsPanel?.hidden) {
returnFocus = tabFor('layers') ?? returnFocus;
setSheet(null);
} else if (sheetBlocked(body)) {
setSheet(null);
}
});
observer.observe(body, { attributes: true, attributeFilter: ['class'] });
if (missionsPanel)
observer.observe(missionsPanel, {
attributes: true,
attributeFilter: ['hidden'],
});
removers.push(() => observer.disconnect());
}
+2 -3
View File
@@ -903,12 +903,11 @@ test('manual Context opens the existing transaction without disabling the tracke
}
});
test('manual Context respects Space Missions, busy transitions, missing tracks and disposal', async () => {
test('manual Context respects an active mode, busy transitions, missing tracks and disposal', async () => {
for (const state of [
{ mode: 'space-missions' },
{ mode: 'flights' },
{ changing: true },
{ entering: 'space-missions' },
{ entering: 'flights' },
{ noTrack: true },
{ disposed: true },
{ sheet: 'layers' },
+6
View File
@@ -83,6 +83,12 @@ const PANEL_NAMES = [
[/display( panel)?|visual( panel)?/, 'left', 'pp-toggles', msg('Visual')],
[/cctv panel|cameras? panel/, 'right', 'cctv-panel', msg('CCTV')],
[/street ?level panel/, 'right', 'street-level-panel', msg('Street Level')],
[
/(space )?missions? panel/,
'right',
'space-missions-panel',
msg('Space Missions'),
],
[/context( panel)?/, 'right', 'global-context-panel', msg('Context')],
];
const CLOSE = /\b(collapse|close|hide|minimi[sz]e|dismiss|shut|fold)\b/;
+10
View File
@@ -123,6 +123,16 @@ test('near-miss lines read as people mean them', () => {
]);
assert.equal(isPanelText('show earthquake data layer'), false);
assert.equal(read('open data layers')[0].item, 'data-panel');
assert.equal(
read('open space missions panel')[0].item,
'space-missions-panel',
);
assert.equal(
read('close the missions panel')[0].item,
'space-missions-panel',
);
// Without "panel" it is the layer, not its panel.
assert.equal(isPanelText('show space missions'), false);
assert.deepEqual(read('go to trinidad and tobago and show flights'), [
{ kind: 'place', place: 'trinidad and tobago' },
{ kind: 'layer', id: 'flights', enabled: true },
+7 -13
View File
@@ -503,19 +503,13 @@ export const COMMANDS = Object.freeze([
name: 'Visual',
},
),
cmd(
'open-context',
msg('Open Context'),
'context missions panel open',
'radar',
{
kind: 'panel',
action: 'open',
side: 'right',
item: 'global-context-panel',
name: 'Context',
},
),
cmd('open-context', msg('Open Context'), 'context panel open', 'radar', {
kind: 'panel',
action: 'open',
side: 'right',
item: 'global-context-panel',
name: 'Context',
}),
cmd('reset', msg('Reset view'), 'home start over reset camera', 'public', {
kind: 'camera',
act: 'reset',
+2
View File
@@ -22,6 +22,7 @@ const SHARE_PANEL_STATE_SPECS = Object.freeze([
{ id: 'radio-panel' },
{ id: 'scene-panel' },
{ id: 'global-context-panel' },
{ id: 'space-missions-panel' },
{ id: 'pp-toggles' },
{ id: 'param-slider-panel' },
]);
@@ -48,6 +49,7 @@ const COCKPIT_ENTRY_COLLAPSE_PANEL_IDS = Object.freeze([
'utilities-panel',
'pp-toggles',
'global-context-panel',
'space-missions-panel',
'radio-panel',
]);
+25
View File
@@ -427,6 +427,31 @@ test('destroying the chrome inside Cockpit puts back the panels its entry closed
assert.equal(data.classList.contains('collapsed'), false);
});
test('Cockpit entry folds the Space Missions panel away and exit brings it back', () => {
document.body.innerHTML = `<div id="space-missions-panel"></div>`;
const store = usePanelChromeStore(createPinia());
const chrome = panelChrome(store);
const missions = document.getElementById('space-missions-panel');
followPanelState(store, 'space-missions-panel', missions);
chrome.enterCockpit();
assert.equal(missions.classList.contains('collapsed'), true);
chrome.exitCockpit();
assert.equal(missions.classList.contains('collapsed'), false);
chrome.destroy();
});
test('a share link records whether the Space Missions panel is open', () => {
document.body.innerHTML = `<div id="space-missions-panel"></div>`;
const store = usePanelChromeStore(createPinia());
const chrome = panelChrome(store);
const state = chrome._buildSharePanelState();
assert.deepEqual(
state.specs.filter((spec) => spec.id === 'space-missions-panel'),
[{ id: 'space-missions-panel', collapsed: false }],
);
chrome.destroy();
});
test('the accordion closes peers through the real store, and opens them again', () => {
document.body.innerHTML = `
<div id="data-panel" data-panel-id="data-panel"></div>
+1
View File
@@ -237,6 +237,7 @@ export class PanelLayoutController {
this._recentImageryPanel,
this._streetLevelPanel,
globalContextPanel,
document.getElementById('space-missions-panel'),
document.getElementById('radio-panel'),
]) {
if (panel) this._rightStackResizeObserver.observe(panel);
+4
View File
@@ -31,6 +31,10 @@ export const PANEL_RAIL_ITEMS = Object.freeze({
},
'street-level-panel': { icon: 'streetview', label: msg('STREET LEVEL') },
'global-context-panel': { icon: 'radar', label: msg('CONTEXT') },
'space-missions-panel': {
icon: 'rocket_launch',
label: msg('Space Missions'),
},
});
/**
+11
View File
@@ -164,6 +164,17 @@ test('the default theme geometry change leaves the base gutters alone', () => {
assert.match(display?.body || '', /font-size:\s*12px/);
});
test('Data Layers, Context and Space Missions share the 14px side gutters', () => {
const gutters = rules.find(
({ selector, body }) =>
/:is\(\s*\.data-panel-inner,\s*\.global-context-panel-inner,\s*\.space-missions-panel-inner\s*\)$/.test(
selector,
) && /padding-left:\s*14px/.test(body),
);
assert.ok(gutters, 'one rule sets the shared gutters');
assert.match(gutters.body, /padding-right:\s*14px/);
});
test('rail titles and dock labels share one set of label tokens', () => {
// command-dock-trays.css sets the dock's label type; earlier dock rules
// for the same selector are overridden by it.
-3
View File
@@ -35,9 +35,6 @@ export function readShellElements(document = globalThis.document) {
_globalContextFlightsBtn: document.getElementById(
'global-context-flights-btn',
),
_globalContextMissionsBtn: document.getElementById(
'global-context-missions-btn',
),
_installationsSearchBtn: document.getElementById(
'installations-search-btn',
),
+5 -4
View File
@@ -1038,15 +1038,16 @@ export class ShellFacade {
/**
* Reads global context mode state for voice/state-sync consumers.
* @returns {{mode: 'flights'|'space-missions'|null, active: boolean, changing: boolean, entering: 'flights'|'space-missions'|null, snapshotCaptured: boolean}}
* @returns {{mode: 'flights'|null, active: boolean, changing: boolean, entering: 'flights'|null, snapshotCaptured: boolean}}
*/
getContextModeState(...args) {
return this._contextControls?.getContextModeState(...args);
}
/**
* Sets global context mode (Contacts / Space Missions / off) for voice.
* @param {'contacts'|'space-missions'|'off'|null} mode - Requested context target.
* Sets global context mode (Contacts / off) for voice. Space Missions is
* an ordinary layer, not a Context mode.
* @param {'contacts'|'off'|null} mode - Requested context target.
* @param {object} [options]
* @param {string|Symbol|null} [options.notificationToken]
* @param {AbortSignal|null} [options.signal]
@@ -1056,7 +1057,7 @@ export class ShellFacade {
* lane. Cockpit choreography calls this facade INTERNALLY for its own
* enter/rollback steps; those transitions are not a Context request by the
* operator and must stay inert, so they pass `false`.
* @returns {Promise<{ok:boolean, mode:'flights'|'space-missions'|null, active:boolean, action:string, error?:string}>}
* @returns {Promise<{ok:boolean, mode:'flights'|null, active:boolean, action:string, error?:string}>}
*/
setContextMode(...args) {
return this._contextControls?.setContextMode(...args);
+22 -2
View File
@@ -27,7 +27,8 @@ function fixture(theme = 'tactical') {
for (const panel of left.children) panel.parentElement = left;
const rail = node('rail');
const display = node('pp-toggles'), context = node('global-context-panel'), cctv = node('cctv-panel'), radio = node('radio-panel');
rail.children = [display, context, cctv];
const missions = node('space-missions-panel');
rail.children = [display, context, missions, cctv];
for (const panel of rail.children) panel.parentElement = rail;
context.children = [radio];
radio.parentElement = context;
@@ -43,7 +44,7 @@ function fixture(theme = 'tactical') {
shareLinkManager: { claimRestoreLane: (...args) => claimed.push(args), onPanelStateChange() {} },
};
owner.setPanelCollapsed = PanelChrome.prototype.setPanelCollapsed.bind(owner);
return { layers, scenes, display, context, cctv, radio, owner, saved, claimed,
return { layers, scenes, display, context, missions, cctv, radio, owner, saved, claimed,
doc: { documentElement: { dataset: { uiTheme: theme } }, getElementById: (id) => nodes.get(id) },
};
}
@@ -71,6 +72,25 @@ test('explicit opening collapses side peers and claims their restoration lanes i
}
});
test('the Context and Space Missions panels close each other on desktop', () => {
const f = fixture('tactical'), prior = globalThis.document;
globalThis.document = f.doc;
try {
f.owner.setPanelCollapsed('global-context-panel', false, { explicit: true });
f.owner.setPanelCollapsed('space-missions-panel', false, { explicit: true });
assert.equal(f.missions.classList.contains('collapsed'), false);
assert.equal(f.context.classList.contains('collapsed'), true, 'opening Space Missions closes Context');
f.owner.setPanelCollapsed('global-context-panel', false, { explicit: true });
assert.equal(f.context.classList.contains('collapsed'), false);
assert.equal(f.missions.classList.contains('collapsed'), true, 'opening Context closes Space Missions');
// Radio lives inside Context, so opening it closes Space Missions too.
f.owner.setPanelCollapsed('space-missions-panel', false, { explicit: true });
f.owner.setPanelCollapsed('radio-panel', false, { explicit: true });
assert.equal(f.context.classList.contains('collapsed'), false);
assert.equal(f.missions.classList.contains('collapsed'), true);
} finally { globalThis.document = prior; }
});
test('opening already-expanded Radio reveals Context and closes Display', () => {
const f = fixture('tactical'), prior = globalThis.document;
globalThis.document = f.doc;
+87
View File
@@ -0,0 +1,87 @@
const LAYER_ID = 'rocket-launches';
const PANEL_ID = 'space-missions-panel';
/**
* The Space Missions panel's wiring. Space Missions is an ordinary layer: the
* layer owns its data and Satellites dependency, and this connects it to its
* panel. The panel shows while the layer is on, and opens when the person
* turns the layer on (by hand or by voice) or picks a mission on the globe. Opening it closes the
* other right-side panels, Context among them (see setPanelCollapsed).
*/
export class SpaceMissionsControls {
/**
* @param {object} options
* @param {?object} options.layer The Space Missions layer.
* @param {object} options.store The Space Missions store.
* @param {object} options.actions
* @param {(panelId: string, collapsed: boolean, options?: object) => void} options.actions.setPanelCollapsed
* @param {() => boolean} options.actions.isCockpitActive
* @param {() => void} [options.actions.revealPanel] Opens the phone sheet that
* holds the panel; does nothing on desktop.
*/
constructor({ layer, store, actions }) {
this._layer = layer || null;
this._store = store;
this._actions = actions;
this._manager = null;
this._unsubscribeManager = null;
this.destroyed = false;
store.connect(this._layer);
store.publish(null);
store.setEnabled(false);
this._unsubscribePanel =
this._layer?.subscribePanel?.((view) => store.publish(view)) ?? null;
this._unsubscribeGlobePick =
this._layer?.subscribeGlobePick?.(() => this._reveal()) ?? null;
}
/** Follow a data manager's Space Missions visibility; null disconnects. */
connect(manager) {
this._unsubscribeManager?.();
this._unsubscribeManager = null;
this._manager = manager || null;
if (this.destroyed) return;
this._syncEnabled();
this._unsubscribeManager =
this._manager?.subscribe?.((change) => this._handleChange(change)) ??
null;
}
_syncEnabled() {
this._store.setEnabled(Boolean(this._manager?.isEnabled?.(LAYER_ID)));
}
_handleChange(change) {
if (this.destroyed || change?.layerId !== LAYER_ID) return;
if (!String(change.type || '').startsWith('visibility')) return;
this._syncEnabled();
if (
change.type === 'visibility' &&
change.enabled &&
(change.origin === 'user' || change.origin === 'voice')
)
this._reveal();
}
/** Open the panel, unless the Cockpit owns the screen. */
_reveal() {
if (this.destroyed || this._actions.isCockpitActive?.()) return;
this._actions.setPanelCollapsed(PANEL_ID, false, { explicit: true });
// A phone shows the rail only as tab sheets: open the Missions sheet too.
this._actions.revealPanel?.();
}
destroy() {
if (this.destroyed) return;
this.destroyed = true;
this._unsubscribeManager?.();
this._unsubscribeManager = null;
this._unsubscribePanel?.();
this._unsubscribePanel = null;
this._unsubscribeGlobePick?.();
this._unsubscribeGlobePick = null;
this._store.connect(null);
this._store.publish(null);
this._store.setEnabled(false);
}
}
+152
View File
@@ -0,0 +1,152 @@
// The Space Missions panel's wiring, apart from Context.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createPinia, setActivePinia } from 'pinia';
import { useSpaceMissionsStore } from './stores/spaceMissions.js';
import { SpaceMissionsControls } from './spaceMissionsControls.js';
function layerDouble() {
const panelListeners = new Set();
const pickListeners = new Set();
return {
panelListeners,
pickListeners,
subscribePanel(listener) {
panelListeners.add(listener);
return () => panelListeners.delete(listener);
},
subscribeGlobePick(listener) {
pickListeners.add(listener);
return () => pickListeners.delete(listener);
},
publish(view) {
for (const listener of panelListeners) listener(view);
},
pick(id) {
for (const listener of pickListeners) listener(id);
},
};
}
function managerDouble() {
const listeners = new Set();
const enabled = new Set();
return {
listeners,
enabled,
isEnabled: (id) => enabled.has(id),
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
emit(change) {
if (change.type === 'visibility') {
if (change.enabled) enabled.add(change.layerId);
else enabled.delete(change.layerId);
}
for (const listener of listeners) listener(change);
},
};
}
function rig({ cockpit = false } = {}) {
setActivePinia(createPinia());
const store = useSpaceMissionsStore();
const layer = layerDouble();
const manager = managerDouble();
const reveals = [];
const sheets = [];
const state = { cockpit };
const controls = new SpaceMissionsControls({
layer,
store,
actions: {
setPanelCollapsed: (...args) => reveals.push(args),
isCockpitActive: () => state.cockpit,
revealPanel: () => sheets.push('space-missions-panel'),
},
});
controls.connect(manager);
return { controls, store, layer, manager, reveals, sheets, state };
}
const userOn = {
type: 'visibility',
layerId: 'rocket-launches',
enabled: true,
origin: 'user',
};
test('the layer publishes its roster and mission to its own store', () => {
const r = rig();
assert.equal(r.store.layer, r.layer);
assert.equal(r.store.roster, null);
const view = { roster: { entries: [] }, mission: { id: 'L1' } };
r.layer.publish(view);
assert.equal(r.store.roster, view.roster);
assert.equal(r.store.mission, view.mission);
});
test('the panel shows while the layer is on', () => {
const r = rig();
assert.equal(r.store.enabled, false);
r.manager.emit({ ...userOn, origin: 'programmatic' });
assert.equal(r.store.enabled, true);
r.manager.emit({ ...userOn, enabled: false });
assert.equal(r.store.enabled, false);
// Another layer's change says nothing about Space Missions.
r.manager.enabled.add('rocket-launches');
r.manager.emit({ ...userOn, layerId: 'satellites' });
assert.equal(r.store.enabled, false);
});
test('a person switching the layer on opens its panel; a restore does not', () => {
const r = rig();
r.manager.emit({ ...userOn, origin: 'share-restore' });
r.manager.emit({ ...userOn, type: 'visibility-requested' });
assert.deepEqual(r.reveals, []);
r.manager.emit(userOn);
assert.deepEqual(r.reveals, [
['space-missions-panel', false, { explicit: true }],
]);
// On a phone the rail shows only as tab sheets: the Missions sheet opens too.
assert.deepEqual(r.sheets, ['space-missions-panel']);
});
test('a mission picked on the globe opens the panel', () => {
const r = rig();
r.layer.pick('L1');
assert.deepEqual(r.reveals, [
['space-missions-panel', false, { explicit: true }],
]);
assert.deepEqual(r.sheets, ['space-missions-panel']);
});
test('the Cockpit keeps the screen: no reveal while it is on', () => {
const r = rig({ cockpit: true });
r.layer.pick('L1');
r.manager.emit(userOn);
r.manager.emit({ ...userOn, origin: 'voice' });
assert.deepEqual(r.reveals, []);
assert.deepEqual(r.sheets, [], 'no phone sheet over the Cockpit either');
r.state.cockpit = false;
r.layer.pick('L1');
assert.equal(r.reveals.length, 1);
});
test('reconnecting and destroy release every subscription and clear the store', () => {
const r = rig();
r.controls.connect(r.manager);
assert.equal(r.manager.listeners.size, 1, 'no duplicate subscription');
r.layer.publish({ roster: { entries: [] }, mission: null });
r.manager.emit(userOn);
r.controls.destroy();
assert.equal(r.manager.listeners.size, 0);
assert.equal(r.layer.panelListeners.size, 0);
assert.equal(r.layer.pickListeners.size, 0);
assert.equal(r.store.layer, null);
assert.equal(r.store.roster, null);
assert.equal(r.store.enabled, false);
r.layer.pick('L1');
assert.equal(r.reveals.length, 1, 'a destroyed control reveals nothing');
});
+3 -31
View File
@@ -5,9 +5,9 @@ import { markRaw, shallowRef } from 'vue';
* The Context panel's mode switch as its view renders it. ContextControls
* presents the selected mode, the transition busy state and the nearby
* sites search (`_presentContext()`) and publishes them here; it
* keeps its listeners and transactions. The Contacts and Space Missions
* layers publish their panels beside it, and the app connects each layer's
* commands.
* keeps its listeners and transactions. The Contacts layer publishes its
* panel beside it, and the app connects the layer's commands. Space Missions
* has its own store (stores/spaceMissions.js).
*/
export const useContextStore = defineStore('gev-context', () => {
/** The presented mode switch; null until the controls first render. */
@@ -37,29 +37,6 @@ export const useContextStore = defineStore('gev-context', () => {
awarenessLayer.value = layer && markRaw(layer);
}
/** The Space Missions roster; null until the layer first presents it. */
const missionRoster = shallowRef(null);
/** The selected space mission; null while none is selected. */
const mission = shallowRef(null);
/**
* @param {?{roster: ?object, mission: ?object}} next The layer's view. The
* layer keeps an unchanged roster's object, which re-renders nothing.
*/
function publishMissions(next) {
missionRoster.value = next?.roster ? markRaw(next.roster) : null;
mission.value = next?.mission ? markRaw(next.mission) : null;
}
/** The Space Missions layer whose panel commands the components call. */
const missionsLayer = shallowRef(null);
/** @param {?object} layer The Space Missions layer, or null to disconnect. */
function connectMissions(layer) {
missionsLayer.value = layer && markRaw(layer);
}
return {
view,
publish,
@@ -67,10 +44,5 @@ export const useContextStore = defineStore('gev-context', () => {
publishAwareness,
awarenessLayer,
connectAwareness,
missionRoster,
mission,
publishMissions,
missionsLayer,
connectMissions,
};
});
+42
View File
@@ -0,0 +1,42 @@
import { defineStore } from 'pinia';
import { markRaw, shallowRef } from 'vue';
/**
* The Space Missions panel as its views render it. The Space Missions layer
* publishes its roster and selected mission here, and SpaceMissionsControls
* publishes whether the layer is on. Nothing here belongs to Context.
*/
export const useSpaceMissionsStore = defineStore('gev-space-missions', () => {
/** Whether the Space Missions layer is on or starting. */
const enabled = shallowRef(false);
/** @param {boolean} next Whether the layer is on or starting. */
function setEnabled(next) {
enabled.value = Boolean(next);
}
/** The roster; null until the layer first presents it. */
const roster = shallowRef(null);
/** The selected space mission; null while none is selected. */
const mission = shallowRef(null);
/**
* @param {?{roster: ?object, mission: ?object}} next The layer's view. The
* layer keeps an unchanged roster's object, which re-renders nothing.
*/
function publish(next) {
roster.value = next?.roster ? markRaw(next.roster) : null;
mission.value = next?.mission ? markRaw(next.mission) : null;
}
/** The Space Missions layer whose panel commands the components call. */
const layer = shallowRef(null);
/** @param {?object} next The Space Missions layer, or null to disconnect. */
function connect(next) {
layer.value = next && markRaw(next);
}
return { enabled, setEnabled, roster, mission, publish, layer, connect };
});
+3
View File
@@ -226,6 +226,7 @@ html:not([lang='en']):not(:lang(zh)):not(:lang(ja))
.recent-imagery-panel-inner,
.street-level-panel-inner,
.global-context-panel-inner,
.space-missions-panel-inner,
#pp-toggles:not(.collapsed),
#pp-toggles.collapsed > .pp-header-row
) {
@@ -243,6 +244,7 @@ html:not([lang='en']):not(:lang(zh)):not(:lang(ja))
.recent-imagery-panel-inner,
.street-level-panel-inner,
.global-context-panel-inner,
.space-missions-panel-inner,
#pp-toggles:not(.collapsed),
#pp-toggles.collapsed > .pp-header-row
):hover {
@@ -1175,6 +1177,7 @@ body.ui-clean-view #data-panel,
body.ui-clean-view #cctv-panel,
body.ui-clean-view #radio-panel,
body.ui-clean-view #global-context-panel,
body.ui-clean-view #space-missions-panel,
body.ui-clean-view #utilities-panel,
body.ui-clean-view #scene-panel {
opacity: 0 !important;
+56 -18
View File
@@ -318,21 +318,54 @@ body.recording-mode .gev-panel-rail {
height: 100%;
box-sizing: border-box;
}
#right-context-rail #context-missions-view:not([hidden]),
#right-context-rail #space-mission-panel-host,
#right-context-rail .space-mission-roster {
/* Keep the mission cycler directly beneath its Data Layers entry. */
[data-layer-id='rocket-launches'] .data-toggle-controls:not([hidden]) {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
gap: 6px;
padding: 5px;
border: 1px solid var(--glass-border);
border-radius: 5px;
}
[data-layer-id='rocket-launches'] .data-toggle-controls-info {
grid-column: 2;
grid-row: 1;
padding-top: 0;
text-align: center;
}
[data-layer-id='rocket-launches'] [data-chip-id='next-mission'] {
grid-column: 3;
grid-row: 1;
}
:root[dir='rtl']
[data-layer-id='rocket-launches']
.chip-icon
.material-symbols-outlined {
transform: scaleX(-1);
}
#space-missions-panel {
width: min(100%, 330px);
min-height: 0;
max-height: var(--right-panel-allocated-height, 100%);
pointer-events: auto;
}
#right-context-rail.layout-focus #context-missions-view:not([hidden]),
#right-context-rail.layout-focus #space-mission-panel-host,
#right-context-rail.layout-focus .space-mission-roster {
display: flex;
flex: 1 1 auto;
flex-direction: column;
#space-missions-panel[hidden] {
display: none;
}
#right-context-rail.layout-focus .space-mission-roster-list {
flex: 1 1 auto;
max-height: none;
.space-missions-panel-inner {
max-height: inherit;
overflow-y: auto;
scrollbar-gutter: stable;
}
#space-missions-panel.collapsed #space-mission-panel-host {
display: none;
}
/* Synchronous intrinsic measurement, independent of focus and allocation.
This attribute is not observed by the rail's layout scheduler. */
@@ -379,8 +412,6 @@ body.recording-mode .gev-panel-rail {
margin-top: 8px;
pointer-events: auto;
}
#space-mission-panel-host:has(#space-mission-panel:not([hidden]))
> .context-mode-standby,
#space-mission-panel-host:has(#space-mission-panel:not([hidden]))
> .space-mission-roster {
display: none;
@@ -1003,7 +1034,8 @@ body.recording-mode .gev-panel-rail {
#global-context-panel .panel-glow {
display: none;
}
.global-context-panel-inner {
.global-context-panel-inner,
.space-missions-panel-inner {
position: relative;
display: flex;
min-height: 0;
@@ -1019,9 +1051,15 @@ body.recording-mode .gev-panel-rail {
-webkit-backdrop-filter: blur(24px) saturate(1.4);
}
/* Data Layers and Context share the 14px side padding of the other default
theme panels, so every title and toggle sits 19px from its edge. */
:root :is(.data-panel-inner, .global-context-panel-inner) {
/* Data Layers, Context and Space Missions share the 14px side padding of the
other default theme panels, so every title and toggle sits 19px from its
edge. */
:root
:is(
.data-panel-inner,
.global-context-panel-inner,
.space-missions-panel-inner
) {
padding-right: 14px;
padding-left: 14px;
}
+14 -1
View File
@@ -36,7 +36,8 @@ body.mobile-shell #mobile-tab-bar {
left: 0;
z-index: 170;
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-auto-flow: column;
grid-auto-columns: minmax(0, 1fr);
height: var(--mobile-tab-space);
padding: 0 max(4px, env(safe-area-inset-right, 0px))
var(--mobile-bottom-inset) max(4px, env(safe-area-inset-left, 0px));
@@ -62,6 +63,14 @@ body.mobile-shell .mobile-tab {
-webkit-tap-highlight-color: transparent;
}
/* Long locales clip to one line instead of widening their column. */
body.mobile-shell .mobile-tab-label {
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
body.mobile-shell .mobile-tab-icon {
font-size: 24px;
line-height: 1;
@@ -129,6 +138,7 @@ body.mobile-shell #right-context-rail {
body.mobile-shell[data-mobile-sheet='layers'] #left-panel-stack,
body.mobile-shell[data-mobile-sheet='cameras'] #right-context-rail,
body.mobile-shell[data-mobile-sheet='context'] #right-context-rail,
body.mobile-shell[data-mobile-sheet='missions'] #right-context-rail,
/* Visual opens from the left rail on wider screens, so it lives in the left
stack and the More sheet is that stack showing Visual alone. */
body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack {
@@ -191,6 +201,9 @@ body.mobile-shell[data-mobile-sheet='context']
body.mobile-shell[data-mobile-sheet='context']
#right-context-rail
> #recent-imagery-panel:not([hidden]),
body.mobile-shell[data-mobile-sheet='missions']
#right-context-rail
> #space-missions-panel:not([hidden]),
body.mobile-shell[data-mobile-sheet='more'] #left-panel-stack > #pp-toggles {
position: relative;
inset: auto;
+1
View File
@@ -14,6 +14,7 @@ body.recording-mode #data-panel,
body.recording-mode #cctv-panel,
body.recording-mode #radio-panel,
body.recording-mode #global-context-panel,
body.recording-mode #space-missions-panel,
body.recording-mode #gev-voice-control,
body.recording-mode #utilities-panel,
body.recording-mode #scene-panel {
+4 -14
View File
@@ -14,8 +14,7 @@ import AwarenessPanel from './panels/AwarenessPanel.vue';
import BhoteKoshiPanel from './panels/BhoteKoshiPanel.vue';
import EntityCard from './panels/EntityCard.vue';
import ViewContext from './panels/ViewContext.vue';
import MissionDetail from './panels/MissionDetail.vue';
import MissionRoster from './panels/MissionRoster.vue';
import SpaceMissionsPanel from './panels/SpaceMissionsPanel.vue';
import RadioPanel from './panels/RadioPanel.vue';
import UiButton from '../kit/UiButton.vue';
import { cockpitEntryFace } from '../cockpitPresentation.js';
@@ -75,7 +74,7 @@ const setPane = (id) => (el) => {
if (target instanceof HTMLElement && target.parentElement !== el) el.appendChild(target);
}
};
// Turning Radio or Launches on asks for the main tab, where they show.
// Turning on Radio reveals the Inspector.
const showView = () => (activeTab.value = 'view');
onMounted(() => {
globalThis.addEventListener?.('gev:context-show-view', showView);
@@ -221,14 +220,10 @@ watch(
<span class="material-symbols-outlined" aria-hidden="true">radar</span>
<span>{{ t('CONTACTS') }}</span>
</button>
<button id="global-context-missions-btn" class="context-mode-button" v-class-toggle="{ active: ctx?.missionsActive }" type="button" role="tab" tabindex="0" :aria-selected="String(ctx?.missionsActive ?? false)" :aria-disabled="ctx && String(ctx.busy)" :aria-busy="ctx && String(ctx.busy)" aria-controls="context-missions-view">
<span class="material-symbols-outlined" aria-hidden="true">rocket_launch</span>
<span>{{ t('SPACE MISSIONS') }}</span>
</button>
</div>
<div id="context-mode-standby" class="context-mode-standby" :hidden="ctx?.enabled">
<strong>{{ t('SELECT CONTEXT') }}</strong>
<span>{{ t('CONTACTS — nearest planes · vessels · sites') }}<br>{{ t('SPACE MISSIONS — launches & orbital assets') }}</span>
<span>{{ t('CONTACTS — nearest planes · vessels · sites') }}</span>
</div>
<section id="context-flights-view" class="context-mode-view" role="tabpanel" aria-labelledby="global-context-flights-btn" :hidden="!ctx?.flightsActive">
<div class="global-context-actions" :aria-label="t('Contact Context actions')">
@@ -241,12 +236,6 @@ watch(
</div>
<AwarenessPanel v-if="!contactsMatchCard" />
</section>
<section id="context-missions-view" class="context-mode-view" role="tabpanel" aria-labelledby="global-context-missions-btn" :hidden="!ctx?.missionsActive">
<div id="space-mission-panel-host">
<MissionRoster />
<MissionDetail />
</div>
</section>
<div v-if="contextOpen" v-show="activeTab === 'view'" id="context-tab-view" role="tabpanel" aria-labelledby="context-tab-btn-view" :class="{ 'context-searching': contextSearchOpen && contextSearchText.trim() }">
<EntityCard :with-contacts="contactsMatchCard">
<AwarenessPanel v-if="contactsMatchCard" compact />
@@ -255,6 +244,7 @@ watch(
</div>
</div>
</RailPanel>
<SpaceMissionsPanel />
<BhoteKoshiPanel />
</aside>
+5 -5
View File
@@ -3,17 +3,17 @@ import { storeToRefs } from 'pinia';
import { nextTick, ref, watch } from 'vue';
import { t } from '../../../i18n/index.js';
import UiSlider from '../../kit/UiSlider.js';
import { useContextStore } from '../../stores/context.js';
import { useSpaceMissionsStore } from '../../stores/spaceMissions.js';
import UiButton from '../../kit/UiButton.vue';
// The selected space mission inside Context. The launches layer presents it
// The selected space mission. The launches layer presents it
// and hides the panel while none is selected; the roster beside it hides
// while it shows. Buttons call the layer's panel commands.
const { mission: m, missionsLayer: layer } = storeToRefs(useContextStore());
const { mission: m, layer } = storeToRefs(useSpaceMissionsStore());
const root = ref(null);
// Each newly presented selection returns the Context panel to the top.
const SCROLLER = '.global-context-panel-inner';
// Each newly presented selection returns the mission panel to the top.
const SCROLLER = '.space-missions-panel-inner';
watch(
() => m.value?.scrollRequest,
async (request) => {
+2 -2
View File
@@ -2,13 +2,13 @@
import { storeToRefs } from 'pinia';
import { onBeforeUpdate, onUpdated, ref } from 'vue';
import { t } from '../../../i18n/index.js';
import { useContextStore } from '../../stores/context.js';
import { useSpaceMissionsStore } from '../../stores/spaceMissions.js';
import UiEmpty from '../../kit/UiEmpty.vue';
// The Space Missions roster. The launches layer presents it; until it does,
// the list shows its loading line. Hover and keyboard focus drive the
// layer's preview, and a click selects the mission.
const { missionRoster: roster, missionsLayer: layer } = storeToRefs(useContextStore());
const { roster, layer } = storeToRefs(useSpaceMissionsStore());
const root = ref(null);
const CONTINUATION = '[data-mission-roster-focus-continuation]';
+7 -1
View File
@@ -1,19 +1,25 @@
<script setup>
import { storeToRefs } from 'pinia';
import { computed } from 'vue';
import { t } from '../../../i18n/index.js';
import { useDisplayStore } from '../../stores/display.js';
import { useSpaceMissionsStore } from '../../stores/spaceMissions.js';
// The phone shell's tab bar and sheet backdrop. They join the end of the
// page when the shell first publishes, after the scene's credits, and leave
// it when the shell is destroyed; desktop CSS hides them meanwhile.
const { phoneShell: phone } = storeToRefs(useDisplayStore());
const { enabled: missionsEnabled } = storeToRefs(useSpaceMissionsStore());
const tabs = computed(() =>
phone.value?.tabs.filter((tab) => tab.sheet !== 'missions' || missionsEnabled.value),
);
</script>
<template>
<Teleport v-if="phone" to="body">
<div id="mobile-sheet-backdrop" :hidden="!phone.sheet"></div>
<nav id="mobile-tab-bar" :aria-label="t('Panels')" :aria-hidden="String(!phone.enabled)">
<button v-for="tab in phone.tabs" :key="tab.sheet" type="button" class="mobile-tab" :data-mobile-sheet="tab.sheet" :aria-expanded="String(phone.sheet === tab.sheet)"><span class="material-symbols-outlined mobile-tab-icon" aria-hidden="true">{{ tab.icon }}</span><span class="mobile-tab-label">{{ t(tab.label) }}</span></button>
<button v-for="tab in tabs" :key="tab.sheet" type="button" class="mobile-tab" :data-mobile-sheet="tab.sheet" :aria-expanded="String(phone.sheet === tab.sheet)"><span class="material-symbols-outlined mobile-tab-icon" aria-hidden="true">{{ tab.icon }}</span><span class="mobile-tab-label">{{ t(tab.label) }}</span></button>
</nav>
</Teleport>
</template>
@@ -0,0 +1,43 @@
<script setup>
import { storeToRefs } from 'pinia';
import { nextTick, ref, watch } from 'vue';
import { t } from '../../../i18n/index.js';
import RailPanel from '../../rail/RailPanel.vue';
import { useSpaceMissionsStore } from '../../stores/spaceMissions.js';
import MissionDetail from './MissionDetail.vue';
import MissionRoster from './MissionRoster.vue';
const { enabled, mission } = storeToRefs(useSpaceMissionsStore());
const host = ref(null);
watch(
() => Boolean(mission.value),
async (selected) => {
// Keep keyboard focus in the panel when the selected mission replaces the roster.
if (!host.value?.contains(document.activeElement)) return;
await nextTick();
const control = selected
? '[data-mission-close]'
: '[data-mission-roster-id]';
host.value?.querySelector(control)?.focus();
},
);
</script>
<template>
<RailPanel
id="space-missions-panel"
:title="t('Space Missions')"
:hidden="!enabled"
:glow="false"
start-collapsed
sideways
scroll
rail-scroller
>
<div id="space-mission-panel-host" ref="host">
<MissionRoster />
<MissionDetail />
</div>
</RailPanel>
</template>
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more