A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.
JavaScript 3d-globecesiumflight-trackinggeospatialgeospatial-intelligencegisosintphotogrammetrysatellite-trackingspatial-intelligencewebglworldview
feat(layers): Recent Imagery — open satellite imagery for a selected box (#716)
Bilawal Sidhu082074a00684
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c4016296b..0bcdebf70 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,20 @@# Changelog+- Add a **Recent Imagery** data layer (NASA GIBS · HLS + VIIRS, keyless).+ Select a box (drag, the current view, or around a pin; up to 1,000 km a+ side) and the right-rail panel lists the last 30 days of Sentinel-2 /+ Landsat (30 m) and, when switched on, VIIRS daily overview imagery over it,+ with thumbnails and scene cloud. Three modes: IMAGE shows one day, VS+ BASEMAP swipes it against the map, A / B swipes two days; a SHOW or A / B+ chip on each day card pins it, arrow keys preview the focused day while a+ slot is empty, and no control moves when anything changes. While imagery is+ shown on Google 3D the map switches to Esri and comes back when it is+ cleared. Either image exports as a PNG; box, pins, mode and split travel in+ share links; the NASA acknowledgement is in the credits and+ `DATA_SOURCES.md`. The swipe is now shared with the Nepal scene+ (`src/ui/imagerySplit.js`, `src/maps/imageryComparison.js`), and+ `MapSourceController.subscribe()` reports every settled map switch.+## Unreleased — weather review- On 3D Tiles, draw a 4096×2048 detail window around the view on each@@ -88,6 +103,7 @@Add feed provenance to analyst/view answers and HUD context while retaining existing response fields and runner ownership (Matt Van Horn, #347).Analyst records for loaded satellites, datacenters and dams, with explicit bounded count/rank coverage (Matt Van Horn, #351).+- Remove the spurious scrollbars that appeared on both panel stacks at narrowwidths (720px and below) as soon as a panel was expanded. The stacks scrollvertically there, and each panel's decorative glow, absolutely positioneddiff --git a/DATA_SOURCES.md b/DATA_SOURCES.mdindex 1c89cd2e0..a9cf38145 100644--- a/DATA_SOURCES.md+++ b/DATA_SOURCES.md@@ -31,6 +31,7 @@ How to read this:| **The Space Devs — Launch Library 2 v2.3** | Recent launch, payload, stage, and recovery metadata for Space Missions (30d) | [The Space Devs terms of use](https://github.com/TheSpaceDevs/Tutorials/blob/main/faqs/faq_TSD.md#terms-of-use): data may be used and shared in any form; avoid forwarding it without added value; attribution is encouraged (not mandatory). [Official API limits](https://ll.thespacedevs.com/docs/): 15 unauthenticated calls/hour; optional token | "Launch Library 2 — The Space Devs" (courtesy attribution) || **Esri World Imagery** (ArcGIS Online tile service) | The keyless satellite basemap — the default landing when no Google/ion credential is configured, and the "Esri Satellite" map stack | [Esri Master Agreement](https://www.esri.com/en-us/legal/terms/full-master-agreement): the public World Imagery service is usable in public-facing apps with attribution; no key is required for this classic endpoint, but Esri governs and can change access — an app at scale should review current ArcGIS Location Platform terms | "Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community" (provider carries the service's own credit line) || **USGS** | Earthquakes | U.S. public domain | "Data courtesy of the U.S. Geological Survey" |+| **NASA GIBS** (WMTS tiles + Worldview Snapshots) and **NASA CMR** (granule catalog) | Recent Imagery layer: HLS S30/L30 (Sentinel-2, Landsat 8/9) and VIIRS true-colour tiles draped on the map, per-day thumbnails and PNG exports; the HLS granule catalog (dates, cloud, footprints) for a selected box | U.S. public domain (NASA data); keyless, browser-direct (CORS `*`); no bulk use — one 30-day catalog query per box, tiles bounded to the box, six tile requests in flight | "We acknowledge the use of imagery provided by services from NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science Data and Information System (ESDIS)." — [gibs.earthdata.nasa.gov](https://gibs.earthdata.nasa.gov), [HLS](https://lpdaac.usgs.gov/products/hlss30v002/) || **OpenStreetMap (Overpass API)** | Road geometry for traffic | ODbL 1.0 | "© OpenStreetMap contributors" || **TomTom Traffic API** (flow vector tiles) | Live congestion coloring for the traffic layer (optional, BYOK) | [TomTom for Developers terms](https://developer.tomtom.com) (proprietary, your own key; free tier currently 200K tile requests/month — see [current pricing](https://docs.tomtom.com/pricing/)) | "Traffic flow data © TomTom" — registered when live mode activates || **OpenStreetMap (Overpass API)** | Viewport-bounded mapped installation context for Global Context | ODbL 1.0 | "© OpenStreetMap contributors" (incomplete mapped context) |diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.mdindex 1ad6f8080..67acfffce 100644--- a/docs/CURRENT-STATE.md+++ b/docs/CURRENT-STATE.md@@ -1149,7 +1149,7 @@ fetching, trailing-24-hour filtering and partial-success caching are unchanged.> rule by a unit pin), and session-dismisses rather than contesting the key; if> one is already up at init it **waits** instead of appearing over it. (2) A> surface can take the screen with **no class to watch** — the Cesium attribution-> lightbox is full-screen at `z-index: 200` against the card's `175`, which left+> lightbox is at `z-index: 200` against the card's `175`, which left> the launcher measurable (`getClientRects()` non-empty) and buried, so ESC> dismissed a card nobody could see and burned the session flag. `isTopmost()`> therefore also **hit-tests the card's own centre** with `elementFromPoint`; any@@ -1961,7 +1961,7 @@ down | auth-failed` (plus the unchanged `missing-key`/`unsupported`) with> - **Compact data-attribution panel:** the complete Cesium credit inventory> remains available without taking over the viewport. Its expanded desktop> panel is capped at 70dvh/36rem, the wrapped 12px credit list scrolls inside-> it, and narrow screens retain Cesium's full-screen surface with an internal+> it, and narrow screens retain Cesium's surface with an internal> scroller. The title, close control, links, and persistent Google/Cesium line> remain unchanged and visible.> - **Distant-aircraft recession:** both civilian and military billboard fleets@@ -3655,6 +3655,18 @@ are omitted rather than framing the wrong part of the globe.- Pure half: `src/annotations/drawMode.js` (session, minimum vertices, double-click de-dup at 0.5 m, vertex ceiling, degenerate-geometry refusal, ring closing, dateline-safe length/area/centroid, hint text). Regression surface: `src/annotations/drawMode.test.mjs` and `src/data/inputOwnership.test.mjs` (pure), `src/annotations/drawToolBehaviour.test.mjs` (the tool driven against DOM and viewer doubles — leases, borrowed input actions, teardown, the Enter key, preview heights), `src/annotations/drawTool.test.mjs` (structural: where files live, which ids the markup carries, what the docs may claim), and the rendered harness `scripts/qa-draw-tool.mjs`.- The annotation tree is a declared ownership group: `./annotations` → `src/annotations/index.js` in `package.json`, with its module graph listed in `scripts/package-boundaries.json`, so an annotation module reaching outside that graph is a gate failure rather than a surprise in a layer's bundle. `drawMode.js`, `drawTool.js` and their tests are in `scripts/format-scope.json`.+### Recent Imagery (September 2026)++- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room.+- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.+- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.+- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.+- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.+- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.+- **Panel.** `#recent-imagery-panel` is static rail markup in `src/ui/templates/context.html` beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`.+- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).+- Regression surface: the colocated `*.test.mjs` beside each module (shared doubles in `src/layers/recentImagery/testDoubles.mjs`; `src/ui/recentImagery.test.mjs` includes a DOM-structure guard: every control keeps its place in the tree, nothing is hidden, and every fixed-height block keeps the class the stylesheet fixes its height by; it has no layout, so it cannot see movement), `src/ui/layerPanel.test.mjs` (mount), `src/maps/controller.test.mjs` (`subscribe`), `src/data/layerState.test.mjs` (codec), `src/sharelink.celestial.test.mjs` (panel token), and the live gate `scripts/qa-recent-imagery.mjs`, which also measures every control's rect across the transitions within 1 px; that measurement is the real layout-shift check.+### 3D Aircraft + Tracking (June 2026)- **The TRACKED contact's 2D↔3D handoff is DEFAULT behaviour (2026-08-19), driven by camera distance alone.** It does NOT consult the DISPLAY-rail `3D` toggle, which continues to own the FLEET (the un-instanced draw-call budget stays the operator's decision). Policy lives in `src/data/trackedModelRegime.js` and is shared by both layers: enter below `TRACKED_MODEL_ENTER_ALT_M` = 150,000 m and hand back to the billboard only above `TRACKED_MODEL_EXIT_ALT_M` = 172,500 m. **The swap distance was set by playtesting on 2026-08-20:** a first pass at 1,000,000 m switched too early; 2D reads correctly at ~600 km and the handoff belongs at ~150 km. **Consequence, recorded on purpose:** the tracked contact now enters 3D NEARER than the FLEET does (`MODEL_ALT_CEIL_M` = 800,000 m, unchanged), so with the DISPLAY-rail `3D` toggle on, 150–800 km draws surrounding contacts as models while the selected one is still a glyph. Nothing double-draws (the fleet pass skips the tracked icao) and aligning the two is a fleet-side decision, deliberately out of scope. **The two thresholds are asymmetric on purpose:** a single threshold makes a tracked orbit sitting ON the boundary strobe billboard↔model as the camera's altitude wobbles across it. Do not collapse them. The latch is scoped per selection, so a new target re-evaluates against the ENTER ceiling rather than inheriting the previous target's exit band. Exactly ONE model is involved; it loads on demand when the regime opens, is HIDDEN (not released) on regime exit so re-entry has no load gap, and is released by the existing teardown on deselect/re-track/destroy. Cockpit and TR-3B suppression are unchanged. **Two invariants around it:** (a) the hysteresis latch AND the load-failure latch are per-selection state cleared by `_resetTrackedSelectionState()` in the tracking lifecycle (deselect / re-track / cross-layer / init / destroy) — the predicate's icao-change guard is defence only, since it needs a drawn frame while nothing is selected and the render governor's idle mode does not promise one; (b) on-demand loading is bounded at 3 attempts per selection with a 1.5 s backoff and one console warning naming the asset — the driver runs every `scene.preUpdate`, so an unbounded catch means a missing GLB spins load→reject at frame rate. The billboard stays the visual throughout a failed load.diff --git a/package.json b/package.jsonindex 3dd681f41..429c13aa7 100644--- a/package.json+++ b/package.json@@ -152,6 +152,7 @@"./aircraft": "./src/layers/aircraft/index.js","./layers/vessels": "./src/layers/vessels/index.js","./layers/earthquakes": "./src/layers/earthquakes/index.js",+ "./layers/recent-imagery": "./src/layers/recentImagery/index.js","./sources/firms-csv": "./src/data/firmsCsv.js","./layers/firms": "./src/layers/firms/index.js","./layers/satellites": "./src/layers/satellites/index.js",diff --git a/scripts/format-scope.json b/scripts/format-scope.jsonindex dc9cc2b0d..97bb0b8f2 100644--- a/scripts/format-scope.json+++ b/scripts/format-scope.json@@ -144,6 +144,8 @@"src/keylessGeocoder.js","src/standalone/placeSearch.js","src/ui/panelDisclosure.js",+ "src/ui/imagerySplit.js",+ "src/ui/imagerySplit.test.mjs","src/ui/surfaceKeyboard.js","src/ui/surfaceKeyboard.test.mjs","src/ui/panelRails.js",@@ -555,6 +557,7 @@"src/maps/catalog.js","src/maps/controller.js","src/maps/controller.test.mjs",+ "src/maps/imageryComparison.js","src/maps/credits.js","src/maps/defaultSources.js","src/maps/google3d.js",@@ -795,5 +798,15 @@"scripts/qa-weather-journey.mjs","scripts/qa-weather-swap.mjs","scripts/qa-weather-teardown.mjs",- "src/layers/weather/imageryHost.test.mjs"+ "src/layers/weather/imageryHost.test.mjs",+ "src/layers/recentImagery/model.test.mjs",+ "src/layers/recentImagery/catalog.test.mjs",+ "src/maps/imageryHost.test.mjs",+ "src/layers/recentImagery/rendering.test.mjs",+ "src/layers/recentImagery/thumbnails.test.mjs",+ "src/layers/recentImagery/index.test.mjs",+ "src/ui/imageryBoxTool.test.mjs",+ "src/ui/recentImagery.test.mjs",+ "src/layers/recentImagery/testDoubles.mjs",+ "scripts/qa-recent-imagery.mjs"]diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.jsonindex a2e1d9519..5273abbf8 100644--- a/scripts/package-boundaries.json+++ b/scripts/package-boundaries.json@@ -631,7 +631,8 @@"src/ui/styles/voice-cost.css","src/ui/styles/first-run.css","src/ui/styles/provider-settings.css",- "src/ui/styles/weather.css"+ "src/ui/styles/weather.css",+ "src/ui/styles/recent-imagery.css"],"external": []},@@ -851,6 +852,18 @@],"external": ["cesium"]},+ "recent-imagery": {+ "exports": ["./layers/recent-imagery"],+ "modules": [+ "src/layers/recentImagery/index.js",+ "src/layers/recentImagery/model.js",+ "src/layers/recentImagery/catalog.js",+ "src/layers/recentImagery/rendering.js",+ "src/layers/recentImagery/thumbnails.js",+ "src/maps/imageryHost.js"+ ],+ "external": ["cesium"]+ },"fire-layer": {"exports": ["./layers/firms"],"modules": [@@ -1162,13 +1175,15 @@"src/maps/availability.js","src/maps/catalog.js","src/maps/controller.js",+ "src/maps/imageryComparison.js","src/maps/credits.js","src/maps/defaultSources.js","src/maps/google3d.js","src/maps/imagery.js","src/maps/registry.js","src/maps/terrain.js",- "src/keySetupCore.mjs"+ "src/keySetupCore.mjs",+ "src/maps/imageryHost.js"],"external": ["cesium"]},@@ -1228,6 +1243,7 @@"modules": ["src/scenes/nepalEvidencePack.js","src/data/bhoteKoshiEvent.js",+ "src/ui/imagerySplit.js","src/data/bhoteKoshiEmbeddedMedia.js","src/data/bhoteKoshiLocator.js","src/data/bhoteKoshiIncidentPlaces.js",@@ -1616,6 +1632,7 @@"src/maps/availability.js","src/maps/catalog.js","src/maps/controller.js",+ "src/maps/imageryComparison.js","src/maps/credits.js","src/maps/defaultSources.js","src/maps/google3d.js",@@ -1872,7 +1889,16 @@"src/layers/cyclones/index.js","src/layers/cyclones/rendering.js","src/layers/cyclones/labels.js",- "src/layers/cyclones/source.js"+ "src/layers/cyclones/source.js",+ "src/app/layers/recentImagery.js",+ "src/layers/recentImagery/index.js",+ "src/layers/recentImagery/model.js",+ "src/layers/recentImagery/catalog.js",+ "src/layers/recentImagery/rendering.js",+ "src/layers/recentImagery/thumbnails.js",+ "src/maps/imageryHost.js",+ "src/ui/recentImagery.js",+ "src/ui/imageryBoxTool.js"],"external": ["hls.js",@@ -1893,6 +1919,8 @@"exports": ["./application/layers"],"modules": ["src/data/bhoteKoshiEvent.js",+ "src/ui/imagerySplit.js",+ "src/maps/imageryComparison.js","src/data/bhoteKoshiEmbeddedMedia.js","src/data/bhoteKoshiLocator.js","src/data/bhoteKoshiIncidentPlaces.js",@@ -2293,7 +2321,14 @@"src/layers/cyclones/index.js","src/layers/cyclones/rendering.js","src/layers/cyclones/labels.js",- "src/layers/cyclones/source.js"+ "src/layers/cyclones/source.js",+ "src/app/layers/recentImagery.js",+ "src/layers/recentImagery/index.js",+ "src/layers/recentImagery/model.js",+ "src/layers/recentImagery/catalog.js",+ "src/layers/recentImagery/rendering.js",+ "src/layers/recentImagery/thumbnails.js",+ "src/maps/imageryHost.js"],"external": ["hls.js",diff --git a/scripts/qa-recent-imagery.mjs b/scripts/qa-recent-imagery.mjsnew file mode 100644index 000000000..1460ed3b5--- /dev/null+++ b/scripts/qa-recent-imagery.mjs@@ -0,0 +1,1480 @@+#!/usr/bin/env node+/**+ * Rendered acceptance for DATA ▸ Recent Imagery against the real NASA+ * endpoints (CMR catalog, GIBS tiles, Worldview snapshots): the rail panel,+ * USE VIEW and the live preview, the three modes (IMAGE, VS BASEMAP, A / B)+ * with their pins, the divider and the Esri surface on Google 3D, Escape+ * order, the oversized-view refusal and ZOOM IN, CLEAR, the share link,+ * map-switch rebind (a manual switch to Google 3D keeps the imagery on+ * Esri), CCTV stability at 900 and 700 px, scroll preservation, a+ * layout-shift measurement across every transition, and disable.+ *+ * Run: start the app (`./scripts/dev-fresh.sh`) and+ * node scripts/qa-recent-imagery.mjs+ * Env: QA_BASE_URL (default http://localhost:4173), QA_SHOT_DIR (default+ * qa-shots/recent-imagery), QA_HEADFUL=1. Every wait is bounded. Without+ * network access to NASA the run skips with exit code 0.+ */+import fs from 'node:fs';+import path from 'node:path';+import puppeteer from 'puppeteer';++const BASE_URL = process.env.QA_BASE_URL || 'http://localhost:4173';+const SHOT_DIR = process.env.QA_SHOT_DIR || 'qa-shots/recent-imagery';+const HEADFUL = process.env.QA_HEADFUL === '1';+const STEP_TIMEOUT = 20_000;+const AUSTIN = { lon: -97.74, lat: 30.27, height: 12_000 };+const PANEL = '#recent-imagery-panel';++async function networkAvailable() {+ try {+ const response = await fetch(+ 'https://cmr.earthdata.nasa.gov/search/collections.json?page_size=1',+ { signal: AbortSignal.timeout(8_000) },+ );+ return response.ok;+ } catch {+ return false;+ }+}++if (!(await networkAvailable())) {+ console.log(+ 'SKIP: cmr.earthdata.nasa.gov is unreachable — the live Recent Imagery gate needs network access.',+ );+ process.exit(0);+}++const browser = await puppeteer.launch({+ headless: !HEADFUL,+ ...(HEADFUL+ ? {+ executablePath:+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ }+ : {}),+ args: [+ '--no-sandbox',+ '--disable-background-timer-throttling',+ '--disable-renderer-backgrounding',+ ...(HEADFUL ? ['--window-size=1280,860'] : []),+ ...(process.platform === 'darwin'+ ? ['--use-angle=metal', '--enable-gpu']+ : ['--use-gl=angle', '--use-angle=swiftshader']),+ ],+});+const page = await browser.newPage();+const errors = [];+page.on('pageerror', (error) => errors.push(`pageerror: ${error.message}`));+let failures = 0;+let checks = 0;+function check(name, passed, detail = '') {+ checks += 1;+ console.log(+ `[${passed ? 'PASS' : 'FAIL'}] ${name}${detail ? ` — ${detail}` : ''}`,+ );+ if (!passed) failures++;+}+fs.mkdirSync(SHOT_DIR, { recursive: true });+const shots = [];+const shot = async (name) => {+ const file = path.join(SHOT_DIR, `${name}.jpg`);+ await page.screenshot({ path: file, type: 'jpeg', quality: 82 });+ shots.push(file);+};+const panelShot = async (name) => {+ const panel = await page.$(PANEL);+ if (!panel) return;+ const file = path.join(SHOT_DIR, `${name}.png`);+ await panel.screenshot({ path: file });+ shots.push(file);+};+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++/** Poll a page predicate; false on timeout instead of throwing. */+async function until(fn, arg, timeout = STEP_TIMEOUT) {+ try {+ await page.waitForFunction(fn, { timeout, polling: 250 }, arg);+ return true;+ } catch {+ return false;+ }+}++/**+ * Page-side helpers every predicate can use: the layer handle, GIBS layers+ * per host with their split directions, and whether a header is on screen.+ */+function installPageHelpers() {+ window.__riQa = {+ layer: () => window.__gevRecentImagery.layer,+ snap: () => window.__gevRecentImagery.layer.getSnapshot(),+ owned: () => window.__gevRecentImagery.layer.diagnostics().ownedCount,+ gibs(collection) {+ const out = [];+ for (let i = 0; i < (collection?.length || 0); i += 1) {+ const layer = collection.get(i);+ if (+ String(layer?.imageryProvider?.url || '').includes(+ 'earthdata.nasa.gov',+ )+ )+ out.push(layer.splitDirection);+ }+ return out;+ },+ hosts() {+ const gev = window.__godsEyeView;+ const globe = this.gibs(gev.viewer.imageryLayers);+ const tileset = this.gibs(gev.tileset?.imageryLayers);+ return {+ globe: globe.length,+ tileset: tileset.length,+ splits: [...globe, ...tileset],+ globeShown: gev.viewer.scene.globe.show,+ };+ },+ splitShown() {+ const line = document.getElementById('recent-imagery-split-line');+ return Boolean(line && !line.hidden);+ },+ headerOnScreen(id) {+ const element = document.getElementById(id);+ const header =+ element?.querySelector('.panel-header, .pp-header-row') || element;+ const rect = header?.getBoundingClientRect();+ return rect+ ? rect.height > 0 && rect.top >= 0 && rect.bottom <= window.innerHeight+ : false;+ },+ activeStack: () =>+ window.__godsEyeView.mapStackController?.getActiveId?.() ?? null,+ };+}++const state = () =>+ page.evaluate(() => {+ const qa = window.__riQa;+ const snapshot = qa.snap();+ const gev = window.__godsEyeView;+ const split = document.getElementById('recent-imagery-split-line');+ const text = (id) => document.getElementById(id)?.textContent || '';+ const hosts = qa.hosts();+ return {+ box: snapshot.box,+ boxError: snapshot.boxError,+ mode: snapshot.mode,+ candidates: snapshot.candidates.map((c) => ({+ key: c.key,+ drapable: c.drapable,+ })),+ focus: snapshot.focus?.key || null,+ pinA: snapshot.pins.a.key,+ pinB: snapshot.pins.b.key,+ preview: snapshot.preview.key,+ shown: snapshot.shown,+ notice: snapshot.notice,+ comparison: snapshot.comparison,+ borrowedEsri: snapshot.borrowedEsri,+ error: snapshot.error,+ diagnostics: qa.layer().diagnostics(),+ cards: document.querySelectorAll('#recent-imagery-panel .ri-card').length,+ panelHidden: document.getElementById('recent-imagery-panel')?.hidden,+ noticeText: text('ri-notice-text'),+ hintText: text('ri-hint'),+ rowA: text('ri-slot-a'),+ rowB: text('ri-slot-b'),+ splitVisible: Boolean(+ split && !split.hidden && split.getBoundingClientRect().height > 0,+ ),+ splitLabels: split+ ? [+ split.querySelector('span.before')?.textContent,+ split.querySelector('span.after')?.textContent,+ ]+ : null,+ splitLeft: split ? split.getBoundingClientRect().left : null,+ splitPosition: gev.viewer.scene.splitPosition,+ canvasWidth: gev.viewer.scene.canvas.clientWidth,+ activeStack: qa.activeStack(),+ gibsOnGlobe: hosts.globe,+ gibsOnTileset: hosts.tileset,+ gibsSplits: hosts.splits,+ };+ });+const hostsDetail = (s) =>+ `owned=${s.diagnostics.ownedCount} host=${s.diagnostics.host} globe=${s.gibsOnGlobe} tileset=${s.gibsOnTileset} splits=${s.gibsSplits}`;++/** Put the camera straight down over a point at a height, no flight. */+const setView = (view) =>+ page.evaluate((target) => {+ const viewer = window.__godsEyeView.viewer;+ viewer.camera.cancelFlight?.();+ viewer.scene.tweens?.removeAll?.();+ viewer.camera.setView({+ destination: viewer.scene.globe.ellipsoid.cartographicToCartesian({+ longitude: (target.lon * Math.PI) / 180,+ latitude: (target.lat * Math.PI) / 180,+ height: target.height,+ }),+ orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },+ });+ viewer.scene.requestRender();+ }, view);++/** Ground width of the camera's view rectangle, in km (0 without one). */+const viewWidthKm = () =>+ page.evaluate(() => {+ const rect = window.__godsEyeView.viewer.camera.computeViewRectangle?.();+ if (!rect) return 0;+ const lat = (rect.south + rect.north) / 2;+ return Math.abs(rect.east - rect.west) * 6371 * Math.cos(lat);+ });++const click = (selector) =>+ page.evaluate((target) => {+ const button = document.querySelector(target);+ if (!button || button.disabled || button.hidden) return false;+ button.click();+ return true;+ }, selector);+const clickAction = (id) => click(`${PANEL} [data-action-id="${id}"]`);+const clickMode = (mode) => click(`${PANEL} .ri-mode-btn[data-mode="${mode}"]`);+const focusStrip = () =>+ page.evaluate(() =>+ document.getElementById('ri-strip')?.focus({ preventScroll: true }),+ );+const pressOnStrip = async (key) => {+ await focusStrip();+ await page.keyboard.press(key);+};++/** Average colour of the canvas centre — the inside of a centred 10 km box. */+async function probe() {+ const base64 = await page.screenshot({+ clip: { x: 540, y: 330, width: 200, height: 200 },+ type: 'png',+ encoding: 'base64',+ });+ return page.evaluate(async (data) => {+ const bitmap = await createImageBitmap(+ await (await fetch(`data:image/png;base64,${data}`)).blob(),+ );+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);+ const context = canvas.getContext('2d');+ context.drawImage(bitmap, 0, 0);+ const pixels = context.getImageData(0, 0, bitmap.width, bitmap.height).data;+ const sum = [0, 0, 0];+ for (let i = 0; i < pixels.length; i += 4)+ for (let c = 0; c < 3; c += 1) sum[c] += pixels[i + c];+ return sum.map((value) => Math.round(value / (pixels.length / 4)));+ }, base64);+}++const tilesSettled = () =>+ until(() => {+ const gev = window.__godsEyeView;+ if (gev.viewer.scene.globe.show) return gev.viewer.scene.globe.tilesLoaded;+ return !gev.tileset || gev.tileset.tilesLoaded;+ });+const backOnPhotoreal = () =>+ until(() => window.__riQa.activeStack() === 'photoreal');+const onEsri = () =>+ until(() => window.__riQa.activeStack() === 'esri-imagery');+const ownedIs = (count) =>+ until((n) => window.__riQa.owned() === n, count, 10_000);++// ── layout-shift measurement ────────────────────────────────────────────────+const CONTROLS = {+ 'select-box': `${PANEL} [data-action-id="select-box"]`,+ 'use-view': `${PANEL} [data-action-id="use-view"]`,+ clear: `${PANEL} [data-action-id="clear"]`,+ notice: '#ri-notice',+ 'zoom-in': '#ri-zoom-in',+ strip: '#ri-strip',+ hint: '#ri-hint',+ 'mode-image': `${PANEL} .ri-mode-btn[data-mode="image"]`,+ 'mode-basemap': `${PANEL} .ri-mode-btn[data-mode="basemap"]`,+ 'mode-ab': `${PANEL} .ri-mode-btn[data-mode="ab"]`,+ 'row-a': '#ri-slot-a',+ 'row-b': '#ri-slot-b',+ 'unpin-a': '#ri-unpin-a',+ 'unpin-b': '#ri-unpin-b',+ opacity: '#ri-opacity',+ swap: '#ri-swap',+ 'export-a': `${PANEL} [data-action-id="export-a"]`,+ 'export-b': `${PANEL} [data-action-id="export-b"]`,+ details: '#ri-details .rail-card-header',+};+const measure = () =>+ page.evaluate((controls) => {+ const body = document.getElementById('recent-imagery-panel-body');+ const out = { bodyScroll: body?.scrollTop ?? null, rects: {} };+ for (const [name, selector] of Object.entries(controls)) {+ const rect = document.querySelector(selector)?.getBoundingClientRect();+ out.rects[name] = rect+ ? [rect.left, rect.top, rect.width, rect.height].map(+ (v) => Math.round(v * 10) / 10,+ )+ : null;+ }+ return out;+ }, CONTROLS);+let layoutBaseline = null;+/** Every control's rect matches the baseline within 1 px. */+async function checkLayout(label) {+ await wait(150);+ const now = await measure();+ if (!layoutBaseline) {+ layoutBaseline = now;+ check(+ `layout baseline recorded (${label})`,+ Object.values(now.rects).every(Boolean),+ JSON.stringify(now.rects),+ );+ return;+ }+ const moved = Object.entries(now.rects).filter(([name, rect]) => {+ const base = layoutBaseline.rects[name];+ return (+ !rect || !base || rect.some((value, i) => Math.abs(value - base[i]) > 1)+ );+ });+ check(+ `no control moves: ${label}`,+ moved.length === 0,+ moved+ .map(+ ([name, rect]) =>+ `${name} ${JSON.stringify(layoutBaseline.rects[name])}→${JSON.stringify(rect)}`,+ )+ .join(' '),+ );+}++try {+ await page.setViewport({ width: 1280, height: 860 });+ await page.goto(`${BASE_URL}/?welcome=0`, { waitUntil: 'domcontentloaded' });+ const booted = await until(+ () =>+ window.__gevRecentImagery &&+ window.__godsEyeView &&+ document.getElementById('loading-screen')?.classList.contains('hidden'),+ null,+ 90_000,+ );+ check('the app boots with the Recent Imagery handle', booted);+ if (!booted) throw new Error('boot timeout');+ await page.evaluate(installPageHelpers);++ await setView(AUSTIN);+ await tilesSettled();+ const initialStack = await page.evaluate(() => window.__riQa.activeStack());+ const photoreal = initialStack === 'photoreal';+ console.log(`initial map stack: ${initialStack}`);+ const onPhotorealOnly = (name, passed, detail) =>+ photoreal+ ? check(name, passed, detail)+ : console.log(`[SKIP] ${name} — the boot stack is ${initialStack}`);++ // ── enable: the panel in the rail, per the rail readout pattern ─────────+ const layerToggle = '[data-layer-id="recent-imagery"] .data-toggle-btn';+ check(+ 'the data panel carries a Recent Imagery toggle',+ await click(layerToggle),+ );+ check(+ 'the layer enables from its toggle',+ await until(() =>+ window.__godsEyeView.dataManager.isEnabled('recent-imagery'),+ ),+ );+ check(+ 'the panel appears on the right rail once enabled',+ await until(+ () => document.getElementById('recent-imagery-panel')?.hidden === false,+ ),+ );+ const railPlacement = await page.evaluate(() => {+ const rail = document.getElementById('right-context-rail');+ const panel = document.getElementById('recent-imagery-panel');+ const body = document.getElementById('recent-imagery-panel-body');+ const order = [...rail.children].map((child) => child.id);+ const at = (id) => order.indexOf(id);+ return {+ inRail: panel?.parentElement === rail,+ beforeContext: at('recent-imagery-panel') < at('global-context-panel'),+ afterWeather: at('weather-panel') < at('recent-imagery-panel'),+ collapsed: panel?.classList.contains('collapsed'),+ scroller: body?.hasAttribute('data-rail-scroller'),+ readoutInBody: body?.firstElementChild?.classList.contains(+ 'recent-imagery-readout',+ ),+ body: body?.offsetHeight,+ title: panel?.querySelector('.panel-title')?.textContent,+ order,+ };+ });+ check(+ 'the panel sits in the rail after WEATHER and before CONTEXT, expanded on first appearance',+ railPlacement.inRail &&+ railPlacement.beforeContext &&+ railPlacement.afterWeather &&+ railPlacement.collapsed === false &&+ railPlacement.body > 0,+ JSON.stringify(railPlacement),+ );+ check(+ 'the body is a rail scroller holding the readout, under a RECENT IMAGERY header',+ railPlacement.scroller &&+ railPlacement.readoutInBody &&+ railPlacement.title === 'RECENT IMAGERY',+ JSON.stringify(railPlacement),+ );+ const listOf = (selector, key) =>+ page.evaluate(+ (sel, field) =>+ [...document.querySelectorAll(sel)]+ .map((node) => node.dataset[field] || node.id)+ .join(','),+ selector,+ key,+ );+ check(+ 'the data-panel row carries only the two source chips',+ (await listOf(+ '[data-layer-id="recent-imagery"] .data-toggle-chip',+ 'chipId',+ )) === 'hls,viirs',+ );+ const actionIds = await listOf(+ `${PANEL} .ri-actions-row [data-action-id]`,+ 'actionId',+ );+ check(+ 'the actions row holds SELECT BOX, USE VIEW and CLEAR',+ actionIds === 'select-box,use-view,clear',+ actionIds,+ );+ const blocks = await listOf(`${PANEL} .recent-imagery-readout > *`, 'none');+ check(+ 'the body is the fixed stack: actions, notice, strip, hint, selection, controls, details',+ blocks ===+ 'ri-actions,ri-notice,ri-strip,ri-hint,ri-selection,ri-controls,ri-details',+ blocks,+ );+ let current = await state();+ check(+ 'before a box: CLEAR is disabled, the hint says what to do, IMAGE is the mode',+ (await page.evaluate(+ () =>+ document.querySelector('#recent-imagery-panel [data-action-id="clear"]')+ ?.disabled,+ )) === true &&+ current.hintText === 'Select a box or use the view' &&+ current.mode === 'image',+ `${current.hintText} ${current.mode}`,+ );+ await checkLayout('empty');+ await panelShot('01-enabled-panel');++ // ── USE VIEW at 12 km: days and the live preview ────────────────────────+ const beforeColour = await probe();+ const viewKm = await viewWidthKm();+ check('USE VIEW is clickable', await clickAction('use-view'));+ const searched = await until(() => {+ const snapshot = window.__riQa.snap();+ return !snapshot.searching && snapshot.candidates.length > 0;+ });+ current = await state();+ check(+ `USE VIEW at 12 km (${viewKm.toFixed(1)} km wide) sets a box and the catalog returns days within 20 s`,+ searched && Boolean(current.box),+ `${current.candidates.length} candidates, error=${current.error} boxError=${current.boxError}`,+ );+ check(+ 'the strip renders one card per day',+ current.cards === current.candidates.length && current.cards > 0,+ `${current.cards} cards`,+ );+ const countText = await page.evaluate(+ () => document.getElementById('recent-imagery-panel-count')?.textContent,+ );+ check(+ 'the header count reads the day count',+ /^\d+ DAYS?$/.test(countText),+ countText,+ );+ const startHere = await page.evaluate(() =>+ [...document.querySelectorAll('#recent-imagery-panel .ri-card-start')]+ .filter((node) => !node.hidden)+ .map((node) => node.closest('.ri-card').dataset.key),+ );+ check(+ 'exactly one card wears START HERE',+ startHere.length === 1,+ startHere.join(','),+ );+ check(+ 'the START HERE day previews on its own',+ await until(() => {+ const snap = window.__riQa.snap();+ return (+ Boolean(snap.preview.key) &&+ snap.preview.slot === 'a' &&+ window.__riQa.owned() === 1+ );+ }),+ );+ current = await state();+ check(+ 'row A reads the previewed day, row B reads the basemap',+ /^IMAGE.+ · preview×$/.test(current.rowA) && current.rowB === 'VSBasemap×',+ `${current.rowA} | ${current.rowB}`,+ );+ onPhotorealOnly(+ 'on Google 3D a shown image borrows the Esri surface',+ await onEsri(),+ );+ const esriNote = await until(+ () =>+ document.getElementById('ri-notice-text')?.textContent ===+ 'Imagery on Esri · Google 3D returns when cleared',+ undefined,+ 5_000,+ );+ current = await state();+ onPhotorealOnly(+ 'the notice says the imagery is on Esri until cleared',+ esriNote,+ current.noticeText,+ );+ check(+ 'one owned imagery layer on the globe, no divider',+ current.diagnostics.ownedCount === 1 &&+ current.gibsOnGlobe + current.gibsOnTileset === 1 &&+ !current.splitVisible,+ hostsDetail(current),+ );+ check(+ 'at least one thumbnail settles (present/empty/error)',+ await until(() =>+ window.__riQa+ .snap()+ .candidates.some((c) => c.thumbnail.status !== 'unknown'),+ ),+ );+ await tilesSettled();+ let changedColour = null;+ for (let deadline = Date.now() + STEP_TIMEOUT; Date.now() < deadline;) {+ const colour = await probe();+ if (Math.hypot(...colour.map((c, i) => c - beforeColour[i])) > 6) {+ changedColour = colour;+ break;+ }+ await page.evaluate(() =>+ window.__godsEyeView.viewer.scene.requestRender(),+ );+ await wait(1000);+ }+ check(+ 'the rendered frame inside the box changes once the preview drapes',+ Boolean(changedColour),+ `before=${beforeColour} after=${changedColour || (await probe())}`,+ );+ await checkLayout('preview');+ await shot('02-preview');+ await panelShot('02-preview-panel');++ // ── arrow keys: the preview follows the focus ───────────────────────────+ await until(() => {+ const snap = window.__riQa.snap();+ return snap.candidates.some(+ (c) => c.key !== snap.preview.key && c.drapable,+ );+ });+ current = await state();+ const targetIndex = current.candidates.findIndex(+ (c) => c.key !== current.preview && c.drapable,+ );+ check(+ 'a present day other than the preview is reachable',+ targetIndex >= 0,+ String(targetIndex),+ );+ const targetKey = current.candidates[targetIndex]?.key;+ await focusStrip();+ await page.keyboard.press('Home');+ for (let i = 0; i < targetIndex; i += 1)+ await page.keyboard.press('ArrowRight');+ const pressedAt = Date.now();+ check(+ 'arrow keys move focus at once',+ await until(+ (key) => window.__riQa.snap().focus?.key === key,+ targetKey,+ 2_000,+ ),+ targetKey,+ );+ const followed = await until(+ (key) => window.__riQa.snap().preview.key === key,+ targetKey,+ 1_500,+ );+ const elapsed = Date.now() - pressedAt;+ check(+ 'the focused present day previews within 1 s',+ followed && elapsed <= 1_250,+ `preview after ${elapsed} ms`,+ );+ current = await state();+ check(+ 'still a single owned layer while scrubbing',+ current.diagnostics.ownedCount === 1,+ hostsDetail(current),+ );+ const flag = await page.evaluate(+ (key) =>+ document.querySelector(+ `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-card-flag`,+ )?.textContent,+ targetKey,+ );+ check('the previewed card wears PREVIEW', flag === 'PREVIEW', flag);++ // ── IMAGE: S pins the focused day; focus no longer moves the map ────────+ await pressOnStrip('s');+ current = await state();+ check(+ 'S pins the focused day and its SHOW chip lights',+ current.pinA === targetKey &&+ (await page.evaluate(+ (key) =>+ document+ .querySelector(+ `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-chip[data-slot="a"]`,+ )+ ?.getAttribute('aria-pressed'),+ targetKey,+ )) === 'true',+ current.pinA,+ );+ check(+ 'row A reads the pinned day without "preview"',+ /^IMAGE.+×$/.test(current.rowA) && !/preview/.test(current.rowA),+ current.rowA,+ );+ await checkLayout('pinned');+ await page.keyboard.press(targetIndex > 0 ? 'ArrowLeft' : 'ArrowRight');+ await wait(700);+ current = await state();+ check(+ 'with the image pinned, focus moves without changing the map',+ current.focus !== targetKey && current.shown.a === targetKey,+ `focus=${current.focus} shown=${current.shown.a}`,+ );+ await page.evaluate(() => {+ const slider = document.getElementById('ri-opacity');+ slider.value = '60';+ slider.dispatchEvent(new Event('input', { bubbles: true }));+ });+ current = await state();+ check(+ 'OPACITY sets the draped alpha',+ Math.abs((await page.evaluate(() => window.__riQa.snap().alpha)) - 0.6) <+ 1e-9,+ );+ await checkLayout('opacity');++ // ── VS BASEMAP: the pinned day swipes against the basemap ───────────────+ check('VS BASEMAP is one click', await clickMode('basemap'));+ const basemapSwipe = await until(+ () =>+ window.__riQa.snap().shown.swipe === 'basemap' &&+ window.__riQa.splitShown(),+ );+ current = await state();+ check(+ 'VS BASEMAP shows the divider, labelled IMAGE / BASEMAP',+ basemapSwipe &&+ JSON.stringify(current.splitLabels) === '["IMAGE","BASEMAP"]',+ JSON.stringify(current.splitLabels),+ );+ check(+ 'the image is on the left and the basemap on the right: one layer, split LEFT',+ current.diagnostics.ownedCount === 1 &&+ JSON.stringify(current.gibsSplits) === '[-1]',+ hostsDetail(current),+ );+ check(+ 'the divider starts centred',+ Math.abs(current.splitPosition - 0.5) < 0.01 &&+ Math.abs(current.splitLeft - current.canvasWidth / 2) <= 2,+ `splitPosition=${current.splitPosition} left=${current.splitLeft} canvas=${current.canvasWidth}`,+ );+ check(+ 'row B reads the basemap, lit',+ current.rowB === 'VSBasemap×' &&+ (await page.evaluate(() =>+ document.getElementById('ri-slot-b').classList.contains('lit'),+ )),+ current.rowB,+ );+ onPhotorealOnly(+ 'the swipe runs on Esri',+ current.activeStack === 'esri-imagery',+ current.activeStack,+ );+ check(+ 'the hint says SWAP trades the sides (VS BASEMAP)',+ current.hintText === 'Drag the divider · SWAP trades sides',+ current.hintText,+ );+ await checkLayout('vs basemap');+ await tilesSettled();+ await shot('03-vs-basemap');+ await panelShot('03-vs-basemap-panel');++ // ── A / B: pin A, preview then pin B, swipe, SWAP, unpin ────────────────+ check('A / B is one click', await clickMode('ab'));+ current = await state();+ check(+ 'A / B keeps the pin as A and waits for B',+ current.mode === 'ab' &&+ current.pinA === targetKey &&+ !current.splitVisible &&+ /^A.+×$/.test(current.rowA) &&+ current.rowB === 'BNot set×',+ `${current.rowA} | ${current.rowB}`,+ );+ const chipLabels = await page.evaluate(+ (key) =>+ [+ ...document.querySelectorAll(+ `#recent-imagery-panel .ri-card[data-key="${key}"] .ri-chip`,+ ),+ ].map((chip) => chip.textContent),+ targetKey,+ );+ check(+ 'the cards now carry A and B chips',+ JSON.stringify(chipLabels) === '["A","B"]',+ JSON.stringify(chipLabels),+ );+ await checkLayout('A / B, A pinned');+ const secondIndex = (await state()).candidates.findIndex(+ (c) => c.key !== targetKey && c.drapable,+ );+ const secondKey = current.candidates[secondIndex]?.key;+ await focusStrip();+ await page.keyboard.press('Home');+ for (let i = 0; i < secondIndex; i += 1)+ await page.keyboard.press('ArrowRight');+ check(+ 'arrows preview the other day as B against A',+ await until(+ (key) => {+ const snap = window.__riQa.snap();+ return snap.preview.key === key && snap.preview.slot === 'b';+ },+ secondKey,+ 3_000,+ ),+ secondKey,+ );+ await page.keyboard.press('b');+ const abSwipe = await until(+ (key) =>+ window.__riQa.snap().pins.b.key === key &&+ window.__riQa.snap().shown.swipe === 'ab' &&+ window.__riQa.splitShown(),+ secondKey,+ );+ current = await state();+ check(+ 'B pins the second day and the divider reads A / B',+ abSwipe && JSON.stringify(current.splitLabels) === '["A","B"]',+ JSON.stringify(current.splitLabels),+ );+ check(+ 'two owned layers: A left, B right',+ current.diagnostics.ownedCount === 2 &&+ JSON.stringify([...current.gibsSplits].sort()) === '[-1,1]',+ hostsDetail(current),+ );+ check(+ 'the divider recentres for the new comparison',+ Math.abs(current.splitPosition - 0.5) < 0.01,+ String(current.splitPosition),+ );+ check(+ 'row B reads the pinned day',+ /^B.+×$/.test(current.rowB) && !/Not set/.test(current.rowB),+ current.rowB,+ );+ onPhotorealOnly(+ 'the A / B swipe runs on Esri',+ current.activeStack === 'esri-imagery',+ current.activeStack,+ );+ check(+ 'the hint says SWAP trades the sides (A / B)',+ current.hintText === 'Drag the divider · SWAP trades sides',+ current.hintText,+ );+ await checkLayout('A / B, both pinned');+ await tilesSettled();+ await shot('04-ab');+ await panelShot('04-ab-panel');+ // SWAP trades the sides (Space is push-to-talk, so no key does this).+ const splitBeforeSwap = current.splitPosition;+ check('SWAP is one click while the swipe is live', await click('#ri-swap'));+ const swapped = await until(+ () =>+ window.__riQa.snap().swapped === true &&+ document.querySelector('#recent-imagery-split-line span.before')+ ?.textContent === 'B',+ );+ current = await state();+ check(+ 'SWAP trades the divider labels to B / A and keeps the divider where it was',+ swapped &&+ JSON.stringify(current.splitLabels) === '["B","A"]' &&+ JSON.stringify([...current.gibsSplits].sort()) === '[-1,1]' &&+ Math.abs(current.splitPosition - splitBeforeSwap) < 0.01,+ `${JSON.stringify(current.splitLabels)} ${hostsDetail(current)} split=${current.splitPosition}`,+ );+ await checkLayout('A / B, swapped');+ check('SWAP again is one click', await click('#ri-swap'));+ const restored = await until(+ () =>+ window.__riQa.snap().swapped === false &&+ document.querySelector('#recent-imagery-split-line span.before')+ ?.textContent === 'A',+ );+ current = await state();+ check(+ 'SWAP again restores A / B',+ restored && JSON.stringify(current.splitLabels) === '["A","B"]',+ JSON.stringify(current.splitLabels),+ );+ check('B unpins from its ×', await click('#ri-unpin-b'));+ const singleA = await until(+ () =>+ window.__riQa.owned() === 1 &&+ !document.getElementById('recent-imagery-split-line'),+ );+ current = await state();+ check(+ 'unpinning B drops its layer at once: A alone, no divider',+ singleA && current.shown.a === targetKey && !current.shown.b,+ hostsDetail(current),+ );+ check(+ 'without a swipe SWAP keeps its slot, disabled and invisible',+ await page.evaluate(() => {+ const swap = document.getElementById('ri-swap');+ return Boolean(+ swap?.disabled &&+ swap.classList.contains('is-reserved') &&+ getComputedStyle(swap).visibility === 'hidden',+ );+ }),+ );+ onPhotorealOnly(+ 'A alone stays on Esri',+ current.activeStack === 'esri-imagery',+ current.activeStack,+ );+ await checkLayout('B unpinned');+ check('A unpins from its ×', await click('#ri-unpin-a'));+ check('with nothing shown, no layer remains', await ownedIs(0));+ onPhotorealOnly(+ 'with nothing shown, Google 3D comes back',+ await backOnPhotoreal(),+ );+ await checkLayout('A unpinned');++ // ── the share link carries the pins and the mode ────────────────────────+ await clickMode('basemap');+ await pressOnStrip('a');+ const shared = await until(+ () => {+ const params = new URLSearchParams(window.location.hash.slice(1));+ const layers = (params.get('l') || '').split('.');+ const options = params.get('lo') || '';+ return (+ layers.includes('1') &&+ /(^|_)1\.a\.[SLV]\d{8}/.test(options) &&+ /(^|_)1\.m\.1(_|$)/.test(options) &&+ /(^|_)1\.w\.-?\d+/.test(options)+ );+ },+ undefined,+ 8_000,+ );+ check(+ 'the share link carries the layer, the box, the pin and the mode',+ shared,+ await page.evaluate(() => window.location.hash.slice(0, 400)),+ );++ // ── Escape order: preview, then the box tool ────────────────────────────+ await click('#ri-unpin-a');+ await clickMode('image');+ await ownedIs(0);+ await focusStrip();+ await page.keyboard.press('ArrowRight');+ check(+ 'a focus move previews again',+ await until(+ () => Boolean(window.__riQa.snap().preview.key),+ undefined,+ 5_000,+ ),+ );+ check(+ 'SELECT BOX arms the box tool',+ (await clickAction('select-box')) &&+ (await until(() => window.__gevRecentImagery.tool.isActive())),+ );+ await page.keyboard.press('Escape');+ const escapedPreview = await until(+ () => !window.__riQa.snap().preview.key,+ undefined,+ 3_000,+ );+ const stillArmed = await page.evaluate(() =>+ window.__gevRecentImagery.tool.isActive(),+ );+ check(+ 'Escape clears the preview first and leaves SELECT BOX armed',+ escapedPreview && stillArmed,+ `preview cleared=${escapedPreview} toolActive=${stillArmed}`,+ );+ await page.keyboard.press('Escape');+ check(+ 'the next Escape cancels the box tool',+ await until(() => !window.__gevRecentImagery.tool.isActive()),+ );+ onPhotorealOnly(+ 'with the preview cleared Google 3D comes back',+ await backOnPhotoreal(),+ );++ // ── oversized USE VIEW → refusal in the notice line ─────────────────────+ let refusalWidth = 0;+ for (const height of [400_000, 900_000, 1_800_000]) {+ await setView({ ...AUSTIN, height });+ await wait(300);+ refusalWidth = await viewWidthKm();+ if (refusalWidth > 1_100) break;+ }+ const boxBefore = JSON.stringify((await state()).box);+ await clickAction('use-view');+ const refused = await until(+ () =>+ /^View is/.test(+ document.getElementById('ri-notice-text')?.textContent || '',+ ),+ undefined,+ 5_000,+ );+ current = await state();+ check(+ `an oversized USE VIEW (${Math.round(refusalWidth)} km) is refused in the notice line`,+ refused &&+ /^View is [\d,]+ km wide · limit 1,000 km$/.test(current.noticeText),+ current.noticeText,+ );+ check(+ 'the hint says to zoom in or draw a smaller box',+ current.hintText === 'Zoom in or draw a smaller box',+ current.hintText,+ );+ check('the refusal keeps the box', JSON.stringify(current.box) === boxBefore);+ const refusalLine = await page.evaluate(() => {+ const text = document.getElementById('ri-notice-text');+ const chip = document.getElementById('ri-zoom-in');+ const line = document.getElementById('ri-notice').getBoundingClientRect();+ const rect = chip.getBoundingClientRect();+ return {+ fits: text.scrollWidth <= text.clientWidth,+ scrollWidth: text.scrollWidth,+ clientWidth: text.clientWidth,+ chipVisible:+ getComputedStyle(chip).visibility === 'visible' &&+ !chip.disabled &&+ rect.width > 0,+ chipAtEnd: Math.abs(rect.right - line.right) <= 1,+ lineHeight: line.height,+ };+ });+ check(+ 'the refusal fits the notice line without an ellipsis',+ refusalLine.fits,+ JSON.stringify(refusalLine),+ );+ check(+ 'ZOOM IN shows at the right end of the notice line, which keeps its height',+ refusalLine.chipVisible &&+ refusalLine.chipAtEnd &&+ Math.abs(refusalLine.lineHeight - 14) <= 0.5,+ JSON.stringify(refusalLine),+ );+ await checkLayout('refused');+ await panelShot('05-refused-panel');+ // ZOOM IN: straight down to the height whose view is 400 km wide.+ const fitHeight = await page.evaluate(() => {+ const viewer = window.__godsEyeView.viewer;+ const canvas = viewer.scene.canvas;+ const halfWidth =+ Math.tan(viewer.camera.frustum.fovy / 2) *+ (canvas.clientWidth / canvas.clientHeight);+ return Math.min(400, Math.max(5, 400 / (2 * halfWidth))) * 1000;+ });+ check('ZOOM IN is clickable', await click('#ri-zoom-in'));+ const zoomed = await until(+ (target) =>+ Math.abs(+ window.__godsEyeView.viewer.camera.positionCartographic.height - target,+ ) <=+ target * 0.01,+ fitHeight,+ 2_000,+ );+ const zoomedHeight = await page.evaluate(+ () => window.__godsEyeView.viewer.camera.positionCartographic.height,+ );+ check(+ `ZOOM IN flies to ${Math.round(fitHeight / 1000)} km within 2 s`,+ zoomed,+ `height=${Math.round(zoomedHeight)} target=${Math.round(fitHeight)}`,+ );+ await tilesSettled();+ const fittedWidth = await viewWidthKm();+ await clickAction('use-view');+ const fitted = await until(+ () => {+ const snap = window.__riQa.snap();+ return Boolean(snap.box) && !snap.boxError && !snap.zoomToFit;+ },+ undefined,+ 5_000,+ );+ current = await state();+ check(+ `the next USE VIEW (${Math.round(fittedWidth)} km) succeeds and ZOOM IN is reserved again`,+ fitted &&+ (await page.evaluate(() =>+ document.getElementById('ri-zoom-in').classList.contains('is-reserved'),+ )),+ `boxError=${current.boxError} notice=${current.noticeText}`,+ );+ await checkLayout('fitted');++ // ── CLEAR ────────────────────────────────────────────────────────────────+ await setView(AUSTIN);+ await pressOnStrip('ArrowRight');+ await until(() => window.__riQa.owned() === 1, undefined, 5_000);+ await clickAction('clear');+ const clearedAll = await until(() => {+ const snap = window.__riQa.snap();+ return (+ !snap.box &&+ !snap.pins.a.key &&+ !snap.pins.b.key &&+ !snap.preview.key &&+ window.__riQa.owned() === 0+ );+ });+ current = await state();+ check(+ 'CLEAR empties the box, the pins and the preview',+ clearedAll && current.noticeText === 'Box and images cleared',+ `box=${JSON.stringify(current.box)} owned=${current.diagnostics.ownedCount} notice=${current.noticeText}`,+ );+ onPhotorealOnly('CLEAR hands Google 3D back', await backOnPhotoreal());+ await wait(1_500);+ onPhotorealOnly(+ 'after CLEAR the layer does not take Esri again',+ (await page.evaluate(() => window.__riQa.activeStack())) === 'photoreal',+ );+ await checkLayout('cleared');++ // ── map-switch rebind ───────────────────────────────────────────────────+ await tilesSettled();+ await page.evaluate(+ (view) => window.__riQa.layer().boxFromPinAt(view.lon, view.lat),+ AUSTIN,+ );+ const redraped = await until(() => {+ const snap = window.__riQa.snap();+ return (+ !snap.searching &&+ Boolean(snap.preview.key) &&+ window.__riQa.owned() === 1+ );+ });+ check('a 10 km box previews the START HERE day again', redraped);+ const stacks = await page.evaluate(() =>+ window.__godsEyeView.mapStackController+ .getStacks()+ .filter((s) => s.available)+ .map((s) => s.id),+ );+ const setStack = (id) =>+ page.evaluate(+ (stack) => window.__godsEyeView.mapStackController.setStack(stack),+ id,+ );+ /** Wait for the one GIBS drape to sit on the given host only. */+ const drapeOn = (host) =>+ until(+ (where) => {+ const hosts = window.__riQa.hosts();+ return where === 'globe'+ ? hosts.globeShown && hosts.globe === 1 && hosts.tileset === 0+ : !hosts.globeShown && hosts.globe === 0 && hosts.tileset === 1;+ },+ host,+ 10_000,+ );+ if (photoreal && stacks.includes('esri-imagery')) {+ check('the preview sits on the Esri globe', await drapeOn('globe'));+ // While a day is shown the imagery keeps Esri: a manual switch to+ // Google 3D is answered at once with a new lease.+ await setStack('photoreal');+ const kept = (await onEsri()) && (await drapeOn('globe'));+ current = await state();+ check(+ 'switching to Google 3D by hand while a day is shown keeps the imagery on the Esri globe',+ kept && current.diagnostics.host === 'globe',+ `${hostsDetail(current)} stack=${current.activeStack}`,+ );+ check(+ 'the notice says the imagery stays on Esri until CLEAR, and fits',+ current.noticeText === 'Imagery stays on Esri · CLEAR to use Google 3D' &&+ (await page.evaluate(() => {+ const text = document.getElementById('ri-notice-text');+ return text.scrollWidth <= text.clientWidth;+ })),+ current.noticeText,+ );+ await wait(1_500);+ check(+ 'Esri holds after the re-lease: no switch loop',+ (await page.evaluate(() => window.__riQa.activeStack())) ===+ 'esri-imagery',+ );+ // The divider survives a manual switch too.+ await clickMode('basemap');+ await until(() => window.__riQa.splitShown(), undefined, 10_000);+ await setStack('photoreal');+ const dividerKept =+ (await onEsri()) &&+ (await until(+ () =>+ window.__riQa.splitShown() && window.__riQa.snap().comparison.active,+ undefined,+ 10_000,+ ));+ current = await state();+ check(+ 'a manual switch to Google 3D during VS BASEMAP keeps the divider',+ dividerKept &&+ current.shown.swipe === 'basemap' &&+ !current.comparison.suspended,+ `${hostsDetail(current)} stack=${current.activeStack} comparison=${JSON.stringify(current.comparison)}`,+ );+ await tilesSettled();+ await shot('06-google-3d-kept-on-esri');+ await clickMode('image');+ await until(() => !window.__riQa.splitShown(), undefined, 5_000);+ } else {+ const other = stacks.find(+ (id) => id !== initialStack && id !== 'photoreal',+ );+ if (other) {+ await setStack(other);+ check(+ `switching to ${other} keeps the drape on the globe`,+ await drapeOn('globe'),+ );+ await setStack(initialStack);+ } else {+ console.log('[SKIP] map-switch rebind — no second map stack available');+ }+ }++ // ── collapse / expand, CCTV stability, DISPLAY + CONTEXT reachable ──────+ /** Click a panel's collapse button; resolves to whether it is expanded. */+ const togglePanel = (id) =>+ page.evaluate((panelId) => {+ const button = document.querySelector(+ `.panel-collapse-btn[data-collapse-target="${panelId}"]`,+ );+ if (!button) return null;+ button.click();+ return !document.getElementById(panelId)?.classList.contains('collapsed');+ }, id);+ const imageryPanel = 'recent-imagery-panel';+ const collapsedNow = (await togglePanel(imageryPanel)) === false;+ await wait(400);+ const headerOnly = await page.evaluate(() => ({+ panel: document.getElementById('recent-imagery-panel')?.offsetHeight,+ body: document.getElementById('recent-imagery-panel-body')?.offsetHeight,+ }));+ check(+ 'collapsing the panel leaves a header bar only',+ collapsedNow &&+ headerOnly.body === 0 &&+ headerOnly.panel > 0 &&+ headerOnly.panel <= 80,+ JSON.stringify(headerOnly),+ );+ const expandedAgain = await togglePanel(imageryPanel);+ await wait(400);+ const bodyBack = await page.evaluate(+ () => document.getElementById('recent-imagery-panel-body')?.offsetHeight,+ );+ check(+ 'expanding the panel brings the body back',+ expandedAgain === true && bodyBack > 0,+ `body=${bodyBack}`,+ );++ /** Sample both panel heights for 2 s; settled = the tail never changes. */+ const settledHeights = async () => {+ const samples = [];+ for (let i = 0; i < 20; i += 1) {+ samples.push(+ await page.evaluate(() => ({+ imagery: document.getElementById('recent-imagery-panel')+ ?.offsetHeight,+ cctv: document.getElementById('cctv-panel')?.offsetHeight,+ })),+ );+ await wait(100);+ }+ const tail = (key) => new Set(samples.slice(8).map((s) => s[key]));+ return {+ settled: tail('imagery').size === 1 && tail('cctv').size === 1,+ detail: `imagery=${samples.map((s) => s.imagery).join(',')} cctv=${samples.map((s) => s.cctv).join(',')}`,+ };+ };+ const railFit = () =>+ page.evaluate(() => {+ const px = (element) =>+ parseFloat(+ element?.style.getPropertyValue('--right-panel-allocated-height'),+ );+ const cctv = document.getElementById('cctv-panel');+ const imagery = document.getElementById('recent-imagery-panel');+ const rail = document.getElementById('right-context-rail');+ // Reachable: its header is on screen, or the rail's exclusive policy+ // (an expanded panel under the tactical HUD) hid it while collapsed.+ const reach = (id) => {+ const element = document.getElementById(id);+ return (+ window.__riQa.headerOnScreen(id) ||+ (rail?.classList.contains('layout-exclusive') &&+ element?.classList.contains('collapsed') &&+ element.getBoundingClientRect().height === 0)+ );+ };+ return {+ cctvRendered: cctv?.offsetHeight ?? null,+ cctvAllocated: px(cctv),+ imageryRendered: imagery?.offsetHeight ?? null,+ imageryAllocated: px(imagery),+ imageryCollapsed: Boolean(imagery?.classList.contains('collapsed')),+ imageryDisplay: imagery ? getComputedStyle(imagery).display : null,+ focus: rail?.classList.contains('layout-focus'),+ exclusive: rail?.classList.contains('layout-exclusive'),+ display: reach('pp-toggles'),+ context: reach('global-context-panel'),+ };+ });+ for (const height of [900, 700]) {+ const at = `(${height} px viewport)`;+ await page.setViewport({ width: 1280, height });+ await wait(600);+ check(+ `the CCTV panel expands from its launcher ${at}`,+ (await togglePanel('cctv-panel')) === true,+ );+ const expanded = await settledHeights();+ check(+ `the imagery and CCTV panel heights settle with CCTV expanded ${at}`,+ expanded.settled,+ expanded.detail,+ );+ const fit = await railFit();+ check(+ `CCTV renders at its allocated height beside the imagery panel ${at}`,+ !fit.focus ||+ (Number.isFinite(fit.cctvAllocated) &&+ Math.abs(fit.cctvRendered - fit.cctvAllocated) <= 2),+ JSON.stringify(fit),+ );+ // A collapsed panel has no allocation, so it is judged on its own terms:+ // the exclusive rail (one expanded panel) hides it outright, otherwise it+ // is a header bar. An expanded panel must have been allocated a height.+ const imageryFits = fit.imageryCollapsed+ ? fit.exclusive+ ? fit.imageryRendered === 0 && fit.imageryDisplay === 'none'+ : fit.imageryRendered > 0 && fit.imageryRendered <= 80+ : !fit.focus ||+ (Number.isFinite(fit.imageryAllocated) &&+ fit.imageryRendered <= fit.imageryAllocated + 2);+ check(+ `the imagery panel stays within its allocation, or takes no room when the exclusive rail hides it collapsed ${at}`,+ imageryFits,+ JSON.stringify(fit),+ );+ check(+ `DISPLAY and CONTEXT stay reachable ${at}`,+ fit.display && fit.context,+ JSON.stringify(fit),+ );+ await shot(`07-cctv-expanded-${height}`);+ check(+ `the CCTV panel collapses again ${at}`,+ (await togglePanel('cctv-panel')) === false,+ );+ const collapsed = await settledHeights();+ check(+ `the panel heights settle with CCTV collapsed ${at}`,+ collapsed.settled,+ collapsed.detail,+ );+ const imageryExpanded = await page.evaluate(+ () =>+ !document+ .getElementById('recent-imagery-panel')+ ?.classList.contains('collapsed'),+ );+ if (imageryExpanded) await togglePanel(imageryPanel);+ await wait(400);+ const onScreen = await page.evaluate(() =>+ Object.fromEntries(+ [+ 'pp-toggles',+ 'global-context-panel',+ 'recent-imagery-panel',+ 'cctv-panel',+ ].map((id) => [id, window.__riQa.headerOnScreen(id)]),+ ),+ );+ check(+ `DISPLAY, CONTEXT, CCTV and the imagery header are all on screen once everything is collapsed ${at}`,+ Object.values(onScreen).every(Boolean),+ JSON.stringify(onScreen),+ );+ await togglePanel(imageryPanel);+ await wait(400);+ }++ // ── scroll preservation (700 px viewport, body scrollable) ───────────────+ await page.evaluate(() => {+ const header = document.querySelector('#ri-details .rail-card-header');+ if (header?.getAttribute('aria-expanded') !== 'true') header?.click();+ });+ await wait(300);+ const bodyScroll = () =>+ page.evaluate(() => {+ const body = document.getElementById('recent-imagery-panel-body');+ return {+ top: body.scrollTop,+ max: body.scrollHeight - body.clientHeight,+ };+ });+ const start = await page.evaluate(() => {+ const body = document.getElementById('recent-imagery-panel-body');+ const max = body.scrollHeight - body.clientHeight;+ if (max > 0) body.scrollTop = Math.round(max / 2);+ return { max, top: body.scrollTop };+ });+ check(+ 'with DETAILS open at 700 px the body scrolls',+ start.max > 0,+ JSON.stringify(start),+ );+ if (start.max > 0) {+ await page.evaluate(() => {+ const layer = window.__riQa.layer();+ layer.setAlpha(0.9);+ layer.setToolActive(true);+ layer.setToolActive(false);+ });+ await wait(300);+ const afterNotify = await bodyScroll();+ check(+ 'the body scroll position survives alpha and state notifications',+ Math.abs(afterNotify.top - start.top) <= 1,+ `before=${start.top} after=${afterNotify.top}`,+ );+ await focusStrip();+ await page.keyboard.press('ArrowRight');+ await page.keyboard.press('ArrowRight');+ await wait(600);+ const afterArrows = await bodyScroll();+ check(+ 'the body scroll position survives arrow navigation',+ Math.abs(afterArrows.top - start.top) <= 1,+ `before=${start.top} after=${JSON.stringify(afterArrows)}`,+ );+ await shot('08-scrolled');+ }+ await page.setViewport({ width: 1280, height: 860 });++ // ── disable ───────────────────────────────────────────────────────────────+ await click(layerToggle);+ check(+ 'the layer disables from its toggle',+ await until(+ () => !window.__godsEyeView.dataManager.isEnabled('recent-imagery'),+ ),+ );+ const cleared = await until(() => {+ const hosts = window.__riQa.hosts();+ return (+ window.__riQa.owned() === 0 &&+ hosts.globe + hosts.tileset === 0 &&+ !document.getElementById('recent-imagery-split-line')+ );+ });+ current = await state();+ check(+ 'disabling leaves zero owned layers and no split line',+ cleared,+ `${hostsDetail(current)} split=${current.splitVisible}`,+ );+ check('the panel hides when the layer is off', current.panelHidden === true);+ onPhotorealOnly('disabling hands Google 3D back', await backOnPhotoreal());+ await wait(1_500);+ onPhotorealOnly(+ 'disabled, the layer never takes Esri again',+ (await page.evaluate(() => window.__riQa.activeStack())) === 'photoreal',+ );+ await shot('09-disabled');++ check(+ 'no page errors during the run',+ errors.length === 0,+ errors.join(' | '),+ );+} catch (error) {+ check(+ 'run completed',+ false,+ error?.stack || error?.message || String(error),+ );+} finally {+ await browser.close();+}+console.log(`shots: ${shots.join(', ')}`);+console.log(`RESULT: ${checks} checks, ${failures} failures`);+process.exitCode = failures ? 1 : 0;diff --git a/src/app/constructCatalog.js b/src/app/constructCatalog.jsindex b7a6fb3f1..26222c6cb 100644--- a/src/app/constructCatalog.js+++ b/src/app/constructCatalog.js@@ -13,6 +13,7 @@ import { createApplicationRadio } from './layers/radio.js';import { createApplicationTraffic } from './layers/traffic.js';import { createApplicationBikeshare } from './layers/bikeshare.js';import { createApplicationDirections } from './layers/directions.js';+import { createApplicationRecentImagery } from './layers/recentImagery.js';import { createApplicationTransit } from './layers/transit.js';import { createApplicationInstallations } from './layers/militaryInstallations.js';import { createApplicationSatellites } from './layers/satellites.js';@@ -129,6 +130,7 @@ export function createApplicationCatalog({createApplicationTransit({ surface, source: sources.transit }),createApplicationBikeshare({ source: sources.bikeshare }),createApplicationDirections(),+ createApplicationRecentImagery(),vessels,installations,createApplicationAwareness({diff --git a/src/app/constructCatalog.test.mjs b/src/app/constructCatalog.test.mjsindex 34f140101..1d8d33f80 100644--- a/src/app/constructCatalog.test.mjs+++ b/src/app/constructCatalog.test.mjs@@ -39,7 +39,7 @@ test('catalogs construct distinct layers and classification from their suppliedsignal: b.signal,surface: fixtureSurface(b.signal),});- assert.equal(first.layers.length, 26);+ assert.equal(first.layers.length, 27);assert.notEqual(first.weatherClock, second.weatherClock);await first.weatherClock.setTarget('2026-09-21T12:00:00.000Z');assert.match(diff --git a/src/app/layerPresentation.js b/src/app/layerPresentation.jsindex 13211f742..eaa0e0b57 100644--- a/src/app/layerPresentation.js+++ b/src/app/layerPresentation.js@@ -70,6 +70,12 @@ export class LayerPresentation {mount(container) {this.panel.mount(container);}+ /** Hand the Recent Imagery readout factory to the panel (see LayerPanel). */+ attachRecentImagery(factory) {+ // Detaching never builds a panel that teardown already released.+ if (factory) this.panel.attachRecentImagery(factory);+ else this._panel?.attachRecentImagery(null);+ }refresh() {this._panel?._refreshTogglePanel();}diff --git a/src/app/layers/recentImagery.js b/src/app/layers/recentImagery.jsnew file mode 100644index 000000000..1de4b22d4--- /dev/null+++ b/src/app/layers/recentImagery.js@@ -0,0 +1,19 @@+import { createRecentImageryLayer } from '../../layers/recentImagery/index.js';+import { createRecentImageryRenderer } from '../../layers/recentImagery/rendering.js';+import { createThumbnailLoader } from '../../layers/recentImagery/thumbnails.js';+import { governorRequestRender } from '../../renderGovernor.js';++/**+ * Construct the Recent Imagery layer with the real GIBS renderer and the+ * browser thumbnail loader. It takes no data source: the catalog is NASA+ * CMR and the tiles are GIBS, both browser-direct and keyless.+ * @returns {object} A fresh layer instance for this catalog.+ */+export function createApplicationRecentImagery() {+ return createRecentImageryLayer({+ renderer: createRecentImageryRenderer({+ requestRender: governorRequestRender,+ }),+ thumbnails: createThumbnailLoader(),+ });+}diff --git a/src/app/tools.js b/src/app/tools.jsindex 27d0cc2d1..613add71c 100644--- a/src/app/tools.js+++ b/src/app/tools.js@@ -1,6 +1,8 @@import { SceneDirector } from '../scenes/director.js';import { initAnnotations } from '../annotations/index.js';import { initDrawTool } from '../annotations/drawTool.js';+import { initImageryBoxTool } from '../ui/imageryBoxTool.js';+import { createRecentImageryPanel } from '../ui/recentImagery.js';import { initGevVoiceCommands } from '../voice/gevRealtime.js';import { installScopeMask, destroyScopeMask } from '../scopeMask.js';import {@@ -53,6 +55,43 @@ export function createApplicationTools({// lifetime rather than to whoever last pressed the button.const drawTool = initDrawTool({ viewer, annotations });defer(() => drawTool?.destroy());+ // DATA ▸ Recent Imagery: the box tool claims the pointer like Draw and the+ // panel lives on the right rail, so both belong to the application+ // lifetime. The tileset lets the layer drape while the globe is hidden.+ const recentImagery = dataManager.layers.get('recent-imagery')?.module;+ if (recentImagery) {+ recentImagery.attachTileset(tileset);+ const imageryBoxTool = initImageryBoxTool({+ viewer,+ onBox: (box) => recentImagery.setBox(box),+ onCancel: (reason, message, box) => {+ if (message) recentImagery.reportBoxRefusal(message, box);+ },+ onActive: (active) => recentImagery.setToolActive(active),+ // The tool takes Escape in a capture listener, so the panel's order+ // (clear a preview before cancelling the tool) is applied here.+ onEscape: () => recentImagery.clearPreview(),+ });+ // The readout mounts in its rail body through the layer panel, like the+ // weather readout.+ data.presentation.attachRecentImagery((container) =>+ createRecentImageryPanel({+ container,+ viewer,+ layer: recentImagery,+ tool: imageryBoxTool,+ }),+ );+ // The live gate's handle (scripts/qa-recent-imagery.mjs).+ const recentImageryHandle = { layer: recentImagery, tool: imageryBoxTool };+ window.__gevRecentImagery = recentImageryHandle;+ defer(() => {+ if (window.__gevRecentImagery === recentImageryHandle)+ delete window.__gevRecentImagery;+ data.presentation.attachRecentImagery(null);+ imageryBoxTool?.destroy();+ });+ }if (startChrome)defer(startChrome({ loadingScreen, styleManager, dataManager, signal }));// Idle render governor: flips the scene into requestRenderMode wheneverdiff --git a/src/data/bhoteKoshiEvent.js b/src/data/bhoteKoshiEvent.jsindex ce8d4829b..1f56099f9 100644--- a/src/data/bhoteKoshiEvent.js+++ b/src/data/bhoteKoshiEvent.js@@ -22,6 +22,8 @@ import {createBhoteKoshiEmbeddedMedia,resolveEmbeddedMediaSource,} from './bhoteKoshiEmbeddedMedia.js';+import { acquireImageryComparison } from '../maps/imageryComparison.js';+import { createImagerySplit } from '../ui/imagerySplit.js';export const BHOTE_KOSHI_LAYER_ID = 'bhote-koshi-2026';export const BHOTE_KOSHI_OVERLAY_SOURCE_ID = 'bhote-koshi-witnesses';@@ -964,10 +966,7 @@ export function createBhoteKoshiEventLayer({let _enabled = false;let _panel = null;let _panelRefs = null;- let _splitLine = null;- let _splitHandle = null;- let _splitDragging = false;- let _splitPointerId = null;+ let _splitControl = null;let _beforeLayer = null;let _afterLayer = null;let _imageryLayerCollection = null;@@ -1022,14 +1021,11 @@ export function createBhoteKoshiEventLayer({let _playStartedAt = 0;let _playStartProgress = 0;let _animationFrame = null;- let _previousMapStack = null;- let _eventMapGeneration = null;- let _previousSplitPosition = null;+ let _comparisonLease = null;let _introTimer = null;let _introGeneration = 0;let _lastSurgePosition = null;let _lastSurgeVisible = null;- let _lastSplitCssValue = null;let _presentation = 'standalone';let _sceneBeatId = null;let _sceneBeatReveal = 0.36;@@ -2556,79 +2552,20 @@ export function createBhoteKoshiEventLayer({createFloodDataSource();}- function ensureSplitLine(event) {- _splitLine = document.createElement('div');- _splitLine.id = 'bhote-koshi-split-line';- const beforeLabel = document.createElement('span');- const afterLabel = document.createElement('span');- const splitHandle = document.createElement('button');- beforeLabel.className = 'before';- afterLabel.className = 'after';- beforeLabel.textContent = 'A';- beforeLabel.title = event.imagery.before.label;- afterLabel.textContent = 'B';- afterLabel.title = event.imagery.after.label;- splitHandle.type = 'button';- splitHandle.className = 'bhote-koshi-split-handle';- splitHandle.setAttribute('role', 'slider');- splitHandle.setAttribute(- 'aria-label',- 'Historical reference and post-event image divider',- );- splitHandle.setAttribute('aria-valuemin', '0');- splitHandle.setAttribute('aria-valuemax', '100');- splitHandle.setAttribute('aria-orientation', 'horizontal');- splitHandle.textContent = '↔';- splitHandle.addEventListener('pointerdown', handleSplitPointerDown);- splitHandle.addEventListener('pointermove', handleSplitPointerMove);- splitHandle.addEventListener('pointerup', finishSplitPointerDrag);- splitHandle.addEventListener('pointercancel', finishSplitPointerDrag);- splitHandle.addEventListener('keydown', handleSplitKeyDown);- _splitHandle = splitHandle;- _splitLine.append(beforeLabel, splitHandle, afterLabel);- document.body.appendChild(_splitLine);- }-- function setSplitFromClientX(clientX) {- const viewportWidth =- Number(document.documentElement?.clientWidth) ||- Number(window.innerWidth) ||- 0;- if (viewportWidth <= 0 || !Number.isFinite(Number(clientX))) return;- setSplit(Number(clientX) / viewportWidth);- }-- function handleSplitPointerDown(event) {- if (event.button != null && event.button !== 0) return;- event.preventDefault?.();- _splitDragging = true;- _splitPointerId = event.pointerId ?? null;- _splitHandle?.setPointerCapture?.(event.pointerId);- setSplitFromClientX(event.clientX);- }-- function handleSplitPointerMove(event) {- if (!_splitDragging) return;- if (_splitPointerId != null && event.pointerId !== _splitPointerId) return;- event.preventDefault?.();- setSplitFromClientX(event.clientX);- }-- function finishSplitPointerDrag(event) {- if (!_splitDragging) return;- if (_splitPointerId != null && event.pointerId !== _splitPointerId) return;- _splitHandle?.releasePointerCapture?.(event.pointerId);- _splitDragging = false;- _splitPointerId = null;- }-- function handleSplitKeyDown(event) {- if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;- event.preventDefault?.();- const step = event.shiftKey ? 0.05 : 0.01;- if (event.key === 'Home') setSplit(0);- else if (event.key === 'End') setSplit(1);- else setSplit(_split + (event.key === 'ArrowRight' ? step : -step));+ function createSplitControl(event) {+ _splitControl = createImagerySplit({+ scene: _viewer.scene,+ initialValue: _split,+ id: 'bhote-koshi-split-line',+ handleClass: 'bhote-koshi-split-handle',+ cssProperty: '--bhote-koshi-split',+ beforeTitle: event.imagery.before.label,+ afterTitle: event.imagery.after.label,+ ariaLabel: 'Historical reference and post-event image divider',+ formatValueText: (beforePercent, afterPercent) =>+ `A historical reference ${beforePercent} percent, B post-event ${afterPercent} percent`,+ onChange: setSplit,+ });}function applyCinematicCamera() {@@ -3211,7 +3148,7 @@ export function createBhoteKoshiEventLayer({_panelRefs.observedStatus.hidden = !imageryAvailable;if (_panelRefs?.progressInput)_panelRefs.progressInput.hidden = !scrubberAvailable;- if (_splitLine) _splitLine.hidden = !imageryAvailable;+ _splitControl?.setVisible(imageryAvailable);if (_beforeLayer) _beforeLayer.show = imageryAvailable;if (_afterLayer) _afterLayer.show = imageryAvailable;if (_panelRefs?.caveat) {@@ -3328,24 +3265,7 @@ export function createBhoteKoshiEventLayer({function setSplit(split) {_split = clampUnit(split);- if (_viewer && _viewer.scene.splitPosition !== _split)- _viewer.scene.splitPosition = _split;- const cssValue = `${_split * 100}%`;- if (_lastSplitCssValue !== cssValue) {- document.documentElement.style.setProperty(- '--bhote-koshi-split',- cssValue,- );- _lastSplitCssValue = cssValue;- }- if (_splitHandle) {- const beforePercent = Math.round(_split * 100);- _splitHandle.setAttribute('aria-valuenow', String(beforePercent));- _splitHandle.setAttribute(- 'aria-valuetext',- `A historical reference ${beforePercent} percent, B post-event ${100 - beforePercent} percent`,- );- }+ _splitControl?.setValue(_split);syncPanel();renderHost.request('bhote-koshi-split');}@@ -3428,7 +3348,6 @@ export function createBhoteKoshiEventLayer({async function enable(viewer, { origin = 'local-restore', signal } = {}) {_viewer = viewer;_enabled = true;- _previousSplitPosition = viewer.scene.splitPosition;// Public lifecycle passes signal, not intent origin, to enable. Its atomic// restore has already applied the scene parameters; those own presentation.// A missing origin is passive, never authority to focus or start playback.@@ -3437,24 +3356,20 @@ export function createBhoteKoshiEventLayer({const event = await loadEvent();throwIfEnableCancelled(signal, _enabled);registerDynamicCredit(viewer, BHOTE_KOSHI_CREDIT);- _previousMapStack = _mapStackController?.getActiveId?.() || null;- if (- !sceneDirected &&- _mapStackController &&- _previousMapStack !== 'esri-imagery'- ) {- await _mapStackController.setStack('esri-imagery');+ if (_mapStackController) {+ _comparisonLease = acquireImageryComparison(_mapStackController, {+ owner: BHOTE_KOSHI_LAYER_ID,+ switchPolicy: sceneDirected ? 'preserve' : 'esri',+ });+ await _comparisonLease.ready;}- _eventMapGeneration = sceneDirected- ? null- : (_mapStackController?.getSwitchGeneration?.() ?? null);throwIfEnableCancelled(signal, _enabled);await createImagery(event);throwIfEnableCancelled(signal, _enabled);await syncTerrainComparison();throwIfEnableCancelled(signal, _enabled);createFloodDataSource();- ensureSplitLine(event);+ createSplitControl(event);const panelView = createPanel(event, {close: () =>_dataManager?.setEnabled(BHOTE_KOSHI_LAYER_ID, false, {@@ -3573,17 +3488,8 @@ export function createBhoteKoshiEventLayer({?.classList.remove('bhote-event-active');_panel = null;_panelRefs = null;- _splitDragging = false;- _splitPointerId = null;- _splitLine?.remove();- _splitLine = null;- _splitHandle = null;- document.documentElement.style.removeProperty('--bhote-koshi-split');- _lastSplitCssValue = null;- if (_viewer?.scene && _previousSplitPosition != null) {- _viewer.scene.splitPosition = _previousSplitPosition;- }- _previousSplitPosition = null;+ _splitControl?.destroy();+ _splitControl = null;_progress = 0;_split = 0.5;_presentation = 'standalone';@@ -3601,20 +3507,10 @@ export function createBhoteKoshiEventLayer({cancel?.(_sceneSeekFrame);_sceneSeekFrame = null;}- const previousMapStack = _previousMapStack;- const eventMapGeneration = _eventMapGeneration;- _previousMapStack = null;- _eventMapGeneration = null;+ const comparisonLease = _comparisonLease;+ _comparisonLease = null;try {- if (- _mapStackController &&- previousMapStack &&- previousMapStack !== 'esri-imagery' &&- _mapStackController.getActiveId?.() === 'esri-imagery' &&- _mapStackController.getSwitchGeneration?.() === eventMapGeneration- ) {- await _mapStackController.setStack(previousMapStack);- }+ await comparisonLease?.release();} finally {renderHost.request('bhote-koshi-disable');}diff --git a/src/data/dataCredits.js b/src/data/dataCredits.jsindex 79931d218..e5ef9d2b2 100644--- a/src/data/dataCredits.js+++ b/src/data/dataCredits.js@@ -77,6 +77,15 @@ export const DATA_CREDITS = [key: 'usgs',html: 'Earthquakes: Data courtesy of the U.S. Geological Survey',},+ {+ key: 'nasa-gibs',+ html:+ 'Recent imagery: We acknowledge the use of imagery provided by services from ' ++ "NASA's Global Imagery Browse Services (GIBS), part of NASA's Earth Science " ++ 'Data and Information System (ESDIS). ' ++ '<a href="https://gibs.earthdata.nasa.gov" target="_blank" rel="noopener">gibs.earthdata.nasa.gov</a> · ' ++ '<a href="https://lpdaac.usgs.gov/products/hlss30v002/" target="_blank" rel="noopener">HLS product page</a>',+ },{key: 'overpass',html:diff --git a/src/data/layerState.js b/src/data/layerState.jsindex 9dfa099af..da1b86b9e 100644--- a/src/data/layerState.js+++ b/src/data/layerState.js@@ -212,6 +212,84 @@ function integerOption(key, token, defaultValue) {});}+/**+ * A share-link-only option: the whole-state codec carries it, but the stored+ * local blob always holds its default.+ */+function shareOnlyOption(spec) {+ return Object.freeze({ ...spec, shareOnly: true });+}++/**+ * A signed integer in `[min, max]`, rejected (never clamped) outside it: a+ * clamped box edge would be a different box, not a shorter spelling.+ */+function boundedIntegerOption(key, token, defaultValue, { min, max }) {+ const parse = (value) => {+ const number =+ typeof value === 'number'+ ? value+ : /^-?\d{1,9}$/.test(String(value).trim())+ ? Number(String(value).trim())+ : NaN;+ return Number.isInteger(number) && number >= min && number <= max+ ? number+ : null;+ };+ return Object.freeze({+ key,+ token,+ defaultValue,+ normalize: parse,+ encode: (value) => String(value),+ decode: parse,+ });+}++/**+ * Recent Imagery day: runtime key `S30:2026-09-18`, URL form `S20260918`.+ * The calendar is checked both ways, and "today" is never consulted, so a+ * link decodes the same whenever it is opened.+ */+const IMAGERY_LETTERS = Object.freeze({ S30: 'S', L30: 'L', VIIRS: 'V' });+const IMAGERY_PRODUCTS = Object.freeze({ S: 'S30', L: 'L30', V: 'VIIRS' });++function imageryKey(product, year, month, day) {+ const time = Date.UTC(Number(year), Number(month) - 1, Number(day));+ const iso = Number.isFinite(time)+ ? new Date(time).toISOString().slice(0, 10)+ : '';+ return product && iso === `${year}-${month}-${day}`+ ? `${product}:${iso}`+ : null;+}++function imageryPinOption(key, token) {+ return Object.freeze({+ key,+ token,+ defaultValue: null,+ normalize: (value) => {+ const match = /^(S30|L30|VIIRS):(\d{4})-(\d{2})-(\d{2})$/.exec(+ typeof value === 'string' ? value.trim() : '',+ );+ return match ? imageryKey(match[1], match[2], match[3], match[4]) : null;+ },+ encode: (value) => {+ const [product, day] = value.split(':');+ return `${IMAGERY_LETTERS[product]}${day.replaceAll('-', '')}`;+ },+ decode: (value) => {+ const match = /^([SLV])(\d{4})(\d{2})(\d{2})$/.exec(+ typeof value === 'string' ? value : '',+ );+ return match+ ? imageryKey(IMAGERY_PRODUCTS[match[1]], match[2], match[3], match[4])+ : null;+ },+ });+}+const OPTION_GROUPS = Object.freeze({'weather-lightning': Object.freeze([enumOption('opacity', 'o', 'strong', ['light', 'strong'], {@@ -303,6 +381,23 @@ const OPTION_GROUPS = Object.freeze({booleanOption('showProjection', 'p', true),booleanOption('autoHop', 'a', false),]),+ 'recent-imagery': Object.freeze([+ // Box edges in degrees × 100000; latitudes stop at the Web-Mercator limit.+ boundedIntegerOption('west', 'w', null, { min: -18000000, max: 18000000 }),+ boundedIntegerOption('south', 's', null, { min: -8505110, max: 8505110 }),+ boundedIntegerOption('east', 'e', null, { min: -18000000, max: 18000000 }),+ boundedIntegerOption('north', 'n', null, { min: -8505110, max: 8505110 }),+ imageryPinOption('a', 'a'),+ imageryPinOption('b', 'b'),+ // 0 one image, 1 image against the basemap, 2 two images A / B.+ boundedIntegerOption('mode', 'm', 0, { min: 0, max: 2 }),+ // The swipe position is one comparison's framing, not a preference: a+ // stored split resurfaced in the next session's first comparison.+ shareOnlyOption(+ boundedIntegerOption('split', 'p', 50, { min: 0, max: 100 }),+ ),+ booleanOption('viirs', 'v', false),+ ]),radio: Object.freeze([Object.freeze({key: 'filter',@@ -420,6 +515,12 @@ export const LAYER_STATE_REGISTRY = Object.freeze([disposition: 'enabled+options',optionOwner: 'radio',}),+ Object.freeze({+ id: 'recent-imagery',+ token: '1',+ disposition: 'enabled+options',+ optionOwner: 'recent-imagery',+ }),Object.freeze({id: 'rocket-launches',token: 'x',@@ -699,13 +800,28 @@ export function decodeLayerStateParams(params) {return normalizeLayerState({ enabledLayerIds, options: rawOptions });}-/** Stable local-storage representation (full IDs for debuggability). */+/** Options with share-link-only values reset to their defaults. */+function withoutShareOnlyOptions(options) {+ const out = {};+ for (const ownerId of OPTION_OWNER_IDS) {+ out[ownerId] = { ...(options?.[ownerId] || {}) };+ for (const spec of optionSpecs(ownerId)) {+ if (spec.shareOnly) out[ownerId][spec.key] = spec.defaultValue;+ }+ }+ return out;+}++/**+ * Stable local-storage representation (full IDs for debuggability), with+ * share-link-only options at their defaults.+ */export function serializeStoredLayerState(state) {const normalized = normalizeLayerState(state);return JSON.stringify({v: LAYER_STATE_VERSION,l: normalized.enabledLayerIds,- o: normalized.options,+ o: withoutShareOnlyOptions(normalized.options),});}@@ -717,7 +833,7 @@ export function parseStoredLayerState(raw) {return null;return normalizeLayerState({enabledLayerIds: parsed.l,- options: parsed.o,+ options: withoutShareOnlyOptions(parsed.o),});} catch {return null;diff --git a/src/data/layerState.test.mjs b/src/data/layerState.test.mjsindex 81110286b..51d39bc61 100644--- a/src/data/layerState.test.mjs+++ b/src/data/layerState.test.mjs@@ -25,7 +25,10 @@ import { stampInitialShareGesture } from '../navigationPolicy.js';function deferred() {let resolve;let reject;- const promise = new Promise((res, rej) => { resolve = res; reject = rej; });+ const promise = new Promise((res, rej) => {+ resolve = res;+ reject = rej;+ });return { promise, resolve, reject };}@@ -33,7 +36,8 @@ function paramsForLayer(id) {if (id === 'flights' || id === 'military') {return { models3d: false, models3dMode: 'proximity', irBoost: true };}- if (id === 'satellites') return { catalog: 'core', showPoints: false, showOrbits: false };+ if (id === 'satellites')+ return { catalog: 'core', showPoints: false, showOrbits: false };if (id === 'cctv') {return {coverageMode: 'on',@@ -64,41 +68,62 @@ function fakeLayer(id, hooks = {}) {name: id,icon: '',source: 'test',- async init() { return hooks.init ? hooks.init() : true; },- async enable() { return hooks.enable ? hooks.enable() : true; },- async update() { return hooks.update ? hooks.update() : true; },- async disable() { return hooks.disable ? hooks.disable() : true; },- ...(hooks.resolveTrackingRestoreTarget ? {- async resolveTrackingRestoreTarget(targetId, options) {- return hooks.resolveTrackingRestoreTarget(targetId, options);- },- } : {}),- ...(params ? {- setParams(next = {}, options = {}) {- if (hooks.setParams) {- const result = hooks.setParams(next, options);- if (result === false) return false;- // 'defer' models the production tracking latch: the layer ACCEPTS the- // request and holds it pending, but getParams() keeps reporting the- // previous (still-untracked) value until the subject really arrives.- if (result === 'defer') return true;+ async init() {+ return hooks.init ? hooks.init() : true;+ },+ async enable() {+ return hooks.enable ? hooks.enable() : true;+ },+ async update() {+ return hooks.update ? hooks.update() : true;+ },+ async disable() {+ return hooks.disable ? hooks.disable() : true;+ },+ ...(hooks.resolveTrackingRestoreTarget+ ? {+ async resolveTrackingRestoreTarget(targetId, options) {+ return hooks.resolveTrackingRestoreTarget(targetId, options);+ },}- params = { ...params, ...next };- return true;- },- /** Test seam: a deferred subject finally arrives on a later poll. */- _arrive(next) { params = { ...params, ...next }; },- getParams() { return { ...params }; },- ...(hooks.cancelPendingTrackingRestore ? {- cancelPendingTrackingRestore(options) { hooks.cancelPendingTrackingRestore(options); },- } : {}),- } : {}),+ : {}),+ ...(params+ ? {+ setParams(next = {}, options = {}) {+ if (hooks.setParams) {+ const result = hooks.setParams(next, options);+ if (result === false) return false;+ // 'defer' models the production tracking latch: the layer ACCEPTS the+ // request and holds it pending, but getParams() keeps reporting the+ // previous (still-untracked) value until the subject really arrives.+ if (result === 'defer') return true;+ }+ params = { ...params, ...next };+ return true;+ },+ /** Test seam: a deferred subject finally arrives on a later poll. */+ _arrive(next) {+ params = { ...params, ...next };+ },+ getParams() {+ return { ...params };+ },+ ...(hooks.cancelPendingTrackingRestore+ ? {+ cancelPendingTrackingRestore(options) {+ hooks.cancelPendingTrackingRestore(options);+ },+ }+ : {}),+ }+ : {}),};}function productionManager(hooksById = {}) {const manager = new DataLayerManager({});- for (const id of REGISTERED_LAYER_IDS) manager.register(fakeLayer(id, hooksById[id] || {}));+ for (const id of REGISTERED_LAYER_IDS)+ manager.register(fakeLayer(id, hooksById[id] || {}));manager.finalizeRegistrations(LAYER_STATE_REGISTRY);return manager;}@@ -112,8 +137,13 @@ function manualTimers(startMs = 0) {let queued = null;return {now: () => nowMs,- setTimer: (fn, ms) => { queued = { fn, ms }; return queued; },- clearTimer: (handle) => { if (queued === handle) queued = null; },+ setTimer: (fn, ms) => {+ queued = { fn, ms };+ return queued;+ },+ clearTimer: (handle) => {+ if (queued === handle) queued = null;+ },/** Fire queued polls, advancing the clock, until nothing re-arms. */runUntilIdle(maxTicks = 2_000) {for (let tick = 0; tick < maxTicks; tick += 1) {@@ -133,7 +163,9 @@ function memoryStorage(initial = null) {if (initial !== null) values.set(LAYER_STATE_STORAGE_KEY, initial);return {writes: [],- getItem(key) { return values.has(key) ? values.get(key) : null; },+ getItem(key) {+ return values.has(key) ? values.get(key) : null;+ },setItem(key, value) {values.set(key, value);this.writes.push([key, value]);@@ -145,8 +177,12 @@ function shareSink() {return {provider: null,updates: 0,- setLayerStateProvider(provider) { this.provider = provider; },- onLayerStateChange() { this.updates += 1; },+ setLayerStateProvider(provider) {+ this.provider = provider;+ },+ onLayerStateChange() {+ this.updates += 1;+ },};}@@ -158,32 +194,53 @@ function encode(state) {test('production registry is exact, canonical, and rejects incomplete contracts', async () => {assert.equal(validateLayerStateRegistry(), true);- assert.equal(REGISTERED_LAYER_IDS.length, 26);- assert.equal(new Set(REGISTERED_LAYER_IDS).size, 26);+ assert.equal(REGISTERED_LAYER_IDS.length, 27);+ assert.equal(new Set(REGISTERED_LAYER_IDS).size, 27);assert.ok(REGISTERED_LAYER_IDS.includes('transit'));assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort());assert.throws(- () => validateLayerStateRegistry([...LAYER_STATE_REGISTRY, LAYER_STATE_REGISTRY[0]]),+ () =>+ validateLayerStateRegistry([+ ...LAYER_STATE_REGISTRY,+ LAYER_STATE_REGISTRY[0],+ ]),/Duplicate layer-state id/,);const manager = new DataLayerManager({});manager.register(fakeLayer('earthquakes'));- assert.throws(() => manager.register(fakeLayer('earthquakes')), /Duplicate data-layer id/);- await assert.rejects(manager.restoreLayerState('earthquakes', { enabled: true }), /finalized/);+ assert.throws(+ () => manager.register(fakeLayer('earthquakes')),+ /Duplicate data-layer id/,+ );+ await assert.rejects(+ manager.restoreLayerState('earthquakes', { enabled: true }),+ /finalized/,+ );assert.throws(() => manager.finalizeRegistrations([]), /registry mismatch/);assert.throws(- () => manager.finalizeRegistrations([{ id: 'earthquakes', disposition: 'default' }]),+ () =>+ manager.finalizeRegistrations([+ { id: 'earthquakes', disposition: 'default' },+ ]),/Invalid layer serialization disposition/,);- assert.equal(manager.finalizeRegistrations([- { id: 'earthquakes', disposition: 'enabled-only' },- ]), true);+ assert.equal(+ manager.finalizeRegistrations([+ { id: 'earthquakes', disposition: 'enabled-only' },+ ]),+ true,+ );assert.throws(() => manager.register(fakeLayer('radio')), /finalized/);- assert.throws(() => manager.registerForQa(fakeLayer('radio')), /not authorized/);+ assert.throws(+ () => manager.registerForQa(fakeLayer('radio')),+ /not authorized/,+ );const qaManager = new DataLayerManager({}, { allowQaRegistration: true });qaManager.register(fakeLayer('earthquakes'));- qaManager.finalizeRegistrations([{ id: 'earthquakes', disposition: 'enabled-only' }]);+ qaManager.finalizeRegistrations([+ { id: 'earthquakes', disposition: 'enabled-only' },+ ]);qaManager.registerForQa(fakeLayer('radio'));assert.equal(qaManager.layers.has('radio'), true);assert.equal(await qaManager.unregisterForQa('radio'), true);@@ -191,7 +248,10 @@ test('production registry is exact, canonical, and rejects incomplete contracts'});test('v2 codec distinguishes absent from empty and keeps canonical deterministic ordering', () => {- assert.equal(decodeLayerStateParams(new URLSearchParams('lat=1&lon=2')), null);+ assert.equal(+ decodeLayerStateParams(new URLSearchParams('lat=1&lon=2')),+ null,+ );assert.equal(decodeLayerStateParams(new URLSearchParams('v=1&l=e')), null);assert.equal(decodeLayerStateParams(new URLSearchParams('v=3&l=e')), null);assert.equal(decodeLayerStateParams(new URLSearchParams('v=2')), null);@@ -223,24 +283,38 @@ test('v2 codec distinguishes absent from empty and keeps canonical deterministic},});assert.equal(encode(first), encode(second));- assert.deepEqual(decodeLayerStateParams(new URLSearchParams(encode(first))), first);+ assert.deepEqual(+ decodeLayerStateParams(new URLSearchParams(encode(first))),+ first,+ );});test('unknown enabled-layer tokens reject the payload instead of becoming an empty set', () => {- assert.equal(decodeLayerStateParams(new URLSearchParams('v=2&l=unknown')), null);- assert.equal(decodeLayerStateParams(new URLSearchParams('v=2&l=c.unknown')), null);+ assert.equal(+ decodeLayerStateParams(new URLSearchParams('v=2&l=unknown')),+ null,+ );+ assert.equal(+ decodeLayerStateParams(new URLSearchParams('v=2&l=c.unknown')),+ null,+ );});test('Nepal event and locator have distinct enabled-only share tokens', () => {const decoded = decodeLayerStateParams(new URLSearchParams('v=2&l=h.z'));- assert.deepEqual(decoded.enabledLayerIds, ['bhote-koshi-2026', 'bhote-koshi-locator']);+ assert.deepEqual(decoded.enabledLayerIds, [+ 'bhote-koshi-2026',+ 'bhote-koshi-locator',+ ]);assert.ok(encode(decoded).includes('l=h.z'));});test('unknown and forbidden option fields are ignored while missing options use codec defaults', () => {- const decoded = decodeLayerStateParams(new URLSearchParams(- 'v=2&l=c.e&lo=c.c.v_c.z.1_z.c.1_f.e.1_f.m.a_r.f.n_r.v.35',- ));+ const decoded = decodeLayerStateParams(+ new URLSearchParams(+ 'v=2&l=c.e&lo=c.c.v_c.z.1_z.c.1_f.e.1_f.m.a_r.f.n_r.v.35',+ ),+ );assert.deepEqual(decoded.enabledLayerIds, ['cctv', 'earthquakes']);assert.deepEqual(decoded.options.cctv, {coverageMode: 'viewshed',@@ -278,9 +352,18 @@ test('unknown and forbidden option fields are ignored while missing options use});const serialized = `${encode(raw)} ${serializeStoredLayerState(raw)}`;for (const forbidden of [- 'private-camera', 'calibration', 'autoHopSec', 'irBoost', 'showPoints',- 'showOrbits', 'private-station', 'audioState', 'voiceDucked', 'secret',- ]) assert.equal(serialized.includes(forbidden), false, forbidden);+ 'private-camera',+ 'calibration',+ 'autoHopSec',+ 'irBoost',+ 'showPoints',+ 'showOrbits',+ 'private-station',+ 'audioState',+ 'voiceDucked',+ 'secret',+ ])+ assert.equal(serialized.includes(forbidden), false, forbidden);});test('Radio genre ids with spaces and ampersands round-trip through v2', () => {@@ -295,19 +378,23 @@ test('Radio genre ids with spaces and ampersands round-trip through v2', () => {});test('mirrored option owners decode into the owner owner-options bucket', () => {- const decoded = decodeLayerStateParams(new URLSearchParams(- 'v=2&l=f.m&lo=m.u.xyz',- ));+ const decoded = decodeLayerStateParams(+ new URLSearchParams('v=2&l=f.m&lo=m.u.xyz'),+ );assert.deepEqual(decoded.enabledLayerIds, ['flights', 'military']);assert.equal(decoded.options.flights.selectedFlightsTrackingId, null);assert.equal(decoded.options.flights.selectedMilitaryTrackingId, 'xyz');});test('ambiguous cross-family tracking IDs fail closed instead of racing feed arrival', () => {- const decoded = decodeLayerStateParams(new URLSearchParams(- 'v=2&l=f.m.s&lo=f.t.flightA_f.u.militaryB_s.t.25544',- ));- assert.deepEqual(decoded.enabledLayerIds, ['flights', 'military', 'satellites']);+ const decoded = decodeLayerStateParams(+ new URLSearchParams('v=2&l=f.m.s&lo=f.t.flightA_f.u.militaryB_s.t.25544'),+ );+ assert.deepEqual(decoded.enabledLayerIds, [+ 'flights',+ 'military',+ 'satellites',+ ]);assert.equal(decoded.options.flights.selectedFlightsTrackingId, null);assert.equal(decoded.options.flights.selectedMilitaryTrackingId, null);assert.equal(decoded.options.satellites.selectedSatTrackingId, null);@@ -329,8 +416,18 @@ test('compact URL omits absent-meaning option state and still resolves to it', (// meant to the links already in the wild, so `false` is what belongs in a// URL-omission test. The default's own value is pinned in the fresh-boot test// below, and the divergence itself in the two codec tests above.- state.options.flights = { models3d: false, models3dMode: 'proximity', selectedFlightsTrackingId: null, selectedMilitaryTrackingId: null };- state.options.satellites = { catalog: 'core', showPoints: true, showOrbits: true, selectedSatTrackingId: null };+ state.options.flights = {+ models3d: false,+ models3dMode: 'proximity',+ selectedFlightsTrackingId: null,+ selectedMilitaryTrackingId: null,+ };+ state.options.satellites = {+ catalog: 'core',+ showPoints: true,+ showOrbits: true,+ selectedSatTrackingId: null,+ };state.options.wind.overlay = 'speed'; // Frozen v2 omitted-token meaning; new boots use trails.const params = encodeLayerStateParams(new URLSearchParams('v=2'), state);assert.equal(params.has('lo'), false);@@ -360,16 +457,34 @@ test('a fresh boot starts 3D aircraft ON in proximity — codec, both layers, anconst paramsCalls = [];const manager = productionManager({- flights: { setParams: (params) => { paramsCalls.push({ ...params }); return true; } },- military: { setParams: (params) => { paramsCalls.push({ ...params }); return true; } },+ flights: {+ setParams: (params) => {+ paramsCalls.push({ ...params });+ return true;+ },+ },+ military: {+ setParams: (params) => {+ paramsCalls.push({ ...params });+ return true;+ },+ },+ });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),});- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });await coordinator.start();assert.equal(coordinator.source, 'defaults');assert.equal(coordinator.getDurableState().options.flights.models3d, true);- assert.equal(coordinator.getDurableState().options.flights.models3dMode, 'proximity');- assert.deepEqual(paramsCalls, [],- 'a fresh boot restores nothing — which is exactly why the module initializers below must match');+ assert.equal(+ coordinator.getDurableState().options.flights.models3dMode,+ 'proximity',+ );+ assert.deepEqual(+ paramsCalls,+ [],+ 'a fresh boot restores nothing — which is exactly why the module initializers below must match',+ );coordinator.destroy();// The other three surfaces, read from source, because each is the literal a@@ -377,25 +492,51 @@ test('a fresh boot starts 3D aircraft ON in proximity — codec, both layers, anconst { readFile } = await import('node:fs/promises');for (const name of ['flights.js', 'militaryFlights.js']) {const source = readLayerSource(new URL(`./${name}`, import.meta.url));- assert.match(source, /^\s*(?:let |flightState\.)_models3dEnabled = true;$/m,- `${name}: the fleet starts armed, matching the codec default`);- assert.match(source, /^\s*(?:let |flightState\.)_models3dMode = 'proximity';/m,- `${name}: and starts in proximity, matching the codec default`);+ assert.match(+ source,+ /^\s*(?:let |flightState\.)_models3dEnabled = true;$/m,+ `${name}: the fleet starts armed, matching the codec default`,+ );+ assert.match(+ source,+ /^\s*(?:let |flightState\.)_models3dMode = 'proximity';/m,+ `${name}: and starts in proximity, matching the codec default`,+ );}const ui = await readShellSource();- assert.match(ui, /^\s*this\.(?:flightState\.)?_models3dEnabled = true;$/m,- 'ui.js: the DISPLAY rail believes 3D is on before any layer-state sync arrives');- assert.match(ui, /this\.(?:flightState\.)?_models3dMode = 'proximity';/,- 'ui.js: and believes the mode is proximity');- const html = expandApplicationHtml(await readFile(new URL('../../index.html', import.meta.url), 'utf8'));- assert.match(html, /class="pp-toggle-btn active" id="models3d-toggle" aria-pressed="true"/,- 'index.html: the 3D button paints lit on first paint, before ui.js runs — and says so');- assert.match(ui, /this\._models3dBtn\?\.setAttribute\(\s*'aria-pressed',\s*String\(this\.(?:flightState\.)?_models3dEnabled\),?\s*\)/,- 'ui.js: and keeps aria-pressed synchronized, so the lit state is not colour-only');- assert.match(html, /class="pp-slider-row visible" id="models3d-mode-row"/,- 'index.html: and the Proximity/All row paints open with it');- assert.match(html, /id="models3d-mode-proximity"[^>]*aria-checked="true"/,- 'index.html: Proximity is the selected mode in the markup');+ assert.match(+ ui,+ /^\s*this\.(?:flightState\.)?_models3dEnabled = true;$/m,+ 'ui.js: the DISPLAY rail believes 3D is on before any layer-state sync arrives',+ );+ assert.match(+ ui,+ /this\.(?:flightState\.)?_models3dMode = 'proximity';/,+ 'ui.js: and believes the mode is proximity',+ );+ const html = expandApplicationHtml(+ await readFile(new URL('../../index.html', import.meta.url), 'utf8'),+ );+ assert.match(+ html,+ /class="pp-toggle-btn active" id="models3d-toggle" aria-pressed="true"/,+ 'index.html: the 3D button paints lit on first paint, before ui.js runs — and says so',+ );+ assert.match(+ ui,+ /this\._models3dBtn\?\.setAttribute\(\s*'aria-pressed',\s*String\(this\.(?:flightState\.)?_models3dEnabled\),?\s*\)/,+ 'ui.js: and keeps aria-pressed synchronized, so the lit state is not colour-only',+ );+ assert.match(+ html,+ /class="pp-slider-row visible" id="models3d-mode-row"/,+ 'index.html: and the Proximity/All row paints open with it',+ );+ assert.match(+ html,+ /id="models3d-mode-proximity"[^>]*aria-checked="true"/,+ 'index.html: Proximity is the selected mode in the markup',+ );});test('a v2 link written before the flip still means what its author saw: 3D OFF', () => {@@ -406,20 +547,29 @@ test('a v2 link written before the flip still means what its author saw: 3D OFF'//// `v=2&l=f` is the canonical parent-era link. It must decode OFF forever.const parentEra = decodeLayerStateParams(new URLSearchParams('v=2&l=f'));- assert.equal(parentEra.options.flights.models3d, false,- 'an omitted `e` is a v2 author saying OFF, not "whatever today\'s default is"');+ assert.equal(+ parentEra.options.flights.models3d,+ false,+ 'an omitted `e` is a v2 author saying OFF, not "whatever today\'s default is"',+ );// The nastier one: an OFF link that DID remember a non-default mode. Reading// the omission as the new default would resurrect it as ON + All.- const parentEraAll = decodeLayerStateParams(new URLSearchParams('v=2&l=f&lo=f.m.a'));+ const parentEraAll = decodeLayerStateParams(+ new URLSearchParams('v=2&l=f&lo=f.m.a'),+ );assert.equal(parentEraAll.options.flights.models3d, false);- assert.equal(parentEraAll.options.flights.models3dMode, 'all',- 'the mode it really carried survives; only the omission is read as OFF');+ assert.equal(+ parentEraAll.options.flights.models3dMode,+ 'all',+ 'the mode it really carried survives; only the omission is read as OFF',+ );// A parent-era link that carried 3D ON wrote it explicitly (ON was non-default// then), so it still restores ON. Both eras round-trip.assert.equal(- decodeLayerStateParams(new URLSearchParams('v=2&l=f&lo=f.e.1')).options.flights.models3d,+ decodeLayerStateParams(new URLSearchParams('v=2&l=f&lo=f.e.1')).options+ .flights.models3d,true,);});@@ -431,11 +581,22 @@ test('the new default is written EXPLICITLY, so no omission is ambiguous', () =>// OFF links for their recipients.const on = createDefaultLayerState();on.enabledLayerIds = ['flights'];- assert.equal(on.options.flights.models3d, true, 'precondition: ON is the default');+ assert.equal(+ on.options.flights.models3d,+ true,+ 'precondition: ON is the default',+ );const onEncoded = encode(on);- assert.match(onEncoded, /(^|&)lo=[^&]*f\.e\.1/,- 'a fresh ON link states ON outright rather than relying on omission');- assert.equal(decodeLayerStateParams(new URLSearchParams(onEncoded)).options.flights.models3d, true);+ assert.match(+ onEncoded,+ /(^|&)lo=[^&]*f\.e\.1/,+ 'a fresh ON link states ON outright rather than relying on omission',+ );+ assert.equal(+ decodeLayerStateParams(new URLSearchParams(onEncoded)).options.flights+ .models3d,+ true,+ );// And OFF is the omission, matching what v2 already meant — one meaning, one// encoding, across both eras.@@ -443,13 +604,21 @@ test('the new default is written EXPLICITLY, so no omission is ambiguous', () =>off.enabledLayerIds = ['flights'];off.options.flights = { ...off.options.flights, models3d: false };const offEncoded = encode(off);- assert.doesNotMatch(offEncoded, /f\.e\./,- 'OFF is the absent token, exactly as it was before the flip');- assert.equal(decodeLayerStateParams(new URLSearchParams(offEncoded)).options.flights.models3d, false);+ assert.doesNotMatch(+ offEncoded,+ /f\.e\./,+ 'OFF is the absent token, exactly as it was before the flip',+ );+ assert.equal(+ decodeLayerStateParams(new URLSearchParams(offEncoded)).options.flights+ .models3d,+ false,+ );// An interim build briefly emitted `f.e.0`; it must still decode as OFF.assert.equal(- decodeLayerStateParams(new URLSearchParams('v=2&l=f&lo=f.e.0')).options.flights.models3d,+ decodeLayerStateParams(new URLSearchParams('v=2&l=f&lo=f.e.0')).options+ .flights.models3d,false,);});@@ -464,41 +633,82 @@ test('a share link that carries 3D OFF still restores OFF at both aircraft layerconst encoded = encode(state);const decoded = decodeLayerStateParams(new URLSearchParams(encoded));- assert.equal(decoded.options.flights.models3d, false, 'the link decodes back to OFF');+ assert.equal(+ decoded.options.flights.models3d,+ false,+ 'the link decodes back to OFF',+ );assert.equal(decoded.options.flights.models3dMode, 'proximity');// And the restore really pushes OFF at both aircraft layers — `military`// mirrors the `flights` option owner, so one shared link disarms both.const calls = { flights: [], military: [] };const manager = productionManager({- flights: { setParams: (params) => { calls.flights.push({ ...params }); return true; } },- military: { setParams: (params) => { calls.military.push({ ...params }); return true; } },+ flights: {+ setParams: (params) => {+ calls.flights.push({ ...params });+ return true;+ },+ },+ military: {+ setParams: (params) => {+ calls.military.push({ ...params });+ return true;+ },+ },+ });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),});- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });- await coordinator.start({ shareLayerState: decoded, shareCreatedAtMs: 1_000 });- assert.deepEqual(calls.flights, [{ models3d: false, models3dMode: 'proximity' }]);- assert.deepEqual(calls.military, [{ models3d: false, models3dMode: 'proximity' }]);+ await coordinator.start({+ shareLayerState: decoded,+ shareCreatedAtMs: 1_000,+ });+ assert.deepEqual(calls.flights, [+ { models3d: false, models3dMode: 'proximity' },+ ]);+ assert.deepEqual(calls.military, [+ { models3d: false, models3dMode: 'proximity' },+ ]);assert.equal(coordinator.getDurableState().options.flights.models3d, false);coordinator.destroy();});test('explicit navigation tracking clear removes the active durable ID from the generated hash', async () => {const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });await coordinator.start();await manager.setEnabled('flights', true, { origin: 'user' });- manager.setLayerParams('flights', { selectedFlightsTrackingId: 'abc123' }, { origin: 'user' });- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, 'abc123');+ manager.setLayerParams(+ 'flights',+ { selectedFlightsTrackingId: 'abc123' },+ { origin: 'user' },+ );+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ 'abc123',+ );assert.equal(encode(coordinator.getDurableState()).includes('abc123'), true);- manager.setLayerParams('flights', { selectedFlightsTrackingId: null }, { origin: 'tool' });- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, null);+ manager.setLayerParams(+ 'flights',+ { selectedFlightsTrackingId: null },+ { origin: 'tool' },+ );+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ null,+ );assert.equal(encode(coordinator.getDurableState()).includes('abc123'), false);coordinator.destroy();});test('a direct Context selection promotes its owned tracker layer before persisting the ID', async () => {const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });await coordinator.start();await manager.setEnabled('flights', true, { origin: 'programmatic' });manager.setLayerParams(@@ -506,75 +716,140 @@ test('a direct Context selection promotes its owned tracker layer before persist{ selectedFlightsTrackingId: 'context-flight' },{ origin: 'programmatic' },);- assert.equal(manager.adoptLayerVisibility('flights', true, {- origin: 'user',- adoptedFromSelection: true,- }), true);- assert.equal(manager.adoptLayerParams(- 'flights',- { selectedFlightsTrackingId: 'context-flight' },- { origin: 'user' },- ), true);+ assert.equal(+ manager.adoptLayerVisibility('flights', true, {+ origin: 'user',+ adoptedFromSelection: true,+ }),+ true,+ );+ assert.equal(+ manager.adoptLayerParams(+ 'flights',+ { selectedFlightsTrackingId: 'context-flight' },+ { origin: 'user' },+ ),+ true,+ );const durable = coordinator.getDurableState();assert.equal(durable.enabledLayerIds.includes('flights'), true);- assert.equal(durable.options.flights.selectedFlightsTrackingId, 'context-flight');+ assert.equal(+ durable.options.flights.selectedFlightsTrackingId,+ 'context-flight',+ );assert.equal(encode(durable).includes('context-flight'), true);coordinator.destroy();});test('explicit Flight to Satellite replacement keeps the new Satellite ID durable', async () => {const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });await coordinator.start();await manager.setEnabled('flights', true, { origin: 'user' });await manager.setEnabled('satellites', true, { origin: 'user' });- manager.setLayerParams('flights', { selectedFlightsTrackingId: 'abc123' }, { origin: 'user' });- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, 'abc123');+ manager.setLayerParams(+ 'flights',+ { selectedFlightsTrackingId: 'abc123' },+ { origin: 'user' },+ );+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ 'abc123',+ );// UI replacement ordering clears the prior family before a direct tracker// publishes its already-applied selection through adoptLayerParams().- manager.setLayerParams('flights', { selectedFlightsTrackingId: null }, { origin: 'user' });- manager.setLayerParams('satellites', { selectedSatTrackingId: 25544 }, { origin: 'programmatic' });- assert.equal(manager.adoptLayerParams(+ manager.setLayerParams(+ 'flights',+ { selectedFlightsTrackingId: null },+ { origin: 'user' },+ );+ manager.setLayerParams('satellites',{ selectedSatTrackingId: 25544 },- { origin: 'user' },- ), true);+ { origin: 'programmatic' },+ );+ assert.equal(+ manager.adoptLayerParams(+ 'satellites',+ { selectedSatTrackingId: 25544 },+ { origin: 'user' },+ ),+ true,+ );const durable = coordinator.getDurableState();assert.equal(durable.options.flights.selectedFlightsTrackingId, null);assert.equal(durable.options.flights.selectedMilitaryTrackingId, null);assert.equal(durable.options.satellites.selectedSatTrackingId, 25544);- assert.equal(new URLSearchParams(encode(durable)).get('lo')?.includes('s.t.25544'), true);+ assert.equal(+ new URLSearchParams(encode(durable)).get('lo')?.includes('s.t.25544'),+ true,+ );coordinator.destroy();});test('explicit layer OFF clears its durable selected entity and prevents later resurrection', async () => {const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });await coordinator.start();await manager.setEnabled('flights', true, { origin: 'user' });- manager.setLayerParams('flights', { selectedFlightsTrackingId: 'abc123' }, { origin: 'user' });- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, 'abc123');+ manager.setLayerParams(+ 'flights',+ { selectedFlightsTrackingId: 'abc123' },+ { origin: 'user' },+ );+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ 'abc123',+ );await manager.setEnabled('flights', false, { origin: 'user' });- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, null);- assert.equal(Boolean(- new URLSearchParams(encode(coordinator.getDurableState())).get('lo')?.includes('f.t.'),- ), false);+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ null,+ );+ assert.equal(+ Boolean(+ new URLSearchParams(encode(coordinator.getDurableState()))+ .get('lo')+ ?.includes('f.t.'),+ ),+ false,+ );coordinator.destroy();});test('unrelated explicit params retain the family live active ID while cancelling only pending state', async () => {const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });await coordinator.start();- assert.equal(manager.setLayerParams('flights', {- selectedFlightsTrackingId: 'active001',- }, { origin: 'programmatic' }), true);+ assert.equal(+ manager.setLayerParams(+ 'flights',+ {+ selectedFlightsTrackingId: 'active001',+ },+ { origin: 'programmatic' },+ ),+ true,+ );await manager.setEnabled('flights', true, { origin: 'user' });- assert.equal(manager.setLayerParams('flights', {- models3d: true,- }, { origin: 'user' }), true);+ assert.equal(+ manager.setLayerParams(+ 'flights',+ {+ models3d: true,+ },+ { origin: 'user' },+ ),+ true,+ );assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId,'active001',@@ -587,7 +862,11 @@ test('stored state is deterministic, rejects other versions, and stays within astate.enabledLayerIds = [...REGISTERED_LAYER_IDS].reverse();state.options.flights = { models3d: true, models3dMode: 'all' };state.options.satellites = { catalog: 'dense' };- state.options.cctv = { coverageMode: 'viewshed', showProjection: false, autoHop: true };+ state.options.cctv = {+ coverageMode: 'viewshed',+ showProjection: false,+ autoHop: true,+ };state.options.radio = { filter: 'genre:experimental-ambient', volume: 1 };const stored = serializeStoredLayerState(state);assert.deepEqual(parseStoredLayerState(stored), normalizeLayerState(state));@@ -599,33 +878,58 @@ test('restore applies sanitized params after init and before enable', async () =const order = [];const manager = productionManager({flights: {- init: () => { order.push('init'); return true; },- setParams: () => { order.push('params'); return true; },- enable: () => { order.push('enable'); return true; },- update: () => { order.push('update'); return true; },+ init: () => {+ order.push('init');+ return true;+ },+ setParams: () => {+ order.push('params');+ return true;+ },+ enable: () => {+ order.push('enable');+ return true;+ },+ update: () => {+ order.push('update');+ return true;+ },},});- const outcome = await manager.restoreLayerState('flights', {- enabled: true,- params: { models3d: true, models3dMode: 'all' },- }, { origin: 'share-restore' });+ const outcome = await manager.restoreLayerState(+ 'flights',+ {+ enabled: true,+ params: { models3d: true, models3dMode: 'all' },+ },+ { origin: 'share-restore' },+ );assert.deepEqual(order, ['init', 'params', 'enable', 'update']);assert.equal(outcome.succeeded, true);assert.equal(outcome.persistenceWrite, false);- assert.deepEqual(outcome.appliedOptions, { models3d: true, models3dMode: 'all' });+ assert.deepEqual(outcome.appliedOptions, {+ models3d: true,+ models3dMode: 'all',+ });});test('manager forwards passive restore origin into module parameter application', async () => {const seen = [];const manager = productionManager({flights: {- setParams: (_params, options) => { seen.push(options); },+ setParams: (_params, options) => {+ seen.push(options);+ },},});- await manager.restoreLayerState('flights', {- enabled: false,- params: { selectedFlightsTrackingId: 'abc123' },- }, { origin: 'share-restore' });+ await manager.restoreLayerState(+ 'flights',+ {+ enabled: false,+ params: { selectedFlightsTrackingId: 'abc123' },+ },+ { origin: 'share-restore' },+ );assert.deepEqual(seen, [{ origin: 'share-restore', paramsIntentEpoch: 1 }]);});@@ -633,15 +937,25 @@ test('explicit manager params and visibility revoke module-owned pending trackinconst cancellations = [];const manager = productionManager({flights: {- cancelPendingTrackingRestore: (options) => { cancellations.push(options); },+ cancelPendingTrackingRestore: (options) => {+ cancellations.push(options);+ },},});- await manager.restoreLayerState('flights', {- enabled: false,- params: { selectedFlightsTrackingId: 'late001' },- }, { origin: 'share-restore' });- assert.deepEqual(cancellations, [], 'passive restoration cannot cancel itself');+ await manager.restoreLayerState(+ 'flights',+ {+ enabled: false,+ params: { selectedFlightsTrackingId: 'late001' },+ },+ { origin: 'share-restore' },+ );+ assert.deepEqual(+ cancellations,+ [],+ 'passive restoration cannot cancel itself',+ );manager.setLayerParams('flights', { models3d: true }, { origin: 'voice' });await manager.setEnabled('flights', false, { origin: 'user' });@@ -667,18 +981,29 @@ test('share payload wins over local, passive restore writes nothing, and expliciassert.equal(share.provider().enabledLayerIds.length, 0);await manager.setEnabled('earthquakes', true, { origin: 'user' });- assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['earthquakes']);+ assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [+ 'earthquakes',+ ]);assert.equal(storage.writes.length, 1);await manager.setEnabled('traffic', true, { origin: 'scene' });assert.equal(storage.writes.length, 1);- assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['earthquakes']);+ assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [+ 'earthquakes',+ ]);await manager.setEnabled('traffic', true, { origin: 'tool' });assert.equal(storage.writes.length, 2);- assert.deepEqual(coordinator.getDurableState().enabledLayerIds, ['earthquakes', 'traffic']);+ assert.deepEqual(coordinator.getDurableState().enabledLayerIds, [+ 'earthquakes',+ 'traffic',+ ]);- manager.setLayerParams('cctv', { selectedCameraId: 'private-camera' }, { origin: 'user' });+ manager.setLayerParams(+ 'cctv',+ { selectedCameraId: 'private-camera' },+ { origin: 'user' },+ );assert.equal(storage.writes.length, 2);assert.deepEqual(coordinator.getDurableState().options.cctv, {coverageMode: 'on',@@ -690,9 +1015,16 @@ test('share payload wins over local, passive restore writes nothing, and expliciassert.equal(storage.writes.length, 2);assert.equal(coordinator.getDurableState().options.cctv.coverageMode, 'on');- manager.setLayerParams('cctv', { coverageMode: 'viewshed' }, { origin: 'voice' });+ manager.setLayerParams(+ 'cctv',+ { coverageMode: 'viewshed' },+ { origin: 'voice' },+ );assert.equal(storage.writes.length, 3);- assert.equal(coordinator.getDurableState().options.cctv.coverageMode, 'viewshed');+ assert.equal(+ coordinator.getDurableState().options.cctv.coverageMode,+ 'viewshed',+ );coordinator.destroy();});@@ -702,7 +1034,9 @@ test('absent share payload restores local state without rewriting it', async ()local.options.radio = { filter: 'talk', volume: 0.42 };const storage = memoryStorage(serializeStoredLayerState(local));const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage,+ });const results = await coordinator.start();assert.equal(coordinator.source, 'local');assert.equal(manager.isEnabled('earthquakes'), true);@@ -714,7 +1048,10 @@ test('absent share payload restores local state without rewriting it', async ()audioState: 'playing',voiceDucked: true,});- assert.equal(results.every((result) => result.persistenceWrite === false), true);+ assert.equal(+ results.every((result) => result.persistenceWrite === false),+ true,+ );assert.deepEqual(storage.writes, []);coordinator.destroy();});@@ -724,7 +1061,9 @@ test('historical share payload suppresses unrelated local layer preferences', aslocal.enabledLayerIds = ['traffic', 'radio'];const storage = memoryStorage(serializeStoredLayerState(local));const manager = productionManager();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage,+ });await coordinator.start({ allowLocalState: false });assert.equal(coordinator.source, 'legacy-share');assert.deepEqual(coordinator.getDurableState().enabledLayerIds, []);@@ -735,11 +1074,17 @@ test('historical share payload suppresses unrelated local layer preferences', astest('one layer failure is isolated from sibling restoration', async () => {const manager = productionManager({- cctv: { init: () => { throw new Error('missing key'); } },+ cctv: {+ init: () => {+ throw new Error('missing key');+ },+ },});const state = createDefaultLayerState();state.enabledLayerIds = ['cctv', 'earthquakes'];- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });const results = await coordinator.start({ shareLayerState: state });assert.equal(manager.isEnabled('cctv'), false);assert.equal(manager.isEnabled('earthquakes'), true);@@ -748,7 +1093,10 @@ test('one layer failure is isolated from sibling restoration', async () => {assert.equal(failed.phase, 'init');assert.equal(failed.errorClass, 'Error');assert.equal(failed.error, 'missing key');- assert.equal(results.find((result) => result.layerId === 'earthquakes').succeeded, true);+ assert.equal(+ results.find((result) => result.layerId === 'earthquakes').succeeded,+ true,+ );coordinator.destroy();});@@ -768,7 +1116,10 @@ test('later explicit visibility during delayed restore wins for that layer only'const results = await restore;assert.equal(manager.isEnabled('radio'), false);assert.equal(manager.isEnabled('earthquakes'), true);- assert.equal(results.find((result) => result.layerId === 'radio').cancellationReason, 'superseded');+ assert.equal(+ results.find((result) => result.layerId === 'radio').cancellationReason,+ 'superseded',+ );assert.equal(storage.writes.length, 1);coordinator.destroy();});@@ -796,19 +1147,33 @@ test('share restore waits for a superseding same-target visibility successor', a});const state = createDefaultLayerState();state.enabledLayerIds = ['radio'];- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });let restoreSettled = false;- const restore = coordinator.start({ shareLayerState: state })- .then((result) => { restoreSettled = true; return result; });+ const restore = coordinator+ .start({ shareLayerState: state })+ .then((result) => {+ restoreSettled = true;+ return result;+ });await firstUpdateStarted.promise;let successorSettled = false;- const explicitOn = manager.setEnabled('radio', true, { origin: 'user' })- .then((result) => { successorSettled = true; return result; });+ const explicitOn = manager+ .setEnabled('radio', true, { origin: 'user' })+ .then((result) => {+ successorSettled = true;+ return result;+ });releaseFirstUpdate.resolve();await secondUpdateStarted.promise;await Promise.resolve();- assert.equal(restoreSettled, false, 'aggregate must wait for the authoritative successor');+ assert.equal(+ restoreSettled,+ false,+ 'aggregate must wait for the authoritative successor',+ );assert.equal(successorSettled, false);releaseSecondUpdate.resolve();@@ -820,7 +1185,10 @@ test('share restore waits for a superseding same-target visibility successor', aassert.equal(radio.authoritativeIntentEpoch, radio.successorIntentEpoch);assert.equal(radio.authoritativeEnabled, true);assert.equal(radio.succeeded, true);- assert.equal(manager.getLayerLifecycleState('radio').lifecycleState, 'enabled');+ assert.equal(+ manager.getLayerLifecycleState('radio').lifecycleState,+ 'enabled',+ );coordinator.destroy();});@@ -845,17 +1213,27 @@ test('share restore waits for a superseding opposite-target visibility successor});const state = createDefaultLayerState();state.enabledLayerIds = ['radio'];- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });let restoreSettled = false;- const restore = coordinator.start({ shareLayerState: state })- .then((result) => { restoreSettled = true; return result; });+ const restore = coordinator+ .start({ shareLayerState: state })+ .then((result) => {+ restoreSettled = true;+ return result;+ });await updateStarted.promise;const explicitOff = manager.setEnabled('radio', false, { origin: 'user' });releaseUpdate.resolve();await disableStarted.promise;await Promise.resolve();- assert.equal(restoreSettled, false, 'aggregate must wait for the OFF successor to settle');+ assert.equal(+ restoreSettled,+ false,+ 'aggregate must wait for the OFF successor to settle',+ );releaseDisable.resolve();assert.equal(await explicitOff, true);@@ -865,8 +1243,15 @@ test('share restore waits for a superseding opposite-target visibility successorassert.equal(radio.successorEnabled, false);assert.equal(radio.authoritativeIntentEpoch, radio.successorIntentEpoch);assert.equal(radio.authoritativeEnabled, false);- assert.equal(radio.succeeded, false, 'the newer OFF must not count as successful shared ON');- assert.equal(manager.getLayerLifecycleState('radio').lifecycleState, 'disabled');+ assert.equal(+ radio.succeeded,+ false,+ 'the newer OFF must not count as successful shared ON',+ );+ assert.equal(+ manager.getLayerLifecycleState('radio').lifecycleState,+ 'disabled',+ );coordinator.destroy();});@@ -894,10 +1279,17 @@ test('later explicit params during init replace options without cancelling visibconst coordinator = new LayerStateCoordinator(manager, share, { storage });const restore = coordinator.start({ shareLayerState: state });await initStarted.promise;- assert.equal(manager.setLayerParams('flights', {- models3d: false,- models3dMode: 'proximity',- }, { origin: 'user' }), true);+ assert.equal(+ manager.setLayerParams(+ 'flights',+ {+ models3d: false,+ models3dMode: 'proximity',+ },+ { origin: 'user' },+ ),+ true,+ );initGate.resolve();const results = await restore;assert.equal(manager.isEnabled('flights'), true);@@ -907,10 +1299,15 @@ test('later explicit params during init replace options without cancelling visibselectedFlightsTrackingId: null,selectedMilitaryTrackingId: null,});- assert.equal(results.find((result) => result.layerId === 'flights').succeeded, true);+ assert.equal(+ results.find((result) => result.layerId === 'flights').succeeded,+ true,+ );assert.equal(storage.writes.length, 1);assert.equal(- new URLSearchParams(encode(share.provider())).get('lo')?.includes('f.t.late001') || false,+ new URLSearchParams(encode(share.provider()))+ .get('lo')+ ?.includes('f.t.late001') || false,false,);coordinator.destroy();@@ -927,7 +1324,10 @@ test('explicit navigation preserves unrelated visibility and option restoration'await initGate.promise;return true;},- setParams: (params) => { paramsCalls.push(params); return true; },+ setParams: (params) => {+ paramsCalls.push(params);+ return true;+ },},});const state = createDefaultLayerState();@@ -938,7 +1338,9 @@ test('explicit navigation preserves unrelated visibility and option restoration'selectedFlightsTrackingId: 'stale-flight',selectedMilitaryTrackingId: null,};- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage: memoryStorage() });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage: memoryStorage(),+ });const restore = coordinator.start({ shareLayerState: state });await initStarted.promise;// Navigation owns only camera and pending entity selection. It must not@@ -946,11 +1348,16 @@ test('explicit navigation preserves unrelated visibility and option restoration'initGate.resolve();const results = await restore;assert.equal(manager.isEnabled('flights'), true);- assert.deepEqual(paramsCalls, [{- models3d: true,- models3dMode: 'all',- }]);- assert.equal(results.find((result) => result.layerId === 'flights').succeeded, true);+ assert.deepEqual(paramsCalls, [+ {+ models3d: true,+ models3dMode: 'all',+ },+ ]);+ assert.equal(+ results.find((result) => result.layerId === 'flights').succeeded,+ true,+ );coordinator.destroy();});@@ -985,7 +1392,9 @@ test('startup gesture clears passive Follow but preserves slow layer and display};state.options.radio = { filter: 'genre:r&b', volume: 0.42 };const storage = memoryStorage();- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage,+ });const restore = coordinator.start({ shareLayerState: state });await Promise.all([flightsStarted.promise, radioStarted.promise]);@@ -993,7 +1402,9 @@ test('startup gesture clears passive Follow but preserves slow layer and displaystampInitialShareGesture(({ cancelPendingSelection }) => {cameraGeneration += 1;if (cancelPendingSelection) {- coordinator.cancelPendingShareTracking('startup-gesture', { clearSelection: true });+ coordinator.cancelPendingShareTracking('startup-gesture', {+ clearSelection: true,+ });}});flightsInit.resolve();@@ -1016,8 +1427,14 @@ test('startup gesture clears passive Follow but preserves slow layer and displayaudioState: 'playing',voiceDucked: true,});- assert.equal(results.find((result) => result.layerId === 'flights').succeeded, true);- assert.equal(results.find((result) => result.layerId === 'radio').succeeded, true);+ assert.equal(+ results.find((result) => result.layerId === 'flights').succeeded,+ true,+ );+ assert.equal(+ results.find((result) => result.layerId === 'radio').succeeded,+ true,+ );assert.deepEqual(storage.writes, []);coordinator.destroy();});@@ -1026,7 +1443,10 @@ test('tracking restore refreshes the destination feed before the module resolvesconst order = [];const manager = productionManager({flights: {- update: () => { order.push('refresh'); return true; },+ update: () => {+ order.push('refresh');+ return true;+ },resolveTrackingRestoreTarget: (targetId, options) => {order.push(`resolve:${targetId}:${options.origin}`);return { status: 'found', source: 'test' };@@ -1049,8 +1469,14 @@ test('shared flight selection is deferred until destination refresh and then folconst paramsCalls = [];const manager = productionManager({flights: {- setParams: (params) => { paramsCalls.push({ ...params }); return true; },- resolveTrackingRestoreTarget: (targetId) => ({ status: 'found', targetId }),+ setParams: (params) => {+ paramsCalls.push({ ...params });+ return true;+ },+ resolveTrackingRestoreTarget: (targetId) => ({+ status: 'found',+ targetId,+ }),},});const state = createDefaultLayerState();@@ -1065,14 +1491,19 @@ test('shared flight selection is deferred until destination refresh and then folonTrackingRestoreStatus: (status) => statuses.push(status),});await coordinator.start({ shareLayerState: state, shareCreatedAtMs: 1_000 });- assert.deepEqual(paramsCalls, [{ models3d: true, models3dMode: 'proximity' }]);+ assert.deepEqual(paramsCalls, [+ { models3d: true, models3dMode: 'proximity' },+ ]);const result = await coordinator.restoreShareTrackingSelection();assert.equal(result.status, 'found');assert.equal(result.classification, 'followed');assert.equal(result.cleared, false);assert.equal(statuses.length, 1);- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, 'abc123');+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ 'abc123',+ );assert.deepEqual(storage.writes, []);coordinator.destroy();});@@ -1083,11 +1514,11 @@ test('authoritative missing target clears only the passive ID and uses strict exconst manager = productionManager({flights: {resolveTrackingRestoreTarget: () => ({ status: 'missing' }),- setParams: (next) => (- Object.hasOwn(next, 'selectedFlightsTrackingId') && next.selectedFlightsTrackingId+ setParams: (next) =>+ Object.hasOwn(next, 'selectedFlightsTrackingId') &&+ next.selectedFlightsTrackingId? 'defer'- : true- ),+ : true,},});const state = createDefaultLayerState();@@ -1109,10 +1540,21 @@ test('authoritative missing target clears only the passive ID and uses strict exclearTimer: timers.clearTimer,onTrackingRestoreStatus: (status) => statuses.push(status),});- await coordinator.start({ shareLayerState: state, shareCreatedAtMs: copiedAtMs });+ await coordinator.start({+ shareLayerState: state,+ shareCreatedAtMs: copiedAtMs,+ });const pending = await coordinator.restoreShareTrackingSelection();- assert.equal(pending.classification, 'pending', 'absence must first be held pending');- assert.equal(statuses.length, 1, 'pending is published for soft progress feedback');+ assert.equal(+ pending.classification,+ 'pending',+ 'absence must first be held pending',+ );+ assert.equal(+ statuses.length,+ 1,+ 'pending is published for soft progress feedback',+ );assert.equal(statuses[0].classification, 'pending');timers.runUntilIdle();const result = statuses.at(-1);@@ -1124,7 +1566,10 @@ test('authoritative missing target clears only the passive ID and uses strict exconst boundary = await run({ nowMs: 190_000, copiedAtMs: 100_000 });assert.equal(boundary.result.classification, 'unavailable');assert.equal(boundary.result.cleared, true);- assert.equal(boundary.durable.options.flights.selectedFlightsTrackingId, null);+ assert.equal(+ boundary.durable.options.flights.selectedFlightsTrackingId,+ null,+ );assert.equal(boundary.durable.options.flights.models3d, true);assert.equal(boundary.durable.options.flights.models3dMode, 'all');assert.deepEqual(boundary.writes, []);@@ -1138,12 +1583,15 @@ test('feed failure is not misreported as target absence and malformed time neverconst statuses = [];const manager = productionManager({satellites: {- resolveTrackingRestoreTarget: () => ({ status: 'source-unavailable', reason: 'partial catalog' }),- setParams: (next) => (- Object.hasOwn(next, 'selectedSatTrackingId') && next.selectedSatTrackingId+ resolveTrackingRestoreTarget: () => ({+ status: 'source-unavailable',+ reason: 'partial catalog',+ }),+ setParams: (next) =>+ Object.hasOwn(next, 'selectedSatTrackingId') &&+ next.selectedSatTrackingId? 'defer'- : true- ),+ : true,},});const state = createDefaultLayerState();@@ -1187,7 +1635,10 @@ test('feed failure is not misreported as target absence and malformed time never// the share. These pin both directions.// ----------------------------------------------------------------------------function pendingTrackingFixture({ resolveStatus = 'missing', copiedAtMs = null } = {}) {+function pendingTrackingFixture({+ resolveStatus = 'missing',+ copiedAtMs = null,+} = {}) {const storage = memoryStorage();const statuses = [];const paramsCalls = [];@@ -1199,7 +1650,8 @@ function pendingTrackingFixture({ resolveStatus = 'missing', copiedAtMs = null }paramsCalls.push({ params: { ...next }, origin: options?.origin });// Production holds the id pending; getParams keeps reporting untracked// until the subject actually arrives on a later poll.- return Object.hasOwn(next, 'selectedFlightsTrackingId') && next.selectedFlightsTrackingId+ return Object.hasOwn(next, 'selectedFlightsTrackingId') &&+ next.selectedFlightsTrackingId? 'defer': true;},@@ -1258,14 +1710,21 @@ test('share tracking policies pin each owner, key, label, and acquisition deadlitest('a shared subject that has not arrived yet is held pending, never declared gone', async () => {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });const pending = await f.coordinator.restoreShareTrackingSelection();assert.equal(pending.status, 'pending');assert.equal(pending.classification, 'pending');assert.equal(pending.cleared, false);// No notice, and the subject survives in durable state AND in the URL.- assert.equal(f.statuses.length, 1, 'a not-yet-arrived subject publishes progress');+ assert.equal(+ f.statuses.length,+ 1,+ 'a not-yet-arrived subject publishes progress',+ );assert.equal(f.statuses[0].classification, 'pending');assert.equal(f.coordinator.getDurableState().options.flights.selectedFlightsTrackingId,@@ -1273,22 +1732,33 @@ test('a shared subject that has not arrived yet is held pending, never declared'the shared subject must not be cleared while it is still pending',);// The layer's own deferred-restore latch was armed, under the passive origin.- const armed = f.paramsCalls.filter((call) => call.params.selectedFlightsTrackingId === 'late007');+ const armed = f.paramsCalls.filter(+ (call) => call.params.selectedFlightsTrackingId === 'late007',+ );assert.equal(armed.length, 1, 'the layer latch is armed exactly once');assert.equal(armed[0].origin, 'share-restore', 'arming must stay passive');- assert.deepEqual(f.storage.writes, [], 'recipient preferences are never written');+ assert.deepEqual(+ f.storage.writes,+ [],+ 'recipient preferences are never written',+ );f.coordinator.destroy();});test('a pending shared subject latches on when it arrives on a later poll', async () => {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });await f.coordinator.restoreShareTrackingSelection();assert.equal(f.statuses.length, 1);assert.equal(f.statuses[0].classification, 'pending');// The contact shows up on a later feed poll, exactly as the layer latch would.- f.manager.layers.get('flights').module._arrive({ selectedFlightsTrackingId: 'late007' });+ f.manager.layers+ .get('flights')+ .module._arrive({ selectedFlightsTrackingId: 'late007' });f.timers.runUntilIdle();assert.equal(f.statuses.length, 2);@@ -1305,17 +1775,29 @@ test('a pending shared subject latches on when it arrives on a later poll', asyntest('caller abort after pending handoff revokes the watch and layer latch exactly once', async () => {const f = pendingTrackingFixture();const caller = new AbortController();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });- const pending = await f.coordinator.restoreShareTrackingSelection({ signal: caller.signal });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });+ const pending = await f.coordinator.restoreShareTrackingSelection({+ signal: caller.signal,+ });assert.equal(pending.classification, 'pending');caller.abort('caller-cancelled');f.timers.runUntilIdle();caller.abort('late-repeat');- assert.deepEqual(f.statuses.map((status) => status.classification), ['pending', 'cancelled']);+ assert.deepEqual(+ f.statuses.map((status) => status.classification),+ ['pending', 'cancelled'],+ );assert.equal(f.statuses[1].reason, 'caller-cancelled');- assert.equal(f.cancellations.length, 1, 'the module latch is revoked exactly once');+ assert.equal(+ f.cancellations.length,+ 1,+ 'the module latch is revoked exactly once',+ );assert.equal(f.cancellations[0].reason, 'caller-cancelled');assert.equal(f.coordinator.getDurableState().options.flights.selectedFlightsTrackingId,@@ -1329,16 +1811,20 @@ test('a failed deferred-latch arm publishes one terminal failure and never ACQUIfor (const armFailure of [() => false,() => Promise.reject(new Error('async latch rejection')),- () => { throw new Error('sync latch throw'); },+ () => {+ throw new Error('sync latch throw');+ },]) {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });const setLayerParams = f.manager.setLayerParams.bind(f.manager);- f.manager.setLayerParams = (layerId, params, options) => (+ f.manager.setLayerParams = (layerId, params, options) =>params?.selectedFlightsTrackingId? armFailure()- : setLayerParams(layerId, params, options)- );+ : setLayerParams(layerId, params, options);const result = await f.coordinator.restoreShareTrackingSelection();f.timers.runUntilIdle();@@ -1351,14 +1837,20 @@ test('a failed deferred-latch arm publishes one terminal failure and never ACQUI['source-unavailable'],'a rejected latch never publishes pending progress',);- assert.equal(f.coordinator.getDurableState().options.flights.selectedFlightsTrackingId, null);+ assert.equal(+ f.coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ null,+ );f.coordinator.destroy();}});test('same-target supersession cancels the old acquisition before publishing the successor', async () => {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });await f.coordinator.restoreShareTrackingSelection();await f.coordinator.restoreShareTrackingSelection();@@ -1374,11 +1866,15 @@ test('same-target supersession cancels the old acquisition before publishing thetest('destroying or superseding the coordinator clears pending progress explicitly', async () => {for (const teardown of [(coordinator) => coordinator.destroy(),- (coordinator) => coordinator.cancelPendingShareTracking('explicit-navigation'),+ (coordinator) =>+ coordinator.cancelPendingShareTracking('explicit-navigation'),(coordinator) => coordinator.cancelPendingRestores('explicit-navigation'),]) {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });await f.coordinator.restoreShareTrackingSelection();teardown(f.coordinator);f.timers.runUntilIdle();@@ -1406,7 +1902,9 @@ test('tracking resolver false and rejection stay source-unavailable while AbortEconst semanticFalse = await run(() => false);assert.equal(semanticFalse.status, 'source-unavailable');- const rejected = await run(() => Promise.reject(new Error('feed unavailable')));+ const rejected = await run(() =>+ Promise.reject(new Error('feed unavailable')),+ );assert.equal(rejected.status, 'source-unavailable');assert.equal(rejected.reason, 'feed unavailable');@@ -1461,16 +1959,25 @@ test('newer explicit tracked target cancels stale shared resolution without clea...state.options.flights,selectedFlightsTrackingId: 'stale001',};- const coordinator = new LayerStateCoordinator(manager, shareSink(), { storage });+ const coordinator = new LayerStateCoordinator(manager, shareSink(), {+ storage,+ });await coordinator.start({ shareLayerState: state });const restore = coordinator.restoreShareTrackingSelection();- manager.setLayerParams('flights', {- selectedFlightsTrackingId: 'newer002',- }, { origin: 'user' });+ manager.setLayerParams(+ 'flights',+ {+ selectedFlightsTrackingId: 'newer002',+ },+ { origin: 'user' },+ );resolution.resolve({ status: 'missing' });const result = await restore;assert.equal(result.status, 'cancelled');- assert.equal(coordinator.getDurableState().options.flights.selectedFlightsTrackingId, 'newer002');+ assert.equal(+ coordinator.getDurableState().options.flights.selectedFlightsTrackingId,+ 'newer002',+ );assert.equal(storage.writes.length, 1);coordinator.destroy();});@@ -1507,21 +2014,40 @@ test('oversized and out-of-grammar tracking IDs are rejected, never truncated',);// Decoding (the untrusted-URL door).- const decoded = decodeLayerStateParams(new URLSearchParams([- ['v', '2'], ['l', 'f'], ['lo', `f.t.${huge}`],- ]));+ const decoded = decodeLayerStateParams(+ new URLSearchParams([+ ['v', '2'],+ ['l', 'f'],+ ['lo', `f.t.${huge}`],+ ]),+ );assert.equal(decoded, null, 'an oversized lo payload fails closed');// A merely long-but-under-cap ID is still out of grammar, and rejected// WITHOUT taking the rest of the payload down with it.- const longish = decodeLayerStateParams(new URLSearchParams([- ['v', '2'], ['l', 'f'], ['lo', `f.e.1_f.t.${'b'.repeat(40)}`],- ]));+ const longish = decodeLayerStateParams(+ new URLSearchParams([+ ['v', '2'],+ ['l', 'f'],+ ['lo', `f.e.1_f.t.${'b'.repeat(40)}`],+ ]),+ );assert.deepEqual(longish.enabledLayerIds, ['flights']);assert.equal(longish.options.flights.selectedFlightsTrackingId, null);- assert.equal(longish.options.flights.models3d, true, 'sibling options survive');+ assert.equal(+ longish.options.flights.models3d,+ true,+ 'sibling options survive',+ );- for (const bad of ['ab cd', 'ab/cd', '../../etc', 'a'.repeat(17), '<script>', '']) {+ for (const bad of [+ 'ab cd',+ 'ab/cd',+ '../../etc',+ 'a'.repeat(17),+ '<script>',+ '',+ ]) {assert.equal(normalizeLayerState({enabledLayerIds: ['flights'],@@ -1538,7 +2064,10 @@ test('oversized and out-of-grammar tracking IDs are rejected, never truncated',enabledLayerIds: ['flights'],options: { flights: { selectedFlightsTrackingId: good } },});- assert.equal(state.options.flights.selectedFlightsTrackingId, good.toLowerCase());+ assert.equal(+ state.options.flights.selectedFlightsTrackingId,+ good.toLowerCase(),+ );const params = new URLSearchParams([['v', '2']]);encodeLayerStateParams(params, state);assert.equal(@@ -1551,7 +2080,12 @@ test('oversized and out-of-grammar tracking IDs are rejected, never truncated',test('an oversized enabled-layer field fails closed instead of decoding a prefix', () => {assert.equal(- decodeLayerStateParams(new URLSearchParams([['v', '2'], ['l', 'f.'.repeat(5_000)]])),+ decodeLayerStateParams(+ new URLSearchParams([+ ['v', '2'],+ ['l', 'f.'.repeat(5_000)],+ ]),+ ),null,);});@@ -1570,13 +2104,23 @@ test('an oversized enabled-layer field fails closed instead of decoding a prefixtest('an explicit parameter change revokes the pending watch, not just its controller', async () => {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });await f.coordinator.restoreShareTrackingSelection();- assert.deepEqual(f.statuses.map((status) => status.classification), ['pending']);+ assert.deepEqual(+ f.statuses.map((status) => status.classification),+ ['pending'],+ );// The operator changes an unrelated Flights option. Production cancels the// module latch on exactly this event, so nothing is restoring any more.- await f.manager.setLayerParams('flights', { models3d: true }, { origin: 'user' });+ await f.manager.setLayerParams(+ 'flights',+ { models3d: true },+ { origin: 'user' },+ );f.timers.runUntilIdle();assert.deepEqual(@@ -1590,9 +2134,15 @@ test('an explicit parameter change revokes the pending watch, not just its contrtest('the owner layer going away revokes the pending watch at any origin', async () => {for (const origin of ['programmatic', 'user']) {const f = pendingTrackingFixture();- await f.coordinator.start({ shareLayerState: f.state, shareCreatedAtMs: f.copiedAtMs });+ await f.coordinator.start({+ shareLayerState: f.state,+ shareCreatedAtMs: f.copiedAtMs,+ });await f.coordinator.restoreShareTrackingSelection();- assert.deepEqual(f.statuses.map((status) => status.classification), ['pending']);+ assert.deepEqual(+ f.statuses.map((status) => status.classification),+ ['pending'],+ );await f.manager.setEnabled('flights', false, { origin });f.timers.runUntilIdle();@@ -1625,8 +2175,18 @@ test('wind appearance shares round trip while old links retain weather defaults'paused: false,});const legacy = decodeLayerStateParams(new URLSearchParams('v=2&l=k'));- assert.equal(legacy.options.wind.overlay, 'speed', 'old links retain their authored field');- assert.equal(decodeLayerStateParams(new URLSearchParams(encode(createDefaultLayerState()))).options.wind.overlay, 'none', 'new default is encoded explicitly');+ assert.equal(+ legacy.options.wind.overlay,+ 'speed',+ 'old links retain their authored field',+ );+ assert.equal(+ decodeLayerStateParams(+ new URLSearchParams(encode(createDefaultLayerState())),+ ).options.wind.overlay,+ 'none',+ 'new default is encoded explicitly',+ );const old = normalizeLayerState({ options: { wind: { model: 'ifs' } } });assert.deepEqual(old.options.wind, { ...defaults, model: 'ifs' });const invalid = normalizeLayerState({@@ -1643,7 +2203,13 @@ test('wind appearance shares round trip while old links retain weather defaults'});test('observed weather round trips product and opacity without persisting historical playback', () => {- const state = normalizeLayerState({ enabledLayerIds: ['weather-radar', 'weather-satellite'], options: { 'weather-radar': { opacity: 'light', play: true }, 'weather-satellite': { product: 'clouds', opacity: 'light', step: -1 } } });+ const state = normalizeLayerState({+ enabledLayerIds: ['weather-radar', 'weather-satellite'],+ options: {+ 'weather-radar': { opacity: 'light', play: true },+ 'weather-satellite': { product: 'clouds', opacity: 'light', step: -1 },+ },+ });const params = new URLSearchParams(encode(state));const decoded = decodeLayerStateParams(params);assert.deepEqual(decoded, state);@@ -1653,12 +2219,202 @@ test('observed weather round trips product and opacity without persisting histortest('satellite infrared display mode round trips and invalid or absent values use filtered', () => {for (const infrared of ['full', 'filtered', undefined, 'invalid']) {- const state = normalizeLayerState({ enabledLayerIds: ['weather-satellite'], options: {- 'weather-satellite': { infrared, product: 'clouds', step: -1, play: true },- } });- assert.deepEqual(decodeLayerStateParams(new URLSearchParams(encode(state))), state);- assert.equal(state.options['weather-satellite'].infrared, infrared === 'full' ? 'full' : 'filtered');- assert.equal(Object.hasOwn(state.options['weather-satellite'], 'step'), false);- assert.equal(Object.hasOwn(state.options['weather-satellite'], 'play'), false);+ const state = normalizeLayerState({+ enabledLayerIds: ['weather-satellite'],+ options: {+ 'weather-satellite': {+ infrared,+ product: 'clouds',+ step: -1,+ play: true,+ },+ },+ });+ assert.deepEqual(+ decodeLayerStateParams(new URLSearchParams(encode(state))),+ state,+ );+ assert.equal(+ state.options['weather-satellite'].infrared,+ infrared === 'full' ? 'full' : 'filtered',+ );+ assert.equal(+ Object.hasOwn(state.options['weather-satellite'], 'step'),+ false,+ );+ assert.equal(+ Object.hasOwn(state.options['weather-satellite'], 'play'),+ false,+ );+ }+});++// Recent Imagery (`1`): the box travels as four integers at degrees × 100000,+// the two days as product letter + compact date, the split as a percent.+const imageryOptions = (lo) =>+ decodeLayerStateParams(+ new URLSearchParams([+ ['v', '2'],+ ['l', '1'],+ ['lo', lo],+ ]),+ ).options['recent-imagery'];++test('recent-imagery box, days, mode, split and overview toggle round-trip under token 1; defaults stay out of the URL', () => {+ const entry = LAYER_STATE_REGISTRY.find((row) => row.id === 'recent-imagery');+ assert.deepEqual(+ [entry.token, entry.disposition, entry.optionOwner],+ ['1', 'enabled+options', 'recent-imagery'],+ );+ assert.deepEqual(createDefaultLayerState().options['recent-imagery'], {+ west: null,+ south: null,+ east: null,+ north: null,+ a: null,+ b: null,+ mode: 0,+ split: 50,+ viirs: false,+ });+ const state = createDefaultLayerState();+ state.enabledLayerIds = ['recent-imagery', 'flights'];+ state.options['recent-imagery'] = {+ west: -9781235,+ south: -3020000,+ east: -9770000,+ north: 3040000,+ a: 'S30:2026-09-18',+ b: 'L30:2026-09-10',+ mode: 2,+ split: 37,+ viirs: true,+ };+ const encoded = encode(state);+ assert.ok(+ encoded.includes(+ '1.w.-9781235_1.s.-3020000_1.e.-9770000_1.n.3040000_1.a.S20260918_1.b.L20260910_1.m.2_1.p.37_1.v.1',+ ),+ encoded,+ );+ const decoded = decodeLayerStateParams(new URLSearchParams(encoded));+ assert.deepEqual(+ decoded.options['recent-imagery'],+ state.options['recent-imagery'],+ );+ assert.deepEqual(decoded.options.flights, state.options.flights);+ const bare = createDefaultLayerState();+ bare.enabledLayerIds = ['recent-imagery'];+ assert.doesNotMatch(+ new URLSearchParams(encode(bare)).get('lo') || '',+ /(^|_)1\./,+ );+ // The codec is calendar-only: a link decodes the same whenever it is opened.+ assert.equal(imageryOptions('1.a.L19991231').a, 'L30:1999-12-31');+ assert.equal(imageryOptions('1.b.V20991231').b, 'VIIRS:2099-12-31');+});++test('recent-imagery rejects impossible days and out-of-range edges instead of rolling or clamping them', () => {+ for (const bad of [+ 'S20260230',+ 'L20261301',+ 'S20260900',+ 'X20260918',+ 's20260918',+ 'S2026091',+ 'S30:2026-09-18',+ ])+ assert.equal(imageryOptions(`1.a.${bad}`).a, null, bad);+ assert.equal(+ imageryOptions('1.b.S20240229').b,+ 'S30:2024-02-29',+ 'a real leap day',+ );+ assert.equal(imageryOptions('1.b.S20230229').b, null);+ const mixed = imageryOptions('1.a.S20260230_1.b.V20260921_1.p.80');+ assert.deepEqual(+ [mixed.a, mixed.b, mixed.split],+ [null, 'VIIRS:2026-09-21', 80],+ );+ for (const bad of [+ '1.w.18000001',+ '1.n.8505111',+ '1.s.-8505111',+ '1.w.1.5',+ '1.w.abc',+ '1.w.1234567890',+ ]) {+ const field = { w: 'west', s: 'south', n: 'north' }[bad.split('.')[1]];+ assert.equal(imageryOptions(bad)[field], null, bad);}+ assert.equal(imageryOptions('1.w.18000000').west, 18000000);+ assert.equal(imageryOptions('1.p.101').split, 50);+ assert.equal(imageryOptions('1.m.1').mode, 1);+ for (const bad of ['1.m.3', '1.m.-1', '1.m.x'])+ assert.equal(imageryOptions(bad).mode, 0, bad);+ assert.deepEqual(+ normalizeLayerState({+ enabledLayerIds: ['recent-imagery'],+ options: {+ 'recent-imagery': {+ a: 'S30:2026-02-30',+ b: ' L30:2026-09-10 ',+ split: 150,+ west: 'abc',+ north: -8505110,+ },+ },+ }).options['recent-imagery'],+ {+ west: null,+ south: null,+ east: null,+ north: -8505110,+ a: null,+ b: 'L30:2026-09-10',+ mode: 0,+ split: 50,+ viirs: false,+ },+ );+ // An oversized payload fails closed at the shared 512-character cap.+ const long = '1.a.S20260918_'.repeat(40);+ assert.ok(imageryOptions(long.slice(0, 512)));+ assert.equal(+ decodeLayerStateParams(+ new URLSearchParams([+ ['v', '2'],+ ['l', '1'],+ ['lo', long.slice(0, 513)],+ ]),+ ),+ null,+ );+});++test('the recent-imagery split is share-link only: never stored locally, and a stored value reads as the default', () => {+ const state = createDefaultLayerState();+ state.enabledLayerIds = ['recent-imagery'];+ state.options['recent-imagery'] = {+ a: 'S30:2026-09-18',+ split: 8,+ viirs: true,+ };+ assert.ok(encode(state).includes('1.p.8'));+ const stored = JSON.parse(serializeStoredLayerState(state)).o[+ 'recent-imagery'+ ];+ assert.deepEqual(+ [stored.split, stored.a, stored.viirs],+ [50, 'S30:2026-09-18', true],+ );+ const previous = JSON.stringify({+ v: 2,+ l: ['recent-imagery'],+ o: { 'recent-imagery': { split: 8 } },+ });+ assert.equal(+ parseStoredLayerState(previous).options['recent-imagery'].split,+ 50,+ );});diff --git a/src/layers/recentImagery/catalog.js b/src/layers/recentImagery/catalog.jsnew file mode 100644index 000000000..96b314690--- /dev/null+++ b/src/layers/recentImagery/catalog.js@@ -0,0 +1,219 @@+/**+ * NASA CMR granule catalog for the HLS products, folded with the VIIRS+ * overview days into one candidate list.+ */+import {+ CATALOG_DAYS,+ PRODUCTS,+ coverageFor,+ groupGranulesByDay,+ mergeCandidates,+ utcDay,+ validateBox,+ viirsCandidates,+} from './model.js';++const CMR_ENDPOINT = 'https://cmr.earthdata.nasa.gov/search';+const DAY_MS = 86_400_000;+const CMR_PAGE_SIZE = 200;+/**+ * Most records read per collection. A 1,000 km box can touch hundreds of HLS+ * tiles a day; past this cap the newest days (the sort order) are kept and+ * the result is `truncated`.+ */+const CMR_MAX_RECORDS = 2000;+const CMR_SEARCH_AFTER = 'CMR-Search-After';++/**+ * Read one product's granules across CMR pages, sending back each response's+ * `CMR-Search-After` cursor until a short page, a missing cursor or the+ * record cap ends the walk. `truncated` is measured against CMR's `hits`.+ * @param {{ product: string, url: string, fetchImpl: typeof fetch, signal?: AbortSignal, maxRecords?: number }} request+ * @returns {Promise<{ granules: Array<object>, truncated: boolean }>}+ */+export async function fetchCmrPages({+ product,+ url,+ fetchImpl,+ signal,+ maxRecords = CMR_MAX_RECORDS,+}) {+ const granules = [];+ let hits = 0;+ let cursor = null;+ for (;;) {+ const init = { signal };+ if (cursor) init.headers = { [CMR_SEARCH_AFTER]: cursor };+ const response = await fetchImpl(url, init);+ if (!response?.ok)+ throw new Error(`HTTP ${response?.status ?? 'error'} from CMR`);+ const page = parseCmrUmm(await response.json(), product);+ granules.push(...page.granules);+ hits = Math.max(hits, page.hits);+ cursor = response.headers?.get?.(CMR_SEARCH_AFTER) ?? null;+ if (+ !cursor ||+ page.granules.length < CMR_PAGE_SIZE ||+ granules.length >= maxRecords ||+ granules.length >= hits+ )+ break;+ }+ return { granules, truncated: hits > granules.length };+}++function finiteOrNull(value) {+ if (value === null || value === undefined || value === '') return null;+ const numeric = Number(value);+ return Number.isFinite(numeric) ? numeric : null;+}++function isoOrNull(value) {+ return typeof value === 'string' && Number.isFinite(Date.parse(value))+ ? value+ : null;+}++function ringOf(points) {+ const ring = points+ .map(([lon, lat]) => [finiteOrNull(lon), finiteOrNull(lat)])+ .filter(([lon, lat]) => lon !== null && lat !== null);+ return ring.length >= 3 ? ring : null;+}++function footprintOf(geometry) {+ const polygon = geometry?.GPolygons?.[0]?.Boundary?.Points;+ if (Array.isArray(polygon)) {+ const ring = ringOf(polygon.map((p) => [p?.Longitude, p?.Latitude]));+ if (ring) return ring;+ }+ const r = geometry?.BoundingRectangles?.[0];+ if (!r) return null;+ const [w, s, e, n] = [+ r.WestBoundingCoordinate,+ r.SouthBoundingCoordinate,+ r.EastBoundingCoordinate,+ r.NorthBoundingCoordinate,+ ];+ const ring = ringOf([+ [w, s],+ [e, s],+ [e, n],+ [w, n],+ ]);+ return ring?.length === 4 ? ring : null;+}++/**+ * Parse a CMR `granules.umm_json` response. Every field is optional upstream;+ * granules without a parseable start time are dropped.+ * @param {object} json+ * @param {string} product `S30` | `L30`+ * @returns {{ granules: Array<object>, hits: number }}+ */+export function parseCmrUmm(json, product) {+ const granules = [];+ for (const item of Array.isArray(json?.items) ? json.items : []) {+ const umm = item?.umm || {};+ const meta = item?.meta || {};+ const range = umm.TemporalExtent?.RangeDateTime || {};+ const timeStart = isoOrNull(range.BeginningDateTime);+ if (!timeStart) continue;+ const cloud = Array.isArray(umm.AdditionalAttributes)+ ? umm.AdditionalAttributes.find((a) => a?.Name === 'CLOUD_COVERAGE')+ ?.Values?.[0]+ : null;+ granules.push({+ id: String(+ meta['concept-id'] || umm.GranuleUR || meta['native-id'] || '',+ ),+ product,+ timeStart,+ timeEnd: isoOrNull(range.EndingDateTime) || timeStart,+ cloud: finiteOrNull(cloud),+ footprint: footprintOf(+ umm.SpatialExtent?.HorizontalSpatialDomain?.Geometry,+ ),+ });+ }+ return { granules, hits: finiteOrNull(json?.hits) ?? granules.length };+}++/**+ * CMR granule search URL for one HLS product over a box and time window.+ * @param {{ product: string, box: object, startIso: string, endIso: string }} query+ * @returns {string}+ */+export function cmrSearchUrl({ product, box, startIso, endIso }) {+ const spec = PRODUCTS[product];+ if (!spec?.cmrCollection)+ throw new TypeError(`No CMR collection for product: ${product}`);+ const result = validateBox(box);+ if (!result.ok) throw new TypeError(result.message);+ const { west, south, east, north } = result.box;+ return (+ `${CMR_ENDPOINT}/granules.umm_json` ++ `?collection_concept_id=${spec.cmrCollection}` ++ `&bounding_box=${west},${south},${east},${north}` ++ `&temporal=${startIso},${endIso}` ++ `&sort_key=-start_date&page_size=${CMR_PAGE_SIZE}`+ );+}++/**+ * Search both HLS collections concurrently and fold the results with the+ * VIIRS overview days. One product failing still yields the other's days plus+ * an `errors` entry; an invalid box or clock throws a TypeError.+ * @param {{ box: object, days?: number, now?: Date, fetchImpl?: typeof fetch, signal?: AbortSignal }} request+ * @returns {Promise<{ candidates: Array<object>, truncated: boolean, errors: Array<{ product: string, message: string }> }>}+ */+export async function searchHls({+ box,+ days = CATALOG_DAYS,+ now = new Date(),+ fetchImpl = globalThis.fetch,+ signal,+} = {}) {+ const validated = validateBox(box);+ if (!validated.ok) throw new TypeError(validated.message);+ if (typeof fetchImpl !== 'function')+ throw new TypeError('A fetch implementation is required');+ const nowMs = now instanceof Date ? now.getTime() : Date.parse(now);+ if (!Number.isFinite(nowMs)) throw new TypeError('A valid clock is required');+ const endIso = new Date(nowMs).toISOString();+ const startIso = `${utcDay(new Date(nowMs - (days - 1) * DAY_MS))}T00:00:00Z`;+ const products = ['S30', 'L30'];+ const settled = await Promise.allSettled(+ products.map((product) =>+ fetchCmrPages({+ product,+ url: cmrSearchUrl({ product, box: validated.box, startIso, endIso }),+ fetchImpl,+ signal,+ }),+ ),+ );+ const granules = [];+ const errors = [];+ let truncated = false;+ settled.forEach((result, index) => {+ if (result.status === 'fulfilled') {+ granules.push(...result.value.granules);+ truncated ||= result.value.truncated;+ } else {+ errors.push({+ product: products[index],+ message: String(result.reason?.message || result.reason),+ });+ }+ });+ const hls = groupGranulesByDay(granules).map((candidate) => ({+ ...candidate,+ coverage: coverageFor(candidate, validated.box),+ }));+ return {+ candidates: mergeCandidates([hls, viirsCandidates(endIso, days)]),+ truncated,+ errors,+ };+}diff --git a/src/layers/recentImagery/catalog.test.mjs b/src/layers/recentImagery/catalog.test.mjsnew file mode 100644index 000000000..462e26216--- /dev/null+++ b/src/layers/recentImagery/catalog.test.mjs@@ -0,0 +1,296 @@+import test from 'node:test';+import assert from 'node:assert/strict';++import {+ cmrSearchUrl,+ fetchCmrPages,+ parseCmrUmm,+ searchHls,+} from './catalog.js';+import { BOX, response } from './testDoubles.mjs';++function ummItem({+ conceptId = 'G1-LPCLOUD',+ begin = '2026-09-18T17:12:01.000Z',+ end = '2026-09-18T17:12:31.000Z',+ cloud = '12',+ polygon = [+ [-98, 30],+ [-97, 30],+ [-97, 31],+ [-98, 31],+ ],+ rectangle = null,+} = {}) {+ const Geometry = {};+ if (polygon)+ Geometry.GPolygons = [+ {+ Boundary: {+ Points: polygon.map(([Longitude, Latitude]) => ({+ Longitude,+ Latitude,+ })),+ },+ },+ ];+ if (rectangle)+ Geometry.BoundingRectangles = [+ {+ WestBoundingCoordinate: rectangle[0],+ SouthBoundingCoordinate: rectangle[1],+ EastBoundingCoordinate: rectangle[2],+ NorthBoundingCoordinate: rectangle[3],+ },+ ];+ return {+ meta: { 'concept-id': conceptId },+ umm: {+ TemporalExtent: {+ RangeDateTime: { BeginningDateTime: begin, EndingDateTime: end },+ },+ AdditionalAttributes: [+ { Name: 'SPATIAL_COVERAGE', Values: ['100'] },+ ...(cloud === undefined+ ? []+ : [{ Name: 'CLOUD_COVERAGE', Values: [cloud] }]),+ ],+ SpatialExtent: { HorizontalSpatialDomain: { Geometry } },+ },+ };+}++test('umm_json granules carry id, times, scene cloud and a footprint ring', () => {+ const { granules, hits } = parseCmrUmm(+ {+ hits: 9,+ items: [+ ummItem(),+ ummItem({+ conceptId: 'G2',+ cloud: '3.5',+ polygon: null,+ rectangle: [-98.5, 29.5, -97.5, 30.5],+ }),+ {+ meta: {},+ umm: {+ GranuleUR: 'HLS.L30.only-ur',+ TemporalExtent: {+ RangeDateTime: { BeginningDateTime: '2026-09-01T16:00:00Z' },+ },+ },+ },+ ummItem({ conceptId: 'G-bad-cloud', cloud: 'n/a' }),+ ummItem({+ conceptId: 'G-two-points',+ polygon: [+ [0, 0],+ [1, 1],+ ],+ }),+ { meta: { 'concept-id': 'G-no-time' }, umm: {} },+ {+ meta: { 'concept-id': 'G-bad-time' },+ umm: {+ TemporalExtent: { RangeDateTime: { BeginningDateTime: 'soon' } },+ },+ },+ null,+ ],+ },+ 'S30',+ );+ assert.equal(hits, 9);+ assert.deepEqual(granules[0], {+ id: 'G1-LPCLOUD',+ product: 'S30',+ timeStart: '2026-09-18T17:12:01.000Z',+ timeEnd: '2026-09-18T17:12:31.000Z',+ cloud: 12,+ footprint: [+ [-98, 30],+ [-97, 30],+ [-97, 31],+ [-98, 31],+ ],+ });+ assert.equal(granules[1].cloud, 3.5);+ assert.deepEqual(granules[1].footprint, [+ [-98.5, 29.5],+ [-97.5, 29.5],+ [-97.5, 30.5],+ [-98.5, 30.5],+ ]);+ assert.deepEqual(+ granules.slice(2).map((g) => [g.id, g.cloud, g.footprint]),+ [+ ['HLS.L30.only-ur', null, null],+ ['G-bad-cloud', null, granules[0].footprint],+ ['G-two-points', 12, null],+ ],+ 'missing fields stay unknown; granules without a start time are dropped',+ );+ assert.equal(granules[2].timeEnd, '2026-09-01T16:00:00Z');+ assert.deepEqual(parseCmrUmm(null, 'S30'), { granules: [], hits: 0 });+});++test('the CMR query names the collection, box, window and page size with literal commas', () => {+ assert.equal(+ cmrSearchUrl({+ product: 'S30',+ box: BOX,+ startIso: '2026-08-23T00:00:00Z',+ endIso: '2026-09-21T12:00:00.000Z',+ }),+ 'https://cmr.earthdata.nasa.gov/search/granules.umm_json?collection_concept_id=C2021957295-LPCLOUD&bounding_box=-97.8,30.2,-97.7,30.3&temporal=2026-08-23T00:00:00Z,2026-09-21T12:00:00.000Z&sort_key=-start_date&page_size=200',+ );+ assert.match(+ cmrSearchUrl({ product: 'L30', box: BOX, startIso: 'a', endIso: 'b' }),+ /collection_concept_id=C2021957657-LPCLOUD/,+ );+ assert.throws(+ () => cmrSearchUrl({ product: 'VIIRS', box: BOX }),+ /No CMR collection/,+ );+});++/** Route a CMR request to the S30 or L30 handler by collection id. */+function cmrFetch(handlers, calls = []) {+ return async (url, init) => {+ calls.push({ url, init });+ const handler = handlers[url.includes('C2021957295') ? 'S30' : 'L30'];+ return typeof handler === 'function'+ ? handler()+ : response({ json: handler });+ };+}++test('both HLS collections fold with the VIIRS days; one failing product is reported, not fatal', async () => {+ const calls = [];+ const signal = new AbortController().signal;+ const result = await searchHls({+ box: BOX,+ now: new Date('2026-09-21T12:00:00Z'),+ signal,+ fetchImpl: cmrFetch(+ {+ S30: {+ hits: 2,+ items: [+ ummItem(),+ ummItem({ conceptId: 'G-old', begin: '2026-09-08T17:12:01Z' }),+ ],+ },+ L30: () => response({ ok: false, status: 503 }),+ },+ calls,+ ),+ });+ assert.deepEqual(result.errors, [+ { product: 'L30', message: 'HTTP 503 from CMR' },+ ]);+ assert.equal(result.truncated, false);+ assert.equal(calls[0].init.signal, signal);+ assert.match(+ calls[0].url,+ /temporal=2026-08-23T00:00:00Z,2026-09-21T12:00:00\.000Z/,+ '30 UTC days ending now',+ );+ const keys = result.candidates.map((c) => c.key);+ assert.equal(keys.length, 32);+ assert.deepEqual(keys.slice(2, 5), [+ 'VIIRS:2026-09-19',+ 'S30:2026-09-18',+ 'VIIRS:2026-09-18',+ ]);+ assert.ok(keys.includes('S30:2026-09-08'));+ assert.equal(+ result.candidates.find((c) => c.key === 'S30:2026-09-18').coverage,+ 'full',+ 'coverage is computed against the box',+ );++ const thrown = await searchHls({+ box: BOX,+ days: 2,+ now: '2026-09-21T00:00:00Z',+ fetchImpl: cmrFetch({+ S30: () => {+ throw new Error('network down');+ },+ L30: { hits: 500, items: [ummItem({ conceptId: 'G-L30' })] },+ }),+ });+ assert.deepEqual(thrown.errors, [+ { product: 'S30', message: 'network down' },+ ]);+ assert.equal(thrown.truncated, true, 'CMR has more hits than were read');+ assert.deepEqual(+ thrown.candidates.map((c) => c.key),+ ['VIIRS:2026-09-21', 'VIIRS:2026-09-20', 'L30:2026-09-18'],+ );+});++test('an invalid box or clock is refused before any request', async () => {+ let called = false;+ const fetchImpl = async () => {+ called = true;+ };+ await assert.rejects(+ searchHls({+ box: { west: 179, south: 0, east: -179, north: 1 },+ fetchImpl,+ }),+ /dateline/,+ );+ await assert.rejects(+ searchHls({ box: BOX, now: 'never', fetchImpl }),+ /clock/,+ );+ assert.equal(called, false);+});++test('CMR pages follow the CMR-Search-After cursor up to 2,000 records and truncation stays honest', async () => {+ const items = (count) =>+ Array.from({ length: count }, (_, i) => ummItem({ conceptId: `G-${i}` }));+ const cursors = [];+ const paged = await fetchCmrPages({+ product: 'S30',+ url: 'https://cmr/x',+ fetchImpl: async (url, init) => {+ const page = cursors.push(init.headers?.['CMR-Search-After'] ?? null);+ return response({+ headers: { 'CMR-Search-After': `cursor-${page}` },+ json: { hits: 450, items: items(page < 3 ? 200 : 50) },+ });+ },+ });+ assert.equal(paged.granules.length, 450);+ assert.equal(paged.truncated, false);+ assert.deepEqual(cursors, [null, 'cursor-1', 'cursor-2']);++ let pages = 0;+ const capped = await fetchCmrPages({+ product: 'L30',+ url: 'https://cmr/y',+ fetchImpl: async () => {+ pages += 1;+ return response({+ headers: { 'cmr-search-after': 'more' },+ json: { hits: 5000, items: items(200) },+ });+ },+ });+ assert.equal(pages, 10);+ assert.equal(capped.granules.length, 2000);+ assert.equal(capped.truncated, true);++ const noCursor = await fetchCmrPages({+ product: 'S30',+ url: 'u',+ fetchImpl: async () => response({ json: { hits: 900, items: items(200) } }),+ });+ assert.equal(noCursor.granules.length, 200);+ assert.equal(noCursor.truncated, true);+});diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.jsnew file mode 100644index 000000000..23b12f44c--- /dev/null+++ b/src/layers/recentImagery/index.js@@ -0,0 +1,1453 @@+/**+ * Recent Imagery layer: pick a box, list the last 30 days of HLS (Sentinel-2 /+ * Landsat) and VIIRS imagery that touch it, and drape the days the operator+ * pins. No polling — work happens when the box changes. Rendering, thumbnails+ * and the catalog are injected, so the state machine runs under `node:test`.+ *+ * The mode is explicit. IMAGE shows one pinned day (slot `a`); VS BASEMAP+ * swipes that day (left) against the basemap (right); A / B swipes day `a`+ * (left) against day `b` (right). While the mode's slot is empty the focused+ * day previews in it. Two draped layers at most, and while any image is on+ * the map it borrows the Esri surface on Google 3D, and keeps it: a manual+ * switch back to Google 3D while a day is shown is answered with a new lease;+ * the map controller's own fallback to Google 3D is not, so a failing Esri+ * map is never retried in a loop.+ */+import { searchHls } from './catalog.js';+import { NO_IMAGERY_HOST, resolveImageryHost } from '../../maps/imageryHost.js';+import {+ CATALOG_DAYS,+ PRODUCTS,+ boxCentre,+ boxFromPin,+ boxFromRectangle,+ boxSideKm,+ dequantizeBox,+ fitViewHeightM,+ formatCandidateReadout,+ parseCandidateKey,+ quantizeBox,+ rankLatest,+ shortDay,+ utcDay,+ validateBox,+ viewTooLargeMessage,+} from './model.js';++/**+ * Quiet time after the last arrow key before the focused day previews, so a+ * burst of key presses drapes only the day it lands on.+ */+export const FOCUS_DEBOUNCE_MS = 250;++/** Quiet time after the last divider move before the split is published. */+export const SPLIT_PUBLISH_MS = 400;++/** The three modes, in share-link order (`m` = index). */+export const MODES = Object.freeze(['image', 'basemap', 'ab']);++const COMPARISON_IN_USE = 'Comparison in use by another scene';+const COMPARISON_UNAVAILABLE = 'Esri map unavailable · no swipe';+const COMPARISON_NEEDS_GLOBE = 'Swipe needs a globe map';+const ESRI_KEPT = 'Imagery stays on Esri · CLEAR to use Google 3D';+/** ZOOM IN's flight time, in seconds. */+const ZOOM_FIT_SECONDS = 1.2;+const DEFAULT_SPLIT = 0.5;+const SLOT_IDS = ['a', 'b'];+const BOX_EDGES = ['west', 'south', 'east', 'north'];+const OTHER_SLOT = { a: 'b', b: 'a' };++const clampUnit = (value, fallback) => {+ const number = Number(value);+ return Number.isFinite(number) ? Math.max(0, Math.min(1, number)) : fallback;+};+const boxSignature = (box) =>+ box ? BOX_EDGES.map((edge) => Number(box[edge]).toFixed(6)).join(',') : '';+const sourceOf = (product) => PRODUCTS[product]?.source || null;+const toDegrees = (radians) => (radians * 180) / Math.PI;+const toRadians = (degrees) => (degrees * Math.PI) / 180;+const ellipsoidOf = (viewer) =>+ viewer?.scene?.ellipsoid || viewer?.scene?.globe?.ellipsoid || null;++/**+ * The ground under the canvas centre, in degrees; null when the centre is+ * sky or the viewer cannot pick.+ * @param {object} viewer+ * @returns {{ lon: number, lat: number } | null}+ */+function viewCentre(viewer) {+ const ellipsoid = ellipsoidOf(viewer);+ const canvas = viewer?.scene?.canvas;+ const width = Number(canvas?.clientWidth);+ const height = Number(canvas?.clientHeight);+ if (!ellipsoid?.cartesianToCartographic || !(width > 0) || !(height > 0))+ return null;+ const hit = viewer.camera?.pickEllipsoid?.(+ { x: width / 2, y: height / 2 },+ ellipsoid,+ );+ const ground = hit ? ellipsoid.cartesianToCartographic(hit) : null;+ return ground+ ? { lon: toDegrees(ground.longitude), lat: toDegrees(ground.latitude) }+ : null;+}+const modeFrom = (value) =>+ MODES.includes(value)+ ? value+ : Number.isInteger(Number(value)) && value !== '' && value !== null+ ? MODES[Number(value)] || null+ : null;++/**+ * Create the layer.+ * @param {{ catalog?: { searchHls: Function }, renderer: object, thumbnails: object, host?: Function, now?: () => Date, days?: number, setTimeoutImpl?: Function, clearTimeoutImpl?: Function }} options+ */+export function createRecentImageryLayer({+ catalog = { searchHls },+ renderer,+ thumbnails,+ host = resolveImageryHost,+ now = () => new Date(),+ days = CATALOG_DAYS,+ setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),+ clearTimeoutImpl = (id) => globalThis.clearTimeout(id),+} = {}) {+ let _viewer = null;+ let _tileset = null;+ let _mapStackController = null;+ let _dataManager = null;+ let _enabled = false;+ let _destroyed = false;+ let _applyingParams = false;++ let _box = null;+ /** The refusal notice; persists until the next successful box. */+ let _boxError = null;+ /** Where ZOOM IN flies for an oversized box or view (degrees), or null. */+ let _refusalTarget = null;+ let _candidates = [];+ let _truncated = false;+ let _catalogErrors = [];+ let _catalogError = null;+ let _searching = false;+ let _searchAbort = null;+ let _lastUpdate = null;++ const _sources = { hls: true, viirs: false };+ let _showUnavailable = false;+ let _focusKey = null;+ let _visible = { first: 0, last: 5 };++ let _mode = 'image';+ const _assigned = { a: null, b: null };+ /** The focused day shown while the mode's slot is empty. */+ let _previewKey = null;+ /** A preview armed by the arrow-key debounce: `{ key }`, key may be null. */+ let _pending = null;+ let _pendingTimer = null;+ /** A focused day still being probed: it previews once present. */+ let _followKey = null;+ let _auto = null;+ let _notice = null;+ let _split = DEFAULT_SPLIT;+ let _splitFromLink = false;+ let _splitTimer = null;+ let _swipeKind = 'none';+ /**+ * SWAP: the two sides of the divider traded (A right and B left, or the+ * image right of the basemap). Session-only: the share link never carries+ * it, and every new comparison starts unswapped.+ */+ let _swapped = false;+ let _alpha = 1;++ let _lease = null;+ let _leaseFromPhotoreal = false;+ /** The stack the lease switched to, once ready. */+ let _leaseStackId = null;+ /** The controller's switch generation right after the lease was taken. */+ let _leaseGeneration = null;+ /** The last switch generation answered with a new lease. */+ let _keptGeneration = null;+ /**+ * The lease was let go because the map controller fell back to Google 3D+ * on its own; the next manual switch to Google 3D may take Esri again.+ */+ let _droppedByFallback = false;+ let _releasing = null;+ let _comparisonReady = false;+ let _comparisonError = null;+ let _hostInfo = { collection: null, kind: 'none' };++ let _toolActive = false;+ let _toolHandler = null;+ let _rowListener = null;+ let _unsubscribeThumbnails = null;+ let _unsubscribeMap = null;+ const _listeners = new Set();++ const candidateFor = (key) =>+ (key && _candidates.find((candidate) => candidate.key === key)) || null;+ const sourceOn = (candidate) =>+ Boolean(candidate && _sources[sourceOf(candidate.product)]);++ /** Worldview's Data-Present header is the only proof a day has pixels. */+ const availability = (candidate) => {+ const status = thumbnails.get(candidate.key)?.status;+ return status === 'empty' || status === 'present'+ ? status+ : candidate.availability;+ };+ const withAvailability = (candidate) => ({+ ...candidate,+ availability: availability(candidate),+ });+ const drapable = (candidate) =>+ sourceOn(candidate) && availability(candidate) === 'present';++ const sourcedCandidates = () => _candidates.filter(sourceOn);+ /** Source-on candidates, minus confirmed-empty days unless asked for. */+ const stripList = () =>+ _showUnavailable+ ? sourcedCandidates()+ : sourcedCandidates().filter((c) => availability(c) !== 'empty');+ const focusIndexIn = (list) =>+ _focusKey ? list.findIndex((candidate) => candidate.key === _focusKey) : -1;++ /** The slot a pinned day occupies in the current mode, if any. */+ const activeSlotOf = (key) =>+ !key+ ? null+ : key === _assigned.a+ ? 'a'+ : _mode === 'ab' && key === _assigned.b+ ? 'b'+ : null;+ /** The slot a preview fills: the mode's first empty slot. */+ function previewSlot() {+ if (_mode !== 'ab') return _assigned.a ? null : 'a';+ if (!_assigned.a) return 'a';+ return _assigned.b ? null : 'b';+ }++ /** What the map shows: one key per renderer slot, and the swipe kind. */+ function plan() {+ const out = { a: null, b: null, preview: null, swipe: 'none' };+ if (!_enabled || !_box) return out;+ const live = (key) => (drapable(candidateFor(key)) ? key : null);+ out.a = live(_assigned.a);+ if (_mode === 'ab') out.b = live(_assigned.b);+ const slot = previewSlot();+ const preview =+ slot && !activeSlotOf(_previewKey) ? live(_previewKey) : null;+ if (preview) {+ out[slot] = preview;+ out.preview = slot;+ }+ if (_mode === 'basemap' && out.a) out.swipe = 'basemap';+ else if (_mode === 'ab' && out.a && out.b) out.swipe = 'ab';+ return out;+ }++ /**+ * Keep focus on the same day across probe results, source toggles and the+ * availability filter; when its card leaves the strip, move to the nearest+ * card still shown (ties go to the older day).+ */+ function reconcileFocus() {+ const list = stripList();+ if (!list.length) {+ _focusKey = null;+ return;+ }+ if (focusIndexIn(list) >= 0) return;+ const previous = _candidates.findIndex((c) => c.key === _focusKey);+ let best = list[0];+ if (previous >= 0) {+ let bestDistance = Infinity;+ for (const candidate of list) {+ const index = _candidates.indexOf(candidate);+ const distance = Math.abs(index - previous);+ if (+ distance < bestDistance ||+ (distance === bestDistance && index > previous)+ ) {+ best = candidate;+ bestDistance = distance;+ }+ }+ }+ _focusKey = best.key;+ }++ const rank = (list) =>+ rankLatest(list.map(withAvailability), { truncated: _truncated });++ /** Focus the START HERE day and preview it when the mode's slot is empty. */+ function autoPreview() {+ const ranked = rank(sourcedCandidates());+ if (!ranked.candidate) return;+ const key = ranked.candidate.key;+ if (!_focusKey) _focusKey = key;+ if (!previewSlot() || activeSlotOf(key)) return;+ _auto = { key, reason: ranked.reason, certain: ranked.certain };+ if (drapable(candidateFor(key))) _previewKey = key;+ else _followKey = key;+ }++ /**+ * A day whose probe came back empty leaves the map: JPEG products have no+ * alpha and would drape black "no data" tiles. A pinned day is unpinned and+ * an empty automatic preview is re-ranked.+ */+ function pruneEmpty() {+ let changed = false;+ for (const slotId of SLOT_IDS) {+ const pinned = candidateFor(_assigned[slotId]);+ if (pinned && availability(pinned) === 'empty') {+ _assigned[slotId] = null;+ changed = true;+ }+ }+ const preview = candidateFor(_previewKey);+ if (preview && availability(preview) === 'empty') {+ const wasAuto = _auto?.key === preview.key;+ _previewKey = null;+ _auto = null;+ changed = true;+ if (wasAuto) autoPreview();+ }+ // A followed day that turns out empty is dropped; an automatic one hands+ // over to the next ranked day.+ const followed = candidateFor(_followKey);+ if (followed && availability(followed) === 'empty') {+ const wasAuto = _auto?.key === followed.key;+ _followKey = null;+ if (wasAuto) {+ _auto = null;+ autoPreview();+ }+ changed = true;+ }+ return changed;+ }++ function notify(reason = 'state') {+ if (_destroyed) return;+ reconcileFocus();+ const snapshot = _listeners.size ? layer.getSnapshot() : null;+ for (const listener of [..._listeners]) {+ try {+ listener(snapshot, reason);+ } catch (error) {+ console.warn('[Data:RecentImagery] listener failed:', error);+ }+ }+ if (reason === 'state') _rowListener?.();+ }++ /**+ * Publish what a direct interaction changed, so the durable state and the+ * share link follow it. Never while applying params (a restore): a nested+ * intent would supersede the one being applied.+ */+ function publish(keys) {+ if (_applyingParams || _destroyed || !_dataManager?.adoptLayerParams)+ return;+ const params = layer.getParams();+ const picked = {};+ for (const key of keys) picked[key] = params[key];+ try {+ _dataManager.adoptLayerParams(layer.id, picked, { origin: 'user' });+ } catch (error) {+ console.warn('[Data:RecentImagery] publish failed:', error);+ }+ }++ function clearSplitTimer() {+ if (_splitTimer !== null) clearTimeoutImpl(_splitTimer);+ _splitTimer = null;+ }++ function syncHost() {+ const next = host({ viewer: _viewer, tileset: _tileset }) || {+ collection: null,+ kind: 'none',+ };+ const changed =+ next.collection !== _hostInfo.collection || next.kind !== _hostInfo.kind;+ _hostInfo = next;+ renderer.rebind(next);+ return changed;+ }++ /**+ * Hand the lease back. The release restores the map asynchronously; no new+ * lease is taken until it settles, and then the state is reconciled, so a+ * new image inside that window re-acquires.+ */+ function releaseComparison() {+ const lease = _lease;+ forgetLease();+ if (_notice === ESRI_KEPT) _notice = null;+ if (!lease) return;+ const releasing = Promise.resolve()+ .then(() => lease.release())+ .catch((error) => {+ console.warn('[Data:RecentImagery] comparison release failed:', error);+ })+ .then(() => {+ if (_releasing === releasing) _releasing = null;+ if (_destroyed) return;+ if (_enabled) syncRender();+ notify();+ });+ _releasing = releasing;+ }++ function forgetLease() {+ _droppedByFallback = false;+ _lease = null;+ _leaseFromPhotoreal = false;+ _leaseStackId = null;+ _leaseGeneration = null;+ _comparisonReady = false;+ _comparisonError = null;+ }++ function acquireComparison() {+ if (_lease || _releasing || _comparisonError || _comparisonReady) return;+ if (!_mapStackController?.acquireImageryComparison) {+ _comparisonReady = true;+ return;+ }+ const fromPhotoreal = _mapStackController.getActiveId?.() === 'photoreal';+ let lease;+ try {+ lease = _mapStackController.acquireImageryComparison({+ owner: 'recent-imagery',+ switchPolicy: 'esri-if-photoreal',+ });+ } catch {+ _comparisonError = COMPARISON_IN_USE;+ return;+ }+ _lease = lease;+ _leaseFromPhotoreal = fromPhotoreal;+ // Read after the lease issued its switch, so that switch is known as ours.+ _leaseGeneration = _mapStackController.getSwitchGeneration?.() ?? null;+ Promise.resolve(lease.ready)+ .catch(() => null)+ .then((result) => {+ if (_destroyed || _lease !== lease) return;+ if (result?.status === 'ready') {+ _comparisonReady = true;+ _leaseStackId = result.activeId ?? null;+ } else _comparisonError = COMPARISON_UNAVAILABLE;+ if (_enabled) syncRender({ comparison: false });+ notify();+ });+ }++ /**+ * While a day is shown the imagery keeps the Esri surface. A manual switch+ * (the operator's, not the lease's own) that lands on Google 3D is+ * answered at once with a new lease under the same policy; the old lease+ * no longer owns the map, so it lets go without a switch of its own, and+ * the new one remembers Google 3D for CLEAR. An automatic one (the+ * controller's fallback or recovery after Esri failed) is not retried: the+ * lease lets go, restoring nothing, and the days show without a swipe+ * until the operator switches to Google 3D by hand. Once per switch+ * generation, never while releasing (CLEAR and disable return to Google+ * 3D), and never without a lease to renew or one a fallback let go, so a+ * lease another owner holds stays refused.+ * @returns {boolean} Whether the lease was renewed, refused or let go.+ */+ function keepEsri() {+ const controller = _mapStackController;+ if (!_enabled || _destroyed || _releasing) return false;+ if (!_lease && !_droppedByFallback) return false;+ if (controller?.getActiveId?.() !== 'photoreal') return false;+ const shown = plan();+ if (!shown.a && !shown.b) return false;+ const generation = controller.getSwitchGeneration?.() ?? null;+ if (generation === _leaseGeneration || generation === _keptGeneration)+ return false;+ _keptGeneration = generation;+ const automatic = controller.getSwitchOrigin?.() === 'automatic';+ const previous = _lease;+ forgetLease();+ try {+ void previous?.release();+ } catch (error) {+ console.warn('[Data:RecentImagery] comparison release failed:', error);+ }+ if (automatic) {+ _droppedByFallback = true;+ _comparisonError = COMPARISON_UNAVAILABLE;+ if (_notice === ESRI_KEPT) _notice = null;+ return true;+ }+ acquireComparison();+ if (_lease) _notice = ESRI_KEPT;+ else if (_notice === ESRI_KEPT) _notice = null;+ return true;+ }++ /**+ * A settled stack switch (or, without a subscription, the stats poll):+ * rebind to the new host and keep the Esri surface.+ */+ function followMap() {+ if (_destroyed || !_enabled) return;+ const moved = syncHost();+ if (!keepEsri() && !moved) return;+ syncRender();+ notify();+ }++ const swipeGranted = () => _comparisonReady && !_comparisonError;+ /** Whether the divider is live for this plan: granted, on the globe. */+ const swipeLive = (shown) =>+ shown.swipe !== 'none' && swipeGranted() && _hostInfo.kind === 'globe';++ /**+ * Every new comparison starts unswapped with the divider centred, except+ * once for a split restored from a share link (the author's framing).+ * Scrubbing the second image inside a comparison keeps both as they are.+ */+ function trackSwipeStart(kind) {+ if (kind !== 'none' && kind !== _swipeKind) {+ _swapped = false;+ if (_splitFromLink) _splitFromLink = false;+ else if (_split !== DEFAULT_SPLIT) {+ _split = DEFAULT_SPLIT;+ clearSplitTimer();+ publish(['split']);+ notify('split');+ }+ }+ _swipeKind = kind;+ }++ function syncRender({ comparison = true } = {}) {+ if (_destroyed) return;+ syncHost();+ pruneEmpty();+ const shown = plan();+ trackSwipeStart(shown.swipe);+ const live = swipeLive(shown);+ for (const slotId of SLOT_IDS) {+ const candidate = candidateFor(shown[slotId]);+ if (candidate && _hostInfo.collection) {+ renderer.showSlot(slotId, candidate, _box, {+ alpha: _alpha,+ splitDirection: !live+ ? 'none'+ : (slotId === 'a') !== _swapped+ ? 'left'+ : 'right',+ });+ } else {+ renderer.hideSlot(slotId);+ }+ }+ if (!comparison) return;+ if (shown.a || shown.b) acquireComparison();+ else if (_lease || _comparisonReady || _comparisonError)+ releaseComparison();+ }++ /**+ * Probe the visible strip window, then the pinned and previewed days+ * wherever they sit: a pin restored or assigned off-screen never drapes+ * until its probe says present, so it goes at the focused card's priority.+ */+ function requestThumbnails() {+ if (!_enabled || !_box) return;+ const list = stripList();+ if (!list.length) return;+ reconcileFocus();+ thumbnails.requestOrdered(list, _box, {+ focusIndex: Math.max(0, focusIndexIn(list)),+ firstVisible: _visible.first,+ lastVisible: _visible.last,+ extra: 2,+ });+ for (const key of new Set([+ _assigned.a,+ _assigned.b,+ _previewKey,+ _followKey,+ ])) {+ const candidate = candidateFor(key);+ if (sourceOn(candidate)) thumbnails.request(candidate, _box, 0);+ }+ }++ function resetCatalog() {+ _candidates = [];+ _truncated = false;+ _catalogErrors = [];+ _catalogError = null;+ _auto = null;+ }++ function cancelSearch() {+ _searchAbort?.abort();+ _searchAbort = null;+ _searching = false;+ }++ async function runSearch() {+ cancelSearch();+ const abort = new AbortController();+ _searchAbort = abort;+ _searching = true;+ _catalogError = null;+ notify();+ try {+ const result = await catalog.searchHls({+ box: _box,+ days,+ now: now(),+ signal: abort.signal,+ });+ if (abort.signal.aborted) return;+ _candidates = result?.candidates || [];+ _truncated = Boolean(result?.truncated);+ _catalogErrors = result?.errors || [];+ _lastUpdate = Date.now();+ // Drop days the catalog no longer lists; start from a pinned day or+ // the recommended one.+ for (const slotId of SLOT_IDS)+ if (!candidateFor(_assigned[slotId])) _assigned[slotId] = null;+ _previewKey = null;+ _auto = null;+ _focusKey =+ [_assigned.a, _assigned.b].find((key) => activeSlotOf(key)) || null;+ if (!_focusKey) autoPreview();+ } catch (error) {+ if (abort.signal.aborted) return;+ resetCatalog();+ _catalogError = error?.message || 'Imagery catalog unavailable';+ } finally {+ if (_searchAbort === abort) {+ _searchAbort = null;+ _searching = false;+ }+ }+ syncRender();+ requestThumbnails();+ notify();+ }++ function clearPending() {+ if (_pendingTimer !== null) clearTimeoutImpl(_pendingTimer);+ _pendingTimer = null;+ _pending = null;+ }++ /** Make `key` (or nothing) the preview now. */+ function applyPreview(key) {+ clearPending();+ _followKey = null;+ if (key === _previewKey) return false;+ if (_auto?.key !== key) _auto = null;+ _previewKey = key;+ if (_enabled) syncRender();+ return true;+ }++ /** Arm the debounce for the focused day, or follow it until it is probed. */+ function schedulePreviewFromFocus() {+ clearPending();+ _followKey = null;+ const candidate = candidateFor(_focusKey);+ if (!candidate || !_enabled || !previewSlot()) return;+ // A pinned day is already on the map; focusing it takes the preview off.+ const key = activeSlotOf(candidate.key) ? null : candidate.key;+ if (key === _previewKey) return;+ if (key && !drapable(candidate)) {+ _followKey = key;+ return;+ }+ _pending = { key };+ _pendingTimer = setTimeoutImpl(() => {+ _pendingTimer = null;+ const pending = _pending;+ _pending = null;+ if (_destroyed || !pending) return;+ if (pending.key && !drapable(candidateFor(pending.key))) return;+ if (applyPreview(pending.key)) notify();+ }, FOCUS_DEBOUNCE_MS);+ }++ /**+ * @param {string} message+ * @param {{ lon: number, lat: number } | null} [target] Where ZOOM IN flies.+ */+ function refuseBox(message, target = null) {+ _boxError = message;+ _refusalTarget = target;+ notify();+ return false;+ }++ /** ZOOM IN applies to a box over the cap only: fly to its centre. */+ const oversizedCentre = (box) =>+ validateBox(box).reason === 'too-large' ? boxCentre(box) : null;++ function applyBox(box) {+ const result = validateBox(box);+ if (!result.ok) return refuseBox(result.message, oversizedCentre(box));+ _boxError = null;+ _refusalTarget = null;+ _notice = null;+ if (+ boxSignature(result.box) === boxSignature(_box) &&+ (_searching || _candidates.length)+ ) {+ notify();+ return true;+ }+ clearPending();+ _followKey = null;+ _previewKey = null;+ _box = result.box;+ thumbnails.clear();+ resetCatalog();+ _focusKey = null;+ if (_enabled) {+ // The old box's drapes come down now, not when the new search lands.+ syncRender();+ void runSearch();+ } else notify();+ return true;+ }++ /** A user-chosen box, published once accepted. */+ function chooseBox(box) {+ const accepted = applyBox(box);+ if (accepted) publish(BOX_EDGES);+ return accepted;+ }++ function guidance() {+ if (_enabled && _hostInfo.kind === 'none') return NO_IMAGERY_HOST;+ if (_comparisonError) return _comparisonError;+ if (+ _enabled &&+ plan().swipe !== 'none' &&+ swipeGranted() &&+ _hostInfo.kind === 'tileset'+ )+ return COMPARISON_NEEDS_GLOBE;+ return _catalogError;+ }++ function notes() {+ const out = [];+ if (_truncated) out.push('Catalog truncated · a newer clear day may exist');+ for (const error of _catalogErrors) {+ const label = PRODUCTS[error.product]?.label || error.product;+ out.push(`${label} catalog unavailable · ${error.message}`);+ }+ const today = utcDay(now());+ const viirsToday = candidateFor(`VIIRS:${today}`);+ if (viirsToday?.availability === 'unknown' && _sources.viirs)+ out.push('Daily overview for today may still be empty until the pass');+ return out;+ }++ function imageSnapshot(key) {+ const parsed = parseCandidateKey(key);+ const sourceOff = Boolean(parsed) && !_sources[sourceOf(parsed.product)];+ return {+ key: key || null,+ candidate: candidateFor(key),+ label: parsed+ ? `${shortDay(parsed.day)} · ${PRODUCTS[parsed.product].name} · ${PRODUCTS[parsed.product].resolutionM} m`+ : null,+ sourceOff,+ drapable: drapable(candidateFor(key)),+ };+ }++ function applySources(next) {+ let changed = false;+ for (const id of ['hls', 'viirs']) {+ if (next?.[id] == null || Boolean(next[id]) === _sources[id]) continue;+ _sources[id] = Boolean(next[id]);+ changed = true;+ const pending = candidateFor(_pending?.key);+ if (!_sources[id] && pending && sourceOf(pending.product) === id)+ clearPending();+ }+ return changed;+ }++ const layer = {+ id: 'recent-imagery',+ name: 'Recent Imagery',+ icon: '🛰',+ source: 'NASA GIBS · HLS + VIIRS',+ updateInterval: 0,++ init(viewer) {+ _viewer = viewer || null;+ return true;+ },++ enable(viewer) {+ if (_destroyed) return false;+ if (viewer) _viewer = viewer;+ _enabled = true;+ _comparisonError = null;+ _unsubscribeThumbnails?.();+ _unsubscribeThumbnails = thumbnails.subscribe(() => {+ // A probe can take a pinned day off the map or let a followed focus+ // preview; both change more than the cards, so a full notification+ // follows the thumbnail one.+ const pruned = pruneEmpty();+ if (pruned) syncRender();+ const followed =+ Boolean(_followKey) &&+ _followKey === _focusKey &&+ drapable(candidateFor(_followKey)) &&+ applyPreview(_followKey);+ // A pinned or previewed day that was still being probed drapes now.+ const shown = plan();+ const owned = renderer.getOwned?.() || {};+ const drapesChanged = SLOT_IDS.some(+ (slotId) => (owned[slotId]?.key || null) !== shown[slotId],+ );+ if (drapesChanged && !pruned && !followed) syncRender();+ notify('thumbnail');+ if (pruned || followed || drapesChanged) notify();+ });+ syncHost();+ if (_box && !_candidates.length) void runSearch();+ else {+ syncRender();+ requestThumbnails();+ }+ notify();+ return true;+ },++ disable() {+ cancelSearch();+ clearPending();+ _followKey = null;+ thumbnails.clear();+ _unsubscribeThumbnails?.();+ _unsubscribeThumbnails = null;+ _toolHandler?.();+ _toolActive = false;+ _enabled = false;+ resetCatalog();+ _previewKey = null;+ _swipeKind = 'none';+ for (const slotId of SLOT_IDS) renderer.hideSlot(slotId);+ releaseComparison();+ notify();+ return true;+ },++ /** No polling: candidates change with the box, not with the clock. */+ async update() {},++ destroy() {+ if (_destroyed) return;+ if (_enabled) this.disable();+ clearPending();+ clearSplitTimer();+ _unsubscribeMap?.();+ _unsubscribeMap = null;+ renderer.destroy();+ thumbnails.destroy();+ _listeners.clear();+ _rowListener = null;+ _toolHandler = null;+ _viewer = null;+ _tileset = null;+ _mapStackController = null;+ _dataManager = null;+ _destroyed = true;+ },++ /**+ * Keep the map controller for the Esri lease and hear every settled+ * stack switch, so the drapes move to the new host the moment it+ * changes, and a manual switch to Google 3D while a day is shown takes+ * Esri back, while an automatic fallback lets it go (`keepEsri`).+ * @param {object | null} controller+ */+ attachMapStackController(controller) {+ _unsubscribeMap?.();+ _unsubscribeMap = null;+ _mapStackController = controller || null;+ const off = controller?.subscribe?.(followMap);+ _unsubscribeMap = typeof off === 'function' ? off : null;+ },++ /** The layer manager, to publish direct interactions as params. */+ attachDataManager(manager) {+ _dataManager = manager || null;+ },++ /** The photoreal tileset, for draping while the globe is hidden. */+ attachTileset(tileset) {+ _tileset = tileset || null;+ if (_enabled && syncHost()) {+ syncRender();+ notify();+ }+ },++ /** The UI registers how the box tool is cancelled (CLEAR, disable). */+ setToolHandler(handler) {+ _toolHandler = typeof handler === 'function' ? handler : null;+ },++ /** The UI reports whether the box tool is live. */+ setToolActive(active) {+ if (Boolean(active) === _toolActive) return;+ _toolActive = Boolean(active);+ notify();+ },++ /**+ * Select a box; a refusal stays on the panel until a box succeeds.+ * @param {object} box Degrees box.+ * @returns {boolean}+ */+ setBox(box) {+ return chooseBox(box);+ },++ /**+ * The box tool refused a drag: keep its reason on the panel. With the+ * dragged box, an oversized drag offers ZOOM IN.+ * @param {string} message+ * @param {object} [box] Degrees box.+ */+ reportBoxRefusal(message, box = null) {+ const text = typeof message === 'string' ? message.trim() : '';+ if (!text) return false;+ refuseBox(text, box ? oversizedCentre(box) : null);+ return true;+ },++ /**+ * Use the camera's view rectangle as the box. A view wider than the cap+ * is refused with its size, never silently shrunk.+ * @param {object} [viewer]+ * @returns {boolean}+ */+ useCurrentView(viewer = _viewer) {+ const rectangle = viewer?.camera?.computeViewRectangle?.();+ if (!rectangle)+ return refuseBox('Point the camera at the ground to use the view');+ const box = boxFromRectangle(rectangle);+ if (validateBox(box).reason === 'too-large') {+ const { width, height } = boxSideKm(box);+ return refuseBox(+ viewTooLargeMessage(Math.max(width, height)),+ viewCentre(viewer) || boxCentre(box),+ );+ }+ return chooseBox(box);+ },++ /**+ * ZOOM IN: fly top-down to the refused box's or view's centre, at the+ * height whose view is about 400 km wide for this canvas and FOV.+ * @returns {number | null} The target height in metres, or null when+ * there is nothing to fit.+ */+ zoomToFit() {+ const target = _boxError ? _refusalTarget : null;+ const camera = _viewer?.camera;+ const ellipsoid = ellipsoidOf(_viewer);+ if (!target || !camera?.flyTo || !ellipsoid?.cartographicToCartesian)+ return null;+ const canvas = _viewer.scene?.canvas;+ const height = fitViewHeightM({+ width: canvas?.clientWidth,+ height: canvas?.clientHeight,+ fovy: camera.frustum?.fovy,+ });+ camera.flyTo({+ destination: ellipsoid.cartographicToCartesian({+ longitude: toRadians(target.lon),+ latitude: toRadians(target.lat),+ height,+ }),+ orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 },+ duration: ZOOM_FIT_SECONDS,+ });+ return height;+ },++ /** A 10 km box centred on a point. */+ boxFromPinAt(lon, lat) {+ const box = boxFromPin(lon, lat);+ return box ? chooseBox(box) : refuseBox('That point cannot anchor a box');+ },++ /**+ * Move focus in the strip (index into the shown cards). While the mode's+ * slot is empty the focused day previews after `FOCUS_DEBOUNCE_MS`, once+ * it is probed present.+ * @param {number} index+ */+ focus(index) {+ const list = stripList();+ if (!list.length) return;+ const next = Math.max(+ 0,+ Math.min(list.length - 1, Math.trunc(Number(index)) || 0),+ );+ if (list[next].key === _focusKey) return;+ _focusKey = list[next].key;+ schedulePreviewFromFocus();+ requestThumbnails();+ notify();+ },++ /** The strip reports which cards are on screen. */+ setVisibleRange(first, last) {+ const lo = Math.max(0, Math.trunc(Number(first)) || 0);+ const hi = Math.max(lo, Math.trunc(Number(last)) || lo);+ if (lo === _visible.first && hi === _visible.last) return;+ _visible = { first: lo, last: hi };+ requestThumbnails();+ },++ /**+ * Focus a day and preview it now (a card click). A day still being+ * probed is followed; an empty day never drapes and the previous preview+ * stays. With the mode's slots full the click only moves focus.+ * @param {string} key+ * @returns {boolean} Whether that day is now the preview.+ */+ preview(key) {+ const candidate = candidateFor(key);+ if (!sourceOn(candidate)) return false;+ if (stripList().includes(candidate)) _focusKey = candidate.key;+ if (!previewSlot() || !_enabled) {+ clearPending();+ _followKey = null;+ notify();+ return false;+ }+ if (activeSlotOf(candidate.key)) {+ applyPreview(null);+ notify();+ return false;+ }+ if (!drapable(candidate)) {+ clearPending();+ _followKey = availability(candidate) === 'empty' ? null : candidate.key;+ notify();+ return false;+ }+ applyPreview(candidate.key);+ notify();+ return true;+ },++ /**+ * Take the preview off the map (Escape). Pinned days stay.+ * @returns {boolean} Whether a preview was showing or on its way.+ */+ clearPreview() {+ const had = Boolean(_pending || _followKey || plan().preview);+ clearPending();+ _followKey = null;+ if (_previewKey) {+ _previewKey = null;+ _auto = null;+ if (_enabled) syncRender();+ }+ if (had) notify();+ return had;+ },++ /**+ * Pin a day in slot `a` or `b`, or unpin the slot with `null`. A day is+ * in one slot at most: pinning it in the other slot moves it. Empty days+ * cannot be pinned.+ * @param {'a'|'b'} slot+ * @param {string | null} key+ * @returns {boolean} Whether the pins changed.+ */+ setAssignment(slot, key) {+ if (!SLOT_IDS.includes(slot)) return false;+ let next = null;+ if (key != null) {+ const candidate = candidateFor(key);+ if (!sourceOn(candidate) || availability(candidate) === 'empty')+ return false;+ next = candidate.key;+ if (stripList().includes(candidate)) _focusKey = next;+ }+ if (_assigned[slot] === next) return false;+ if (next && _assigned[OTHER_SLOT[slot]] === next)+ _assigned[OTHER_SLOT[slot]] = null;+ _assigned[slot] = next;+ // The preview belonged to the old pins; the next focus move brings it back.+ clearPending();+ _followKey = null;+ _previewKey = null;+ _auto = null;+ if (_enabled) {+ syncRender();+ requestThumbnails();+ }+ publish(['a', 'b']);+ notify();+ return true;+ },++ /**+ * Pin `key` in `slot`, or unpin it when it is already there.+ * @param {'a'|'b'} slot+ * @param {string} key+ * @returns {boolean} Whether the pins changed.+ */+ toggleAssignment(slot, key) {+ return layer.setAssignment(slot, _assigned[slot] === key ? null : key);+ },++ /**+ * Switch the mode: `image`, `basemap` (the pinned day against the+ * basemap) or `ab` (two pinned days). Pins survive a mode switch; the+ * B pin only drapes in `ab`.+ * @param {'image'|'basemap'|'ab'} mode+ * @returns {boolean} Whether the mode changed.+ */+ setMode(mode) {+ const next = modeFrom(mode);+ if (!next || next === _mode) return false;+ _mode = next;+ clearPending();+ _followKey = null;+ if (_enabled) syncRender();+ publish(['mode']);+ notify();+ return true;+ },++ /**+ * Turn the source groups on or off. Off takes their cards and drapes+ * away and labels their pins "Source off"; on restores them.+ * @param {{ hls?: boolean, viirs?: boolean }} next+ * @returns {boolean} Whether anything changed.+ */+ setSources(next) {+ if (!applySources(next)) return false;+ if (_enabled) {+ syncRender();+ requestThumbnails();+ }+ notify();+ return true;+ },++ /** Show or hide confirmed-empty days in the strip. */+ setShowUnavailable(value) {+ if (Boolean(value) === _showUnavailable) return;+ _showUnavailable = Boolean(value);+ if (_enabled) requestThumbnails();+ notify();+ },++ /** Split position 0–1; the split control owns the scene write. */+ setSplit(value) {+ const next = clampUnit(value, _split);+ if (next === _split) return;+ _split = next;+ clearSplitTimer();+ _splitTimer = setTimeoutImpl(() => {+ _splitTimer = null;+ publish(['split']);+ }, SPLIT_PUBLISH_MS);+ notify('split');+ },++ /**+ * SWAP: trade the two sides of a live divider (A moves right and B left;+ * in VS BASEMAP the image moves right of the basemap). Again restores.+ * The divider position stays; nothing is published.+ * @returns {boolean} Whether a live swipe was swapped.+ */+ swapSides() {+ if (!_enabled || _destroyed || !swipeLive(plan())) return false;+ _swapped = !_swapped;+ syncRender({ comparison: false });+ notify();+ return true;+ },++ /** One opacity for both drapes. */+ setAlpha(value) {+ const next = clampUnit(value, _alpha);+ if (next === _alpha) return;+ _alpha = next;+ for (const slotId of SLOT_IDS) renderer.setAlpha(slotId, next);+ notify('alpha');+ },++ /**+ * Forget the box, the candidates, both pins, the preview and any pending+ * pick; reset opacity and split and cancel the box tool. Mode and+ * sources survive.+ */+ clear() {+ cancelSearch();+ clearPending();+ clearSplitTimer();+ _followKey = null;+ _toolHandler?.();+ thumbnails.clear();+ _box = null;+ _boxError = null;+ _refusalTarget = null;+ resetCatalog();+ _focusKey = null;+ _assigned.a = null;+ _assigned.b = null;+ _previewKey = null;+ _split = DEFAULT_SPLIT;+ _swapped = false;+ if (_alpha !== 1) {+ _alpha = 1;+ for (const slotId of SLOT_IDS) renderer.setAlpha(slotId, 1);+ }+ _notice = 'Box and images cleared';+ syncRender();+ publish([...BOX_EDGES, 'a', 'b', 'split']);+ notify();+ },++ /** Everything the panel renders. */+ getSnapshot() {+ reconcileFocus();+ const list = stripList();+ const focusIndex = Math.max(0, focusIndexIn(list));+ const ranked = rank(list);+ const shown = plan();+ const previewKey = shown.preview ? shown[shown.preview] : null;+ const pendingKey = _pending?.key || _followKey || null;+ // The focused day is its card's entry, so the readout sees the same+ // map and probe state the strip does.+ const candidates = list.map((candidate, index) => ({+ ...candidate,+ index,+ pinned:+ candidate.key === _assigned.a+ ? 'a'+ : candidate.key === _assigned.b+ ? 'b'+ : null,+ preview: candidate.key === previewKey,+ pending: candidate.key === pendingKey,+ drapable: drapable(candidate),+ thumbnail: thumbnails.get(candidate.key),+ }));+ const focus = candidates[focusIndex] || null;+ const comparing = swipeLive(shown);+ return {+ enabled: _enabled,+ box: _box,+ boxSizeKm: _box ? boxSideKm(_box) : null,+ boxError: _boxError,+ /** An oversized box or view: the panel offers ZOOM IN. */+ zoomToFit: Boolean(_boxError && _refusalTarget),+ searching: _searching,+ sources: { ..._sources },+ showUnavailable: _showUnavailable,+ hiddenCount: _showUnavailable+ ? 0+ : sourcedCandidates().length - list.length,+ candidates,+ focusIndex,+ focus,+ readout: focus ? formatCandidateReadout(focus, now()) : '',+ recommended: ranked.candidate+ ? { key: ranked.candidate.key, reason: ranked.reason }+ : null,+ mode: _mode,+ pins: { a: imageSnapshot(_assigned.a), b: imageSnapshot(_assigned.b) },+ preview: {+ ...imageSnapshot(previewKey),+ slot: shown.preview,+ pending: pendingKey,+ },+ shown: { a: shown.a, b: shown.b, swipe: shown.swipe },+ alpha: _alpha,+ split: _split,+ swapped: _swapped,+ comparison: {+ active: comparing,+ suspended:+ shown.swipe !== 'none' &&+ swipeGranted() &&+ _hostInfo.kind === 'tileset',+ },+ // Only while the borrowed map is still the one showing: an operator+ // who switched back by hand is not told the imagery is on Esri.+ borrowedEsri:+ Boolean(_lease) &&+ _comparisonReady &&+ _leaseFromPhotoreal &&+ _leaseStackId !== null &&+ _mapStackController?.getActiveId?.() === _leaseStackId,+ notes: notes(),+ auto: _auto,+ toolActive: _toolActive,+ error: guidance(),+ notice: _notice,+ };+ },++ /**+ * @param {(snapshot: object, reason: string) => void} listener+ * @returns {() => void}+ */+ subscribe(listener) {+ _listeners.add(listener);+ return () => _listeners.delete(listener);+ },++ /** The data-panel row carries the two source toggles only. */+ getRowControls() {+ return {+ chips: [+ {+ id: 'hls',+ label: 'MORE DETAIL · 30 m',+ active: _sources.hls,+ title: 'Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days',+ params: { hls: !_sources.hls },+ },+ {+ id: 'viirs',+ label: 'DAILY OVERVIEW · 250 m',+ active: _sources.viirs,+ title:+ 'VIIRS daily mosaic, 250 m, follows broad changes; little detail under 25 km',+ params: { viirs: !_sources.viirs },+ },+ ],+ };+ },++ setRowControlsListener(listener) {+ _rowListener = typeof listener === 'function' ? listener : null;+ },++ /**+ * Share-link and row-chip options: box edges as integers at degrees ×+ * 100000, the `a` and `b` pins, `mode` (0 image, 1 basemap, 2 A / B),+ * `split` percent, `hls` / `viirs` source toggles.+ * @param {object} params+ * @returns {boolean}+ */+ setParams(params) {+ if (!params || typeof params !== 'object') return false;+ _applyingParams = true;+ try {+ let changed = applySources(params);+ if (BOX_EDGES.every((edge) => params[edge] != null)) {+ const box = dequantizeBox(params);+ if (box) applyBox(box);+ }+ // Read before the pins so a link's framing is in place when its+ // comparison first renders. Local storage never keeps the split, so+ // only a non-default value can have come from a link.+ if (params.split != null && Number.isFinite(Number(params.split))) {+ _split = clampUnit(Number(params.split) / 100, _split);+ _splitFromLink = _split !== DEFAULT_SPLIT;+ }+ const mode = params.mode == null ? null : modeFrom(params.mode);+ if (mode && mode !== _mode) {+ _mode = mode;+ changed = true;+ }+ if ('a' in params || 'b' in params) {+ clearPending();+ _followKey = null;+ for (const slotId of SLOT_IDS) {+ if (slotId in params)+ _assigned[slotId] = parseCandidateKey(params[slotId])+ ? params[slotId]+ : null;+ }+ if (_assigned.a && _assigned.a === _assigned.b) _assigned.b = null;+ _previewKey = null;+ _auto = null;+ const pinned = _assigned.a || _assigned.b;+ if (pinned && candidateFor(pinned)) _focusKey = pinned;+ changed = true;+ }+ if (changed && _enabled) {+ syncRender();+ requestThumbnails();+ }+ notify();+ return true;+ } finally {+ _applyingParams = false;+ }+ },++ getParams() {+ const quantized = quantizeBox(_box);+ return {+ west: quantized?.west ?? null,+ south: quantized?.south ?? null,+ east: quantized?.east ?? null,+ north: quantized?.north ?? null,+ a: _assigned.a,+ b: _assigned.b,+ mode: MODES.indexOf(_mode),+ split: Math.round(_split * 100),+ viirs: _sources.viirs,+ };+ },++ getStats() {+ // Without a controller subscription the stats poll is the only steady+ // heartbeat, so it doubles as the map-stack watch.+ if (!_unsubscribeMap) followMap();+ return {+ count: _candidates.length,+ lastUpdate: _lastUpdate,+ error: guidance(),+ };+ },++ /** Renderer, host and lease state for tests and the live gate. */+ diagnostics() {+ const shown = plan();+ return {+ host: _hostInfo.kind,+ ownedCount: renderer.ownedCount(),+ lease: Boolean(_lease),+ releasing: Boolean(_releasing),+ mode: _mode,+ pins: { ..._assigned },+ preview: _previewKey,+ shown,+ pending: _pending ? _pending.key : undefined,+ following: _followKey,+ splitFromLink: _splitFromLink,+ };+ },+ };+ return layer;+}diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjsnew file mode 100644index 000000000..7675d0f3a--- /dev/null+++ b/src/layers/recentImagery/index.test.mjs@@ -0,0 +1,1387 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';+import { acquireImageryComparison } from '../../maps/imageryComparison.js';+import { MapSourceController } from '../../maps/controller.js';+import { createDefaultMapSources } from '../../maps/defaultSources.js';+import { resetPointerOwnership } from '../../data/inputOwnership.js';+import { initImageryBoxTool } from '../../ui/imageryBoxTool.js';+import {+ FOCUS_DEBOUNCE_MS,+ MODES,+ SPLIT_PUBLISH_MS,+ createRecentImageryLayer,+} from './index.js';+import {+ BOX,+ CANDIDATES,+ boxToolFakes,+ candidate,+ fakeCatalog,+ fakeController,+ fakeRenderer,+ fakeThumbnails,+ manualTimers,+ settle,+} from './testDoubles.mjs';++const NOW = new Date('2026-09-21T15:00:00Z');+const LINK_BOX = {+ west: -9780000,+ south: 3020000,+ east: -9770000,+ north: 3030000,+};+const S18 = 'S30:2026-09-18';+const L16 = 'L30:2026-09-16';+const V21 = 'VIIRS:2026-09-21';+const V15 = 'VIIRS:2026-09-15';++/**+ * A photoreal map controller with the real lease (`acquireImageryComparison`):+ * one owner, an asynchronous stack switch and a restore on release. `stuck`+ * never leaves photoreal, so the lease fails. With `subscribable`, every+ * settled switch notifies its subscribers, as `MapSourceController` does,+ * after `onSettled(id)` has moved the host.+ */+function leasingController({ stuck = false, subscribable = false } = {}) {+ const subscribers = new Set();+ const controller = {+ calls: [],+ acquisitions: 0,+ _activeId: 'photoreal',+ _generation: 0,+ onSettled: null,+ getActiveId() {+ return this._activeId;+ },+ getSwitchGeneration() {+ return this._generation;+ },+ async setStack(id) {+ this.calls.push(['setStack', id]);+ const generation = ++this._generation;+ await settle();+ if (generation !== this._generation) return { status: 'superseded' };+ if (!stuck) this._activeId = id;+ this.onSettled?.(this._activeId);+ for (const listener of [...subscribers]) listener();+ return { status: 'ready', activeId: this._activeId };+ },+ acquireImageryComparison(options) {+ this.acquisitions += 1;+ return acquireImageryComparison(this, options);+ },+ };+ /** Tell every subscriber the (unchanged) switch settled again. */+ controller.notify = () => {+ for (const listener of [...subscribers]) listener();+ };+ if (subscribable)+ controller.subscribe = (listener) => {+ subscribers.add(listener);+ return () => subscribers.delete(listener);+ };+ return controller;+}++/** The layer manager's publish hook, recording what the layer adopts. */+function fakeDataManager(layerRef) {+ const adopted = [];+ return {+ adopted,+ adoptLayerParams(id, params, options) {+ const live = layerRef.layer.getParams();+ assert.ok(+ Object.entries(params).every(([key, value]) =>+ Object.is(live[key], value),+ ),+ 'adopted params match the live params',+ );+ adopted.push([id, params, options.origin]);+ return true;+ },+ };+}++/**+ * The daily overview is off on a first run; the fixture turns it on so the+ * strip holds all four candidates unless told otherwise.+ */+function fixture({+ hostKind = 'globe',+ controller = fakeController(),+ viirs = true,+} = {}) {+ const renderer = fakeRenderer();+ const thumbnails = fakeThumbnails();+ const catalog = fakeCatalog();+ const timers = manualTimers();+ const hostState = { kind: hostKind };+ const collections = { none: null, globe: {}, tileset: {} };+ const layer = createRecentImageryLayer({+ catalog,+ renderer,+ thumbnails,+ host: () => ({+ collection: collections[hostState.kind],+ kind: hostState.kind,+ }),+ now: () => NOW,+ setTimeoutImpl: timers.setTimeoutImpl,+ clearTimeoutImpl: timers.clearTimeoutImpl,+ });+ if (viirs) layer.setSources({ viirs: true });+ const viewer = { camera: {} };+ const reasons = [];+ layer.subscribe((snapshot, reason) => reasons.push(reason));+ layer.init(viewer);+ if (controller) layer.attachMapStackController(controller);+ const dataManager = fakeDataManager({ layer });+ layer.attachDataManager(dataManager);+ const toolCalls = [];+ layer.setToolHandler(() => toolCalls.push('cancel'));+ /** Enable, select BOX and land the catalog. */+ const ready = async (candidates) => {+ layer.enable();+ layer.setBox(BOX);+ catalog.resolveLast(candidates);+ await settle();+ };+ const owned = () => renderer.getOwned();+ /** Slot keys and split directions, compactly. */+ const drapes = () => {+ const o = renderer.getOwned();+ return {+ a: o.a && `${o.a.key}|${o.a.splitDirection}`,+ b: o.b && `${o.b.key}|${o.b.splitDirection}`,+ };+ };+ return {+ layer,+ renderer,+ thumbnails,+ catalog,+ controller,+ dataManager,+ hostState,+ viewer,+ reasons,+ timers,+ toolCalls,+ ready,+ owned,+ drapes,+ snap: () => layer.getSnapshot(),+ diag: () => layer.diagnostics(),+ };+}++const settleTimes = async (count = 4) => {+ for (let i = 0; i < count; i += 1) await settle();+};++test('a refused box is loud, says its size and persists until a box succeeds; so does a tool refusal', async () => {+ const f = fixture();+ f.layer.enable();+ assert.equal(+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 }),+ false,+ );+ assert.match(f.snap().boxError, /^Box is 2,226 km wide · limit 1,000 km$/);+ assert.equal(f.snap().error, null, 'a box refusal is not a layer error');+ assert.equal(f.catalog.searches.length, 0);+ assert.equal(+ f.layer.reportBoxRefusal('Select one side of the dateline'),+ true,+ );+ assert.equal(f.layer.reportBoxRefusal(''), false);+ f.layer.setSources({ viirs: false });+ assert.equal(f.snap().boxError, 'Select one side of the dateline');+ // A share-link box spanning the world is refused too, not read as a sliver.+ f.layer.setParams({+ west: -18000000,+ south: -8000000,+ east: 18000000,+ north: 8000000,+ });+ assert.match(f.snap().boxError, /^Box is [\d,]+ km wide/);+ assert.equal(f.snap().box, null);+ assert.equal(f.layer.setBox(BOX), true);+ assert.equal(f.snap().boxError, null);+});++test('a valid box searches and previews the START HERE day alone in IMAGE mode', async () => {+ const f = fixture();+ f.layer.enable();+ f.layer.setBox(BOX);+ assert.equal(f.snap().searching, true);+ assert.equal(f.catalog.searches[0].request.days, 30);+ f.catalog.resolveLast();+ await settle();+ const snapshot = f.snap();+ assert.equal(snapshot.searching, false);+ assert.equal(snapshot.mode, 'image');+ assert.equal(snapshot.candidates.length, 4);+ assert.deepEqual(snapshot.auto, { key: S18, reason: 'clear', certain: true });+ assert.deepEqual(snapshot.recommended, { key: S18, reason: 'clear' });+ assert.equal(snapshot.focus.key, S18, 'focus starts on it');+ assert.equal(snapshot.preview.key, S18);+ assert.equal(snapshot.preview.slot, 'a');+ assert.equal(snapshot.preview.label, 'Sep 18 · Sentinel-2 · 30 m');+ assert.equal(snapshot.candidates[1].preview, true);+ const none = {+ key: null,+ candidate: null,+ label: null,+ sourceOff: false,+ drapable: false,+ };+ assert.deepEqual(snapshot.pins, { a: none, b: none });+ assert.deepEqual(snapshot.shown, { a: S18, b: null, swipe: 'none' });+ assert.deepEqual(f.drapes(), { a: `${S18}|none`, b: null });+ assert.equal(f.layer.getStats().count, 4);+ assert.ok(+ f.thumbnails.calls.some((c) => c[0] === 'ordered' && c[1].length === 4),+ );+ assert.deepEqual(+ f.dataManager.adopted.map(([, params]) => Object.keys(params)),+ [['west', 'south', 'east', 'north']],+ 'the chosen box is published',+ );+ // The same box again is a no-op; a new box aborts the running search.+ f.layer.setBox(BOX);+ assert.equal(f.catalog.searches.length, 1);+ f.layer.setBox({ ...BOX, east: -97.6 });+ f.layer.setBox({ ...BOX, east: -97.5 });+ assert.equal(f.catalog.searches[1].request.signal.aborted, true);+ f.catalog.resolveLast();+ await settle();+ assert.equal(f.snap().preview.key, S18);+});++test('the focused day is the enriched strip entry, never the raw catalog candidate', async () => {+ const f = fixture();+ await f.ready();+ f.thumbnails.setStatus(S18, 'present');+ let { focus, candidates, focusIndex } = f.snap();+ assert.equal(focus.preview, true);+ assert.equal(focus.pinned, null);+ assert.equal(focus.drapable, true);+ assert.equal(focus.thumbnail.status, 'present');+ assert.deepEqual(focus, candidates[focusIndex]);+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ f.layer.focus(1);+ ({ focus } = f.snap());+ assert.equal(focus.key, S18);+ assert.equal(focus.pinned, 'a');+ assert.equal(f.snap().candidates[2].pinned, 'b');+});++test('a catalog of partial-coverage days still yields a START HERE day, labelled partial', async () => {+ const f = fixture();+ await f.ready(+ CANDIDATES.map((c) =>+ c.product === 'VIIRS' ? c : { ...c, coverage: 'partial' },+ ),+ );+ assert.equal(f.snap().auto.reason, 'partial');+ assert.deepEqual(f.snap().recommended, { key: S18, reason: 'partial' });+});++test('IMAGE: SHOW pins a day, focus stops moving the map, a second SHOW moves the pin and unpinning drops the layer at once', async () => {+ const f = fixture();+ await f.ready();+ assert.equal(f.layer.toggleAssignment('a', L16), true);+ assert.equal(f.snap().pins.a.key, L16);+ assert.equal(f.snap().preview.key, null, 'the preview gives way');+ assert.deepEqual(f.drapes(), { a: `${L16}|none`, b: null });+ assert.equal(f.snap().focus.key, L16, 'focus follows the pin');+ // Focus no longer changes the map.+ f.thumbnails.setStatus(V15, 'present');+ f.layer.focus(3);+ assert.equal(f.timers.armed(), 0);+ assert.equal(f.layer.preview(V15), false, 'a click only focuses');+ assert.equal(f.snap().focus.key, V15);+ assert.deepEqual(f.drapes(), { a: `${L16}|none`, b: null });+ // SHOW on another day moves the pin.+ f.layer.toggleAssignment('a', S18);+ assert.deepEqual(f.drapes(), { a: `${S18}|none`, b: null });+ // SHOW again unpins; nothing replaces it until focus moves.+ assert.equal(f.layer.toggleAssignment('a', S18), true);+ assert.equal(f.snap().pins.a.key, null);+ assert.equal(f.renderer.ownedCount(), 0);+ f.layer.focus(2);+ f.timers.flush();+ assert.deepEqual(f.drapes(), { a: `${L16}|none`, b: null });+ assert.equal(f.snap().preview.key, L16);+ assert.deepEqual(+ f.dataManager.adopted.slice(1).map(([, params]) => params),+ [+ { a: L16, b: null },+ { a: S18, b: null },+ { a: null, b: null },+ ],+ );+ // Unknown, empty or off-source days cannot be pinned.+ assert.equal(f.layer.setAssignment('a', 'nope'), false);+ f.thumbnails.probe(V21, 'empty');+ assert.equal(f.layer.setAssignment('a', V21), false);+ assert.equal(f.layer.setAssignment('c', S18), false);+});++test('VS BASEMAP: the day swipes on the left with no second layer; the preview swipes too; the lease borrows Esri', async () => {+ const controller = leasingController();+ const f = fixture({ controller });+ await f.ready();+ await settleTimes();+ assert.equal(controller.getActiveId(), 'esri-imagery', 'a preview borrows');+ assert.equal(f.snap().borrowedEsri, true);+ assert.equal(f.layer.setMode('basemap'), true);+ assert.equal(f.layer.setMode('basemap'), false);+ assert.equal(f.snap().mode, 'basemap');+ assert.deepEqual(f.snap().shown, { a: S18, b: null, swipe: 'basemap' });+ assert.equal(f.snap().comparison.active, true);+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: null });+ f.layer.setAssignment('a', L16);+ assert.deepEqual(f.drapes(), { a: `${L16}|left`, b: null });+ assert.equal(f.renderer.ownedCount(), 1);+ assert.deepEqual(f.dataManager.adopted.at(-2)[1], { mode: 1 });+ // Back to IMAGE: the same pin, no divider.+ f.layer.setMode('image');+ assert.deepEqual(f.drapes(), { a: `${L16}|none`, b: null });+ assert.equal(f.snap().comparison.active, false);+ assert.deepEqual(MODES, ['image', 'basemap', 'ab']);+});++test('A / B: A pins, the focused day previews as B against it, B pins, and a day is in one slot only', async () => {+ const f = fixture();+ await f.ready();+ f.controller.lease.settle();+ await settle();+ f.layer.setMode('ab');+ assert.deepEqual(+ f.drapes(),+ { a: `${S18}|none`, b: null },+ 'the preview fills A',+ );+ f.layer.setAssignment('a', S18);+ assert.deepEqual(f.drapes(), { a: `${S18}|none`, b: null });+ assert.equal(f.snap().preview.key, null);+ // The next focus previews in B, behind the swipe.+ f.layer.focus(2);+ f.timers.flush();+ assert.equal(f.snap().preview.slot, 'b');+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: `${L16}|right` });+ assert.equal(f.snap().comparison.active, true);+ // Focus back on A's own card takes the B preview off.+ f.layer.focus(1);+ f.timers.flush();+ assert.deepEqual(f.drapes(), { a: `${S18}|none`, b: null });+ f.layer.setAssignment('b', L16);+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: `${L16}|right` });+ // Pinning B's day as A moves it: A is L16, B is empty again.+ f.layer.setAssignment('a', L16);+ assert.deepEqual([f.snap().pins.a.key, f.snap().pins.b.key], [L16, null]);+ assert.deepEqual(f.drapes(), { a: `${L16}|none`, b: null });+ f.layer.setAssignment('b', S18);+ // B alone is a single image.+ f.layer.setAssignment('a', null);+ assert.deepEqual(f.drapes(), { a: null, b: `${S18}|none` });+ // Pins survive a mode switch; B only drapes in A / B.+ f.layer.setAssignment('a', L16);+ f.layer.setMode('image');+ assert.deepEqual(f.drapes(), { a: `${L16}|none`, b: null });+ f.layer.setMode('ab');+ assert.deepEqual(f.drapes(), { a: `${L16}|left`, b: `${S18}|right` });+ assert.ok(f.renderer.peak() <= 2, 'never more than two layers');+});++test('the divider recentres on every new comparison but not while scrubbing the second day', async () => {+ const f = fixture();+ await f.ready();+ f.controller.lease.settle();+ await settle();+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ f.layer.setSplit(0.8);+ assert.equal(f.timers.armed(), 1, 'split publish is debounced');+ assert.equal([...f.timers.pending.values()][0].ms, SPLIT_PUBLISH_MS);+ f.timers.flush();+ assert.deepEqual(f.dataManager.adopted.at(-1)[1], { split: 80 });+ f.layer.setAssignment('b', null);+ assert.equal(f.snap().split, 0.8, 'one image keeps the last framing');+ f.layer.preview(L16);+ assert.equal(f.snap().shown.swipe, 'ab');+ assert.equal(f.snap().split, 0.5, 'a new comparison starts centred');+ f.layer.setSplit(0.3);+ f.thumbnails.setStatus(V15, 'present');+ f.layer.focus(3);+ f.timers.flush();+ assert.equal(f.snap().shown.b, V15);+ assert.equal(f.snap().split, 0.3, 'scrubbing B keeps the divider');+ f.layer.setMode('basemap');+ assert.equal(f.snap().split, 0.5, 'a new kind of comparison recentres');+});++test('SWAP trades the sides of a live divider, again restores, never publishes and resets on a new comparison or CLEAR', async () => {+ const f = fixture();+ await f.ready();+ f.controller.lease.settle();+ await settle();+ const directions = () => [+ f.owned().a?.splitDirection,+ f.owned().b?.splitDirection,+ ];+ // IMAGE mode: no swipe, nothing to swap.+ assert.equal(f.layer.swapSides(), false);+ assert.equal(f.snap().swapped, false);+ // VS BASEMAP: the image moves to the right half, the basemap shows left.+ f.layer.setMode('basemap');+ assert.deepEqual(directions(), ['left', undefined]);+ assert.equal(f.layer.swapSides(), true);+ assert.equal(f.snap().swapped, true);+ assert.deepEqual(directions(), ['right', undefined]);+ assert.equal(f.layer.swapSides(), true);+ assert.deepEqual(directions(), ['left', undefined]);+ // A / B: A moves right and B left; the divider position stays.+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ f.layer.setSplit(0.3);+ const adopted = f.dataManager.adopted.length;+ f.layer.swapSides();+ assert.deepEqual(directions(), ['right', 'left']);+ assert.equal(f.snap().split, 0.3);+ assert.equal(f.dataManager.adopted.length, adopted, 'nothing published');+ assert.equal('swapped' in f.layer.getParams(), false, 'not in the link');+ // Unpinning B ends the comparison; the next one starts unswapped.+ f.layer.setAssignment('b', null);+ f.layer.preview(L16);+ assert.equal(f.snap().shown.swipe, 'ab');+ assert.equal(f.snap().swapped, false, 'a new comparison is unswapped');+ assert.deepEqual(directions(), ['left', 'right']);+ f.layer.swapSides();+ f.layer.clear();+ assert.equal(f.snap().swapped, false, 'CLEAR resets it');+});++test('any image on the map holds the Esri lease; the last image cleared hands Google 3D back', async () => {+ const controller = leasingController();+ const f = fixture({ controller });+ await f.ready();+ await settleTimes();+ assert.deepEqual(controller.calls, [['setStack', 'esri-imagery']]);+ f.layer.setAssignment('a', S18);+ f.layer.clearPreview();+ await settleTimes();+ assert.equal(controller.getActiveId(), 'esri-imagery', 'still showing A');+ f.layer.setAssignment('a', null);+ assert.equal(f.renderer.ownedCount(), 0);+ await settleTimes();+ assert.equal(controller.getActiveId(), 'photoreal');+ assert.equal(f.snap().borrowedEsri, false);+ // A new image borrows again; disable hands it back.+ f.layer.preview(L16);+ await settleTimes();+ assert.equal(controller.getActiveId(), 'esri-imagery');+ f.layer.disable();+ await settleTimes();+ assert.equal(controller.getActiveId(), 'photoreal');+});++test('a refused lease is guidance and the images still drape without a swipe', async () => {+ const f = fixture({ controller: fakeController({ refuse: true }) });+ await f.ready();+ f.layer.setMode('basemap');+ assert.equal(f.snap().error, 'Comparison in use by another scene');+ assert.deepEqual(f.drapes(), { a: `${S18}|none`, b: null });+ f.layer.clearPreview();+ assert.equal(f.snap().error, null, 'nothing shown, nothing refused');+});++test('a lease that cannot reach the Esri map never shows the divider and says why', async () => {+ const f = fixture({ controller: leasingController({ stuck: true }) });+ await f.ready();+ f.layer.setMode('basemap');+ await settleTimes();+ assert.equal(f.snap().comparison.active, false);+ assert.equal(f.snap().error, 'Esri map unavailable · no swipe');+ assert.equal(f.owned().a.splitDirection, 'none');+});++test('unpin then pin before the release settles recovers the lease', async () => {+ const controller = leasingController();+ const f = fixture({ controller });+ await f.ready();+ f.layer.setMode('basemap');+ f.layer.setAssignment('a', S18);+ await settleTimes();+ assert.equal(controller.getActiveId(), 'esri-imagery');+ f.layer.setAssignment('a', null);+ assert.equal(f.diag().releasing, true);+ f.layer.setAssignment('a', L16);+ assert.equal(f.diag().lease, false, 'no lease while releasing');+ await settleTimes(8);+ assert.equal(f.diag().lease, true);+ assert.equal(f.snap().comparison.active, true);+ assert.equal(controller.getActiveId(), 'esri-imagery');+});++/**+ * A / B on Esri from Google 3D, with the host following the active stack:+ * Google 3D hides the globe (tileset host), every other stack is a globe.+ */+async function comparingOnEsri() {+ const controller = leasingController({ subscribable: true });+ const f = fixture({ controller, hostKind: 'tileset' });+ controller.onSettled = (id) => {+ f.hostState.kind = id === 'photoreal' ? 'tileset' : 'globe';+ };+ await f.ready();+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ await settleTimes(8);+ assert.equal(controller.getActiveId(), 'esri-imagery');+ assert.equal(f.snap().comparison.active, true);+ assert.deepEqual(controller.calls, [['setStack', 'esri-imagery']]);+ return { controller, f };+}++test('a manual switch to Google 3D while a day is shown takes Esri back once and the divider stays', async () => {+ const { controller, f } = await comparingOnEsri();+ // The operator picks Google 3D by hand: the layer re-leases Esri at once.+ await controller.setStack('photoreal');+ await settleTimes(8);+ assert.deepEqual(controller.calls, [+ ['setStack', 'esri-imagery'],+ ['setStack', 'photoreal'],+ ['setStack', 'esri-imagery'],+ ]);+ assert.equal(controller.getActiveId(), 'esri-imagery');+ assert.equal(f.snap().shown.swipe, 'ab');+ assert.equal(f.snap().comparison.active, true);+ assert.equal(f.snap().comparison.suspended, false);+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: `${L16}|right` });+ assert.equal(+ f.snap().notice,+ 'Imagery stays on Esri · CLEAR to use Google 3D',+ );+ assert.equal(f.snap().error, null);+ // Once per switch generation: a repeated notification is not a new+ // switch, and the re-lease's own switch landing on Google 3D (a fallback)+ // is not the operator's.+ controller.notify();+ controller._activeId = 'photoreal';+ controller.notify();+ await settleTimes(8);+ assert.equal(controller.calls.length, 3, 'no second re-lease');+ controller._activeId = 'esri-imagery';+ controller.notify();+ // Globe stacks just rebind: Esri → OSM keeps the swipe and switches nothing.+ await controller.setStack('osm');+ await settleTimes(8);+ assert.equal(controller.calls.length, 4);+ assert.equal(controller.getActiveId(), 'osm');+ assert.equal(f.snap().comparison.active, true);+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: `${L16}|right` });+});++test('CLEAR after a re-lease hands Google 3D back and does not take Esri again', async () => {+ const { controller, f } = await comparingOnEsri();+ await controller.setStack('photoreal');+ await settleTimes(8);+ assert.equal(controller.getActiveId(), 'esri-imagery');+ const acquisitions = controller.acquisitions;+ f.layer.clear();+ await settleTimes(8);+ assert.equal(controller.getActiveId(), 'photoreal');+ assert.deepEqual(controller.calls.at(-1), ['setStack', 'photoreal']);+ assert.equal(controller.calls.length, 4);+ assert.equal(controller.acquisitions, acquisitions, 'no new lease');+ assert.equal(f.diag().lease, false);+ assert.equal(f.snap().notice, 'Box and images cleared');+});++test('disable after a re-lease hands Google 3D back and does not take Esri again', async () => {+ const { controller, f } = await comparingOnEsri();+ await controller.setStack('photoreal');+ await settleTimes(8);+ const acquisitions = controller.acquisitions;+ f.layer.disable();+ await settleTimes(8);+ assert.equal(controller.getActiveId(), 'photoreal');+ assert.equal(controller.calls.length, 4);+ assert.equal(controller.acquisitions, acquisitions);+ assert.equal(f.diag().lease, false);+});++test('a re-lease refused by another owner says so, drapes without a swipe and does not loop', async () => {+ const { controller, f } = await comparingOnEsri();+ const acquire = controller.acquireImageryComparison;+ controller.acquireImageryComparison = function () {+ this.acquisitions += 1;+ throw new Error('Imagery comparison is already held by nepal');+ };+ await controller.setStack('photoreal');+ await settleTimes(8);+ assert.equal(controller.acquisitions, 2, 'one attempt');+ assert.equal(f.snap().error, 'Comparison in use by another scene');+ assert.notEqual(+ f.snap().notice,+ 'Imagery stays on Esri · CLEAR to use Google 3D',+ );+ assert.equal(f.snap().comparison.active, false);+ assert.equal(f.owned().a.kind, 'tileset');+ assert.equal(f.owned().a.splitDirection, 'none');+ // More notifications and renders never try again.+ controller.notify();+ controller.notify();+ f.layer.setAlpha(0.5);+ f.layer.setMode('basemap');+ f.layer.setMode('ab');+ await settleTimes(8);+ assert.equal(controller.acquisitions, 2);+ assert.deepEqual(controller.calls.at(-1), ['setStack', 'photoreal']);+ controller.acquireImageryComparison = acquire;+});++test('without a lease (another owner held it first) a switch to Google 3D takes nothing', async () => {+ const controller = leasingController({ subscribable: true });+ const nepal = acquireImageryComparison(controller, { owner: 'nepal' });+ await nepal.ready;+ controller.calls.length = 0;+ const f = fixture({ controller, hostKind: 'tileset' });+ await f.ready();+ f.layer.setMode('basemap');+ assert.equal(f.snap().error, 'Comparison in use by another scene');+ await controller.setStack('photoreal');+ await settleTimes(8);+ assert.deepEqual(controller.calls, [['setStack', 'photoreal']]);+ assert.equal(f.snap().error, 'Comparison in use by another scene');+});++/**+ * The real `MapSourceController` on Google 3D over the default sources, with+ * Esri tiles that can fail after it activated (`failEsriTiles`) and an OSM+ * map that never activates, so a tile fallback recovers to Google 3D.+ * Every `setStack` (the layer's, the operator's, the fallback's) is+ * recorded in `calls`.+ */+function failingMapController() {+ const listeners = new Set();+ const esriErrors = {+ addEventListener(fn) {+ listeners.add(fn);+ return () => listeners.delete(fn);+ },+ };+ const registry = createDefaultMapSources({ googleTileset: { show: true } });+ for (const source of registry.sources) {+ if (!source.imagery) continue;+ const id = source.descriptor.id;+ source.imagery =+ id === 'osm'+ ? async () => {+ throw new Error('OSM offline');+ }+ : async () => ({+ id,+ errorEvent:+ id === 'esri-imagery' ? esriErrors : { addEventListener() {} },+ });+ source.terrain = {+ id: 'keyless',+ create: async () => ({ provider: { id: 'terrain' } }),+ };+ }+ const viewer = {+ scene: {+ globe: { show: false },+ requestRender() {},+ frameState: {+ creditDisplay: {+ addStaticCredit() {},+ removeStaticCredit() {},+ },+ },+ primitives: { add() {}, remove() {} },+ },+ imageryLayers: { add() {}, remove() {} },+ };+ const controller = new MapSourceController(viewer, {+ registry,+ initialStack: 'photoreal',+ createImageryLayer: (provider) => ({ provider }),+ onError: () => {},+ });+ const calls = [];+ const setStack = controller.setStack.bind(controller);+ controller.setStack = (id, options) => {+ calls.push(id);+ return setStack(id, options);+ };+ const failEsriTiles = () => {+ for (const fn of [...listeners]) fn({});+ for (const fn of [...listeners]) fn({});+ };+ return { controller, calls, failEsriTiles };+}++for (const path of ['subscription', 'stats poll']) {+ test(`an automatic fallback to Google 3D drops the swipe instead of re-leasing Esri; a manual switch re-leases once (${path})`, async () => {+ const { controller, calls, failEsriTiles } = failingMapController();+ // Without `subscribe` the layer watches the map from the stats poll.+ const attached =+ path === 'subscription'+ ? controller+ : {+ getActiveId: () => controller.getActiveId(),+ getSwitchGeneration: () => controller.getSwitchGeneration(),+ getSwitchOrigin: () => controller.getSwitchOrigin(),+ acquireImageryComparison: (options) =>+ controller.acquireImageryComparison(options),+ };+ const f = fixture({ controller: attached, hostKind: 'tileset' });+ Object.defineProperty(f.hostState, 'kind', {+ get: () =>+ controller.getActiveId() === 'photoreal' ? 'tileset' : 'globe',+ });+ const watch = async () => {+ await settleTimes(8);+ if (path === 'stats poll') f.layer.getStats();+ await settleTimes(8);+ };+ await f.ready();+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ await watch();+ assert.equal(controller.getActiveId(), 'esri-imagery');+ assert.equal(f.snap().comparison.active, true);+ assert.deepEqual(calls, ['esri-imagery']);++ // Esri tiles fail: the controller falls back to OSM, OSM cannot+ // activate, and it recovers to Google 3D. Nobody chose Google 3D, so+ // the layer lets the lease go and shows both days without a swipe.+ failEsriTiles();+ await watch();+ assert.deepEqual(calls, ['esri-imagery', 'osm'], 'no Esri retry');+ assert.equal(controller.getActiveId(), 'photoreal');+ assert.equal(controller.getSwitchOrigin(), 'automatic');+ assert.equal(f.diag().lease, false);+ assert.equal(f.diag().host, 'tileset');+ assert.equal(f.snap().shown.swipe, 'ab');+ assert.equal(f.snap().comparison.active, false);+ assert.deepEqual(f.drapes(), { a: `${S18}|none`, b: `${L16}|none` });+ assert.equal(f.owned().a.kind, 'tileset');+ assert.equal(f.snap().error, 'Esri map unavailable · no swipe');+ assert.notEqual(+ f.snap().notice,+ 'Imagery stays on Esri · CLEAR to use Google 3D',+ );+ // More polls, renders and dead Esri listeners never retry.+ failEsriTiles();+ f.layer.setAlpha(0.5);+ f.layer.setMode('basemap');+ f.layer.setMode('ab');+ await watch();+ assert.deepEqual(calls, ['esri-imagery', 'osm']);++ // The operator picks Google 3D by hand: that is answered once.+ await controller.setStack('photoreal');+ await watch();+ await watch();+ assert.deepEqual(calls, [+ 'esri-imagery',+ 'osm',+ 'photoreal',+ 'esri-imagery',+ ]);+ assert.equal(controller.getActiveId(), 'esri-imagery');+ assert.equal(f.diag().lease, true);+ assert.equal(f.snap().comparison.active, true);+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: `${L16}|right` });+ assert.equal(+ f.snap().notice,+ 'Imagery stays on Esri · CLEAR to use Google 3D',+ );+ assert.equal(f.snap().error, null);+ controller.destroy();+ });+}++test('without a host the drapes hide and say so; the stats poll rebinds when no subscription exists', async () => {+ const f = fixture({ hostKind: 'none' });+ await f.ready();+ assert.equal(f.renderer.ownedCount(), 0);+ assert.equal(f.layer.getStats().error, NO_IMAGERY_HOST);+ assert.equal(f.snap().error, NO_IMAGERY_HOST);+ f.hostState.kind = 'tileset';+ assert.equal(f.layer.getStats().error, null);+ assert.equal(f.owned().a.kind, 'tileset');+});++test('a controller subscription moves the drape to the new host on every settled switch', async () => {+ const listeners = new Set();+ const controller = {+ ...fakeController(),+ subscribe(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ const f = fixture({ controller });+ await f.ready();+ f.hostState.kind = 'tileset';+ f.layer.getStats();+ assert.equal(+ f.owned().a.kind,+ 'globe',+ 'the poll defers to the subscription',+ );+ const before = f.reasons.length;+ for (const listener of listeners) listener();+ assert.equal(f.owned().a.kind, 'tileset');+ assert.equal(f.reasons.length, before + 1, 'the panel re-renders');+ f.hostState.kind = 'globe';+ for (const listener of listeners) listener();+ assert.equal(f.owned().a.kind, 'globe');+ const quiet = f.reasons.length;+ for (const listener of listeners) listener();+ assert.equal(f.reasons.length, quiet, 'a no-op switch is quiet');+ f.layer.destroy();+ assert.equal(listeners.size, 0);+});++test('a catalog failure is exposed and leaves nothing draped', async () => {+ const f = fixture();+ f.layer.enable();+ f.layer.setBox(BOX);+ f.catalog.searches[0].reject(new Error('CMR down'));+ await settle();+ assert.equal(f.snap().error, 'CMR down');+ assert.equal(f.snap().candidates.length, 0);+ assert.equal(f.renderer.ownedCount(), 0);+});++test('share links restore the box, both pins, the mode and a non-default split once, without publishing back', async () => {+ const f = fixture();+ f.layer.setParams({ split: 50 });+ assert.equal(f.diag().splitFromLink, false, 'a stored default is not a link');+ f.layer.setParams({+ ...LINK_BOX,+ a: S18,+ b: L16,+ mode: 2,+ split: 30,+ });+ assert.equal(f.diag().splitFromLink, true);+ f.layer.enable();+ f.catalog.resolveLast();+ await settle();+ f.controller.lease.settle();+ await settle();+ assert.equal(f.snap().mode, 'ab');+ assert.deepEqual(f.drapes(), { a: `${S18}|left`, b: `${L16}|right` });+ assert.equal(f.snap().auto, null, 'a restored pin is never auto');+ assert.equal(f.snap().focus.key, S18);+ assert.equal(f.snap().split, 0.3, 'the link framing is honoured');+ assert.equal(f.diag().splitFromLink, false, 'and consumed');+ assert.deepEqual(f.layer.getParams(), {+ ...LINK_BOX,+ a: S18,+ b: L16,+ mode: 2,+ split: 30,+ viirs: true,+ });+ assert.deepEqual(f.dataManager.adopted, [], 'a restore publishes nothing');+ // String modes and junk.+ f.layer.setParams({ mode: 'basemap' });+ assert.equal(f.snap().mode, 'basemap');+ f.layer.setParams({ mode: 7 });+ assert.equal(f.snap().mode, 'basemap');+ // A pin repeated in both slots keeps A.+ f.layer.setParams({ a: L16, b: L16, mode: 2 });+ assert.deepEqual([f.snap().pins.a.key, f.snap().pins.b.key], [L16, null]);+});++test('restored pins the catalog no longer lists are dropped and START HERE previews', async () => {+ const f = fixture();+ f.layer.setParams({ ...LINK_BOX, a: 'S30:2026-09-01', b: 'S30:2026-09-02' });+ f.layer.enable();+ f.catalog.resolveLast();+ await settle();+ assert.equal(f.snap().pins.a.key, null);+ assert.equal(f.snap().preview.key, S18);+ assert.equal(f.snap().auto.reason, 'clear');+});++test('the data-panel row carries only the two source chips', async () => {+ const f = fixture({ viirs: false });+ await f.ready();+ const { chips } = f.layer.getRowControls();+ assert.deepEqual(+ chips.map(({ id, label, active, params }) => [id, label, active, params]),+ [+ ['hls', 'MORE DETAIL · 30 m', true, { hls: false }],+ ['viirs', 'DAILY OVERVIEW · 250 m', false, { viirs: true }],+ ],+ );+ f.layer.setParams(chips[1].params);+ assert.equal(f.layer.getRowControls().chips[1].active, true);+ assert.equal(f.layer.getParams().viirs, true);+});++test('USE VIEW takes the camera rectangle and refuses a view over the cap instead of shrinking it', () => {+ const f = fixture();+ f.layer.enable();+ assert.equal(f.layer.useCurrentView(), false);+ assert.equal(+ f.snap().boxError,+ 'Point the camera at the ground to use the view',+ );+ const rad = (deg) => (deg * Math.PI) / 180;+ const view = (west, south, east, north) => () => ({+ west: rad(west),+ south: rad(south),+ east: rad(east),+ north: rad(north),+ });+ f.viewer.camera.computeViewRectangle = view(-97.8, 30.2, -97.7, 30.3);+ assert.equal(f.layer.useCurrentView(), true);+ assert.ok(Math.abs(f.snap().box.west + 97.8) < 1e-9);+ f.viewer.camera.computeViewRectangle = view(-108, 20, -88, 40);+ assert.equal(f.layer.useCurrentView(), false);+ assert.match(f.snap().boxError, /^View is 2,2\d\d km wide · limit 1,000 km$/);+ assert.equal(f.catalog.searches.length, 1, 'nothing searched');+ assert.ok(Math.abs(f.snap().box.west + 97.8) < 1e-9, 'the box is kept');+});++test('ZOOM IN: an oversized box or view flies top-down to its centre at the height whose view is 400 km wide', () => {+ const f = fixture();+ const flights = [];+ const deg = (rad) => (rad * 180) / Math.PI;+ const rad = (value) => (value * Math.PI) / 180;+ // A 1000 × 500 canvas with a 60° horizontal FOV.+ const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / 2);+ const expected = 400_000 / (2 * Math.tan(Math.PI / 6));+ let centreHit = null;+ Object.assign(f.viewer, {+ scene: {+ canvas: { clientWidth: 1000, clientHeight: 500 },+ ellipsoid: {+ cartographicToCartesian: (c) => ({ ...c, cartesian: true }),+ cartesianToCartographic: (c) => c && { ...c },+ },+ },+ });+ Object.assign(f.viewer.camera, {+ frustum: { fovy },+ flyTo: (options) => flights.push(options),+ pickEllipsoid: (position) => {+ assert.deepEqual(position, { x: 500, y: 250 }, 'the canvas centre');+ return centreHit;+ },+ });+ f.layer.enable();+ assert.equal(f.snap().zoomToFit, false);+ assert.equal(f.layer.zoomToFit(), null, 'nothing refused, nothing to fit');+ // A box over the cap: its centre.+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });+ assert.equal(f.snap().zoomToFit, true);+ const height = f.layer.zoomToFit();+ assert.ok(Math.abs(height - expected) < 1e-6, String(height));+ assert.equal(flights.length, 1);+ const [flight] = flights;+ assert.ok(Math.abs(deg(flight.destination.longitude) - 10) < 1e-9);+ assert.ok(Math.abs(deg(flight.destination.latitude) - 10) < 1e-9);+ assert.equal(flight.destination.height, height);+ assert.deepEqual(flight.orientation, {+ heading: 0,+ pitch: -Math.PI / 2,+ roll: 0,+ });+ assert.equal(flight.duration, 1.2);+ // A view over the cap: the ground under the canvas centre.+ f.viewer.camera.computeViewRectangle = () => ({+ west: rad(-108),+ south: rad(20),+ east: rad(-88),+ north: rad(40),+ });+ centreHit = { longitude: rad(-97), latitude: rad(31), height: 0 };+ assert.equal(f.layer.useCurrentView(), false);+ assert.equal(f.snap().zoomToFit, true);+ f.layer.zoomToFit();+ assert.ok(Math.abs(deg(flights[1].destination.longitude) + 97) < 1e-9);+ assert.ok(Math.abs(deg(flights[1].destination.latitude) - 31) < 1e-9);+ // Sky at the centre: the view rectangle's centre instead.+ centreHit = null;+ f.layer.useCurrentView();+ f.layer.zoomToFit();+ assert.ok(Math.abs(deg(flights[2].destination.longitude) + 98) < 1e-9);+ assert.ok(Math.abs(deg(flights[2].destination.latitude) - 30) < 1e-9);+ // The box tool's own oversized drag carries its box.+ f.layer.reportBoxRefusal('Box is 2,226 km wide · limit 1,000 km', {+ west: 0,+ south: 0,+ east: 20,+ north: 20,+ });+ assert.equal(f.snap().zoomToFit, true);+ // Other refusals and a box that succeeds offer nothing to fit.+ f.layer.reportBoxRefusal('Select one side of the dateline');+ assert.equal(f.snap().zoomToFit, false);+ f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 });+ assert.equal(f.snap().zoomToFit, false);+ assert.equal(f.layer.zoomToFit(), null);+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });+ assert.equal(f.snap().zoomToFit, true);+ f.layer.setBox(BOX);+ assert.equal(f.snap().zoomToFit, false);+ assert.equal(f.layer.zoomToFit(), null);+ assert.equal(flights.length, 3);+});++test('alpha, split and visible range notify without re-rendering the row', async () => {+ const f = fixture();+ let rowRenders = 0;+ f.layer.setRowControlsListener(() => rowRenders++);+ await f.ready();+ const rows = rowRenders;+ f.layer.setAlpha(0.4);+ assert.deepEqual(f.renderer.calls.at(-1), ['alpha', 'b', 0.4]);+ assert.equal(f.owned().a.alpha, 1, 'the fake keeps the look it was given');+ f.layer.setSplit(0.25);+ f.layer.setVisibleRange(1, 3);+ assert.equal(f.thumbnails.calls.at(-1)[2].firstVisible, 1);+ assert.equal(rowRenders, rows);+ assert.deepEqual(f.reasons.slice(-2), ['alpha', 'split']);+ f.layer.setAlpha('bad');+ assert.equal(f.snap().alpha, 0.4);+});++test('disable releases the lease, hides the drapes and cancels the tool; pins come back on enable', async () => {+ const f = fixture();+ await f.ready();+ f.layer.setMode('basemap');+ f.layer.setAssignment('a', S18);+ f.controller.lease.settle();+ await settle();+ f.layer.disable();+ await settle();+ assert.equal(f.renderer.ownedCount(), 0);+ assert.deepEqual(f.controller.calls.at(-1), ['release']);+ assert.deepEqual(f.toolCalls, ['cancel']);+ assert.equal(f.snap().enabled, false);+ f.layer.enable();+ f.catalog.resolveLast();+ await settle();+ assert.equal(f.snap().pins.a.key, S18);+ assert.equal(f.snap().shown.swipe, 'basemap');+ f.layer.destroy();+ assert.ok(f.renderer.calls.some((c) => c[0] === 'destroy'));+ assert.ok(f.thumbnails.calls.some((c) => c[0] === 'destroy'));+ assert.equal(f.layer.enable(), false);+});++test('an empty day never drapes: the automatic preview re-ranks, a pick is refused and an empty pin is unpinned', async () => {+ const f = fixture();+ await f.ready();+ const before = f.reasons.length;+ f.thumbnails.probe(S18, 'empty');+ assert.equal(f.snap().preview.key, L16);+ assert.equal(f.snap().auto.reason, 'cloudy');+ assert.equal(f.owned().a.key, L16);+ assert.deepEqual(f.reasons.slice(before), ['thumbnail', 'state']);+ f.thumbnails.probe(V15, 'empty');+ f.layer.setShowUnavailable(true);+ assert.equal(f.layer.preview(V15), false);+ assert.equal(f.diag().following, null, 'an empty day is not followed');+ assert.equal(f.owned().a.key, L16, 'the previous preview stays');+ // A restored pin that resolves empty is unpinned.+ const g = fixture();+ g.layer.setParams({ ...LINK_BOX, a: S18, b: L16, mode: 2 });+ g.layer.enable();+ g.catalog.resolveLast();+ await settle();+ assert.equal(g.renderer.ownedCount(), 2);+ g.thumbnails.probe(S18, 'empty');+ assert.equal(g.snap().pins.a.key, null);+ assert.deepEqual(g.drapes(), { a: null, b: `${L16}|none` });+});++test('an automatic overview that probes empty hands over to the next ranked day', async () => {+ const f = fixture();+ await f.ready([CANDIDATES[0], CANDIDATES[3]]);+ assert.equal(f.diag().following, V21, 'the newest overview is followed');+ f.thumbnails.probe(V21, 'empty');+ assert.equal(f.diag().following, V15, 'the next overview takes over');+ assert.equal(f.snap().preview.pending, V15);+ f.thumbnails.probe(V15, 'present');+ assert.deepEqual(f.drapes(), { a: `${V15}|none`, b: null });+});++test('a pinned day still being probed drapes once the probe says present', async () => {+ const f = fixture();+ f.layer.setParams({ ...LINK_BOX, a: V21, mode: 0 });+ f.layer.enable();+ f.catalog.resolveLast();+ await settle();+ assert.equal(f.snap().pins.a.key, V21);+ assert.equal(f.renderer.ownedCount(), 0, 'unknown days never drape');+ f.thumbnails.probe(V21, 'present');+ assert.deepEqual(f.drapes(), { a: `${V21}|none`, b: null });+});++/** Thirty daily VIIRS days, newest first, from NOW back. */+const dailyViirs = () =>+ Array.from({ length: 30 }, (_, back) =>+ candidate(+ 'VIIRS',+ new Date(Date.UTC(2026, 8, 21 - back)).toISOString().slice(0, 10),+ ),+ );++test('restored pins outside the visible strip window are probed and swipe once present', async () => {+ const f = fixture();+ const days = dailyViirs();+ const newest = days[0].key;+ const older = days[25].key;+ assert.equal(older, 'VIIRS:2026-08-27');+ f.layer.setVisibleRange(0, 5);+ f.layer.setParams({ ...LINK_BOX, a: newest, b: older, mode: 2 });+ f.layer.enable();+ f.catalog.resolveLast(days);+ await settle();+ assert.ok(+ f.thumbnails.requested.includes(older),+ 'the offscreen B pin is probed',+ );+ assert.deepEqual(+ f.thumbnails.requests.find(([key]) => key === older),+ [older, 0],+ 'at the focused card priority',+ );+ f.thumbnails.probeRequested('present');+ f.controller.lease.settle();+ await settle();+ assert.deepEqual(f.snap().shown, { a: newest, b: older, swipe: 'ab' });+ assert.deepEqual(f.drapes(), { a: `${newest}|left`, b: `${older}|right` });+});++test('pinning an offscreen day probes it at once', async () => {+ const f = fixture();+ const days = dailyViirs();+ const older = days[25].key;+ f.layer.setVisibleRange(0, 5);+ await f.ready(days);+ f.layer.setMode('ab');+ assert.ok(!f.thumbnails.requested.includes(older), 'not probed yet');+ assert.equal(f.layer.setAssignment('b', older), true);+ assert.deepEqual(f.thumbnails.requests.at(-1), [older, 0]);+ f.thumbnails.probe(older, 'present');+ assert.equal(f.snap().shown.b, older);+});++test('turning a source off hides its cards and drapes, disarms its pending preview and labels its pins "Source off"', async () => {+ const f = fixture();+ await f.ready();+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.thumbnails.setStatus(V21, 'present');+ f.layer.setAssignment('b', V21);+ f.layer.setAssignment('b', null);+ f.layer.focus(2);+ assert.equal(f.diag().pending, L16);+ assert.equal(f.layer.setSources({ hls: false }), true);+ assert.equal(f.diag().pending, undefined);+ f.timers.flush();+ const snapshot = f.snap();+ assert.deepEqual(+ snapshot.candidates.map((c) => c.key),+ [V21, V15],+ );+ assert.equal(snapshot.pins.a.sourceOff, true);+ assert.equal(f.owned().a, null);+ assert.equal(f.layer.getParams().a, S18, 'the link keeps it');+ f.layer.setSources({ hls: true });+ assert.equal(f.owned().a.key, S18);+ assert.equal(f.layer.setSources({ hls: true }), false);+});++test('arrow focus previews the focused present day after the 250 ms debounce; only the last of a burst drapes', async () => {+ const f = fixture();+ await f.ready();+ f.thumbnails.setStatus(V15, 'present');+ f.layer.focus(2);+ assert.equal(f.snap().preview.key, S18, 'not yet');+ assert.equal(f.snap().preview.pending, L16);+ assert.equal(f.snap().candidates[2].pending, true);+ assert.equal([...f.timers.pending.values()][0].ms, FOCUS_DEBOUNCE_MS);+ assert.equal(FOCUS_DEBOUNCE_MS, 250);+ f.layer.focus(3);+ assert.equal(f.timers.armed(), 1, 'a single timer');+ f.timers.flush();+ assert.equal(f.snap().preview.key, V15);+ assert.equal(f.snap().auto, null);+ assert.equal(f.renderer.ownedCount(), 1, 'never a second layer');+ // Focus back on the previewed day disarms everything.+ f.layer.focus(2);+ f.layer.focus(3);+ assert.equal(f.timers.armed(), 0);+ assert.equal(f.diag().pending, undefined);+});++test('an unprobed day never drapes; a followed one previews once the probe says present, unless focus moved on', async () => {+ const f = fixture();+ await f.ready();+ f.layer.focus(0);+ assert.equal(f.timers.armed(), 0, 'no debounce for an unconfirmed day');+ assert.equal(f.diag().following, V21);+ f.thumbnails.probe(V21, 'present');+ assert.equal(f.snap().preview.key, V21);+ assert.equal(f.diag().following, null);+ // A click on an unknown day is followed too; moving focus away forgets it.+ assert.equal(f.layer.preview(V15), false);+ assert.equal(f.diag().following, V15);+ f.layer.focus(2);+ f.timers.flush();+ f.thumbnails.probe(V15, 'present');+ assert.equal(f.snap().preview.key, L16, 'not followed');+});++test('a card click previews at once; a repeat click is a no-op and focus follows', async () => {+ const f = fixture();+ await f.ready();+ const shows = () => f.renderer.calls.filter((c) => c[0] === 'show').length;+ const before = shows();+ assert.equal(f.layer.preview(L16), true);+ assert.equal(f.snap().focus.key, L16);+ assert.equal(f.owned().a.key, L16);+ f.layer.preview(L16);+ assert.equal(shows(), before + 1, 'no redraw');+ assert.equal(f.layer.preview('nope'), false);+});++test('Escape order: clearPreview takes the preview off and keeps pins; nothing to clear says so', async () => {+ const f = fixture();+ await f.ready();+ assert.equal(f.layer.clearPreview(), true);+ assert.equal(f.renderer.ownedCount(), 0);+ assert.equal(f.snap().preview.key, null);+ assert.equal(f.layer.clearPreview(), false);+ f.layer.setAssignment('a', S18);+ assert.equal(f.layer.clearPreview(), false, 'a pin is not a preview');+ assert.equal(f.owned().a.key, S18);+ // A preview still on its way counts.+ f.layer.setMode('ab');+ f.layer.focus(2);+ assert.equal(f.layer.clearPreview(), true);+ assert.equal(f.timers.armed(), 0);+});++test('CLEAR forgets the box, pins, preview, pending pick, opacity, split and the tool; mode and sources survive', async () => {+ const f = fixture();+ await f.ready();+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAlpha(0.3);+ f.layer.setSplit(0.2);+ f.layer.setSources({ viirs: false });+ f.layer.focus(1);+ f.layer.clear();+ const snapshot = f.snap();+ assert.deepEqual(+ [+ snapshot.box,+ snapshot.pins.a.key,+ snapshot.pins.b.key,+ snapshot.preview.key,+ snapshot.alpha,+ snapshot.split,+ snapshot.mode,+ ],+ [null, null, null, null, 1, 0.5, 'ab'],+ );+ assert.equal(snapshot.notice, 'Box and images cleared');+ assert.equal(snapshot.sources.viirs, false);+ assert.equal(f.renderer.ownedCount(), 0);+ assert.equal(f.timers.armed(), 0);+ assert.deepEqual(f.toolCalls, ['cancel']);+ assert.deepEqual(f.dataManager.adopted.at(-1)[1], {+ west: null,+ south: null,+ east: null,+ north: null,+ a: null,+ b: null,+ split: 50,+ });+});++test('confirmed-empty days hide behind the toggle and focus keeps its key or moves to the nearest older card', async () => {+ const f = fixture();+ await f.ready();+ f.layer.focus(2);+ f.thumbnails.probe(L16, 'empty');+ assert.deepEqual(+ f.snap().candidates.map((c) => c.key),+ [V21, S18, V15],+ );+ assert.equal(f.snap().hiddenCount, 1);+ assert.equal(f.snap().focus.key, V15, 'ties go older');+ f.layer.setShowUnavailable(true);+ assert.equal(f.snap().candidates.length, 4);+ assert.equal(f.snap().hiddenCount, 0);+ assert.equal(f.snap().focus.key, V15, 'same key kept');+ assert.equal(f.snap().candidates[2].drapable, false);+});++test('a new box takes the old drapes down at once; pins the new catalog still lists survive', async () => {+ const f = fixture();+ await f.ready();+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ f.layer.setBox({ ...BOX, north: 30.4 });+ assert.equal(f.renderer.ownedCount(), 0, 'down before the search lands');+ f.catalog.resolveLast();+ await settle();+ assert.equal(f.snap().shown.swipe, 'ab');+ assert.equal(f.renderer.ownedCount(), 2);+});++test('with SELECT BOX armed, Escape clears the preview first and the next Escape cancels the tool', async () => {+ resetPointerOwnership();+ const f = fixture();+ const fakes = boxToolFakes();+ const cancels = [];+ const tool = initImageryBoxTool({+ viewer: fakes.viewer,+ cesium: fakes.cesium,+ pickWorld: fakes.pickWorld,+ documentRef: fakes.documentRef,+ onBox: (box) => f.layer.setBox(box),+ onCancel: (reason) => cancels.push(reason),+ onActive: (active) => f.layer.setToolActive(active),+ // The wiring in src/app/tools.js.+ onEscape: () => f.layer.clearPreview(),+ });+ await f.ready();+ assert.equal(tool.start(), true);+ fakes.key('Escape');+ assert.equal(f.snap().preview.key, null, 'Escape clears the preview');+ assert.equal(tool.isActive(), true, 'and leaves SELECT BOX armed');+ fakes.key('Escape');+ assert.equal(tool.isActive(), false);+ assert.deepEqual(cancels, ['escape']);+ assert.equal(f.snap().toolActive, false);+ await tool.destroy();+});diff --git a/src/layers/recentImagery/model.js b/src/layers/recentImagery/model.jsnew file mode 100644index 000000000..23f503e9e--- /dev/null+++ b/src/layers/recentImagery/model.js@@ -0,0 +1,613 @@+/**+ * Pure domain model for the Recent Imagery layer: products, the selection box,+ * per-day candidates, ranking and the keyless URL builders. No DOM, no Cesium,+ * no network.+ */++/** How far back the catalog looks, in UTC days. */+export const CATALOG_DAYS = 30;++const MAX_BOX_SIDE_KM = 1000;+/** ZOOM IN lands where the top-down view is this wide, well inside the cap. */+const FIT_VIEW_KM = 400;+const FIT_HEIGHT_KM = Object.freeze({ min: 5, max: 400 });+/** GIBS EPSG:3857 tiles do not exist beyond the Web-Mercator limit. */+const MERCATOR_LAT_LIMIT = 85.0511;+const MAX_CLOUD_FOR_CLEAR = 20;+const PIN_BOX_SIDE_KM = 10;+const WVS_ENDPOINT = 'https://wvs.earthdata.nasa.gov/api/v1/snapshot';+const KM_PER_DEG_LAT = 111.32;+const QUANTUM = 100000;+const DAY_MS = 86_400_000;+const PRODUCT_ORDER = ['S30', 'L30', 'VIIRS'];+const MONTHS = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');++/**+ * Keyless, browser-direct imagery products. HLS products are searched via+ * CMR; the VIIRS overview is a daily global mosaic with no granule catalog.+ * `source` is the on/off group the row chips toggle.+ */+export const PRODUCTS = Object.freeze({+ S30: Object.freeze({+ label: 'HLS S30',+ name: 'Sentinel-2',+ source: 'hls',+ sensor: 'Sentinel-2 via HLS',+ resolutionM: 30,+ gibsLayer: 'HLS_S30_Nadir_BRDF_Adjusted_Reflectance',+ maxLevel: 12,+ format: 'png',+ cmrCollection: 'C2021957295-LPCLOUD',+ overview: false,+ }),+ L30: Object.freeze({+ label: 'HLS L30',+ name: 'Landsat 8/9',+ source: 'hls',+ sensor: 'Landsat 8/9 via HLS',+ resolutionM: 30,+ gibsLayer: 'HLS_L30_Nadir_BRDF_Adjusted_Reflectance',+ maxLevel: 12,+ format: 'png',+ cmrCollection: 'C2021957657-LPCLOUD',+ overview: false,+ }),+ VIIRS: Object.freeze({+ label: 'VIIRS',+ name: 'Daily overview',+ source: 'viirs',+ sensor: 'VIIRS NOAA-21',+ resolutionM: 250,+ gibsLayer: 'VIIRS_NOAA21_CorrectedReflectance_TrueColor',+ maxLevel: 9,+ format: 'jpg',+ cmrCollection: null,+ overview: true,+ }),+});++const finite = (value) => typeof value === 'number' && Number.isFinite(value);+const toRadians = (degrees) => (degrees * Math.PI) / 180;+const pad2 = (value) => String(value).padStart(2, '0');++/**+ * Coerce a box to `{ west, south, east, north }` with south ≤ north. West and+ * east are not swapped: west > east crosses the dateline and `validateBox`+ * rejects it. Null when any edge is nonfinite.+ */+function normalizeBox(box) {+ if (!box || typeof box !== 'object') return null;+ const [west, south, east, north] = [+ box.west,+ box.south,+ box.east,+ box.north,+ ].map(Number);+ if (![west, south, east, north].every(Number.isFinite)) return null;+ return {+ west,+ south: Math.min(south, north),+ east,+ north: Math.max(south, north),+ };+}++/**+ * Side lengths of a box in km: the box's own longitude span (never the+ * shorter way round the globe) at its mid-latitude, and its latitude span.+ * @param {object} box Degrees box.+ * @returns {{ width: number, height: number }}+ */+export function boxSideKm(box) {+ const normalized = normalizeBox(box);+ if (!normalized) return { width: NaN, height: NaN };+ const midLat = (normalized.south + normalized.north) / 2;+ return {+ width:+ (normalized.east - normalized.west) *+ KM_PER_DEG_LAT *+ Math.cos(toRadians(midLat)),+ height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,+ };+}++const refuse = (reason, message) => ({ ok: false, reason, message });++/**+ * Validate a selection box for the catalog and the tile providers.+ * @param {object} box Degrees box.+ * @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}+ */+export function validateBox(box) {+ const normalized = normalizeBox(box);+ if (!normalized) return refuse('invalid', 'Box edges must be finite');+ const { west, south, east, north } = normalized;+ if (Math.abs(west) > 180 || Math.abs(east) > 180)+ return refuse('invalid', 'Longitudes must be within ±180°');+ if (west > east) return refuse('dateline', 'Select one side of the dateline');+ if (+ Math.abs(south) > MERCATOR_LAT_LIMIT ||+ Math.abs(north) > MERCATOR_LAT_LIMIT+ )+ return refuse(+ 'polar',+ `Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,+ );+ if (east === west || north === south)+ return refuse('degenerate', 'Box must enclose an area');+ const { width, height } = boxSideKm(normalized);+ if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM)+ return refuse('too-large', tooLargeMessage(Math.max(width, height)));+ return { ok: true, box: normalized };+}++const formatKm = (km) => Math.round(Number(km) || 0).toLocaleString('en-US');++// One short line each: the panel's hint says what to do about it.+function tooLargeMessage(sideKm) {+ return `Box is ${formatKm(sideKm)} km wide · limit ${formatKm(MAX_BOX_SIDE_KM)} km`;+}++/** The refusal for USE VIEW when the camera sees more than the cap allows. */+export function viewTooLargeMessage(sideKm) {+ return `View is ${formatKm(sideKm)} km wide · limit ${formatKm(MAX_BOX_SIDE_KM)} km`;+}++/**+ * The camera height, in metres, at which a top-down view is `FIT_VIEW_KM`+ * wide: the horizontal half-angle is atan(tan(fovy / 2) · width / height).+ * Clamped to 5–400 km; without a canvas or FOV, a square 60° view.+ * @param {{ width?: number, height?: number, fovy?: number }} view Canvas size in px, vertical FOV in radians.+ * @returns {number}+ */+export function fitViewHeightM({ width, height, fovy } = {}) {+ const aspect = Number(width) / Number(height);+ const valid =+ Number.isFinite(aspect) && aspect > 0 && fovy > 0 && fovy < Math.PI;+ const halfWidth = valid ? Math.tan(fovy / 2) * aspect : Math.tan(Math.PI / 6);+ const km = FIT_VIEW_KM / (2 * halfWidth);+ return Math.min(FIT_HEIGHT_KM.max, Math.max(FIT_HEIGHT_KM.min, km)) * 1000;+}++/**+ * The centre of a box that does not cross the dateline, in degrees.+ * @param {object} box Degrees box.+ * @returns {{ lon: number, lat: number } | null}+ */+export function boxCentre(box) {+ const normalized = normalizeBox(box);+ if (!normalized) return null;+ return {+ lon: (normalized.west + normalized.east) / 2,+ lat: (normalized.south + normalized.north) / 2,+ };+}++/**+ * A square box centred on a pin, `sideKm` on the ground (the east–west extent+ * widens by 1/cos(lat)); null when the result would not validate.+ * @param {number} lon Degrees.+ * @param {number} lat Degrees.+ * @param {number} [sideKm]+ * @returns {object | null}+ */+export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) {+ if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0)+ return null;+ const cosLat = Math.cos(toRadians(lat));+ if (cosLat <= 0) return null;+ const halfLat = sideKm / 2 / KM_PER_DEG_LAT;+ const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat);+ const clampLat = (value) =>+ Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value));+ const result = validateBox({+ west: lon - halfLon,+ south: clampLat(lat - halfLat),+ east: lon + halfLon,+ north: clampLat(lat + halfLat),+ });+ return result.ok ? result.box : null;+}++function mapBox(box, fn) {+ if (!box || typeof box !== 'object') return null;+ return normalizeBox({+ west: fn(box.west),+ south: fn(box.south),+ east: fn(box.east),+ north: fn(box.north),+ });+}++/** Degrees box from a radians rectangle (Cesium `Rectangle` shape). */+export function boxFromRectangle(rectangle) {+ return mapBox(rectangle, (radians) => (Number(radians) * 180) / Math.PI);+}++/** Degrees box → signed integers at degrees × 100000 (the share-link form). */+export function quantizeBox(box) {+ return mapBox(normalizeBox(box), (value) => Math.round(value * QUANTUM));+}++/** Inverse of `quantizeBox`. */+export function dequantizeBox(ints) {+ return mapBox(ints, (value) => Number(value) / QUANTUM);+}++function isValidDay(day) {+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day));+ if (!match) return false;+ const time = Date.UTC(+ Number(match[1]),+ Number(match[2]) - 1,+ Number(match[3]),+ );+ return (+ Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === day+ );+}++/**+ * UTC calendar day (`YYYY-MM-DD`) of an ISO timestamp, Date or day string;+ * null when unparseable or not a real day.+ * @param {string | number | Date} value+ * @returns {string | null}+ */+export function utcDay(value) {+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value))+ return isValidDay(value) ? value : null;+ const time = value instanceof Date ? value.getTime() : Date.parse(value);+ return Number.isFinite(time)+ ? new Date(time).toISOString().slice(0, 10)+ : null;+}++/** `Sep 18` for a `YYYY-MM-DD` day; '' otherwise. */+export function shortDay(day) {+ const match = /^\d{4}-(\d{2})-(\d{2})$/.exec(String(day || ''));+ return match ? `${MONTHS[Number(match[1]) - 1]} ${Number(match[2])}` : '';+}++/** `17:12` (UTC) for an ISO timestamp; '' when unparseable. */+export function hhmm(iso) {+ const time = Date.parse(iso);+ if (!Number.isFinite(time)) return '';+ const date = new Date(time);+ return `${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;+}++/** Candidate key: `PRODUCT:YYYY-MM-DD`. */+export function candidateKey(product, day) {+ return `${product}:${day}`;+}++/** Split a candidate key; null when the product is unknown or the day invalid. */+export function parseCandidateKey(key) {+ const match = /^(S30|L30|VIIRS):(\d{4}-\d{2}-\d{2})$/.exec(String(key));+ if (!match || !isValidDay(match[2])) return null;+ return { product: match[1], day: match[2] };+}++const cloudOf = (granule) => (finite(granule?.cloud) ? granule.cloud : null);++function buildCandidate(product, day, granules) {+ const clouds = granules.map(cloudOf).filter((value) => value !== null);+ const starts = granules+ .map((granule) => Date.parse(granule.timeStart))+ .filter(Number.isFinite);+ const ends = granules+ .map((granule) => Date.parse(granule.timeEnd ?? granule.timeStart))+ .filter(Number.isFinite);+ return {+ key: candidateKey(product, day),+ product,+ day,+ granules,+ cloud: clouds.length+ ? { min: Math.min(...clouds), max: Math.max(...clouds) }+ : null,+ timeRange:+ starts.length && ends.length+ ? {+ start: new Date(Math.min(...starts)).toISOString(),+ end: new Date(Math.max(...ends)).toISOString(),+ }+ : null,+ availability: granules.length ? 'present' : 'empty',+ coverage: 'unknown',+ };+}++/**+ * Group granules into one candidate per product and UTC day of `timeStart`,+ * newest first. Granules without a known product or start time are dropped.+ * @param {Array<object>} granules+ * @returns {Array<object>}+ */+export function groupGranulesByDay(granules) {+ const buckets = new Map();+ for (const granule of Array.isArray(granules) ? granules : []) {+ const day = utcDay(granule?.timeStart);+ if (!PRODUCTS[granule?.product] || !day) continue;+ const key = candidateKey(granule.product, day);+ if (!buckets.has(key))+ buckets.set(key, { product: granule.product, day, granules: [] });+ buckets.get(key).granules.push(granule);+ }+ return mergeCandidates([+ [...buckets.values()].map(({ product, day, granules: list }) =>+ buildCandidate(product, day, list),+ ),+ ]);+}++/**+ * One VIIRS overview candidate per UTC day for the last `days` days, today+ * first. Availability stays unknown until the thumbnail probe answers;+ * coverage is full because the overview is a global mosaic.+ * @param {string | Date} todayIso+ * @param {number} [days]+ * @returns {Array<object>}+ */+export function viirsCandidates(todayIso, days = CATALOG_DAYS) {+ const today = utcDay(todayIso);+ if (!today) return [];+ const start = Date.parse(`${today}T00:00:00Z`);+ const out = [];+ for (let i = 0; i < Math.max(0, Math.trunc(days)); i += 1) {+ const day = new Date(start - i * DAY_MS).toISOString().slice(0, 10);+ out.push({+ key: candidateKey('VIIRS', day),+ product: 'VIIRS',+ day,+ granules: [],+ cloud: null,+ timeRange: null,+ availability: 'unknown',+ coverage: 'full',+ });+ }+ return out;+}++/**+ * Merge candidate lists newest day first, then S30, L30, VIIRS; the first+ * occurrence of a key wins.+ * @param {Array<Array<object>>} lists+ * @returns {Array<object>}+ */+export function mergeCandidates(lists) {+ const byKey = new Map();+ for (const list of lists) {+ for (const candidate of list || []) {+ if (candidate?.key && !byKey.has(candidate.key))+ byKey.set(candidate.key, candidate);+ }+ }+ return [...byKey.values()].sort((a, b) =>+ a.day !== b.day+ ? a.day < b.day+ ? 1+ : -1+ : PRODUCT_ORDER.indexOf(a.product) - PRODUCT_ORDER.indexOf(b.product),+ );+}++function pointInPolygon(lon, lat, ring) {+ let inside = false;+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {+ const [xi, yi] = ring[i];+ const [xj, yj] = ring[j];+ const crosses =+ yi > lat !== yj > lat &&+ lon < ((xj - xi) * (lat - yi)) / (yj - yi || Number.EPSILON) + xi;+ if (crosses) inside = !inside;+ }+ return inside;+}++/**+ * How much of the box a candidate's granule footprints cover, sampled at the+ * four corners and the centre: `full`, `partial`, or `unknown` without+ * footprints.+ * @param {object} candidate+ * @param {object} box Degrees box.+ * @returns {'full' | 'partial' | 'unknown'}+ */+export function coverageFor(candidate, box) {+ const normalized = normalizeBox(box);+ const footprints = (candidate?.granules || [])+ .map((granule) => granule?.footprint)+ .filter((ring) => Array.isArray(ring) && ring.length >= 3);+ if (!normalized || !footprints.length) return 'unknown';+ const { west, south, east, north } = normalized;+ const samples = [+ [west, south],+ [east, south],+ [east, north],+ [west, north],+ [(west + east) / 2, (south + north) / 2],+ ];+ return samples.every(([lon, lat]) =>+ footprints.some((ring) => pointInPolygon(lon, lat, ring)),+ )+ ? 'full'+ : 'partial';+}++/**+ * Pick the START HERE day. Coverage first: a present HLS day that covers the+ * whole box (`full`, or `unknown` without footprints) beats a newer sliver at+ * the box edge, which changes none of the frame when draped. Within a tier+ * the newest day whose granules ALL have known cloud ≤ `maxCloud` wins+ * (`clear`), else the newest (`cloudy`); only slivers left → `partial`; else+ * the newest non-empty VIIRS day (`overview`). `certain` is false when the+ * catalog was truncated.+ * @param {Array<object>} candidates+ * @param {{ maxCloud?: number, truncated?: boolean }} [options]+ * @returns {{ candidate: object | null, reason: 'clear' | 'cloudy' | 'partial' | 'overview' | null, certain: boolean }}+ */+export function rankLatest(+ candidates,+ { maxCloud = MAX_CLOUD_FOR_CLEAR, truncated = false } = {},+) {+ const sorted = mergeCandidates([candidates]);+ const certain = !truncated;+ const present = (c) => c.availability !== 'empty';+ const hlsDay = (c) =>+ PRODUCTS[c.product] &&+ !PRODUCTS[c.product].overview &&+ present(c) &&+ c.granules.length > 0;+ const coversBox = (c) => c.coverage !== 'partial';+ const clearSky = (c) =>+ c.granules.every((granule) => {+ const cloud = cloudOf(granule);+ return cloud !== null && cloud <= maxCloud;+ });+ const tiers = [+ [(c) => hlsDay(c) && coversBox(c) && clearSky(c), 'clear'],+ [(c) => hlsDay(c) && coversBox(c), 'cloudy'],+ [(c) => hlsDay(c) && clearSky(c), 'partial'],+ [hlsDay, 'partial'],+ [(c) => c.product === 'VIIRS' && present(c), 'overview'],+ ];+ for (const [matches, reason] of tiers) {+ const candidate = sorted.find(matches);+ if (candidate) return { candidate, reason, certain };+ }+ return { candidate: null, reason: null, certain };+}++function daysAgoLabel(day, now) {+ const today = utcDay(now);+ if (!today) return null;+ const delta = Math.round(+ (Date.parse(`${today}T00:00:00Z`) - Date.parse(`${day}T00:00:00Z`)) /+ DAY_MS,+ );+ if (delta <= 0) return 'today';+ return delta === 1 ? 'yesterday' : `${delta} days ago`;+}++function cloudLabel(cloud) {+ if (!cloud) return 'cloud unknown';+ const min = Math.round(cloud.min);+ const max = Math.round(cloud.max);+ return min === max ? `${min}% scene cloud` : `${min}–${max}% scene cloud`;+}++/**+ * One-line UTC readout, e.g.+ * `Sep 18, 2026 17:12Z · 3 days ago · Sentinel-2 via HLS · 30 m · 12% scene cloud`.+ * @param {object} candidate+ * @param {string | number | Date} [now]+ * @returns {string}+ */+export function formatCandidateReadout(candidate, now = new Date()) {+ const product = PRODUCTS[candidate?.product];+ if (!product || !candidate?.day) return '';+ const [y, m, d] = candidate.day.split('-').map(Number);+ let when = `${MONTHS[m - 1]} ${d}, ${y}`;+ if (candidate.timeRange?.start) {+ const start = hhmm(candidate.timeRange.start);+ const end = candidate.timeRange.end ? hhmm(candidate.timeRange.end) : start;+ when +=+ (candidate.granules?.length || 0) > 1 && end !== start+ ? ` ${start}–${end}Z`+ : ` ${start}Z`;+ }+ const parts = [when];+ const ago = daysAgoLabel(candidate.day, now);+ if (ago) parts.push(ago);+ parts.push(product.sensor, `${product.resolutionM} m`);+ if (product.overview) parts.push('overview');+ parts.push(cloudLabel(candidate.cloud));+ return parts.join(' · ');+}++/**+ * GIBS WMTS REST template with `{s}`, `{z}`, `{y}`, `{x}` placeholders (y+ * precedes x in the GIBS path).+ * @param {string} product+ * @param {string} day `YYYY-MM-DD`+ * @returns {string}+ */+export function gibsTemplate(product, day) {+ const spec = PRODUCTS[product];+ if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);+ return `https://gibs-{s}.earthdata.nasa.gov/wmts/epsg3857/best/${spec.gibsLayer}/default/${day}/GoogleMapsCompatible_Level${spec.maxLevel}/{z}/{y}/{x}.${spec.format}`;+}++/**+ * Worldview Snapshots URL for a thumbnail or export. EPSG:4326 BBOX order is+ * lat,lon: `south,west,north,east`.+ * @param {{ product: string, day: string, box: object, width: number, height: number, format?: string }} request+ * @returns {string}+ */+export function wvsSnapshotUrl({+ product,+ day,+ box,+ width,+ height,+ format = 'image/png',+}) {+ const spec = PRODUCTS[product];+ const normalized = normalizeBox(box);+ if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);+ if (!normalized) throw new TypeError('A finite box is required');+ const bbox = [+ normalized.south,+ normalized.west,+ normalized.north,+ normalized.east,+ ]+ .map((value) => String(Number(value.toFixed(6))))+ .join(',');+ return (+ `${WVS_ENDPOINT}?REQUEST=GetSnapshot&LAYERS=${spec.gibsLayer}` ++ `&CRS=EPSG:4326&TIME=${day}&BBOX=${bbox}` ++ `&WIDTH=${Math.round(width)}&HEIGHT=${Math.round(height)}&FORMAT=${format}`+ );+}++/**+ * Thumbnail load order: the focused card (clamped into the visible range),+ * the visible cards outward from it, then `extra` cards beyond each edge.+ * @param {number} focusIndex+ * @param {number} firstVisible+ * @param {number} lastVisible+ * @param {number} total+ * @param {number} [extra]+ * @returns {number[]}+ */+export function thumbnailOrder(+ focusIndex,+ firstVisible,+ lastVisible,+ total,+ extra = 2,+) {+ const count = Math.max(0, Math.trunc(total));+ if (!count) return [];+ const clamp = (value) => Math.max(0, Math.min(count - 1, Math.trunc(value)));+ const first = clamp(Math.min(firstVisible, lastVisible));+ const last = clamp(Math.max(firstVisible, lastVisible));+ const focus = Math.max(first, Math.min(last, clamp(focusIndex)));+ const order = [];+ const push = (index) => {+ if (index >= 0 && index < count && !order.includes(index))+ order.push(index);+ };+ push(focus);+ for (let step = 1; step <= last - first; step += 1) {+ if (focus + step <= last) push(focus + step);+ if (focus - step >= first) push(focus - step);+ }+ for (let step = 1; step <= Math.max(0, Math.trunc(extra)); step += 1) {+ push(last + step);+ push(first - step);+ }+ return order;+}diff --git a/src/layers/recentImagery/model.test.mjs b/src/layers/recentImagery/model.test.mjsnew file mode 100644index 000000000..7de9e0e7c--- /dev/null+++ b/src/layers/recentImagery/model.test.mjs@@ -0,0 +1,439 @@+import test from 'node:test';+import assert from 'node:assert/strict';++import {+ boxFromPin,+ boxFromRectangle,+ boxSideKm,+ coverageFor,+ boxCentre,+ dequantizeBox,+ fitViewHeightM,+ formatCandidateReadout,+ gibsTemplate,+ groupGranulesByDay,+ mergeCandidates,+ parseCandidateKey,+ quantizeBox,+ rankLatest,+ shortDay,+ thumbnailOrder,+ utcDay,+ validateBox,+ viewTooLargeMessage,+ viirsCandidates,+ wvsSnapshotUrl,+} from './model.js';+import { BOX } from './testDoubles.mjs';++function granule(overrides = {}) {+ return {+ id: 'g',+ product: 'S30',+ timeStart: '2026-09-18T17:12:00.000Z',+ timeEnd: '2026-09-18T17:12:30.000Z',+ cloud: 12,+ footprint: null,+ ...overrides,+ };+}++function hls(product, day, clouds, extra = {}) {+ const granules = clouds.map((cloud, index) =>+ granule({+ id: `${product}-${day}-${index}`,+ product,+ timeStart: `${day}T17:1${index}:00.000Z`,+ timeEnd: `${day}T17:1${index}:30.000Z`,+ cloud,+ }),+ );+ return { ...groupGranulesByDay(granules)[0], ...extra };+}++test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {+ const reason = (box) => validateBox(box).reason;+ assert.equal(+ reason({ west: 179, south: 0, east: -179, north: 1 }),+ 'dateline',+ );+ assert.equal(+ reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),+ 'polar',+ );+ assert.equal(+ reason({ west: 0, south: -85.0512, east: 0.5, north: -84 }),+ 'polar',+ );+ // Refusals fit the one-line notice.+ assert.equal(+ validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message,+ 'Imagery stops at ±85.05° latitude',+ );+ assert.equal(+ validateBox({ west: 179, south: 0, east: -179, north: 1 }).message,+ 'Select one side of the dateline',+ );+ assert.equal(+ validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok,+ true,+ );+ assert.equal(+ reason({ west: 10, south: 10, east: 10, north: 11 }),+ 'degenerate',+ );+ assert.equal(+ reason({ west: Infinity, south: 0, east: 1, north: 1 }),+ 'invalid',+ );+ assert.equal(reason({ west: -181, south: 0, east: 1, north: 1 }), 'invalid');+ assert.equal(reason(undefined), 'invalid');+ // The cap is 1,000 km a side, and the refusal says how big the box is.+ const tall = validateBox({ west: 0, south: 0, east: 0.1, north: 10 });+ assert.equal(tall.reason, 'too-large');+ assert.equal(tall.message, 'Box is 1,113 km wide · limit 1,000 km');+ assert.equal(+ reason({ west: 0, south: 0, east: 10, north: 0.1 }),+ 'too-large',+ );+ assert.equal(validateBox({ west: 0, south: 0, east: 8, north: 8 }).ok, true);+ assert.equal(+ viewTooLargeMessage(2400),+ 'View is 2,400 km wide · limit 1,000 km',+ );+ // Latitudes are ordered; longitudes are never swapped.+ assert.deepEqual(+ validateBox({ west: -97.8, south: 30.3, east: -97.7, north: 30.2 }).box,+ BOX,+ );+});++test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400 km; a box centre', () => {+ const near = (actual, expected, label) =>+ assert.ok(Math.abs(actual - expected) < 1e-6, `${label}: ${actual}`);+ // A 1000 × 500 canvas with Cesium's 60° horizontal FOV: tan(fovy / 2) is+ // tan(30°) / 2, so the view is 2 · h · tan(30°) wide.+ const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) / 2);+ const height = fitViewHeightM({ width: 1000, height: 500, fovy });+ near(height, 400_000 / (2 * Math.tan(Math.PI / 6)), 'wide canvas');+ near(+ 2 * height * Math.tan(fovy / 2) * 2,+ 400_000,+ 'the view at that height is 400 km wide',+ );+ // A tall canvas would need more than 400 km; a very wide one less than 5.+ assert.equal(+ fitViewHeightM({ width: 200, height: 1000, fovy: Math.PI / 3 }),+ 400_000,+ );+ assert.equal(fitViewHeightM({ width: 1000, height: 500, fovy: 3.1 }), 5_000);+ // No canvas or FOV: a square 60° view.+ near(+ fitViewHeightM({ width: 0, height: 0, fovy: undefined }),+ 400_000 / (2 * Math.tan(Math.PI / 6)),+ 'fallback',+ );+ assert.deepEqual(boxCentre({ west: 0, south: 0, east: 20, north: 10 }), {+ lon: 10,+ lat: 5,+ });+ assert.equal(boxCentre(null), null);+});++test('box width is the longitude span at the mid-latitude, never the shortest arc', () => {+ const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 });+ assert.ok(Math.abs(equator.width - 111.32) < 1e-6);+ assert.ok(Math.abs(equator.height - 111.32) < 1e-6);+ const north = boxSideKm({ west: 0, south: 59.5, east: 1, north: 60.5 });+ assert.ok(north.width > 55 && north.width < 56.5, String(north.width));+ const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 };+ assert.ok(boxSideKm(nearlyGlobal).width > 30000);+ assert.equal(validateBox(nearlyGlobal).reason, 'too-large');+});++test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => {+ for (const [lon, lat] of [+ [-97.75, 30.27],+ [18.07, 59.33],+ [0, 0],+ [-70, -45],+ ]) {+ const box = boxFromPin(lon, lat);+ const { width, height } = boxSideKm(box);+ assert.ok(Math.abs(width - 10) < 0.2, `width ${width} at ${lat}`);+ assert.ok(Math.abs(height - 10) < 0.2, `height ${height} at ${lat}`);+ assert.ok(Math.abs((box.west + box.east) / 2 - lon) < 1e-9);+ }+ assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1);+ assert.equal(boxFromPin(NaN, 0), null);+ assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap');+ assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');+ assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');+ assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');+});++test('rectangles convert from radians and the share-link quantization round-trips', () => {+ const box = boxFromRectangle({+ west: -Math.PI / 2,+ south: 0,+ east: -Math.PI / 4,+ north: Math.PI / 6,+ });+ assert.ok(Math.abs(box.west + 90) < 1e-9 && Math.abs(box.north - 30) < 1e-9);+ assert.equal(boxFromRectangle(null), null);+ const ints = quantizeBox({+ west: -97.812345678,+ south: 30.2,+ east: -97.7,+ north: 30.3999999,+ });+ assert.deepEqual(ints, {+ west: -9781235,+ south: 3020000,+ east: -9770000,+ north: 3040000,+ });+ assert.deepEqual(quantizeBox(dequantizeBox(ints)), ints);+ assert.equal(quantizeBox(null), null);+ assert.equal(dequantizeBox({ west: 'x' }), null);+});++test('days and candidate keys are real UTC calendar days', () => {+ assert.equal(utcDay('2026-09-18T20:00:00-05:00'), '2026-09-19');+ assert.equal(utcDay(new Date(Date.UTC(2026, 0, 1))), '2026-01-01');+ assert.equal(utcDay('2026-02-30'), null);+ assert.equal(utcDay('nope'), null);+ assert.deepEqual(parseCandidateKey('L30:2026-09-10'), {+ product: 'L30',+ day: '2026-09-10',+ });+ assert.equal(parseCandidateKey('X30:2026-09-10'), null);+ assert.equal(parseCandidateKey('S30:2026-02-30'), null);+ assert.equal(shortDay('2026-09-18'), 'Sep 18');+ assert.equal(shortDay('nope'), '');+});++test('granules group into one candidate per product and UTC day, newest first', () => {+ const candidates = groupGranulesByDay([+ granule({ id: 'a', cloud: 12, timeEnd: '2026-09-18T17:12:40Z' }),+ granule({+ id: 'b',+ cloud: 18,+ timeStart: '2026-09-18T17:20:00Z',+ timeEnd: '2026-09-18T17:20:40Z',+ }),+ granule({+ id: 'c',+ cloud: null,+ product: 'L30',+ timeStart: '2026-09-18T16:00:00Z',+ timeEnd: null,+ }),+ granule({ id: 'd', cloud: 3, timeStart: '2026-09-10T17:00:00Z' }),+ granule({ id: 'e', timeStart: 'garbage' }),+ granule({ id: 'f', product: 'nope' }),+ ]);+ assert.deepEqual(+ candidates.map((c) => c.key),+ ['S30:2026-09-18', 'L30:2026-09-18', 'S30:2026-09-10'],+ );+ const [s18, l18] = candidates;+ assert.deepEqual(s18.cloud, { min: 12, max: 18 });+ assert.deepEqual(s18.timeRange, {+ start: '2026-09-18T17:12:00.000Z',+ end: '2026-09-18T17:20:40.000Z',+ });+ assert.equal(s18.availability, 'present');+ assert.equal(l18.cloud, null, 'missing cloud stays unknown');+ assert.equal(l18.timeRange.end, '2026-09-18T16:00:00.000Z');+});++test('VIIRS lists the last 30 UTC days as unprobed full-coverage days', () => {+ const days = viirsCandidates('2026-03-01T13:00:00Z', 3);+ assert.deepEqual(+ days.map((c) => c.key),+ ['VIIRS:2026-03-01', 'VIIRS:2026-02-28', 'VIIRS:2026-02-27'],+ );+ assert.equal(days[0].availability, 'unknown');+ assert.equal(days[0].coverage, 'full');+ assert.equal(viirsCandidates('2026-09-21').length, 30);+ assert.deepEqual(viirsCandidates('bad'), []);+});++test('merging sorts newest day first, then S30, L30, VIIRS, and the first key wins', () => {+ const merged = mergeCandidates([+ viirsCandidates('2026-09-18', 2),+ [hls('L30', '2026-09-18', [5]), hls('S30', '2026-09-17', [5])],+ [hls('S30', '2026-09-18', [7]), hls('S30', '2026-09-18', [99])],+ ]);+ assert.deepEqual(+ merged.map((c) => c.key),+ [+ 'S30:2026-09-18',+ 'L30:2026-09-18',+ 'VIIRS:2026-09-18',+ 'S30:2026-09-17',+ 'VIIRS:2026-09-17',+ ],+ );+ assert.deepEqual(merged[0].cloud, { min: 7, max: 7 });+});++test('coverage samples the box corners and centre against the union of footprints', () => {+ const ring = (west, east) => [+ [west, 30],+ [east, 30],+ [east, 31],+ [west, 31],+ ];+ const withRings = (...rings) => ({+ granules: rings.map((footprint) => granule({ footprint })),+ });+ assert.equal(coverageFor(withRings(ring(-98, -97)), BOX), 'full');+ assert.equal(coverageFor(withRings(ring(-98, -97.75)), BOX), 'partial');+ assert.equal(+ coverageFor(withRings(ring(-98, -97.75), ring(-97.75, -97)), BOX),+ 'full',+ );+ assert.equal(coverageFor(withRings(null), BOX), 'unknown');+});++test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => {+ const candidates = [+ hls('S30', '2026-09-20', [10, null]),+ hls('S30', '2026-09-19', [5, 21]),+ hls('S30', '2026-09-18', [0, 20]),+ ];+ assert.deepEqual(rankLatest([...candidates].reverse()), {+ candidate: candidates[2],+ reason: 'clear',+ certain: true,+ });+ assert.equal(rankLatest(candidates, { truncated: true }).certain, false);+ // Then the newest cloudy HLS day, then the newest non-empty VIIRS day.+ const cloudy = rankLatest([+ hls('L30', '2026-09-20', [45]),+ hls('S30', '2026-09-19', [null]),+ ]);+ assert.equal(cloudy.candidate.key, 'L30:2026-09-20');+ assert.equal(cloudy.reason, 'cloudy');+ const viirs = viirsCandidates('2026-09-21', 3);+ viirs[0] = { ...viirs[0], availability: 'empty' };+ const empty = { ...hls('S30', '2026-09-21', [0]), availability: 'empty' };+ const overview = rankLatest([empty, ...viirs]);+ assert.equal(overview.candidate.key, 'VIIRS:2026-09-20');+ assert.equal(overview.reason, 'overview');+ assert.equal(rankLatest([]).candidate, null);+});++test('START HERE prefers a day that covers the whole box over a newer sliver', () => {+ const full = (day, clouds) => hls('S30', day, clouds, { coverage: 'full' });+ const sliver = (day, clouds) =>+ hls('S30', day, clouds, { coverage: 'partial' });+ const pick = (list) => {+ const { candidate, reason } = rankLatest(list);+ return `${candidate?.day} ${reason}`;+ };+ assert.equal(+ pick([sliver('2026-09-20', [0]), full('2026-09-18', [10])]),+ '2026-09-18 clear',+ );+ assert.equal(+ pick([full('2026-09-20', [null]), sliver('2026-09-19', [0])]),+ '2026-09-20 cloudy',+ );+ // Unknown coverage (no footprints) counts as whole-box.+ assert.equal(+ pick([+ hls('S30', '2026-09-20', [5], { coverage: 'unknown' }),+ full('2026-09-18', [5]),+ ]),+ '2026-09-20 clear',+ );+ // Only slivers: the newest clear one, then the newest at all.+ assert.equal(+ pick([sliver('2026-09-20', [50]), sliver('2026-09-19', [0])]),+ '2026-09-19 partial',+ );+ assert.equal(+ pick([sliver('2026-09-20', [50]), sliver('2026-09-19', [null])]),+ '2026-09-20 partial',+ );+ assert.equal(+ pick([...viirsCandidates('2026-09-21', 2), sliver('2026-09-19', [70])]),+ '2026-09-19 partial',+ 'a sliver still beats the overview',+ );+});++test('the readout is one UTC line with age, sensor, resolution and scene cloud', () => {+ const now = '2026-09-21T12:00:00Z';+ const readout = (granules) =>+ formatCandidateReadout(groupGranulesByDay(granules)[0], now);+ assert.equal(+ readout([granule({ timeStart: '2026-09-18T17:12:10Z' })]),+ 'Sep 18, 2026 17:12Z · 3 days ago · Sentinel-2 via HLS · 30 m · 12% scene cloud',+ );+ assert.equal(+ readout([+ granule({ id: 'a' }),+ granule({+ id: 'b',+ cloud: 18.4,+ timeStart: '2026-09-18T17:20:00Z',+ timeEnd: '2026-09-18T17:20:30Z',+ }),+ ]),+ 'Sep 18, 2026 17:12–17:20Z · 3 days ago · Sentinel-2 via HLS · 30 m · 12–18% scene cloud',+ );+ assert.equal(+ readout([+ granule({+ product: 'L30',+ cloud: null,+ timeStart: '2026-09-20T16:05:00Z',+ timeEnd: null,+ }),+ ]),+ 'Sep 20, 2026 16:05Z · yesterday · Landsat 8/9 via HLS · 30 m · cloud unknown',+ );+ assert.equal(+ formatCandidateReadout(viirsCandidates('2026-09-21', 1)[0], now),+ 'Sep 21, 2026 · today · VIIRS NOAA-21 · 250 m · overview · cloud unknown',+ );+ assert.equal(formatCandidateReadout(null), '');+});++test('GIBS templates put y before x; Worldview snapshots take south,west,north,east', () => {+ assert.equal(+ gibsTemplate('S30', '2026-09-18'),+ 'https://gibs-{s}.earthdata.nasa.gov/wmts/epsg3857/best/HLS_S30_Nadir_BRDF_Adjusted_Reflectance/default/2026-09-18/GoogleMapsCompatible_Level12/{z}/{y}/{x}.png',+ );+ assert.equal(+ gibsTemplate('VIIRS', '2026-09-21'),+ 'https://gibs-{s}.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_NOAA21_CorrectedReflectance_TrueColor/default/2026-09-21/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg',+ );+ assert.match(gibsTemplate('L30', '2026-09-10'), /HLS_L30_.*Level12.*\.png$/);+ assert.throws(() => gibsTemplate('MODIS', '2026-01-01'), /Unknown/);+ assert.equal(+ wvsSnapshotUrl({+ product: 'S30',+ day: '2026-09-18',+ box: BOX,+ width: 256,+ height: 256,+ }),+ 'https://wvs.earthdata.nasa.gov/api/v1/snapshot?REQUEST=GetSnapshot&LAYERS=HLS_S30_Nadir_BRDF_Adjusted_Reflectance&CRS=EPSG:4326&TIME=2026-09-18&BBOX=30.2,-97.8,30.3,-97.7&WIDTH=256&HEIGHT=256&FORMAT=image/png',+ );+ assert.throws(+ () => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }),+ TypeError,+ );+});++test('thumbnails load the focused card, then the visible cards outward, then the margins', () => {+ assert.deepEqual(thumbnailOrder(5, 3, 7, 20), [5, 6, 4, 7, 3, 8, 2, 9, 1]);+ assert.deepEqual(thumbnailOrder(19, 17, 19, 20), [19, 18, 17, 16, 15]);+ assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]);+ assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []);+});diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.jsnew file mode 100644index 000000000..1d0a7893f--- /dev/null+++ b/src/layers/recentImagery/rendering.js@@ -0,0 +1,265 @@+/**+ * Draped-imagery renderer for the Recent Imagery layer: at most two GIBS+ * imagery layers (slot `a`, left of a swipe; slot `b`, right) on whichever+ * host the map stack offers. Against the basemap slot `a` splits left and+ * slot `b` stays empty. Every layer is removed from the collection that owns it, so a+ * host switch or a replaced image never strands one. Tile requests pass a+ * small semaphore of our own; Cesium's global request limits stay untouched.+ */+import * as Cesium from 'cesium';+import { PRODUCTS, gibsTemplate } from './model.js';++const SLOT_IDS = ['a', 'b'];+const SPLIT_ENUM = { left: 'LEFT', right: 'RIGHT', none: 'NONE' };+const NO_HOST = Object.freeze({ collection: null, kind: 'none' });++/** Render reason for a deferred or settled tile request. */+export const TILE_RENDER_REASON = 'recent-imagery-tiles';+/** Delay before the one frame that retries tiles Cesium itself deferred. */+export const TILE_RETRY_DELAY_MS = 250;++function clampAlpha(value) {+ const alpha = Number(value);+ return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;+}++const boxKey = (box) =>+ [box.west, box.south, box.east, box.north].map(Number).join(',');++/**+ * Gate a provider's `requestImage` through the semaphore. Returning+ * `undefined` tells Cesium to retry on a later frame, but under+ * `requestRenderMode` there is no later frame unless something asks — and a+ * deferral must never ask for one itself: the retried tile would defer again+ * and ask again, keeping the scene rendering every frame. So a request that+ * finds our semaphore full asks for nothing (the request holding the slot+ * asks for one frame when it settles), and a request the provider itself+ * deferred goes through the one coalesced delayed retry.+ */+function admitTileRequests(provider, admission, requestRender, retry) {+ const original = provider.requestImage.bind(provider);+ provider.requestImage = (x, y, level, request) => {+ if (admission.inFlight >= admission.limit) return undefined;+ admission.inFlight += 1;+ const release = () => {+ admission.inFlight -= 1;+ };+ let promise;+ try {+ promise = original(x, y, level, request);+ } catch (error) {+ release();+ throw error;+ }+ if (!promise) {+ release();+ retry.schedule();+ return undefined;+ }+ return Promise.resolve(promise).finally(() => {+ release();+ requestRender(TILE_RENDER_REASON);+ });+ };+ return provider;+}++/**+ * Create the renderer.+ * @param {{ cesium?: object, maxTileRequests?: number, requestRender?: (reason: string) => void, setTimeoutImpl?: Function, clearTimeoutImpl?: Function }} [options]+ */+export function createRecentImageryRenderer({+ cesium = Cesium,+ maxTileRequests = 6,+ requestRender = () => {},+ setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),+ clearTimeoutImpl = (id) => globalThis.clearTimeout(id),+} = {}) {+ let host = NO_HOST;+ let destroyed = false;+ const admission = { limit: maxTileRequests, inFlight: 0 };+ /** @type {Record<'a'|'b', null | { layer: object, collection: object, candidate: object, box: object, alpha: number, split: string }>} */+ const owned = { a: null, b: null };++ // One timer for both slots: any number of upstream deferrals while it is+ // armed share the same single retry frame.+ let retryTimer = null;+ const retry = {+ schedule() {+ if (retryTimer !== null) return;+ retryTimer = setTimeoutImpl(() => {+ retryTimer = null;+ if (!destroyed) requestRender(TILE_RENDER_REASON);+ }, TILE_RETRY_DELAY_MS);+ },+ cancel() {+ if (retryTimer !== null) clearTimeoutImpl(retryTimer);+ retryTimer = null;+ },+ };++ function createProvider(candidate, box) {+ const spec = PRODUCTS[candidate.product];+ const provider = new cesium.UrlTemplateImageryProvider({+ url: gibsTemplate(candidate.product, candidate.day),+ subdomains: ['a', 'b', 'c'],+ minimumLevel: 0,+ maximumLevel: spec.maxLevel,+ tilingScheme: new cesium.WebMercatorTilingScheme(),+ rectangle: cesium.Rectangle.fromDegrees(+ box.west,+ box.south,+ box.east,+ box.north,+ ),+ credit: 'NASA GIBS',+ hasAlphaChannel: spec.format === 'png',+ });+ return admitTileRequests(provider, admission, requestRender, retry);+ }++ function removeOwned(slotId) {+ const record = owned[slotId];+ if (!record) return false;+ owned[slotId] = null;+ try {+ record.collection.remove(record.layer, true);+ } catch {+ /* the collection is already gone */+ }+ return true;+ }++ function applyLook(record) {+ record.layer.alpha = record.alpha;+ record.layer.splitDirection =+ cesium.SplitDirection?.[SPLIT_ENUM[record.split] || 'NONE'] ?? 0;+ }++ function mount(slotId, { candidate, box, alpha, split }) {+ const layer = host.collection.addImageryProvider(+ createProvider(candidate, box),+ );+ owned[slotId] = {+ layer,+ collection: host.collection,+ candidate,+ box,+ alpha,+ split,+ };+ applyLook(owned[slotId]);+ }++ return {+ /**+ * Drape a candidate into a slot. The same candidate on the same host only+ * updates its look; anything else replaces the slot's layer.+ * @param {'a'|'b'} slotId+ * @param {object} candidate+ * @param {object} box Degrees box.+ * @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]+ * @returns {boolean} Whether a layer is now draped for the slot.+ */+ showSlot(+ slotId,+ candidate,+ box,+ { alpha = 1, splitDirection = 'none' } = {},+ ) {+ if (destroyed || !candidate?.key || !box) return false;+ if (!host.collection) {+ removeOwned(slotId);+ return false;+ }+ const current = owned[slotId];+ const look = { alpha: clampAlpha(alpha), split: splitDirection };+ if (+ current &&+ current.collection === host.collection &&+ current.candidate.key === candidate.key &&+ boxKey(current.box) === boxKey(box)+ ) {+ if (current.alpha !== look.alpha || current.split !== look.split) {+ Object.assign(current, look);+ applyLook(current);+ requestRender('recent-imagery-look');+ }+ return true;+ }+ removeOwned(slotId);+ mount(slotId, { candidate, box, ...look });+ requestRender('recent-imagery-show');+ return true;+ },++ /** @param {'a'|'b'} slotId */+ hideSlot(slotId) {+ if (removeOwned(slotId)) requestRender('recent-imagery-hide');+ },++ /**+ * @param {'a'|'b'} slotId+ * @param {number} alpha 0–1+ */+ setAlpha(slotId, alpha) {+ const record = owned[slotId];+ const next = clampAlpha(alpha);+ if (!record || record.alpha === next) return;+ record.alpha = next;+ applyLook(record);+ requestRender('recent-imagery-alpha');+ },++ /**+ * Move every owned layer to a new host. Layers are rebuilt there, never+ * re-parented, so the old collection is left as it was found.+ * @param {{ collection: object | null, kind: string }} nextHost+ */+ rebind(nextHost) {+ host = nextHost || NO_HOST;+ let changed = false;+ for (const slotId of SLOT_IDS) {+ const record = owned[slotId];+ if (!record || record.collection === host.collection) continue;+ removeOwned(slotId);+ changed = true;+ if (host.collection && !destroyed) mount(slotId, record);+ }+ if (changed) requestRender('recent-imagery-rebind');+ },++ /** What is draped right now, per slot. */+ getOwned() {+ const out = {};+ for (const slotId of SLOT_IDS) {+ const record = owned[slotId];+ out[slotId] = record+ ? {+ key: record.candidate.key,+ kind: host.kind,+ alpha: record.alpha,+ split: record.split,+ }+ : null;+ }+ return out;+ },++ /** Number of layers this renderer owns (never above two). */+ ownedCount() {+ return SLOT_IDS.filter((slotId) => owned[slotId]).length;+ },++ /** Remove everything and refuse further work. */+ destroy() {+ if (destroyed) return;+ destroyed = true;+ retry.cancel();+ let changed = false;+ for (const slotId of SLOT_IDS) changed = removeOwned(slotId) || changed;+ host = NO_HOST;+ if (changed) requestRender('recent-imagery-destroy');+ },+ };+}diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjsnew file mode 100644index 000000000..ad7e166a8--- /dev/null+++ b/src/layers/recentImagery/rendering.test.mjs@@ -0,0 +1,210 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import {+ TILE_RENDER_REASON,+ TILE_RETRY_DELAY_MS,+ createRecentImageryRenderer,+} from './rendering.js';+import { BOX, manualTimers } from './testDoubles.mjs';++/** A provider whose tile requests stay pending until the test settles them. */+class UrlTemplateImageryProvider {+ constructor(options) {+ this.options = options;+ this.calls = [];+ this.pending = [];+ }+ requestImage(x, y, level) {+ this.calls.push([x, y, level]);+ return new Promise((resolve) => this.pending.push(resolve));+ }+}++function fakeCesium(requestImage) {+ class Provider extends UrlTemplateImageryProvider {}+ if (requestImage) Provider.prototype.requestImage = requestImage;+ return {+ UrlTemplateImageryProvider: Provider,+ WebMercatorTilingScheme: class {},+ Rectangle: {+ fromDegrees: (west, south, east, north) => ({ west, south, east, north }),+ },+ SplitDirection: { LEFT: -1, NONE: 0, RIGHT: 1 },+ };+}++function fakeCollection() {+ const layers = [];+ return {+ layers,+ addImageryProvider(provider) {+ const layer = { provider, alpha: 1, splitDirection: 0 };+ layers.push(layer);+ return layer;+ },+ remove(layer, destroy) {+ layers.splice(layers.indexOf(layer), 1);+ layer.destroyed = destroy;+ },+ };+}++const S30 = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' };+const L30 = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' };+const VIIRS = { key: 'VIIRS:2026-09-20', product: 'VIIRS', day: '2026-09-20' };++function fixture({ requestImage, maxTileRequests } = {}) {+ const renders = [];+ const timers = manualTimers();+ const renderer = createRecentImageryRenderer({+ cesium: fakeCesium(requestImage),+ maxTileRequests,+ requestRender: (reason) => renders.push(reason),+ setTimeoutImpl: timers.setTimeoutImpl,+ clearTimeoutImpl: timers.clearTimeoutImpl,+ });+ const globe = fakeCollection();+ renderer.rebind({ collection: globe, kind: 'globe' });+ const tileFrames = () =>+ renders.filter((reason) => reason === TILE_RENDER_REASON).length;+ return { renderer, globe, renders, timers, tileFrames };+}++test('a slot drapes one GIBS provider bounded to the box; the same day only restyles it', () => {+ const { renderer, globe, renders } = fixture();+ assert.equal(renderer.showSlot('a', S30, BOX, { alpha: 0.8 }), true);+ const [layer] = globe.layers;+ assert.match(+ layer.provider.options.url,+ /^https:\/\/gibs-\{s\}\.earthdata\.nasa\.gov\/.*HLS_S30.*\/2026-09-18\/GoogleMapsCompatible_Level12\/\{z\}\/\{y\}\/\{x\}\.png$/,+ );+ assert.deepEqual(layer.provider.options.subdomains, ['a', 'b', 'c']);+ assert.equal(layer.provider.options.credit, 'NASA GIBS');+ assert.deepEqual(layer.provider.options.rectangle, BOX);+ assert.equal(layer.alpha, 0.8);+ assert.deepEqual(renders, ['recent-imagery-show']);+ assert.deepEqual(renderer.getOwned().a, {+ key: 'S30:2026-09-18',+ kind: 'globe',+ alpha: 0.8,+ split: 'none',+ });+ renderer.showSlot('a', S30, BOX, { alpha: 0.5, splitDirection: 'left' });+ assert.deepEqual(globe.layers, [layer], 'the layer is reused');+ assert.equal(layer.splitDirection, -1);+ // A different day replaces the layer in its own collection.+ renderer.showSlot('a', L30, BOX);+ assert.equal(layer.destroyed, true);+ assert.equal(globe.layers.length, 1);+ // VIIRS is a level-9 JPEG overview with no alpha channel.+ renderer.showSlot('b', VIIRS, BOX, { splitDirection: 'right' });+ assert.equal(globe.layers[1].provider.options.maximumLevel, 9);+ assert.equal(globe.layers[1].provider.options.hasAlphaChannel, false);+ assert.equal(globe.layers[1].splitDirection, 1);+ renderer.setAlpha('b', 7);+ assert.equal(globe.layers[1].alpha, 1, 'alpha clamps to 0–1');+});++test('rapid replacement never owns more than two layers', () => {+ const { renderer, globe } = fixture();+ const days = [S30, L30, VIIRS];+ for (let i = 0; i < 10; i += 1) {+ renderer.showSlot('a', days[i % 3], BOX);+ renderer.showSlot('b', days[(i + 1) % 3], BOX);+ if (i % 4 === 0) renderer.hideSlot('a');+ assert.ok(globe.layers.length <= 2 && renderer.ownedCount() <= 2);+ }+ renderer.hideSlot('a');+ renderer.hideSlot('b');+ assert.equal(globe.layers.length, 0);+});++test('rebind rebuilds the owned layers on the new host and leaves the old one empty', () => {+ const { renderer, globe } = fixture();+ renderer.showSlot('a', S30, BOX, { alpha: 0.6, splitDirection: 'left' });+ renderer.showSlot('b', L30, BOX, { splitDirection: 'right' });+ const tileset = fakeCollection();+ renderer.rebind({ collection: tileset, kind: 'tileset' });+ assert.equal(globe.layers.length, 0);+ assert.deepEqual(+ tileset.layers.map((layer) => [layer.alpha, layer.splitDirection]),+ [+ [0.6, -1],+ [1, 1],+ ],+ );+ assert.equal(renderer.getOwned().a.kind, 'tileset');+ renderer.rebind({ collection: null, kind: 'none' });+ assert.equal(tileset.layers.length, 0);+ assert.equal(renderer.showSlot('a', S30, BOX), false);+ renderer.rebind({ collection: globe, kind: 'globe' });+ renderer.showSlot('a', S30, BOX);+ renderer.destroy();+ assert.equal(globe.layers.length, 0);+ assert.equal(renderer.showSlot('a', S30, BOX), false, 'destroyed');+});++test('above the tile limit a request defers silently; its settlement asks for exactly one frame', async () => {+ const { renderer, globe, timers, tileFrames } = fixture({+ maxTileRequests: 1,+ });+ renderer.showSlot('a', S30, BOX);+ const { provider } = globe.layers[0];+ const first = provider.requestImage(0, 0, 1);+ assert.ok(first instanceof Promise);+ for (let i = 1; i <= 120; i += 1)+ assert.equal(provider.requestImage(i, 0, 1), undefined);+ assert.equal(provider.calls.length, 1, 'deferred requests never go out');+ assert.equal(tileFrames(), 0, 'a deferral asks for no frame');+ assert.equal(timers.armed(), 0);+ provider.pending[0]('tile');+ await first;+ assert.equal(tileFrames(), 1, 'the settlement asks for the retry frame');+ assert.ok(provider.requestImage(200, 0, 1) instanceof Promise);+});++test('upstream deferrals from both slots share one delayed retry frame; destroy disarms it', () => {+ let throwNext = false;+ const { renderer, globe, timers, tileFrames } = fixture({+ maxTileRequests: 1,+ requestImage() {+ if (throwNext) throw new Error('boom');+ return undefined;+ },+ });+ renderer.showSlot('a', S30, BOX);+ renderer.showSlot('b', L30, BOX);+ for (const { provider } of globe.layers)+ for (let i = 0; i < 40; i += 1)+ assert.equal(provider.requestImage(i, 0, 0), undefined);+ // Every deferral released its slot (the limit is one), and none asked+ // for a frame of its own: one timer holds the single retry.+ assert.equal(tileFrames(), 0);+ assert.equal(timers.armed(), 1);+ assert.equal([...timers.pending.values()][0].ms, TILE_RETRY_DELAY_MS);+ timers.flush();+ assert.equal(tileFrames(), 1);+ // A throwing provider releases its slot too.+ throwNext = true;+ assert.throws(() => globe.layers[0].provider.requestImage(0, 0, 0), /boom/);+ throwNext = false;+ globe.layers[0].provider.requestImage(0, 0, 0);+ assert.equal(timers.armed(), 1, 'the next deferral arms a fresh timer');+ renderer.destroy();+ assert.equal(timers.armed(), 0, 'destroy disarms the retry');+ assert.equal(tileFrames(), 1);+});++test('against the basemap slot a splits left with no second layer, and leaving the swipe only restyles it', () => {+ const { renderer, globe, renders } = fixture();+ renderer.showSlot('a', S30, BOX, { splitDirection: 'left' });+ renderer.hideSlot('b');+ assert.equal(globe.layers.length, 1, 'the basemap is the right side');+ assert.equal(globe.layers[0].splitDirection, -1);+ assert.equal(renderer.getOwned().b, null);+ const [layer] = globe.layers;+ renderer.showSlot('a', S30, BOX, { splitDirection: 'none' });+ assert.deepEqual(globe.layers, [layer], 'no rebuild for a new look');+ assert.equal(layer.splitDirection, 0);+ assert.deepEqual(renders, ['recent-imagery-show', 'recent-imagery-look']);+});diff --git a/src/layers/recentImagery/testDoubles.mjs b/src/layers/recentImagery/testDoubles.mjsnew file mode 100644index 000000000..2b00e5b01--- /dev/null+++ b/src/layers/recentImagery/testDoubles.mjs@@ -0,0 +1,368 @@+/**+ * Test doubles shared by the Recent Imagery tests: manual timers, fetch+ * responses, and the Cesium/viewer/document fakes the box tool needs.+ */+import { thumbnailOrder } from './model.js';++export const BOX = Object.freeze({+ west: -97.8,+ south: 30.2,+ east: -97.7,+ north: 30.3,+});++export const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++/** Timers that fire only when the test says so. */+export function manualTimers() {+ const pending = new Map();+ const cleared = [];+ let nextId = 1;+ return {+ pending,+ cleared,+ setTimeoutImpl(fn, ms) {+ const id = nextId++;+ pending.set(id, { fn, ms });+ return id;+ },+ clearTimeoutImpl(id) {+ cleared.push(id);+ pending.delete(id);+ },+ /** Fire every armed timer, in order. */+ flush() {+ const entries = [...pending.values()];+ pending.clear();+ for (const entry of entries) entry.fn();+ },+ armed: () => pending.size,+ };+}++/** A `fetch` response with case-insensitive headers. */+export function response({+ ok = true,+ status = ok ? 200 : 500,+ json = {},+ headers = {},+ blob = { size: 1 },+} = {}) {+ const lower = new Map(+ Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),+ );+ return {+ ok,+ status,+ headers: { get: (name) => lower.get(name.toLowerCase()) ?? null },+ json: async () => json,+ blob: async () => blob,+ };+}++const EVENT_TYPES = {+ LEFT_DOWN: 'down',+ MOUSE_MOVE: 'move',+ LEFT_UP: 'up',+ LEFT_CLICK: 'click',+ LEFT_DOUBLE_CLICK: 'dblclick',+};++/**+ * Cesium, viewer and document fakes for `initImageryBoxTool`. The canvas is+ * 1000 × 500 px mapped linearly onto 0.2° near Austin; y < 40 px is sky.+ */+export function boxToolFakes() {+ const handlers = [];+ class ScreenSpaceEventHandler {+ constructor(canvas) {+ this.canvas = canvas;+ this.actions = new Map();+ this.destroyed = false;+ handlers.push(this);+ }+ setInputAction(fn, type) {+ this.actions.set(type, fn);+ }+ getInputAction(type) {+ return this.actions.get(type);+ }+ removeInputAction(type) {+ this.actions.delete(type);+ }+ destroy() {+ this.destroyed = true;+ }+ }+ class CustomDataSource {+ constructor(name) {+ this.name = name;+ const values = [];+ this.entities = {+ values,+ add: (entity) => (values.push(entity), entity),+ removeAll: () => values.splice(0),+ };+ }+ }+ const color = { withAlpha: (alpha) => ({ alpha }) };+ const cesium = {+ ScreenSpaceEventHandler,+ ScreenSpaceEventType: EVENT_TYPES,+ CustomDataSource,+ CallbackProperty: class {},+ PolylineDashMaterialProperty: class {},+ ClassificationType: { BOTH: 'both' },+ Color: { fromCssColorString: () => color },+ Rectangle: { fromDegrees: () => ({}) },+ Cartesian3: { fromDegreesArray: (values) => values },+ };++ const stock = new ScreenSpaceEventHandler('stock');+ const originalClick = () => 'select';+ const originalDouble = () => 'track';+ stock.setInputAction(originalClick, EVENT_TYPES.LEFT_CLICK);+ stock.setInputAction(originalDouble, EVENT_TYPES.LEFT_DOUBLE_CLICK);+ const sources = [];+ const viewer = {+ renders: 0,+ scene: {+ canvas: { clientWidth: 1000, clientHeight: 500 },+ screenSpaceCameraController: { enableInputs: true },+ requestRender: () => {+ viewer.renders += 1;+ },+ },+ screenSpaceEventHandler: stock,+ dataSources: {+ sources,+ add: (source) => (sources.push(source), Promise.resolve(source)),+ remove: (source) => sources.splice(sources.indexOf(source), 1),+ },+ };++ const listeners = [];+ const classes = new Set();+ const documentRef = {+ listeners,+ classes,+ addEventListener: (type, fn) => listeners.push([type, fn]),+ removeEventListener: (type, fn) => {+ const index = listeners.findIndex((entry) => entry[1] === fn);+ if (index >= 0) listeners.splice(index, 1);+ },+ body: {+ classList: {+ add: (name) => classes.add(name),+ remove: (name) => classes.delete(name),+ },+ },+ };++ const pickWorld = (_viewer, nx, ny) =>+ ny * 500 < 40 ? null : { lon: -97.9 + nx * 0.2, lat: 30.4 - ny * 0.2 };+ /** The live (non-stock) canvas handler, if the tool has one bound. */+ const handler = () =>+ handlers.find((h) => h.canvas !== 'stock' && !h.destroyed) || null;+ const fire = (type, event) =>+ handler()?.actions.get(EVENT_TYPES[type])?.(event);+ /** Dispatch a keydown to the tool's document listener. */+ const key = (name) => {+ const event = {+ key: name,+ prevented: false,+ stopped: false,+ preventDefault() {+ this.prevented = true;+ },+ stopImmediatePropagation() {+ this.stopped = true;+ },+ };+ listeners.find(([type]) => type === 'keydown')?.[1](event);+ return event;+ };+ return {+ cesium,+ viewer,+ documentRef,+ pickWorld,+ handler,+ fire,+ key,+ types: EVENT_TYPES,+ originalClick,+ originalDouble,+ };+}++// ---- the layer's injected parts --------------------------------------++export function candidate(product, day, cloud = 5) {+ const granules =+ product === 'VIIRS'+ ? []+ : [+ {+ id: `${product}-${day}`,+ product,+ timeStart: `${day}T17:12:00Z`,+ timeEnd: `${day}T17:14:00Z`,+ cloud,+ },+ ];+ return {+ key: `${product}:${day}`,+ product,+ day,+ granules,+ cloud: granules.length ? { min: cloud, max: cloud } : null,+ timeRange: granules.length+ ? { start: granules[0].timeStart, end: granules[0].timeEnd }+ : null,+ availability: granules.length ? 'present' : 'unknown',+ coverage: 'full',+ };+}++// Strip order, newest first: V21 (unprobed), S18 (clear), L16 (cloudy), V15.+export const CANDIDATES = Object.freeze([+ candidate('VIIRS', '2026-09-21'),+ candidate('S30', '2026-09-18', 12),+ candidate('L30', '2026-09-16', 60),+ candidate('VIIRS', '2026-09-15'),+]);++export function fakeRenderer() {+ const calls = [];+ const owned = { a: null, b: null };+ let host = { kind: 'none' };+ let peak = 0;+ return {+ calls,+ rebind(next) {+ calls.push(['rebind', next.kind]);+ host = next;+ for (const slot of ['a', 'b'])+ if (owned[slot]) owned[slot] = { ...owned[slot], kind: next.kind };+ },+ showSlot(slot, cand, box, look) {+ if (owned[slot]?.key !== cand.key) calls.push(['show', slot, cand.key]);+ owned[slot] = { key: cand.key, kind: host.kind, ...look };+ peak = Math.max(peak, this.ownedCount());+ return true;+ },+ hideSlot(slot) {+ owned[slot] = null;+ },+ setAlpha(slot, alpha) {+ calls.push(['alpha', slot, alpha]);+ },+ getOwned: () => ({ ...owned }),+ ownedCount: () => ['a', 'b'].filter((slot) => owned[slot]).length,+ peak: () => peak,+ destroy() {+ calls.push(['destroy']);+ },+ };+}++export function fakeThumbnails() {+ const calls = [];+ const listeners = new Set();+ const statuses = new Map();+ /** Every key the layer asked to probe, in the order it asked. */+ const requested = [];+ /** Direct `request` calls: `[key, priority]`. */+ const requests = [];+ const ask = (key) => {+ if (!requested.includes(key)) requested.push(key);+ };+ return {+ calls,+ requested,+ requests,+ requestOrdered(candidates, box, window) {+ calls.push(['ordered', candidates.map((c) => c.key), window]);+ const { focusIndex, firstVisible, lastVisible, extra } = window;+ thumbnailOrder(+ focusIndex,+ firstVisible,+ lastVisible,+ candidates.length,+ extra,+ ).forEach((index) => ask(candidates[index].key));+ },+ request(candidate, box, priority) {+ ask(candidate.key);+ requests.push([candidate.key, priority]);+ },+ /** Settle every requested key still unknown, as the loader would. */+ probeRequested(status = 'present') {+ for (const key of requested)+ if (!statuses.has(key)) this.probe(key, status);+ },+ clear() {+ calls.push(['clear']);+ },+ get: (key) => ({ status: statuses.get(key) || 'unknown' }),+ /** Record a probe result and tell the layer, as the loader does. */+ probe(key, status) {+ statuses.set(key, status);+ for (const listener of listeners) listener(key);+ },+ /** Record a probe result without telling anyone yet. */+ setStatus: (key, status) => statuses.set(key, status),+ subscribe(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ destroy() {+ calls.push(['destroy']);+ },+ };+}++export function fakeCatalog() {+ const searches = [];+ return {+ searches,+ searchHls(request) {+ return new Promise((resolve, reject) => {+ request.signal?.addEventListener('abort', () =>+ reject(new Error('aborted')),+ );+ searches.push({ request, resolve, reject });+ });+ },+ resolveLast(candidates = CANDIDATES) {+ searches.at(-1).resolve({ candidates, truncated: false, errors: [] });+ },+ };+}++/** A map controller whose lease settles when the test says so. */+export function fakeController({ refuse = false } = {}) {+ const calls = [];+ const controller = {+ calls,+ acquireImageryComparison(options) {+ calls.push(['acquire', options.owner, options.switchPolicy]);+ if (refuse) throw new Error('held by bhote');+ let settle;+ const ready = new Promise((resolve) => {+ settle = resolve;+ });+ controller.lease = {+ ready,+ release: () => {+ calls.push(['release']);+ return Promise.resolve();+ },+ settle: (result = { status: 'ready' }) => settle(result),+ };+ return controller.lease;+ },+ };+ return controller;+}diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.jsnew file mode 100644index 000000000..47c383f13--- /dev/null+++ b/src/layers/recentImagery/thumbnails.js@@ -0,0 +1,279 @@+/**+ * Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per+ * candidate day. The response's `Data-Present` header is the only proof that+ * a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and+ * `Acquisition-Time` carries the sensing time. Fetches are bounded, and so+ * are decoded images: residency is least-recently-USED, where a request or a+ * completed decode is a use and a `get` read never is (the panel reads every+ * card on every render, so a read that counted would evict the visible cards+ * first). Eviction revokes the image only; what the probe proved is kept.+ */+import { thumbnailOrder, wvsSnapshotUrl } from './model.js';++const EMPTY = Object.freeze({+ status: 'unknown',+ objectUrl: null,+ acquisitionTime: null,+ loading: false,+});++/**+ * @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options]+ */+export function createThumbnailLoader({+ fetchImpl = globalThis.fetch?.bind(globalThis),+ maxInFlight = 3,+ maxDecoded = 16,+ createObjectUrl = (blob) => URL.createObjectURL(blob),+ revokeObjectUrl = (url) => URL.revokeObjectURL(url),+ size = 256,+} = {}) {+ const limit = Math.max(1, Math.trunc(maxInFlight) || 1);+ const resident = Math.max(1, Math.trunc(maxDecoded) || 1);+ const entries = new Map();+ const listeners = new Set();+ const queue = [];+ let inFlight = 0;+ let touchCounter = 0;+ let destroyed = false;++ function notify(key) {+ for (const listener of [...listeners]) {+ try {+ listener(key);+ } catch (error) {+ console.warn('[Data:RecentImagery] thumbnail listener failed:', error);+ }+ }+ }++ function touch(entry) {+ touchCounter += 1;+ entry.touched = touchCounter;+ }++ function revokeImage(entry) {+ if (!entry.objectUrl) return;+ try {+ revokeObjectUrl(entry.objectUrl);+ } catch {+ /* a revoked URL is already gone */+ }+ entry.objectUrl = null;+ }++ function evictDecoded(keep) {+ const decoded = [...entries.values()]+ .filter((entry) => entry.objectUrl && entry !== keep)+ .sort((a, b) => a.touched - b.touched);+ let count = decoded.length + (keep?.objectUrl ? 1 : 0);+ for (const entry of decoded) {+ if (count <= resident) break;+ revokeImage(entry);+ notify(entry.key);+ count -= 1;+ }+ }++ function enqueue(entry) {+ if (!queue.includes(entry)) queue.push(entry);+ pump();+ }++ async function run(entry) {+ const controller = new AbortController();+ entry.controller = controller;+ entry.loading = true;+ inFlight += 1;+ let status = 'error';+ let objectUrl = null;+ let acquisitionTime = null;+ let cancelled = false;+ try {+ const url = wvsSnapshotUrl({+ product: entry.candidate.product,+ day: entry.candidate.day,+ box: entry.box,+ width: size,+ height: size,+ });+ const response = await fetchImpl(url, { signal: controller.signal });+ if (controller.signal.aborted) {+ cancelled = true;+ } else if (response?.ok) {+ const present = String(+ response.headers?.get?.('Data-Present') ?? 'true',+ ).toLowerCase();+ acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;+ if (present === 'false') {+ status = 'empty';+ } else {+ const blob = await response.blob();+ if (controller.signal.aborted) cancelled = true;+ else {+ objectUrl = createObjectUrl(blob);+ status = 'present';+ }+ }+ }+ } catch (error) {+ if (controller.signal.aborted || error?.name === 'AbortError')+ cancelled = true;+ else status = 'error';+ } finally {+ inFlight -= 1;+ entry.loading = false;+ entry.controller = null;+ }+ // Every settlement frees a slot, so a cancelled fetch pumps too.+ if (cancelled || destroyed || entries.get(entry.key) !== entry) {+ if (objectUrl) revokeObjectUrl(objectUrl);+ pump();+ return;+ }+ // A failed re-fetch of an evicted image keeps what the day proved.+ if (status !== 'error' || entry.status !== 'present') {+ entry.status = status;+ entry.acquisitionTime = acquisitionTime;+ }+ entry.objectUrl = objectUrl;+ touch(entry);+ if (objectUrl) evictDecoded(entry);+ notify(entry.key);+ pump();+ }++ function pump() {+ if (destroyed) return;+ queue.sort((a, b) => a.priority - b.priority);+ while (inFlight < limit && queue.length) {+ const entry = queue.shift();+ if (entries.get(entry.key) !== entry) continue;+ void run(entry);+ }+ }++ return {+ /**+ * Ask for one candidate's thumbnail. Lower priority loads sooner. A day+ * already known is only touched (and re-prioritised while it waits); a+ * known-present day whose image was evicted is fetched again.+ * @param {object} candidate+ * @param {object} box Degrees box.+ * @param {number} [priority]+ */+ request(candidate, box, priority = 0) {+ if (destroyed || !candidate?.key || !box) return;+ const key = candidate.key;+ const existing = entries.get(key);+ if (existing) {+ touch(existing);+ if (existing.loading) return;+ if (existing.status === 'unknown') {+ existing.priority = priority;+ } else if (existing.status === 'present' && !existing.objectUrl) {+ existing.priority = priority;+ enqueue(existing);+ }+ return;+ }+ const entry = {+ key,+ candidate,+ box,+ priority,+ status: 'unknown',+ objectUrl: null,+ acquisitionTime: null,+ loading: false,+ controller: null,+ touched: 0,+ };+ touch(entry);+ entries.set(key, entry);+ enqueue(entry);+ },++ /**+ * Request the visible window of a strip in `thumbnailOrder` priority.+ * @param {Array<object>} candidates+ * @param {object} box+ * @param {{ focusIndex: number, firstVisible: number, lastVisible: number, extra?: number }} window+ */+ requestOrdered(+ candidates,+ box,+ { focusIndex, firstVisible, lastVisible, extra },+ ) {+ const order = thumbnailOrder(+ focusIndex,+ firstVisible,+ lastVisible,+ candidates.length,+ extra,+ );+ order.forEach((index, priority) => {+ this.request(candidates[index], box, priority);+ });+ },++ /**+ * Abort every fetch in flight and forget every unsettled request. A+ * known day whose image was being fetched again keeps what it knows.+ */+ cancelAll() {+ queue.length = 0;+ for (const entry of [...entries.values()]) {+ if (entry.loading) entry.controller?.abort();+ if (entry.status === 'unknown') entries.delete(entry.key);+ }+ },++ /** Cancel everything and revoke every decoded thumbnail. */+ clear() {+ this.cancelAll();+ for (const entry of entries.values()) revokeImage(entry);+ entries.clear();+ },++ /**+ * Read a day's state. A read is not a use: it never changes residency.+ * @param {string} key Candidate key.+ * @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}+ */+ get(key) {+ const entry = entries.get(key);+ if (!entry) return EMPTY;+ return {+ status: entry.status,+ objectUrl: entry.objectUrl,+ acquisitionTime: entry.acquisitionTime,+ loading: entry.loading,+ };+ },++ /** @param {(key: string) => void} listener */+ subscribe(listener) {+ if (typeof listener !== 'function') return () => {};+ listeners.add(listener);+ return () => listeners.delete(listener);+ },++ stats() {+ return {+ inFlight,+ queued: queue.length,+ decoded: [...entries.values()].filter((entry) => entry.objectUrl)+ .length,+ tracked: entries.size,+ };+ },++ destroy() {+ if (destroyed) return;+ this.clear();+ destroyed = true;+ listeners.clear();+ },+ };+}diff --git a/src/layers/recentImagery/thumbnails.test.mjs b/src/layers/recentImagery/thumbnails.test.mjsnew file mode 100644index 000000000..891b2e8dd--- /dev/null+++ b/src/layers/recentImagery/thumbnails.test.mjs@@ -0,0 +1,317 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createThumbnailLoader } from './thumbnails.js';+import { BOX, response, settle } from './testDoubles.mjs';++const candidate = (product, day) => ({+ key: `${product}:${day}`,+ product,+ day,+});++/** A fetch whose responses the test releases, in any order. */+function fakeFetch() {+ const calls = [];+ const impl = (url, { signal } = {}) =>+ new Promise((resolve, reject) => {+ signal?.addEventListener('abort', () =>+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),+ );+ calls.push({ url, signal, resolve });+ });+ const respond = (index, { ok = true, present = 'true' } = {}) =>+ calls[index].resolve(+ response({+ ok,+ headers: {+ 'Data-Present': present,+ 'Acquisition-Time': '2026-09-18T17:12:00Z',+ },+ }),+ );+ return { impl, calls, respond };+}++function fixture(options = {}) {+ const fetch = fakeFetch();+ const created = [];+ const revoked = [];+ const loader = createThumbnailLoader({+ fetchImpl: fetch.impl,+ createObjectUrl: () => {+ created.push(`blob:${created.length + 1}`);+ return created.at(-1);+ },+ revokeObjectUrl: (url) => revoked.push(url),+ ...options,+ });+ return { loader, fetch, created, revoked };+}++test('Data-Present decides the day: present with an object URL and sensing time, empty, or error', async () => {+ const { loader, fetch, created } = fixture();+ const changes = [];+ loader.subscribe((key) => changes.push(key));+ loader.request(candidate('S30', '2026-09-18'), BOX, 0);+ loader.request(candidate('L30', '2026-09-16'), BOX, 1);+ loader.request(candidate('VIIRS', '2026-09-15'), BOX, 2);+ assert.equal(loader.get('S30:2026-09-18').loading, true);+ assert.match(+ fetch.calls[0].url,+ /wvs\.earthdata\.nasa\.gov.*HLS_S30.*TIME=2026-09-18.*WIDTH=256&HEIGHT=256/,+ );+ fetch.respond(0);+ fetch.respond(1, { present: 'false' });+ fetch.respond(2, { ok: false });+ await settle();+ assert.deepEqual(loader.get('S30:2026-09-18'), {+ status: 'present',+ objectUrl: 'blob:1',+ acquisitionTime: '2026-09-18T17:12:00Z',+ loading: false,+ });+ assert.equal(loader.get('L30:2026-09-16').status, 'empty');+ assert.equal(loader.get('VIIRS:2026-09-15').status, 'error');+ assert.deepEqual(created, ['blob:1']);+ assert.deepEqual(changes.sort(), [+ 'L30:2026-09-16',+ 'S30:2026-09-18',+ 'VIIRS:2026-09-15',+ ]);+ assert.equal(loader.get('nope').status, 'unknown');+});++test('at most maxInFlight fetches run and the queue drains by priority', async () => {+ const { loader, fetch } = fixture({ maxInFlight: 2 });+ loader.request(candidate('S30', '2026-09-10'), BOX, 5);+ loader.request(candidate('S30', '2026-09-11'), BOX, 1);+ loader.request(candidate('S30', '2026-09-12'), BOX, 0);+ loader.request(candidate('S30', '2026-09-13'), BOX, 3);+ // The pump is eager: the first two arrivals start at once, the rest queue.+ assert.equal(fetch.calls.length, 2);+ assert.match(fetch.calls[0].url, /TIME=2026-09-10/);+ assert.match(fetch.calls[1].url, /TIME=2026-09-11/);+ assert.deepEqual(loader.stats(), {+ inFlight: 2,+ queued: 2,+ decoded: 0,+ tracked: 4,+ });+ fetch.respond(0);+ await settle();+ assert.equal(fetch.calls.length, 3);+ assert.match(fetch.calls[2].url, /TIME=2026-09-12/, 'priority 0 before 3');+ // A repeat request for a queued key just re-prioritises it.+ loader.request(candidate('S30', '2026-09-13'), BOX, 0);+ assert.equal(loader.stats().tracked, 4);+ fetch.respond(1);+ await settle();+ assert.equal(fetch.calls.length, 4);+ assert.match(fetch.calls[3].url, /TIME=2026-09-13/);+});++test('requestOrdered loads the focused card first, then outward, then the margins', () => {+ const { loader, fetch } = fixture({ maxInFlight: 10 });+ const candidates = Array.from({ length: 8 }, (_, i) =>+ candidate('S30', `2026-09-${String(10 + i).padStart(2, '0')}`),+ );+ loader.requestOrdered(candidates, BOX, {+ focusIndex: 3,+ firstVisible: 2,+ lastVisible: 5,+ extra: 1,+ });+ const days = fetch.calls.map(+ (call) => /TIME=2026-09-(\d\d)/.exec(call.url)[1],+ );+ assert.deepEqual(days, ['13', '14', '12', '15', '16', '11']);+});++test('decoded thumbnails are evicted least-recently-used and revoked; a read is not a use and an evicted day keeps what it learned', async () => {+ const { loader, fetch, revoked } = fixture({+ maxInFlight: 10,+ maxDecoded: 2,+ });+ loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ loader.request(candidate('S30', '2026-09-11'), BOX, 1);+ loader.request(candidate('S30', '2026-09-12'), BOX, 2);+ fetch.respond(0);+ fetch.respond(1);+ await settle();+ assert.equal(loader.stats().decoded, 2);+ loader.get('S30:2026-09-10'); // reading the oldest does not make it recent+ fetch.respond(2);+ await settle();+ assert.equal(loader.stats().decoded, 2);+ assert.deepEqual(revoked, ['blob:1']);+ const evicted = loader.get('S30:2026-09-10');+ assert.equal(evicted.status, 'present', 'availability survives eviction');+ assert.equal(evicted.objectUrl, null);+ assert.equal(evicted.acquisitionTime, '2026-09-18T17:12:00Z');+ assert.equal(loader.stats().tracked, 3, 'the entry is kept');+ assert.equal(loader.get('S30:2026-09-11').objectUrl, 'blob:2');+ assert.equal(loader.get('S30:2026-09-12').objectUrl, 'blob:3');+ // A repeat request IS a use, and re-fetches an evicted day without ever+ // reporting it unknown; 11 is now the LRU and goes when 10 comes back.+ loader.request(candidate('S30', '2026-09-12'), BOX, 0);+ loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ assert.equal(fetch.calls.length, 4, 'an evicted day is fetched again');+ assert.equal(loader.get('S30:2026-09-10').status, 'present');+ assert.equal(loader.get('S30:2026-09-10').loading, true);+ fetch.respond(3);+ await settle();+ assert.equal(loader.get('S30:2026-09-10').objectUrl, 'blob:4');+ assert.deepEqual(revoked, ['blob:1', 'blob:2']);+ assert.equal(loader.get('S30:2026-09-11').status, 'present');+ assert.equal(loader.get('S30:2026-09-12').objectUrl, 'blob:3');+ // A day that already holds an image is not fetched twice.+ loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ assert.equal(fetch.calls.length, 4);+});++test('reading every card in strip order (a snapshot) never decides who is evicted; evicted days stay known and come back on request', async () => {+ const { loader, fetch, revoked } = fixture({+ maxInFlight: 20,+ maxDecoded: 9,+ });+ const candidates = Array.from({ length: 20 }, (_, i) =>+ candidate('S30', `2026-09-${String(i + 1).padStart(2, '0')}`),+ );+ candidates.forEach((c, i) => loader.request(c, BOX, i));+ assert.equal(fetch.calls.length, 20);+ // Decode the strip back to front, leaving the newest card in flight.+ for (let i = 19; i >= 1; i -= 1) fetch.respond(i);+ await settle();+ const holders = () =>+ candidates.filter((c) => loader.get(c.key).objectUrl).map((c) => c.key);+ assert.equal(loader.stats().decoded, 9);+ assert.equal(loader.stats().tracked, 20);+ assert.deepEqual(+ holders(),+ candidates.slice(1, 10).map((c) => c.key),+ 'the nine most recently decoded',+ );+ // Sweep every card in strip order, several times, as getSnapshot does.+ for (let pass = 0; pass < 3; pass += 1)+ for (const c of candidates) loader.get(c.key);+ assert.deepEqual(+ holders(),+ candidates.slice(1, 10).map((c) => c.key),+ );+ // The last decode evicts the least recently DECODED card, not the first+ // card the sweep happened to read.+ fetch.respond(0);+ await settle();+ assert.deepEqual(+ holders(),+ candidates.slice(0, 9).map((c) => c.key),+ );+ assert.equal(revoked.length, 11);+ for (const c of candidates) {+ const entry = loader.get(c.key);+ assert.equal(entry.status, 'present', `${c.key} stays present`);+ assert.equal(entry.acquisitionTime, '2026-09-18T17:12:00Z');+ assert.equal(entry.loading, false);+ }+ // Re-requesting an evicted day fetches it again and it holds an image.+ const evictedKey = candidates[15].key;+ assert.equal(loader.get(evictedKey).objectUrl, null);+ loader.request(candidates[15], BOX, 0);+ assert.equal(fetch.calls.length, 21);+ assert.equal(loader.get(evictedKey).status, 'present');+ fetch.respond(20);+ await settle();+ assert.ok(loader.get(evictedKey).objectUrl);+ assert.equal(loader.stats().decoded, 9);+ assert.equal(loader.stats().tracked, 20);+});++test('cancelAll aborts in-flight fetches and a late settle never leaks an object URL', async () => {+ const { loader, fetch, created, revoked } = fixture({ maxInFlight: 1 });+ loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ loader.request(candidate('S30', '2026-09-11'), BOX, 1);+ const signal = fetch.calls[0].signal;+ loader.cancelAll();+ assert.equal(signal.aborted, true);+ assert.deepEqual(loader.stats(), {+ inFlight: 1,+ queued: 0,+ decoded: 0,+ tracked: 0,+ });+ await settle();+ assert.equal(loader.stats().inFlight, 0);+ assert.deepEqual(created, []);+ assert.deepEqual(revoked, []);+ assert.equal(loader.get('S30:2026-09-10').status, 'unknown');+});++test('clear and destroy revoke every resident thumbnail', async () => {+ const { loader, fetch, revoked } = fixture({ maxInFlight: 10 });+ loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ loader.request(candidate('S30', '2026-09-11'), BOX, 1);+ fetch.respond(0);+ fetch.respond(1);+ await settle();+ loader.clear();+ assert.deepEqual(revoked.sort(), ['blob:1', 'blob:2']);+ assert.equal(loader.stats().tracked, 0);+ loader.request(candidate('S30', '2026-09-12'), BOX, 0);+ fetch.respond(2);+ await settle();+ loader.destroy();+ assert.equal(revoked.length, 3);+ loader.request(candidate('S30', '2026-09-13'), BOX, 0);+ assert.equal(fetch.calls.length, 3, 'a destroyed loader fetches nothing');+});++test('a request queued behind an aborted fetch still starts once the abort settles', async () => {+ // A response that arrives after the abort (the fetch ignored the signal).+ const calls = [];+ const fetchImpl = (url, { signal } = {}) =>+ new Promise((resolve) => calls.push({ url, signal, resolve }));+ const loader = createThumbnailLoader({+ fetchImpl,+ maxInFlight: 1,+ createObjectUrl: () => 'blob:x',+ revokeObjectUrl: () => {},+ });+ loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ loader.clear();+ loader.request(candidate('S30', '2026-09-11'), BOX, 0);+ assert.equal(calls[0].signal.aborted, true);+ assert.deepEqual(loader.stats(), {+ inFlight: 1,+ queued: 1,+ decoded: 0,+ tracked: 1,+ });+ calls[0].resolve({+ ok: true,+ headers: { get: () => null },+ blob: async () => ({}),+ });+ await settle();+ assert.equal(calls.length, 2, 'the replacement request was pumped');+ assert.match(calls[1].url, /TIME=2026-09-11/);+ assert.deepEqual(loader.stats(), {+ inFlight: 1,+ queued: 0,+ decoded: 0,+ tracked: 1,+ });++ // The same sequence when the fetch rejects with AbortError instead.+ const rejecting = fixture({ maxInFlight: 1 });+ rejecting.loader.request(candidate('S30', '2026-09-10'), BOX, 0);+ rejecting.loader.clear();+ rejecting.loader.request(candidate('S30', '2026-09-11'), BOX, 0);+ await settle();+ assert.equal(rejecting.fetch.calls.length, 2);+ assert.deepEqual(rejecting.loader.stats(), {+ inFlight: 1,+ queued: 0,+ decoded: 0,+ tracked: 1,+ });+});diff --git a/src/maps/controller.js b/src/maps/controller.jsindex 5154105a6..e595ede26 100644--- a/src/maps/controller.js+++ b/src/maps/controller.js@@ -1,6 +1,13 @@import { indexMapSources } from './registry.js';import * as Cesium from 'cesium';import { createMapCredits } from './credits.js';+import { acquireImageryComparison } from './imageryComparison.js';++/**+ * Private `setStack` option marking a switch the controller issues itself+ * (a tile-failure fallback); outside callers cannot forge it.+ */+const AUTOMATIC = Symbol('automatic switch');/** Coordinate source lifetimes and scene changes; the registry owns provider choices. */export class MapSourceController {@@ -33,12 +40,15 @@ export class MapSourceController {this._ownedTilesets = new Set();this._disposed = new WeakSet();this._switchGen = 0;+ /** Who chose the current generation's stack: 'manual' | 'automatic'. */+ this._switchOrigin = 'manual';this._isSwitching = false;this._lastError = null;this._imageryLayer = null;this._activeImageryProvider = null;this._removeImageryErrorListener = null;this._terrainMode = null;+ this._subscribers = new Set();this._destroyed = false;}@@ -84,6 +94,16 @@ export class MapSourceController {getSwitchGeneration() {return this._switchGen;}+ /**+ * Who chose the stack of the current switch generation: 'manual' for a+ * `setStack` issued from outside (the operator, a scene, a lease),+ * 'automatic' when the controller replaced it itself (a construction or+ * tile-failure fallback, or a recovery after a failed activation).+ * @returns {'manual' | 'automatic'}+ */+ getSwitchOrigin() {+ return this._switchOrigin;+ }getState(status = this._isSwitching ? 'switching' : 'ready') {return {activeId: this._activeId,@@ -91,6 +111,7 @@ export class MapSourceController {stacks: this.getStacks(),status,lastError: this._lastError,+ switchOrigin: this._switchOrigin,...this._registry.state,};}@@ -98,7 +119,48 @@ export class MapSourceController {this._onChange?.(this.getState(status));}- async setStack(id, { silent = false } = {}) {+ /**+ * Hear every settled activation: a stack switch, a silent switch, a+ * fallback after a failure, a recovery. Unlike `onChange` (the UI's+ * status feed, muted by `silent`), listeners fire once per `setStack`+ * after `_activeId` has settled, so a layer that drapes on the active+ * host can rebind. The state's `switchOrigin` says whether the caller+ * ('manual') or the controller itself ('automatic') chose the settled+ * stack. A listener that throws is logged, never fatal.+ * @param {(state: object) => void} listener+ * @returns {() => void} Unsubscribe.+ */+ subscribe(listener) {+ if (typeof listener !== 'function') return () => {};+ this._subscribers.add(listener);+ return () => {+ this._subscribers.delete(listener);+ };+ }++ _notifySubscribers() {+ if (this._destroyed || !this._subscribers.size) return;+ const state = this.getState();+ for (const listener of [...this._subscribers]) {+ try {+ listener(state);+ } catch (error) {+ console.warn('[MapSourceController] subscriber failed:', error);+ }+ }+ }++ /**+ * Lease the map for an imagery comparison. switchPolicy: 'preserve' (never+ * switch) | 'esri' (switch to Esri imagery from any other stack) |+ * 'esri-if-photoreal' (switch only when Google 3D is active). Throws while+ * another owner holds the lease; see acquireImageryComparison().+ */+ acquireImageryComparison(options) {+ return acquireImageryComparison(this, options);+ }++ async setStack(id, { silent = false, [AUTOMATIC]: automatic = false } = {}) {if (this._destroyed) return this.getState();const stack = this.getStack(id) || this.getStack(this._registry.unknownId);if (!stack) return null;@@ -109,6 +171,7 @@ export class MapSourceController {return this.getState();}const gen = ++this._switchGen;+ this._switchOrigin = automatic ? 'automatic' : 'manual';this._isSwitching = true;this._lastError = null;if (!silent) this._emitChange('switching');@@ -116,6 +179,7 @@ export class MapSourceController {const activation = await this._activate(stack, gen);if (gen !== this._switchGen) return this.getState();this._activeId = activation?.effectiveStackId || stack.id;+ if (this._activeId !== stack.id) this._switchOrigin = 'automatic';if (activation?.fallbackMessage) {this._lastError = activation.fallbackMessage;this._onError?.(activation.fallbackMessage, stack);@@ -133,6 +197,8 @@ export class MapSourceController {recovery.id !== stack.id &&this.isStackAvailable(recovery.id)) {+ // Whatever settles now is the controller's choice, not the caller's.+ this._switchOrigin = 'automatic';try {const activation = await this._activate(recovery, gen);if (gen !== this._switchGen) return this.getState();@@ -145,7 +211,12 @@ export class MapSourceController {}if (!silent) this._emitChange('error');} finally {- if (gen === this._switchGen) this._isSwitching = false;+ if (gen === this._switchGen) {+ this._isSwitching = false;+ // The active id has settled for this generation (activated, fell+ // back, or recovered): every subscriber hears it, silent or not.+ this._notifySubscribers();+ }}return this.getState();}@@ -290,7 +361,7 @@ export class MapSourceController {this.getStack(resolution.effectiveStackId),);const expectedGen = this._switchGen + 1;- void this.setStack(fallback.id, { silent: true })+ void this.setStack(fallback.id, { silent: true, [AUTOMATIC]: true }).then((state) => {if (!this._destroyed &&@@ -324,6 +395,7 @@ export class MapSourceController {destroy() {if (this._destroyed) return;this._destroyed = true;+ this._subscribers.clear();this._switchGen++;this._abort.abort();this._isSwitching = false;diff --git a/src/maps/controller.test.mjs b/src/maps/controller.test.mjsindex a81cfec07..1e6c1413f 100644--- a/src/maps/controller.test.mjs+++ b/src/maps/controller.test.mjs@@ -458,3 +458,384 @@ test('imagery host tileset follows supplied, owned and globe map sources', asynccontroller.destroy();assert.equal(controller.getImageryHostTileset(), null);});++function leaseFixture() {+ const env = publicFixture();+ const switches = [];+ const setStack = env.controller.setStack.bind(env.controller);+ env.controller.setStack = (id, options) => {+ switches.push(id);+ return setStack(id, options);+ };+ return { ...env, switches };+}++test('an imagery comparison lease rejects a second owner synchronously until released', async () => {+ const env = leaseFixture();+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'preserve',+ });+ assert.throws(+ () => env.controller.acquireImageryComparison({ owner: 'recent' }),+ /held by nepal/,+ );+ assert.deepEqual(await lease.ready, {+ status: 'ready',+ activeId: 'photoreal',+ });+ await lease.release();+ const next = env.controller.acquireImageryComparison({ owner: 'recent' });+ assert.deepEqual(await next.ready, {+ status: 'ready',+ activeId: 'photoreal',+ });+ await next.release();+ assert.deepEqual(env.switches, []);+ env.controller.destroy();+});++test("the 'esri' policy switches from any other stack and release restores it", async () => {+ for (const initial of ['photoreal', 'osm']) {+ const env = leaseFixture();+ if (initial !== env.controller.getActiveId())+ await env.controller.setStack(initial);+ env.switches.length = 0;+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ assert.deepEqual(await lease.ready, {+ status: 'ready',+ activeId: 'esri-imagery',+ });+ assert.equal(env.controller.getActiveId(), 'esri-imagery');+ await lease.release();+ assert.equal(env.controller.getActiveId(), initial);+ assert.deepEqual(env.switches, ['esri-imagery', initial]);+ env.controller.destroy();+ }+});++test("the 'esri-if-photoreal' policy leaves any 2D basemap alone", async () => {+ const photoreal = leaseFixture();+ const fromPhotoreal = photoreal.controller.acquireImageryComparison({+ owner: 'recent',+ switchPolicy: 'esri-if-photoreal',+ });+ assert.equal((await fromPhotoreal.ready).activeId, 'esri-imagery');+ await fromPhotoreal.release();+ assert.deepEqual(photoreal.switches, ['esri-imagery', 'photoreal']);+ photoreal.controller.destroy();++ const osm = leaseFixture();+ await osm.controller.setStack('osm');+ osm.switches.length = 0;+ const fromOsm = osm.controller.acquireImageryComparison({+ owner: 'recent',+ switchPolicy: 'esri-if-photoreal',+ });+ assert.deepEqual(await fromOsm.ready, { status: 'ready', activeId: 'osm' });+ await fromOsm.release();+ assert.equal(osm.controller.getActiveId(), 'osm');+ assert.deepEqual(osm.switches, []);+ osm.controller.destroy();+});++test("the 'preserve' policy never switches, whatever is active", async () => {+ for (const initial of ['photoreal', 'esri-imagery', 'osm']) {+ const env = leaseFixture();+ if (initial !== env.controller.getActiveId())+ await env.controller.setStack(initial);+ env.switches.length = 0;+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ });+ assert.deepEqual(await lease.ready, { status: 'ready', activeId: initial });+ await lease.release();+ assert.equal(env.controller.getActiveId(), initial);+ assert.deepEqual(env.switches, []);+ env.controller.destroy();+ }+});++test('release keeps an operator choice made while the comparison was open', async () => {+ const env = leaseFixture();+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ await lease.ready;+ await env.controller.setStack('osm');+ await lease.release();+ assert.equal(env.controller.getActiveId(), 'osm');+ assert.deepEqual(env.switches, ['esri-imagery', 'osm']);+ env.controller.destroy();+});++test('release keeps a fallback that replaced the comparison stack', async () => {+ const env = leaseFixture();+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ await lease.ready;+ const errors = env.providers.get('esri-imagery').errorEvent;+ errors.raise();+ errors.raise();+ await settle();+ assert.equal(env.controller.getActiveId(), 'osm');+ await lease.release();+ assert.equal(env.controller.getActiveId(), 'osm');+ assert.deepEqual(env.switches, ['esri-imagery', 'osm']);+ env.controller.destroy();+});++test('release during acquisition lets no late activation survive', async () => {+ const env = leaseFixture();+ let resolve;+ env.registry.sources.find(+ (source) => source.descriptor.id === 'esri-imagery',+ ).imagery = () =>+ new Promise((done) => {+ resolve = done;+ });+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ await settle();+ const releasing = lease.release();+ resolve(env.providers.get('esri-imagery'));+ assert.deepEqual(await lease.ready, {+ status: 'superseded',+ activeId: 'photoreal',+ });+ await releasing;+ await settle();+ assert.equal(env.controller.getActiveId(), 'photoreal');+ assert.equal(env.viewer.scene.globe.show, false);+ assert.equal(env.imagery.length, 0);+ assert.equal(env.tileset.show, true);+ assert.deepEqual(env.switches, ['esri-imagery', 'photoreal']);+ env.controller.destroy();+});++test('release is idempotent and frees the lease for the next owner', async () => {+ const env = leaseFixture();+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ await lease.ready;+ const first = lease.release();+ assert.equal(lease.release(), first);+ await first;+ await lease.release();+ assert.deepEqual(env.switches, ['esri-imagery', 'photoreal']);+ const next = env.controller.acquireImageryComparison({+ owner: 'recent',+ switchPolicy: 'esri',+ });+ assert.equal((await next.ready).status, 'ready');+ await next.release();+ assert.deepEqual(env.switches, [+ 'esri-imagery',+ 'photoreal',+ 'esri-imagery',+ 'photoreal',+ ]);+ env.controller.destroy();+});++test('an unavailable comparison stack reports failure and release leaves the map alone', async () => {+ const env = leaseFixture();+ const errors = [];+ env.controller._onError = (message) => errors.push(message);+ const esri = env.controller._sources.get('esri-imagery');+ esri.available = false;+ esri.unavailableReason = 'Esri offline';+ const lease = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ assert.deepEqual(await lease.ready, {+ status: 'failed',+ activeId: 'photoreal',+ });+ await lease.release();+ assert.deepEqual(env.switches, ['esri-imagery']);+ assert.deepEqual(errors, ['Esri offline']);+ assert.equal(env.controller.getActiveId(), 'photoreal');+ env.controller.destroy();+});++test('a lease stays owned until its restoration settles, so a rival cannot read the comparison stack as its own', async () => {+ const env = leaseFixture();+ const lease = env.controller.acquireImageryComparison({+ owner: 'recent',+ switchPolicy: 'esri-if-photoreal',+ });+ assert.equal((await lease.ready).activeId, 'esri-imagery');+ // Hold the restore switch open: the map is still on Esri while it runs.+ const setStack = env.controller.setStack;+ let finishRestore;+ env.controller.setStack = (id, options) =>+ new Promise((resolve) => {+ finishRestore = () => resolve(setStack(id, options));+ });+ const releasing = lease.release();+ assert.equal(typeof finishRestore, 'function', 'the restore was issued');+ assert.throws(+ () =>+ env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ }),+ /held by recent/,+ 'the pending restoration still owns the lease',+ );+ finishRestore();+ await releasing;+ assert.equal(env.controller.getActiveId(), 'photoreal');+ env.controller.setStack = setStack;+ const next = env.controller.acquireImageryComparison({+ owner: 'nepal',+ switchPolicy: 'esri',+ });+ assert.deepEqual(await next.ready, {+ status: 'ready',+ activeId: 'esri-imagery',+ });+ await next.release();+ assert.equal(env.controller.getActiveId(), 'photoreal');+ assert.deepEqual(env.switches, [+ 'esri-imagery',+ 'photoreal',+ 'esri-imagery',+ 'photoreal',+ ]);+ env.controller.destroy();+});++test('subscribe hears every settled activation — silent switches, fallbacks and recoveries — until unsubscribed or destroyed', async () => {+ const env = publicFixture();+ const heard = [];+ const off = env.controller.subscribe((state) =>+ heard.push([state.activeId, state.status]),+ );+ assert.equal(typeof off, 'function');+ assert.equal(typeof env.controller.subscribe(null), 'function');+ await env.controller.setStack('esri-imagery');+ assert.deepEqual(heard, [['esri-imagery', 'ready']]);+ // A silent switch mutes onChange but not the subscription.+ const changesBefore = env.changes.length;+ await env.controller.setStack('photoreal', { silent: true });+ assert.equal(env.changes.length, changesBefore, 'onChange stays silent');+ assert.deepEqual(heard.at(-1), ['photoreal', 'ready']);+ // A subscriber that throws does not stop the others.+ const noisy = env.controller.subscribe(() => {+ throw new Error('listener failed');+ });+ const warn = console.warn;+ const warnings = [];+ console.warn = (...args) => warnings.push(args);+ try {+ await env.controller.setStack('esri-imagery');+ } finally {+ console.warn = warn;+ }+ assert.equal(warnings.length, 1);+ assert.deepEqual(heard.at(-1), ['esri-imagery', 'ready']);+ noisy();+ off();+ await env.controller.setStack('photoreal');+ assert.equal(heard.length, 3, 'unsubscribed listeners hear nothing');+ env.controller.destroy();++ // A failed activation that recovers still settles once, on the recovery.+ const recovering = fixture(+ {+ defaultId: 'first',+ recoveryId: 'recovery',+ sources: [+ {+ descriptor: descriptor('first'),+ imagery: async () => {+ throw new Error('first offline');+ },+ },+ { descriptor: descriptor('recovery'), imagery: async () => ({}) },+ ],+ },+ { onError: () => {} },+ );+ const recovered = [];+ recovering.controller.subscribe((state) => recovered.push(state.activeId));+ await recovering.controller.setStack('first');+ assert.deepEqual(recovered, ['recovery']);+ recovering.controller.destroy();+ await recovering.controller.setStack('first');+ assert.deepEqual(recovered, ['recovery'], 'a destroyed controller is mute');+});++test('each switch generation reports its origin: an outside setStack is manual, a fallback or recovery automatic', async () => {+ const env = publicFixture();+ const heard = [];+ env.controller.subscribe((state) =>+ heard.push([state.activeId, state.switchOrigin]),+ );+ await env.controller.setStack('esri-imagery');+ assert.equal(env.controller.getSwitchOrigin(), 'manual');+ const generation = env.controller.getSwitchGeneration();+ // Two tile failures: the controller falls back to OSM on its own.+ const errors = env.providers.get('esri-imagery').errorEvent;+ errors.raise();+ errors.raise();+ await settle();+ assert.equal(env.controller.getActiveId(), 'osm');+ assert.equal(env.controller.getSwitchGeneration(), generation + 1);+ assert.equal(env.controller.getSwitchOrigin(), 'automatic');+ assert.equal(env.controller.getState().switchOrigin, 'automatic');+ // A silent switch from outside is still the caller's choice.+ await env.controller.setStack('photoreal', { silent: true });+ assert.equal(env.controller.getSwitchOrigin(), 'manual');+ assert.deepEqual(heard, [+ ['esri-imagery', 'manual'],+ ['osm', 'automatic'],+ ['photoreal', 'manual'],+ ]);+ env.controller.destroy();++ // A failed activation that recovers settles as automatic.+ const recovering = fixture(+ {+ defaultId: 'first',+ recoveryId: 'recovery',+ sources: [+ {+ descriptor: descriptor('first'),+ imagery: async () => {+ throw new Error('first offline');+ },+ },+ { descriptor: descriptor('recovery'), imagery: async () => ({}) },+ ],+ },+ { onError: () => {} },+ );+ const recovered = [];+ recovering.controller.subscribe((state) =>+ recovered.push([state.activeId, state.switchOrigin]),+ );+ await recovering.controller.setStack('first');+ assert.equal(recovering.controller.getActiveId(), 'recovery');+ assert.equal(recovering.controller.getSwitchOrigin(), 'automatic');+ await recovering.controller.setStack('recovery');+ assert.equal(recovering.controller.getSwitchOrigin(), 'manual');+ assert.deepEqual(recovered, [+ ['recovery', 'automatic'],+ ['recovery', 'manual'],+ ]);+ recovering.controller.destroy();+});diff --git a/src/maps/imageryComparison.js b/src/maps/imageryComparison.jsnew file mode 100644index 000000000..5586bd86e--- /dev/null+++ b/src/maps/imageryComparison.js@@ -0,0 +1,124 @@+/** Basemap that before/after imagery comparisons are read against. */+export const IMAGERY_COMPARISON_STACK_ID = 'esri-imagery';++const SWITCH_POLICIES = new Set(['preserve', 'esri', 'esri-if-photoreal']);+const leases = new WeakMap();++function comparisonTargetId(activeId, switchPolicy) {+ if (!SWITCH_POLICIES.has(switchPolicy))+ throw new Error(+ `Unknown imagery comparison switch policy: ${switchPolicy}`,+ );+ if (switchPolicy === 'esri' && activeId !== IMAGERY_COMPARISON_STACK_ID)+ return IMAGERY_COMPARISON_STACK_ID;+ if (switchPolicy === 'esri-if-photoreal' && activeId === 'photoreal')+ return IMAGERY_COMPARISON_STACK_ID;+ return null;+}++/**+ * Lease the map for an imagery comparison.+ *+ * Works on any controller exposing getActiveId(), getSwitchGeneration() and+ * setStack(id); MapSourceController#acquireImageryComparison delegates here.+ * One lease per controller: acquiring while another owner holds it throws+ * synchronously. The previous stack id and the switch generation are recorded+ * the moment the switch is issued (not after awaiting it), so release() can+ * tell its own switch from a later operator choice. `ready` resolves to+ * `{ status: 'ready' | 'superseded' | 'failed', activeId }`; a resolved+ * setStack() does not mean success because the controller falls back+ * internally. release() is idempotent and restores the previous stack only+ * while the lease's own generation still owns the active stack; releasing+ * during acquisition re-issues the previous stack so the late activation+ * cannot survive. The lease stays owned until that restoration settles (a+ * rival acquiring meanwhile still throws), so nobody can read the comparison+ * stack as their own while it is on its way out; a release with nothing to+ * restore frees the lease synchronously.+ */+export function acquireImageryComparison(+ controller,+ { owner = 'imagery-comparison', switchPolicy = 'preserve' } = {},+) {+ if (!controller)+ throw new Error('Imagery comparison needs a map stack controller');+ const held = leases.get(controller);+ if (held)+ throw new Error(+ held.releasing+ ? `Imagery comparison is still held by ${held.owner} until its release settles`+ : `Imagery comparison is already held by ${held.owner}`,+ );+ const previousId = controller.getActiveId?.() ?? null;+ const targetId = comparisonTargetId(previousId, switchPolicy);+ const lease = {+ owner,+ generation: null,+ acquiring: false,+ releasing: null,+ };+ leases.set(controller, lease);+ const activeId = () => controller.getActiveId?.() ?? null;+ const generation = () => controller.getSwitchGeneration?.() ?? null;++ let ready;+ if (targetId) {+ lease.acquiring = true;+ let switching;+ try {+ switching = Promise.resolve(controller.setStack(targetId));+ } catch (error) {+ switching = Promise.reject(error);+ }+ lease.generation = generation();+ const settle = () => {+ lease.acquiring = false;+ };+ ready = switching.then(+ () => {+ settle();+ const active = activeId();+ const status =+ generation() !== lease.generation+ ? 'superseded'+ : active === targetId+ ? 'ready'+ : 'failed';+ return { status, activeId: active };+ },+ (error) => {+ settle();+ throw error;+ },+ );+ } else {+ ready = Promise.resolve({ status: 'ready', activeId: previousId });+ }++ const disown = () => {+ if (leases.get(controller) === lease) leases.delete(controller);+ };+ const release = () => {+ if (lease.releasing) return lease.releasing;+ const restore =+ Boolean(targetId) &&+ previousId != null &&+ previousId !== targetId &&+ generation() === lease.generation &&+ (lease.acquiring || activeId() === targetId);+ if (!restore) {+ disown();+ lease.releasing = Promise.resolve();+ return lease.releasing;+ }+ lease.releasing = (async () => {+ try {+ await controller.setStack(previousId);+ } finally {+ disown();+ }+ })();+ return lease.releasing;+ };++ return { ready, release };+}diff --git a/src/maps/imageryHost.js b/src/maps/imageryHost.jsnew file mode 100644index 000000000..2e227b47c--- /dev/null+++ b/src/maps/imageryHost.js@@ -0,0 +1,24 @@+/**+ * Where draped imagery can go on the current map stack. A globe stack drapes+ * on `viewer.imageryLayers`; a 3D-tiles stack hides the globe, and Cesium+ * 1.138 drapes imagery onto the tileset's own `imageryLayers` instead. When+ * neither exists there is nowhere to drape and the caller says so.+ */++/** Guidance shown when the active map stack cannot host draped imagery. */+export const NO_IMAGERY_HOST = 'Hidden by this map source · choose a globe map';++/**+ * Resolve the imagery layer collection for the active map stack.+ * @param {{ viewer?: object, tileset?: object }} scene+ * @returns {{ collection: object | null, kind: 'globe' | 'tileset' | 'none' }}+ */+export function resolveImageryHost({ viewer, tileset } = {}) {+ if (viewer?.scene?.globe?.show === true && viewer.imageryLayers) {+ return { collection: viewer.imageryLayers, kind: 'globe' };+ }+ if (tileset?.imageryLayers && !tileset.isDestroyed?.()) {+ return { collection: tileset.imageryLayers, kind: 'tileset' };+ }+ return { collection: null, kind: 'none' };+}diff --git a/src/maps/imageryHost.test.mjs b/src/maps/imageryHost.test.mjsnew file mode 100644index 000000000..edb2c3d0d--- /dev/null+++ b/src/maps/imageryHost.test.mjs@@ -0,0 +1,40 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { NO_IMAGERY_HOST, resolveImageryHost } from './imageryHost.js';++test('a shown globe hosts imagery on the viewer collection', () => {+ const imageryLayers = { id: 'globe' };+ const host = resolveImageryHost({+ viewer: { scene: { globe: { show: true } }, imageryLayers },+ tileset: { imageryLayers: { id: 'tiles' } },+ });+ assert.deepEqual(host, { collection: imageryLayers, kind: 'globe' });+});++test('a hidden globe hands imagery to the tileset collection', () => {+ const imageryLayers = { id: 'tiles' };+ const host = resolveImageryHost({+ viewer: { scene: { globe: { show: false } }, imageryLayers: {} },+ tileset: { imageryLayers, isDestroyed: () => false },+ });+ assert.deepEqual(host, { collection: imageryLayers, kind: 'tileset' });+});++test('no globe and no tileset means nowhere to drape', () => {+ assert.deepEqual(+ resolveImageryHost({+ viewer: { scene: { globe: { show: false } }, imageryLayers: {} },+ tileset: null,+ }),+ { collection: null, kind: 'none' },+ );+ assert.deepEqual(resolveImageryHost({}), { collection: null, kind: 'none' });+ assert.deepEqual(+ resolveImageryHost({+ viewer: { scene: { globe: { show: false } } },+ tileset: { imageryLayers: {}, isDestroyed: () => true },+ }),+ { collection: null, kind: 'none' },+ );+ assert.match(NO_IMAGERY_HOST, /globe map/);+});diff --git a/src/sharelink.celestial.test.mjs b/src/sharelink.celestial.test.mjsindex 25c20c0ea..554b23265 100644--- a/src/sharelink.celestial.test.mjs+++ b/src/sharelink.celestial.test.mjs@@ -138,6 +138,35 @@ test('visual parameters, explicit empty layers, and panel state are v2-only', ()assert.equal(legacy.panelState, null);});+// The panel chrome shares every rail panel, so the link registry must know+// each one: a collapsed Recent Imagery panel used to restore expanded because+// the encoder had no token for it.+test('a collapsed Recent Imagery panel survives the share-link round trip beside the older panels', () => {+ const manager = makeManager();+ manager.setPanelStateProvider(() => ({ specs: [+ { id: 'cctv-panel', collapsed: false },+ { id: 'recent-imagery-panel', collapsed: true },+ { id: 'global-context-panel', collapsed: true },+ ] }));+ clearTimeout(manager._debounceTimer);+ manager._updateHash();+ const params = new URLSearchParams(window.location.hash.slice(1));+ assert.equal(params.get('ui'), 'v.c.0_i.c.1_g.c.1');+ const restored = makeManager(`#v=2&lat=10&lon=20&ui=${params.get('ui')}`)+ .parseInitialHash();+ assert.deepEqual(restored.panelState, { specs: [+ { id: 'cctv-panel', collapsed: false, pinned: null },+ { id: 'recent-imagery-panel', collapsed: true, pinned: null },+ { id: 'global-context-panel', collapsed: true, pinned: null },+ ] });+ // A link written before the token existed decodes exactly as it did.+ const older = makeManager('#v=2&lat=10&lon=20&ui=v.c.1_g.c.0').parseInitialHash();+ assert.deepEqual(older.panelState, { specs: [+ { id: 'cctv-panel', collapsed: true, pinned: null },+ { id: 'global-context-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);diff --git a/src/sharelink.js b/src/sharelink.jsindex e1e7d6c93..08360932b 100644--- a/src/sharelink.js+++ b/src/sharelink.js@@ -40,6 +40,7 @@ const SHARE_PANEL_STATE_REGISTRY = Object.freeze([{ id: 'location-bar', token: 'l', pinnable: true },{ id: 'data-panel', token: 'd', pinnable: false },{ id: 'cctv-panel', token: 'v', pinnable: false },+ { id: 'recent-imagery-panel', token: 'i', pinnable: false },{ id: 'radio-panel', token: 'r', pinnable: false },{ id: 'scene-panel', token: 's', pinnable: false },{ id: 'global-context-panel', token: 'g', pinnable: false },diff --git a/src/ui/imageryBoxTool.js b/src/ui/imageryBoxTool.jsnew file mode 100644index 000000000..98b232f70--- /dev/null+++ b/src/ui/imageryBoxTool.js@@ -0,0 +1,293 @@+/**+ * Box selection for the Recent Imagery layer: press on the world, drag, and+ * release to hand the layer a degrees box. Follows the draw tool's ownership+ * rules — the pointer is claimed for the session, the viewer's own click+ * actions are borrowed and given back, and `destroy()` returns everything —+ * and freezes the camera only while a drag is in progress.+ */+import * as Cesium from 'cesium';+import { pickWorldFromScreen } from '../annotations/annotationResolver.js';+import {+ claimPointer,+ pointerOwner,+ releasePointer,+} from '../data/inputOwnership.js';+import { validateBox } from '../layers/recentImagery/model.js';++/** The id this tool claims the pointer under. */+export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';++/**+ * Wire the box tool.+ * @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps+ * `onEscape` runs before the tool cancels on Escape; returning `true` claims+ * the key (it is still consumed) and leaves the tool armed.+ * @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise<void> } | null}+ */+export function initImageryBoxTool({+ viewer,+ onBox,+ onCancel,+ onActive,+ onEscape,+ cesium = Cesium,+ pickWorld = pickWorldFromScreen,+ documentRef = globalThis.document,+} = {}) {+ if (!viewer?.scene || typeof onBox !== 'function') return null;++ let active = false;+ let destroyed = false;+ /** Drag corners in degrees; `anchor` is null while no drag is live. */+ let anchor = null;+ let corner = null;+ let handler = null;+ let lease = null;+ let savedSingleClick = null;+ let savedDoubleClick = null;+ let savedCameraInputs = null;++ const dragBox = () =>+ anchor && {+ west: Math.min(anchor.lon, corner.lon),+ south: Math.min(anchor.lat, corner.lat),+ east: Math.max(anchor.lon, corner.lon),+ north: Math.max(anchor.lat, corner.lat),+ };++ const dataSource = new cesium.CustomDataSource(+ 'gev-recent-imagery-box-preview',+ );+ let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(+ () => null,+ );+ const stroke = cesium.Color.fromCssColorString('#8be9ff');+ const previewRectangle = () => {+ const box = dragBox();+ return box+ ? cesium.Rectangle.fromDegrees(box.west, box.south, box.east, box.north)+ : undefined;+ };+ const previewOutline = () => {+ const box = dragBox();+ if (!box) return [];+ return cesium.Cartesian3.fromDegreesArray([+ box.west,+ box.south,+ box.east,+ box.south,+ box.east,+ box.north,+ box.west,+ box.north,+ box.west,+ box.south,+ ]);+ };+ const fill = dataSource.entities.add({+ show: false,+ rectangle: {+ coordinates: new cesium.CallbackProperty(previewRectangle, false),+ material: stroke.withAlpha(0.12),+ classificationType: cesium.ClassificationType.BOTH,+ },+ });+ // A rectangle graphic cannot draw a dashed edge on the ground, so the+ // outline is its own draped polyline traced round the same corners.+ const outline = dataSource.entities.add({+ show: false,+ polyline: {+ positions: new cesium.CallbackProperty(previewOutline, false),+ width: 2,+ clampToGround: true,+ classificationType: cesium.ClassificationType.BOTH,+ material: new cesium.PolylineDashMaterialProperty({+ color: stroke.withAlpha(0.95),+ dashLength: 12,+ }),+ },+ });++ const requestRender = () => viewer.scene.requestRender?.();+ const setPreview = (visible) => {+ fill.show = visible;+ outline.show = visible;+ requestRender();+ };+ const worldAt = (position) => {+ if (!position) return null;+ const canvas = viewer.scene.canvas;+ const w = canvas?.clientWidth || canvas?.width || 1;+ const h = canvas?.clientHeight || canvas?.height || 1;+ const point = pickWorld(viewer, position.x / w, position.y / h);+ const lon = Number(point?.lon);+ const lat = Number(point?.lat);+ return Number.isFinite(lon) && Number.isFinite(lat) ? { lon, lat } : null;+ };+ const cameraController = () => viewer.scene.screenSpaceCameraController;++ function freezeCamera() {+ const controller = cameraController();+ if (!controller || savedCameraInputs !== null) return;+ savedCameraInputs = controller.enableInputs;+ controller.enableInputs = false;+ }+ function thawCamera() {+ const controller = cameraController();+ if (controller && savedCameraInputs !== null)+ controller.enableInputs = savedCameraInputs;+ savedCameraInputs = null;+ }++ function endDrag() {+ anchor = null;+ corner = null;+ thawCamera();+ setPreview(false);+ }++ const onDown = (event) => {+ if (!active || destroyed || anchor) return;+ const point = worldAt(event.position);+ if (!point) {+ onCancel?.('sky', 'Press on the ground, not the sky');+ return;+ }+ anchor = point;+ corner = point;+ freezeCamera();+ setPreview(true);+ };+ const onMove = (event) => {+ const point = anchor && !destroyed && worldAt(event.endPosition);+ if (!point) return;+ corner = point;+ requestRender();+ };+ const onUp = (event) => {+ if (!anchor || destroyed) return;+ corner = worldAt(event.position) || corner;+ const box = dragBox();+ const result = validateBox(box);+ if (result.reason === 'degenerate') result.message = 'Drag to size the box';+ endDrag();+ setActive(false);+ if (result.ok) onBox(result.box);+ else onCancel?.(result.reason, result.message, box);+ };+ // Escape is taken from a document capture listener, ahead of every other+ // handler, so the interceptor runs first: when it claims the key (the+ // panel exits a live comparison), the tool stays armed and the key still+ // goes no further; otherwise Escape cancels the session.+ const onKey = (event) => {+ if (!active || destroyed || event.key !== 'Escape') return;+ event.preventDefault?.();+ event.stopImmediatePropagation?.();+ if (onEscape?.() === true) return;+ cancel('escape');+ };++ function bindScene() {+ if (handler) return;+ handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);+ handler.setInputAction(onDown, cesium.ScreenSpaceEventType.LEFT_DOWN);+ handler.setInputAction(onMove, cesium.ScreenSpaceEventType.MOUSE_MOVE);+ handler.setInputAction(onUp, cesium.ScreenSpaceEventType.LEFT_UP);+ const stock = viewer.screenSpaceEventHandler;+ if (stock) {+ savedSingleClick =+ stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK) || null;+ savedDoubleClick =+ stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||+ null;+ stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK);+ stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);+ }+ documentRef?.addEventListener?.('keydown', onKey, true);+ documentRef?.body?.classList?.add?.('gev-imagery-box');+ }++ function releaseScene() {+ if (handler) {+ handler.destroy();+ handler = null;+ }+ const stock = viewer.screenSpaceEventHandler;+ if (stock && savedSingleClick) {+ stock.setInputAction(+ savedSingleClick,+ cesium.ScreenSpaceEventType.LEFT_CLICK,+ );+ }+ if (stock && savedDoubleClick) {+ stock.setInputAction(+ savedDoubleClick,+ cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,+ );+ }+ savedSingleClick = null;+ savedDoubleClick = null;+ documentRef?.removeEventListener?.('keydown', onKey, true);+ documentRef?.body?.classList?.remove?.('gev-imagery-box');+ }++ function setActive(next) {+ if (next === active) return active;+ if (next) {+ lease = claimPointer(IMAGERY_BOX_POINTER_OWNER);+ if (!lease) {+ onCancel?.(+ 'pointer-busy',+ `${pointerOwner()} is using the pointer — close it first`,+ );+ return active;+ }+ active = true;+ bindScene();+ } else {+ if (anchor) endDrag();+ releaseScene();+ releasePointer(lease);+ lease = null;+ active = false;+ }+ onActive?.(active);+ return active;+ }++ function cancel(reason = 'cancel') {+ if (!active || destroyed) return;+ setActive(false);+ onCancel?.(reason);+ }++ return {+ /** Begin a box session. False when the pointer is held elsewhere. */+ start() {+ return !destroyed && setActive(true);+ },+ cancel,+ isActive() {+ return active;+ },+ /** Returns everything; resolves once the preview is detached. */+ destroy() {+ if (destroyed) return attaching;+ if (active) setActive(false);+ destroyed = true;+ releaseScene();+ releasePointer(lease);+ lease = null;+ thawCamera();+ dataSource.entities.removeAll();+ attaching = attaching.then(() => {+ try {+ viewer.dataSources.remove(dataSource, true);+ } catch {+ /* viewer already disposed */+ }+ });+ return attaching;+ },+ };+}diff --git a/src/ui/imageryBoxTool.test.mjs b/src/ui/imageryBoxTool.test.mjsnew file mode 100644index 000000000..e84938ed7--- /dev/null+++ b/src/ui/imageryBoxTool.test.mjs@@ -0,0 +1,154 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import {+ claimPointer,+ pointerOwner,+ releasePointer,+ resetPointerOwnership,+} from '../data/inputOwnership.js';+import {+ IMAGERY_BOX_POINTER_OWNER,+ initImageryBoxTool,+} from './imageryBoxTool.js';+import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';++function fixture(options = {}) {+ resetPointerOwnership();+ const fakes = boxToolFakes();+ const boxes = [];+ const cancels = [];+ const actives = [];+ const tool = initImageryBoxTool({+ viewer: fakes.viewer,+ cesium: fakes.cesium,+ pickWorld: fakes.pickWorld,+ documentRef: fakes.documentRef,+ onBox: (box) => boxes.push(box),+ onCancel: (reason, message) => cancels.push([reason, message]),+ onActive: (active) => actives.push(active),+ ...options,+ });+ const camera = fakes.viewer.scene.screenSpaceCameraController;+ const stockAction = (type) =>+ fakes.viewer.screenSpaceEventHandler.getInputAction(fakes.types[type]);+ const preview = () =>+ fakes.viewer.dataSources.sources[0]?.entities.values.every((e) => e.show);+ return {+ ...fakes,+ tool,+ boxes,+ cancels,+ actives,+ camera,+ stockAction,+ preview,+ };+}++test('a session claims the pointer, borrows the stock clicks, freezes the camera only mid-drag and returns everything with the box', async () => {+ const f = fixture();+ assert.equal(f.tool.start(), true);+ assert.equal(pointerOwner(), IMAGERY_BOX_POINTER_OWNER);+ assert.equal(f.stockAction('LEFT_CLICK'), undefined);+ assert.equal(f.stockAction('LEFT_DOUBLE_CLICK'), undefined);+ assert.ok(f.documentRef.classes.has('gev-imagery-box'));+ assert.equal(f.camera.enableInputs, true, 'not frozen before the press');+ f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });+ assert.equal(f.camera.enableInputs, false);+ assert.equal(f.preview(), true);+ f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 250 } });+ f.fire('MOUSE_MOVE', { endPosition: { x: 500, y: 10 } }); // sky: ignored+ f.fire('LEFT_UP', { position: { x: 500, y: 250 } });+ assert.equal(f.boxes.length, 1);+ const { west, south, east, north } = f.boxes[0];+ assert.deepEqual(+ [west, south, east, north].map((v) => Math.round(v * 1e6) / 1e6),+ [-97.85, 30.3, -97.8, 30.35],+ );+ assert.deepEqual(f.cancels, []);+ assert.equal(f.tool.isActive(), false);+ assert.equal(pointerOwner(), null);+ assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);+ assert.equal(f.stockAction('LEFT_DOUBLE_CLICK'), f.originalDouble);+ assert.equal(f.camera.enableInputs, true);+ assert.equal(f.preview(), false);+ assert.equal(f.documentRef.classes.has('gev-imagery-box'), false);+ assert.equal(f.documentRef.listeners.length, 0);+ assert.equal(f.handler(), null);+ assert.deepEqual(f.actives, [true, false]);+ await f.tool.destroy();+});++test('a sky press, a click without a drag and Escape each say why', async () => {+ const f = fixture();+ f.tool.start();+ f.fire('LEFT_DOWN', { position: { x: 250, y: 10 } });+ assert.deepEqual(f.cancels.at(-1), [+ 'sky',+ 'Press on the ground, not the sky',+ ]);+ assert.equal(f.tool.isActive(), true, 'a sky press keeps the session');+ f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });+ f.fire('LEFT_UP', { position: { x: 250, y: 125 } });+ assert.deepEqual(f.cancels.at(-1), ['degenerate', 'Drag to size the box']);+ f.tool.start();+ assert.equal(f.key('Escape').prevented, true);+ assert.deepEqual(f.cancels.at(-1), ['escape', undefined]);+ assert.equal(pointerOwner(), null);+ await f.tool.destroy();+});++test('an Escape interceptor that claims the key leaves the tool armed; the next Escape cancels', async () => {+ let claim = true;+ let asked = 0;+ const f = fixture({+ onEscape: () => {+ asked += 1;+ return claim;+ },+ });+ f.tool.start();+ const first = f.key('Escape');+ assert.equal(asked, 1);+ assert.equal(+ first.prevented && first.stopped,+ true,+ 'the key goes no further',+ );+ assert.equal(f.tool.isActive(), true);+ claim = false;+ f.key('Escape');+ assert.deepEqual(f.cancels, [['escape', undefined]]);+ f.tool.start();+ f.key('Enter');+ assert.equal(asked, 2, 'other keys never reach the interceptor');+ await f.tool.destroy();+});++test('a held pointer refuses the session and nothing is borrowed', async () => {+ const f = fixture();+ const lease = claimPointer('draw');+ assert.equal(f.tool.start(), false);+ assert.deepEqual(f.cancels, [+ ['pointer-busy', 'draw is using the pointer — close it first'],+ ]);+ assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);+ assert.equal(f.handler(), null);+ releasePointer(lease);+ assert.equal(f.tool.start(), true);+ await f.tool.destroy();+});++test('destroy mid-drag restores the camera, releases the claim and detaches the preview', async () => {+ const f = fixture();+ f.tool.start();+ f.fire('LEFT_DOWN', { position: { x: 250, y: 125 } });+ assert.equal(f.viewer.dataSources.sources.length, 1);+ await f.tool.destroy();+ assert.equal(f.camera.enableInputs, true);+ assert.equal(pointerOwner(), null);+ assert.equal(f.viewer.dataSources.sources.length, 0);+ assert.equal(f.stockAction('LEFT_CLICK'), f.originalClick);+ assert.equal(f.tool.start(), false);+ assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);+});diff --git a/src/ui/imagerySplit.js b/src/ui/imagerySplit.jsnew file mode 100644index 000000000..f22bbc208--- /dev/null+++ b/src/ui/imagerySplit.js@@ -0,0 +1,176 @@+const HANDLE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'Home', 'End']);++function clampUnit(value) {+ return Math.max(0, Math.min(1, Number(value) || 0));+}++function defaultViewportWidth() {+ return (+ Number(document.documentElement?.clientWidth) ||+ Number(globalThis.window?.innerWidth) ||+ 0+ );+}++function defaultValueText(beforePercent, afterPercent) {+ return `A ${beforePercent} percent, B ${afterPercent} percent`;+}++/**+ * Split divider for before/after imagery comparison.+ *+ * Owns the DOM line + handle, pointer capture, keyboard, ARIA, a CSS custom+ * property and scene.splitPosition. `setValue` is the owner's own write and+ * never echoes through `onChange`; `onChange` reports pointer and keyboard+ * changes so the owner can mirror them, and `requestRender` fires whenever+ * the clamped value actually changes. `destroy` is idempotent: it removes the+ * listeners and line, clears the CSS property and restores the scene split+ * captured at creation once.+ */+export function createImagerySplit({+ scene,+ parent = document.body,+ initialValue = 0.5,+ id,+ handleClass,+ cssTarget = document.documentElement,+ cssProperty,+ beforeLabel = 'A',+ afterLabel = 'B',+ beforeTitle,+ afterTitle,+ ariaLabel,+ formatValueText = defaultValueText,+ getViewportWidth = defaultViewportWidth,+ onChange,+ requestRender,+} = {}) {+ const restoreValue = scene ? (scene.splitPosition ?? null) : null;+ const line = document.createElement('div');+ if (id) line.id = id;+ const before = document.createElement('span');+ const after = document.createElement('span');+ const handle = document.createElement('button');+ before.className = 'before';+ after.className = 'after';+ before.textContent = beforeLabel;+ if (beforeTitle != null) before.title = beforeTitle;+ after.textContent = afterLabel;+ if (afterTitle != null) after.title = afterTitle;+ handle.type = 'button';+ if (handleClass) handle.className = handleClass;+ handle.setAttribute('role', 'slider');+ if (ariaLabel != null) handle.setAttribute('aria-label', ariaLabel);+ handle.setAttribute('aria-valuemin', '0');+ handle.setAttribute('aria-valuemax', '100');+ handle.setAttribute('aria-orientation', 'horizontal');+ handle.textContent = '↔';++ let value = null;+ let cssValue = null;+ let dragging = false;+ let pointerId = null;+ let destroyed = false;++ function apply(next, { notify = false, render = true } = {}) {+ const clamped = clampUnit(next);+ const changed = clamped !== value;+ value = clamped;+ if (scene && scene.splitPosition !== value) scene.splitPosition = value;+ const css = `${value * 100}%`;+ if (cssProperty && cssValue !== css) {+ cssTarget.style.setProperty(cssProperty, css);+ cssValue = css;+ }+ const beforePercent = Math.round(value * 100);+ handle.setAttribute('aria-valuenow', String(beforePercent));+ handle.setAttribute(+ 'aria-valuetext',+ formatValueText(beforePercent, 100 - beforePercent),+ );+ if (changed && render) requestRender?.();+ if (changed && notify) onChange?.(value);+ return changed;+ }++ function setFromClientX(clientX) {+ const viewportWidth = Number(getViewportWidth()) || 0;+ if (viewportWidth <= 0 || !Number.isFinite(Number(clientX))) return;+ apply(Number(clientX) / viewportWidth, { notify: true });+ }++ function handlePointerDown(event) {+ if (event.button != null && event.button !== 0) return;+ event.preventDefault?.();+ dragging = true;+ pointerId = event.pointerId ?? null;+ handle.setPointerCapture?.(event.pointerId);+ setFromClientX(event.clientX);+ }++ function handlePointerMove(event) {+ if (!dragging) return;+ if (pointerId != null && event.pointerId !== pointerId) return;+ event.preventDefault?.();+ setFromClientX(event.clientX);+ }++ function finishPointerDrag(event) {+ if (!dragging) return;+ if (pointerId != null && event.pointerId !== pointerId) return;+ handle.releasePointerCapture?.(event.pointerId);+ dragging = false;+ pointerId = null;+ }++ function handleKeyDown(event) {+ if (!HANDLE_KEYS.has(event.key)) return;+ event.preventDefault?.();+ const step = event.shiftKey ? 0.05 : 0.01;+ if (event.key === 'Home') apply(0, { notify: true });+ else if (event.key === 'End') apply(1, { notify: true });+ else+ apply(value + (event.key === 'ArrowRight' ? step : -step), {+ notify: true,+ });+ }++ const listeners = [+ ['pointerdown', handlePointerDown],+ ['pointermove', handlePointerMove],+ ['pointerup', finishPointerDrag],+ ['pointercancel', finishPointerDrag],+ ['keydown', handleKeyDown],+ ];+ for (const [type, listener] of listeners)+ handle.addEventListener(type, listener);+ line.append(before, handle, after);+ parent.appendChild(line);+ apply(initialValue, { render: false });++ return {+ getValue() {+ return value;+ },+ setValue(next) {+ if (destroyed) return false;+ return apply(next);+ },+ setVisible(visible) {+ line.hidden = !visible;+ },+ destroy() {+ if (destroyed) return;+ destroyed = true;+ if (dragging && pointerId != null)+ handle.releasePointerCapture?.(pointerId);+ dragging = false;+ pointerId = null;+ for (const [type, listener] of listeners)+ handle.removeEventListener?.(type, listener);+ line.remove();+ if (cssProperty) cssTarget.style.removeProperty(cssProperty);+ if (scene && restoreValue != null) scene.splitPosition = restoreValue;+ },+ };+}diff --git a/src/ui/imagerySplit.test.mjs b/src/ui/imagerySplit.test.mjsnew file mode 100644index 000000000..23a47b60d--- /dev/null+++ b/src/ui/imagerySplit.test.mjs@@ -0,0 +1,307 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createImagerySplit } from './imagerySplit.js';++class FakeElement {+ constructor(tagName) {+ this.tagName = tagName;+ this.children = [];+ this.removed = false;+ this.captured = [];+ this.released = [];+ this._attributes = new Map();+ this._listeners = new Map();+ }+ setAttribute(name, value) {+ this._attributes.set(name, value);+ }+ getAttribute(name) {+ return this._attributes.get(name) ?? null;+ }+ addEventListener(type, handler) {+ this._listeners.set(type, handler);+ }+ removeEventListener(type, handler) {+ if (this._listeners.get(type) === handler) this._listeners.delete(type);+ }+ dispatch(type, event = {}) {+ return this._listeners.get(type)?.(event);+ }+ setPointerCapture(id) {+ this.captured.push(id);+ }+ releasePointerCapture(id) {+ this.released.push(id);+ }+ append(...children) {+ this.children.push(...children);+ }+ appendChild(child) {+ this.children.push(child);+ return child;+ }+ remove() {+ this.removed = true;+ }+}++function fixture({ initialValue = 0.5, splitPosition = 0.37 } = {}) {+ const body = new FakeElement('body');+ const cssCalls = [];+ const changes = [];+ let renders = 0;+ const scene = { splitPosition };+ const cssTarget = {+ style: {+ setProperty(name, value) {+ cssCalls.push(['set', name, value]);+ },+ removeProperty(name) {+ cssCalls.push(['remove', name]);+ },+ },+ };+ const previous = globalThis.document;+ globalThis.document = {+ body,+ createElement: (tagName) => new FakeElement(tagName),+ documentElement: cssTarget,+ };+ const split = createImagerySplit({+ scene,+ parent: body,+ initialValue,+ id: 'split-line',+ handleClass: 'split-handle',+ cssTarget,+ cssProperty: '--split',+ beforeTitle: 'Before',+ afterTitle: 'After',+ ariaLabel: 'Divider',+ getViewportWidth: () => 1000,+ onChange: (value) => changes.push(value),+ requestRender: () => {+ renders += 1;+ },+ });+ globalThis.document = previous;+ const line = body.children[0];+ const handle = line.children.find((child) => child.tagName === 'button');+ return {+ split,+ scene,+ body,+ line,+ handle,+ cssCalls,+ changes,+ renders: () => renders,+ };+}++test('the split builds its line and applies the initial value without notifying', () => {+ const env = fixture({ initialValue: 0.62 });+ assert.equal(env.line.id, 'split-line');+ assert.equal(env.line.children[0].textContent, 'A');+ assert.equal(env.line.children[0].title, 'Before');+ assert.equal(env.line.children[2].textContent, 'B');+ assert.equal(env.line.children[2].title, 'After');+ assert.equal(env.handle.className, 'split-handle');+ assert.equal(env.handle.getAttribute('role'), 'slider');+ assert.equal(env.handle.getAttribute('aria-label'), 'Divider');+ assert.equal(env.handle.getAttribute('aria-valuenow'), '62');+ assert.equal(+ env.handle.getAttribute('aria-valuetext'),+ 'A 62 percent, B 38 percent',+ );+ assert.equal(env.scene.splitPosition, 0.62);+ assert.deepEqual(env.cssCalls, [['set', '--split', '62%']]);+ assert.deepEqual(env.changes, []);+ assert.equal(env.renders(), 0);+ assert.equal(env.split.getValue(), 0.62);+});++test('keyboard steps 1 percent, 5 percent with Shift, and jumps to Home and End', () => {+ const env = fixture();+ const key = (key, shiftKey = false) => {+ let prevented = false;+ env.handle.dispatch('keydown', {+ key,+ shiftKey,+ preventDefault() {+ prevented = true;+ },+ });+ return prevented;+ };+ assert.equal(key('ArrowRight'), true);+ assert.equal(env.scene.splitPosition, 0.51);+ assert.equal(key('ArrowLeft', true), true);+ assert.equal(env.scene.splitPosition, 0.46);+ assert.equal(key('Home'), true);+ assert.equal(env.scene.splitPosition, 0);+ assert.equal(env.handle.getAttribute('aria-valuenow'), '0');+ assert.equal(key('End'), true);+ assert.equal(env.scene.splitPosition, 1);+ assert.equal(env.handle.getAttribute('aria-valuenow'), '100');+ assert.equal(key('Enter'), false, 'other keys are ignored and not prevented');+ assert.equal(env.scene.splitPosition, 1);+ assert.deepEqual(env.changes, [0.51, 0.46, 0, 1]);+});++test('values clamp to the unit range and only real changes notify or render', () => {+ const env = fixture();+ assert.equal(env.split.setValue(1.4), true);+ assert.equal(env.split.getValue(), 1);+ assert.equal(env.scene.splitPosition, 1);+ assert.equal(env.split.setValue(1), false);+ assert.equal(env.split.setValue(-3), true);+ assert.equal(env.split.getValue(), 0);+ assert.equal(+ env.split.setValue('nonsense'),+ false,+ 'non-numeric input clamps to 0',+ );+ assert.equal(env.renders(), 2, 'render only when the clamped value moved');+ assert.deepEqual(+ env.changes,+ [],+ 'setValue is the owner writing; it never echoes',+ );+ env.handle.dispatch('keydown', { key: 'Home', preventDefault() {} });+ env.handle.dispatch('keydown', { key: 'ArrowLeft', preventDefault() {} });+ assert.deepEqual(+ env.changes,+ [],+ 'interaction that cannot move the value stays silent',+ );+ env.handle.dispatch('keydown', { key: 'End', preventDefault() {} });+ env.handle.dispatch('keydown', { key: 'End', preventDefault() {} });+ assert.deepEqual(env.changes, [1]);+ assert.equal(env.renders(), 3);+ assert.deepEqual(env.cssCalls, [+ ['set', '--split', '50%'],+ ['set', '--split', '100%'],+ ['set', '--split', '0%'],+ ['set', '--split', '100%'],+ ]);+});++test('pointer drags follow the primary pointer only', () => {+ const env = fixture();+ env.handle.dispatch('pointerdown', {+ button: 2,+ clientX: 900,+ pointerId: 1,+ preventDefault() {},+ });+ assert.equal(+ env.scene.splitPosition,+ 0.5,+ 'non-primary buttons never start a drag',+ );+ env.handle.dispatch('pointermove', {+ clientX: 900,+ pointerId: 1,+ preventDefault() {},+ });+ assert.equal(+ env.scene.splitPosition,+ 0.5,+ 'moves without a drag are ignored',+ );+ env.handle.dispatch('pointerdown', {+ button: 0,+ clientX: 250,+ pointerId: 4,+ preventDefault() {},+ });+ assert.equal(env.scene.splitPosition, 0.25);+ assert.deepEqual(env.handle.captured, [4]);+ env.handle.dispatch('pointermove', {+ clientX: 900,+ pointerId: 9,+ preventDefault() {},+ });+ assert.equal(+ env.scene.splitPosition,+ 0.25,+ 'a different pointer id is ignored',+ );+ env.handle.dispatch('pointerup', { pointerId: 9 });+ env.handle.dispatch('pointermove', {+ clientX: 750,+ pointerId: 4,+ preventDefault() {},+ });+ assert.equal(+ env.scene.splitPosition,+ 0.75,+ 'the drag survives a foreign pointerup',+ );+ env.handle.dispatch('pointermove', {+ clientX: Number.NaN,+ pointerId: 4,+ preventDefault() {},+ });+ assert.equal(+ env.scene.splitPosition,+ 0.75,+ 'unusable coordinates are ignored',+ );+ env.handle.dispatch('pointerup', { pointerId: 4 });+ assert.deepEqual(env.handle.released, [4]);+ env.handle.dispatch('pointermove', {+ clientX: 100,+ pointerId: 4,+ preventDefault() {},+ });+ assert.equal(env.scene.splitPosition, 0.75, 'the drag ended');+ assert.deepEqual(env.changes, [0.25, 0.75]);+});++test('visibility toggles the line without touching the value', () => {+ const env = fixture();+ env.split.setVisible(false);+ assert.equal(env.line.hidden, true);+ env.split.setVisible(true);+ assert.equal(env.line.hidden, false);+ assert.equal(env.split.getValue(), 0.5);+});++test('destroy removes the line, clears the CSS property, restores the scene split once, and is idempotent', () => {+ const env = fixture({ initialValue: 0.8, splitPosition: 0.37 });+ env.handle.dispatch('pointerdown', {+ button: 0,+ clientX: 100,+ pointerId: 2,+ preventDefault() {},+ });+ assert.equal(env.scene.splitPosition, 0.1);+ env.split.destroy();+ assert.equal(env.line.removed, true);+ assert.deepEqual(+ env.handle.released,+ [2],+ 'an in-flight drag releases its capture',+ );+ assert.equal(env.cssCalls.at(-1)[0], 'remove');+ assert.equal(env.scene.splitPosition, 0.37);+ assert.equal(env.handle._listeners.size, 0);+ env.scene.splitPosition = 0.9;+ env.split.destroy();+ assert.equal(+ env.scene.splitPosition,+ 0.9,+ 'a second destroy does not restore again',+ );+ assert.equal(env.cssCalls.filter(([kind]) => kind === 'remove').length, 1);+ assert.equal(+ env.split.setValue(0.2),+ false,+ 'a destroyed split ignores writes',+ );+ assert.equal(env.scene.splitPosition, 0.9);+ env.handle.dispatch('keydown', { key: 'End', preventDefault() {} });+ assert.deepEqual(env.changes, [0.1], 'listeners are gone');+});diff --git a/src/ui/layerPanel.js b/src/ui/layerPanel.jsindex 842926189..c06f27dea 100644--- a/src/ui/layerPanel.js+++ b/src/ui/layerPanel.js@@ -31,11 +31,12 @@ const PANEL_GROUPS = [},{label: 'Cameras',- ids: ['cctv', 'alpr-cameras'],+ ids: ['cctv', 'recent-imagery'],},{label: 'Infrastructure',ids: [+ 'alpr-cameras','military-installations','local-datacenters','telegeography-submarine-cables',@@ -126,6 +127,8 @@ export class LayerPanel {this._removers = [];this._destroyed = false;this._cancelRowControlsRefresh = null;+ this._recentImageryFactory = null;+ this._recentImageryPanel = null;}mount(container) {if (this._destroyed) return;@@ -138,8 +141,29 @@ export class LayerPanel {container?.ownerDocument?.getElementById?.('weather-panel-body'),setLayerParams: this.setLayerParams,});+ this._mountRecentImagery();this._renderToggles();}+ /**+ * Host the Recent Imagery readout in its rail body, like the weather+ * readout. The application supplies the factory once the layer, viewer and+ * box tool exist; a remount rebuilds the readout in place.+ * @param {((container: HTMLElement) => { destroy: () => void } | null) | null} factory+ */+ attachRecentImagery(factory) {+ if (this._destroyed) return;+ this._recentImageryFactory = typeof factory === 'function' ? factory : null;+ this._mountRecentImagery();+ }+ _mountRecentImagery() {+ this._recentImageryPanel?.destroy();+ this._recentImageryPanel = null;+ const container = this._toggleContainer?.ownerDocument?.getElementById?.(+ 'recent-imagery-panel-body',+ );+ if (container && this._recentImageryFactory)+ this._recentImageryPanel = this._recentImageryFactory(container) || null;+ }_bind(element, type, listener) {element.addEventListener(type, listener);this._removers.push(() => element.removeEventListener(type, listener));@@ -156,6 +180,9 @@ export class LayerPanel {this._releaseBindings();this._weatherPanel?.destroy();this._weatherPanel = null;+ this._recentImageryPanel?.destroy();+ this._recentImageryPanel = null;+ this._recentImageryFactory = null;this._toggleContainer = null;}_renderToggles() {diff --git a/src/ui/layerPanel.test.mjs b/src/ui/layerPanel.test.mjsindex 62241d95a..dcc6d116d 100644--- a/src/ui/layerPanel.test.mjs+++ b/src/ui/layerPanel.test.mjs@@ -174,3 +174,56 @@ test('readout rows contain only toggles and metadata; ordinary rows retain contrglobalThis.document = previousDocument;}});++test('the Recent Imagery readout mounts in its rail body like the weather readout and is rebuilt or released with the panel', async () => {+ const { LayerPanel } = await import('./layerPanel.js');+ const { railFixture } = await import('./railTestFixture.mjs');+ const f = railFixture();+ const body = f.document.createElement('div');+ f.document.getElementById = (id) =>+ id === 'recent-imagery-panel-body' ? body : null;+ const previousDocument = globalThis.document;+ globalThis.document = f.document;+ const mounted = [];+ const factory = (container) => {+ const readout = {+ container,+ destroyed: false,+ destroy() {+ this.destroyed = true;+ },+ };+ mounted.push(readout);+ return readout;+ };+ const panel = new LayerPanel({+ getLayers: () => [],+ isEnabled: () => false,+ setEnabled() {},+ setLayerParams() {},+ hasRowControls: () => false,+ subscribeRowControls() {},+ getRowControls: () => null,+ });+ try {+ panel.attachRecentImagery(factory);+ assert.equal(mounted.length, 0, 'no body before the panel mounts');+ panel.mount(f.container);+ assert.equal(mounted.length, 1);+ assert.equal(mounted[0].container, body);+ panel.mount(f.container);+ assert.equal(mounted[0].destroyed, true, 'a remount rebuilds it');+ assert.equal(mounted.length, 2);+ panel.attachRecentImagery(null);+ assert.equal(mounted[1].destroyed, true);+ panel.attachRecentImagery(factory);+ assert.equal(mounted.length, 3);+ panel.destroy();+ assert.equal(mounted[2].destroyed, true);+ panel.attachRecentImagery(factory);+ assert.equal(mounted.length, 3, 'a destroyed panel mounts nothing');+ } finally {+ panel.destroy();+ globalThis.document = previousDocument;+ }+});diff --git a/src/ui/panelChrome.js b/src/ui/panelChrome.jsindex 98ad4de5a..15cd45358 100644--- a/src/ui/panelChrome.js+++ b/src/ui/panelChrome.js@@ -12,6 +12,7 @@ const SHARE_PANEL_STATE_SPECS = Object.freeze([{ id: 'data-panel' },{ id: 'cctv-panel' },{ id: 'weather-panel' },+ { id: 'recent-imagery-panel' },{ id: 'radio-panel' },{ id: 'scene-panel' },{ id: 'global-context-panel' },@@ -23,6 +24,7 @@ const COCKPIT_ENTRY_COLLAPSE_PANEL_IDS = Object.freeze(['data-panel','cctv-panel','weather-panel',+ 'recent-imagery-panel','scene-panel','pp-toggles','global-context-panel',@@ -284,6 +286,7 @@ export class PanelChrome {'pp-toggles','cctv-panel','weather-panel',+ 'recent-imagery-panel','global-context-panel',].includes(panelEl?.id);const collapsed = panelEl.classList.contains('collapsed');diff --git a/src/ui/panelLayoutController.js b/src/ui/panelLayoutController.jsindex c2965b214..4847b8cb8 100644--- a/src/ui/panelLayoutController.js+++ b/src/ui/panelLayoutController.js@@ -95,6 +95,7 @@ export class PanelLayoutController {this._ppToggles = document.getElementById('pp-toggles');this._cctvPanel = document.getElementById('cctv-panel');this._weatherPanel = document.getElementById('weather-panel');+ this._recentImageryPanel = document.getElementById('recent-imagery-panel');this._sliderPanel = document.getElementById('param-slider-panel');this._detectionBtn = document.getElementById('detection-toggle');}@@ -195,7 +196,11 @@ export class PanelLayoutController {this._ppToggles.querySelector('.pp-header-row')?.removeAttribute('title');stack.prepend(this._ppToggles);const globalContextPanel = document.getElementById('global-context-panel');- for (const panel of [this._cctvPanel, this._weatherPanel]) {+ for (const panel of [+ this._cctvPanel,+ this._weatherPanel,+ this._recentImageryPanel,+ ]) {if (!panel) continue;for (const property of ['top', 'right', 'bottom', 'left', 'z-index'])panel.style.removeProperty(property);@@ -222,6 +227,7 @@ export class PanelLayoutController {this._ppToggles,this._cctvPanel,this._weatherPanel,+ this._recentImageryPanel,globalContextPanel,]) {if (panel) this._rightStackResizeObserver.observe(panel);diff --git a/src/ui/panelRails.test.mjs b/src/ui/panelRails.test.mjsindex 27cd6b2dc..44c28cef7 100644--- a/src/ui/panelRails.test.mjs+++ b/src/ui/panelRails.test.mjs@@ -577,3 +577,47 @@ test('narrow-screen rails pin every hosted panel glow inside its panel box', ());}});++test('right layout ignores a hidden panel: no lane, no gap, no auto-collapse', () => {+ const f = fixture('right');+ const imagery = element('recent-imagery-panel', { height: 0 });+ imagery.hidden = true;+ imagery.scrollHeight = 0;+ imagery.rect.height = 0;+ f.stack.children.push(imagery);+ imagery.parentElement = f.stack;+ // A tall panel expands into focus mode: the hidden sibling is not among the+ // later panels that focus mode collapses, and it counts for nothing.+ f.expand(f.first, 900);+ f.run();+ assert.equal(f.stack.dataset.layoutMode, 'focus');+ assert.equal(imagery.classList.contains('collapsed'), false);+ assert.equal(imagery.classList.contains('layout-auto-collapsed'), false);+ assert.equal(f.stack.dataset.expandedCount, '1');+ assert.equal(+ imagery.style.getPropertyValue('--right-panel-allocated-height'),+ '',+ );+ assert.equal(imagery.getAttribute('aria-hidden'), undefined);+ const alone = parseFloat(+ f.first.style.getPropertyValue('--right-panel-allocated-height'),+ );+ // Shown (and expanded) it joins the allocation like any other panel.+ imagery.hidden = false;+ imagery.scrollHeight = 300;+ imagery.rect.height = 300;+ const retriesBefore = f.retries();+ f.run();+ assert.ok(+ f.collapsed.includes('recent-imagery-panel'),+ 'focus mode collapses the later panel and asks for another pass',+ );+ assert.equal(f.retries(), retriesBefore + 1);+ f.run();+ assert.equal(f.stack.dataset.expandedCount, '1');+ assert.ok(+ parseFloat(+ f.first.style.getPropertyValue('--right-panel-allocated-height'),+ ) <= alone,+ );+});diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.jsnew file mode 100644index 000000000..27067e4bf--- /dev/null+++ b/src/ui/recentImagery.js@@ -0,0 +1,1083 @@+/**+ * Recent Imagery readout for the right rail (`#recent-imagery-panel`). The+ * body is a fixed stack in which no block changes height and no control+ * moves, whatever the state: box actions, a notice line, the strip of day+ * cards and its hint line, the selection bar (mode, the two slot rows),+ * opacity, SWAP and export, then a collapsed DETAILS card for every note and+ * hedge. Box actions, export and DETAILS are rail-card blocks and cards; the+ * strip and selection bar are this adapter's own keyed DOM. Source toggles+ * live on the data-panel row.+ */+import { createRailCardBlocks } from './railCardBlocks.js';+import { createRailCards } from './railCards.js';+import { createImagerySplit } from './imagerySplit.js';+import {+ PRODUCTS,+ hhmm,+ shortDay,+ wvsSnapshotUrl,+} from '../layers/recentImagery/model.js';++const PANEL_ID = 'recent-imagery-panel';+const OVERVIEW_MIN_BOX_KM = 25;+const ESRI_NOTE = 'Imagery on Esri · Google 3D returns when cleared';+const MODE_LABELS = [+ ['image', 'IMAGE'],+ ['basemap', 'VS BASEMAP'],+ ['ab', 'A / B'],+];+const START_HERE_TITLES = {+ clear: 'Newest low-cloud day for this box · scene cloud, not box cloud',+ cloudy: 'Newest day covering this box · cloudier than 20%',+ partial: 'Newest day with imagery for this box · partial coverage',+ overview: 'Newest daily overview for this box',+};+const START_HERE_REASONS = {+ clear: 'newest clear day',+ cloudy: 'newest day (cloudy)',+ partial: 'newest day (partial coverage)',+ overview: 'newest overview',+};+const PLACEHOLDERS = {+ empty: 'No imagery',+ error: 'Unavailable',+ present: 'Loading',+};+const KEY_STEPS = {+ ArrowLeft: (index) => index - 1,+ ArrowRight: (index) => index + 1,+ Home: () => 0,+ End: (index, total) => total - 1,+};++// Remounting must not reopen a panel the user already collapsed.+const appearedDocuments = new WeakSet();++const sensorLine = (product) =>+ PRODUCTS[product]+ ? `${PRODUCTS[product].name} · ${PRODUCTS[product].resolutionM} m`+ : product || '';+const utcTime = (iso) => (hhmm(iso) ? `${hhmm(iso)}Z` : '');+const longerSideKm = (size) =>+ Math.max(Number(size?.width) || 0, Number(size?.height) || 0);+const kmText = (km) =>+ !Number.isFinite(km)+ ? '?'+ : km >= 100+ ? Math.round(km).toLocaleString('en-US')+ : km.toFixed(1);++function cloudText(candidate) {+ if (candidate.thumbnail?.status === 'empty') return 'no imagery';+ if (!candidate.cloud) return 'cloud unknown';+ const min = Math.round(candidate.cloud.min);+ const max = Math.round(candidate.cloud.max);+ return min === max ? `${min}% cloud` : `${min}–${max}% cloud`;+}++function countText(snapshot) {+ if (!snapshot.box) return 'NO BOX';+ if (snapshot.searching) return 'SEARCHING';+ const count = snapshot.candidates.length;+ return `${count} DAY${count === 1 ? '' : 'S'}`;+}++/** The one-line hint under the strip: the next thing to do, per state. */+function hintText(snapshot) {+ if (snapshot.zoomToFit) return 'Zoom in or draw a smaller box';+ if (!snapshot.box) return 'Select a box or use the view';+ if (snapshot.searching) return 'Searching the last 30 days';+ if (!snapshot.candidates.length) return 'No days to show for this box';+ const { mode, pins, shown } = snapshot;+ if (shown.swipe !== 'none') return 'Drag the divider · SWAP trades sides';+ if (mode === 'ab') {+ if (!pins.a.key && !pins.b.key)+ return '← → preview · A or B pins the focused day';+ return '← → preview the other side · A or B pins it';+ }+ if (pins.a.key) return 'S on another day replaces it · × unpins';+ return '← → preview · S shows the focused day';+}++/**+ * Bring a newly opened card into the scrolled body: one write to the body's+ * own scroll position, never on a refresh.+ */+function revealCard(scroller, card) {+ const height = scroller?.clientHeight;+ if (!(height > 0) || typeof card?.getBoundingClientRect !== 'function')+ return;+ const view = scroller.getBoundingClientRect();+ const box = card.getBoundingClientRect();+ const top = box.top - view.top - (scroller.clientTop || 0);+ const delta =+ top < 0 || box.height > height+ ? top+ : Math.max(0, top + box.height - height);+ if (delta) scroller.scrollTop = (scroller.scrollTop || 0) + delta;+}++/** Depth-first search over `children`, for nodes the blocks module owns. */+function findIn(root, predicate) {+ for (const child of root?.children || []) {+ if (predicate(child)) return child;+ const inner = findIn(child, predicate);+ if (inner) return inner;+ }+ return null;+}++/**+ * Mount the readout into the panel body.+ * @param {{ container: HTMLElement, layer: object, viewer?: object, tool?: object, createSplit?: Function, fetchImpl?: typeof fetch, createObjectUrl?: Function, revokeObjectUrl?: Function, requestRender?: Function }} deps+ * @returns {{ root: HTMLElement, exportImage: (slot?: 'a' | 'b') => Promise<boolean>, destroy: () => void } | null}+ */+export function createRecentImageryPanel({+ container,+ layer,+ viewer = null,+ tool = null,+ createSplit = createImagerySplit,+ fetchImpl = globalThis.fetch?.bind(globalThis),+ createObjectUrl = (blob) => URL.createObjectURL(blob),+ revokeObjectUrl = (url) => URL.revokeObjectURL(url),+ requestRender = () => viewer?.scene?.requestRender?.(),+} = {}) {+ const document = container?.ownerDocument;+ if (!document?.createElement || !layer) return null;+ const panel = document.getElementById?.(PANEL_ID) || null;+ const count = document.getElementById?.(`${PANEL_ID}-count`) || null;++ const listeners = [];+ const listen = (target, type, handler, options) => {+ target.addEventListener(type, handler, options);+ listeners.push([target, type, handler, options]);+ };+ const el = (tag, className, parent, text) => {+ const node = document.createElement(tag);+ if (className) node.className = className;+ if (text != null) node.textContent = text;+ parent?.appendChild(node);+ return node;+ };+ const set = (node, key, value) => {+ if (node[key] !== value) node[key] = value;+ };+ const attribute = (node, key, value) => {+ if (node.getAttribute(key) !== value) node.setAttribute(key, value);+ };+ const toggle = (node, name, on) => {+ if (node.classList.contains(name) !== Boolean(on))+ node.classList.toggle(name, Boolean(on));+ };++ // ---- build: every block exists from the start, in its final order ----+ const root = el('section', 'recent-imagery-readout');+ root.setAttribute('aria-label', 'Recent imagery');++ const actionsHost = el('div', 'ri-block ri-actions-row', root);+ actionsHost.id = 'ri-actions';+ const actions = createRailCardBlocks({+ container: actionsHost,+ cardId: 'recent-imagery',+ onParams: () => {},+ });++ // The notice line: the text, and ZOOM IN in a fixed slot at its right end+ // (reserved, never removed, whenever there is nothing to fit).+ const notice = el('div', 'ri-block ri-line ri-notice', root);+ notice.id = 'ri-notice';+ const noticeText = el('span', 'ri-notice-text', notice);+ noticeText.id = 'ri-notice-text';+ noticeText.setAttribute('role', 'status');+ noticeText.setAttribute('aria-live', 'polite');+ const zoomIn = el('button', 'data-toggle-chip ri-zoom-in', notice, 'ZOOM IN');+ zoomIn.id = 'ri-zoom-in';+ zoomIn.type = 'button';+ zoomIn.title = 'Fly in until the view fits the 1,000 km limit';++ const strip = el('div', 'ri-block ri-strip', root);+ strip.id = 'ri-strip';+ strip.tabIndex = 0;+ strip.setAttribute('role', 'listbox');+ strip.setAttribute('aria-orientation', 'horizontal');+ strip.setAttribute(+ 'aria-label',+ 'Imagery days, newest first · arrows move, S or A and B pin',+ );+ strip.setAttribute('aria-keyshortcuts', 'A B S');+ const stripEmpty = el('div', 'ri-strip-empty', strip);++ const hint = el('div', 'ri-block ri-line ri-hint', root);+ hint.id = 'ri-hint';++ const selection = el('section', 'ri-block ri-selection', root);+ selection.id = 'ri-selection';+ selection.setAttribute('aria-label', 'On the map');+ const modeGroup = el('div', 'ri-mode', selection);+ modeGroup.id = 'ri-mode';+ modeGroup.setAttribute('role', 'radiogroup');+ modeGroup.setAttribute('aria-label', 'Mode');+ const modeButtons = new Map(+ MODE_LABELS.map(([mode, label]) => {+ const node = el('button', 'data-toggle-chip ri-mode-btn', modeGroup);+ node.type = 'button';+ node.textContent = label;+ node.dataset.mode = mode;+ node.setAttribute('role', 'radio');+ return [mode, node];+ }),+ );+ const slotRows = {};+ for (const slotId of ['a', 'b']) {+ const row = el('div', 'ri-slot', selection);+ row.id = `ri-slot-${slotId}`;+ const tag = el('span', 'ri-slot-tag', row);+ const value = el('span', 'ri-slot-value', row);+ const unpin = el('button', 'data-toggle-chip ri-unpin', row, '×');+ unpin.type = 'button';+ unpin.id = `ri-unpin-${slotId}`;+ unpin.dataset.unpin = slotId;+ slotRows[slotId] = { row, tag, value, unpin };+ }++ const controls = el('div', 'ri-block ri-controls', root);+ controls.id = 'ri-controls';+ const opacityLabel = el('label', 'ri-opacity-label', controls);+ el('span', '', opacityLabel, 'OPACITY');+ const opacityValue = el('span', 'ri-opacity-value', opacityLabel, '100%');+ const opacity = el('input', 'ri-opacity', controls);+ opacity.id = 'ri-opacity';+ Object.assign(opacity, {+ type: 'range',+ min: '0',+ max: '100',+ step: '1',+ value: '100',+ });+ opacity.setAttribute('aria-label', 'Imagery opacity');+ opacityLabel.htmlFor = 'ri-opacity';+ // Its slot is always there; it is only usable while a swipe is live.+ const swap = el('button', 'data-toggle-chip ri-swap', controls, 'SWAP');+ swap.id = 'ri-swap';+ swap.type = 'button';+ swap.title = 'Trade the two sides of the divider';+ const exportHost = el('div', 'ri-exports', controls);+ const exports = createRailCardBlocks({+ container: exportHost,+ cardId: 'recent-imagery',+ onParams: () => {},+ });++ const detailsHost = el('div', 'ri-details', root);+ detailsHost.id = 'ri-details';+ let detailsOpen = false;+ let detailsShownOpen = false;+ const details = createRailCards({+ container: detailsHost,+ document,+ cardClassName: 'ri-details-card',+ onOpen: () => {+ detailsOpen = !detailsOpen;+ render();+ },+ });++ container.appendChild(root);++ // ---- state ------------------------------------------------------------+ const cards = new Map();+ let stripKeys = '';+ let snapshot = layer.getSnapshot();+ let split = null;+ let splitSignature = '';+ let exportError = null;+ const exporting = new Set();+ let destroyed = false;++ /**+ * The body is the scroll container and no render may move it: a+ * re-render, a thumbnail arriving or a notification never sends the+ * operator back to the top.+ */+ function preserveScroll(fn) {+ const top = Number(container.scrollTop) || 0;+ try {+ return fn();+ } finally {+ if ((Number(container.scrollTop) || 0) !== top) container.scrollTop = top;+ }+ }++ // ---- box actions ------------------------------------------------------+ function renderActions() {+ actions.update([+ {+ id: 'box',+ type: 'actions',+ actions: [+ {+ id: 'select-box',+ label: 'SELECT BOX',+ title: 'Drag a box on the map (Esc cancels)',+ onClick: () => {+ exportError = null;+ if (tool?.isActive()) tool.cancel('toggle');+ else tool?.start();+ },+ },+ {+ id: 'use-view',+ label: 'USE VIEW',+ title: 'Use the current view as the box',+ onClick: () => {+ exportError = null;+ layer.useCurrentView(viewer);+ },+ },+ {+ id: 'clear',+ label: 'CLEAR',+ title: 'Forget the box and its images',+ disabled: !snapshot.box && !snapshot.boxError,+ onClick: () => {+ exportError = null;+ layer.clear();+ },+ },+ ],+ },+ ]);+ const selectBox = findIn(+ actionsHost,+ (node) => node.dataset?.actionId === 'select-box',+ );+ if (selectBox) {+ attribute(+ selectBox,+ 'aria-pressed',+ String(Boolean(snapshot.toolActive)),+ );+ toggle(selectBox, 'active', snapshot.toolActive);+ }+ }++ // ---- notice -----------------------------------------------------------+ function renderNotice() {+ const warning = snapshot.boxError || snapshot.error || exportError;+ const text =+ warning || snapshot.notice || (snapshot.borrowedEsri ? ESRI_NOTE : '');+ set(noticeText, 'textContent', text);+ attribute(noticeText, 'title', text);+ toggle(notice, 'warn', Boolean(warning));+ toggle(notice, 'info', !warning && Boolean(text));+ // ZOOM IN only for the oversized box or view the notice is showing.+ const fit = Boolean(snapshot.zoomToFit);+ toggle(notice, 'has-action', fit);+ toggle(zoomIn, 'is-reserved', !fit);+ set(zoomIn, 'disabled', !fit);+ attribute(zoomIn, 'aria-hidden', String(!fit));+ }++ // ---- strip ------------------------------------------------------------+ function buildCard(candidate) {+ const card = el('div', 'ri-card');+ card.dataset.key = candidate.key;+ card.setAttribute('role', 'option');+ const entry = { card, image: null, imageUrl: null };+ entry.thumb = el('div', 'ri-thumb', card);+ entry.placeholder = el('span', 'ri-thumb-text', entry.thumb);+ entry.flag = el('span', 'ri-card-flag', entry.thumb);+ entry.start = el('span', 'ri-card-start', entry.thumb, 'START HERE');+ entry.date = el('div', 'ri-card-date', card);+ entry.sensor = el('div', 'ri-card-sensor', card);+ entry.cloud = el('div', 'ri-card-cloud', card);+ const chips = el('div', 'ri-card-chips', card);+ entry.chips = {};+ for (const slotId of ['a', 'b']) {+ const chip = el('button', 'data-toggle-chip ri-chip', chips);+ chip.type = 'button';+ chip.tabIndex = -1;+ chip.dataset.slot = slotId;+ entry.chips[slotId] = chip;+ }+ cards.set(candidate.key, entry);+ return card;+ }++ function updateCard(candidate, index) {+ const entry = cards.get(candidate.key);+ if (!entry) return;+ const { card } = entry;+ const day = shortDay(candidate.day);+ const ab = snapshot.mode === 'ab';+ set(card, 'id', `ri-card-${index}`);+ const focused = index === snapshot.focusIndex;+ toggle(card, 'focused', focused);+ attribute(card, 'aria-selected', String(focused));+ toggle(card, 'pinned', Boolean(candidate.pinned));+ toggle(card, 'preview', Boolean(candidate.preview));+ const status = candidate.thumbnail?.status || 'unknown';+ const objectUrl = candidate.thumbnail?.objectUrl || null;+ const shown = status === 'present' && Boolean(objectUrl);+ if (shown && !entry.image) {+ entry.image = el('img', 'ri-thumb-img');+ entry.image.alt = '';+ entry.image.decoding = 'async';+ entry.thumb.insertBefore(entry.image, entry.thumb.children[0] || null);+ }+ if (entry.image && entry.imageUrl !== (shown ? objectUrl : null)) {+ entry.imageUrl = shown ? objectUrl : null;+ entry.image.src = entry.imageUrl || '';+ }+ if (entry.image) set(entry.image, 'hidden', !shown);+ set(entry.placeholder, 'hidden', shown);+ set(entry.placeholder, 'textContent', PLACEHOLDERS[status] || 'Checking');+ if (entry.thumb.dataset.status !== status)+ entry.thumb.dataset.status = status;+ const flag = candidate.preview+ ? 'PREVIEW'+ : candidate.pending+ ? 'LOADING'+ : '';+ set(entry.flag, 'textContent', flag);+ set(entry.flag, 'hidden', !flag);+ const recommended = snapshot.recommended?.key === candidate.key;+ set(entry.start, 'hidden', !recommended);+ if (recommended)+ set(+ entry.start,+ 'title',+ START_HERE_TITLES[snapshot.recommended.reason] ||+ 'Newest day with imagery for this box',+ );+ set(entry.date, 'textContent', day);+ set(entry.sensor, 'textContent', sensorLine(candidate.product));+ set(entry.cloud, 'textContent', cloudText(candidate));+ const empty = status === 'empty';+ for (const slotId of ['a', 'b']) {+ const chip = entry.chips[slotId];+ const live = slotId === 'a' || ab;+ const on = candidate.pinned === slotId && live;+ const label = slotId === 'a' ? (ab ? 'A' : 'SHOW') : 'B';+ set(chip, 'textContent', label);+ set(chip, 'disabled', empty || !live);+ toggle(chip, 'active', on);+ toggle(chip, 'is-reserved', !live);+ attribute(chip, 'aria-pressed', String(on));+ attribute(chip, 'aria-hidden', String(!live));+ attribute(+ chip,+ 'aria-label',+ ab ? `Pin ${day} as ${slotId.toUpperCase()}` : `Show ${day}`,+ );+ }+ const state = candidate.pinned+ ? ab+ ? ` · pinned ${candidate.pinned.toUpperCase()}`+ : candidate.pinned === 'a'+ ? ' · shown'+ : ''+ : candidate.preview+ ? ' · preview'+ : '';+ attribute(+ card,+ 'aria-label',+ `${day} · ${sensorLine(candidate.product)} · ${cloudText(candidate)}${recommended ? ' · start here' : ''}${state}`,+ );+ }++ function renderStrip() {+ const candidates = snapshot.candidates;+ const keys = candidates.map((candidate) => candidate.key).join('|');+ if (keys !== stripKeys) {+ stripKeys = keys;+ const wanted = new Set(candidates.map((candidate) => candidate.key));+ for (const [key, entry] of [...cards]) {+ if (wanted.has(key)) continue;+ entry.card.remove();+ cards.delete(key);+ }+ candidates.forEach((candidate, index) => {+ const node = cards.get(candidate.key)?.card || buildCard(candidate);+ if (strip.children[index] !== node)+ strip.insertBefore(node, strip.children[index] || null);+ });+ }+ candidates.forEach(updateCard);+ set(+ stripEmpty,+ 'textContent',+ candidates.length+ ? ''+ : !snapshot.box+ ? 'No box'+ : snapshot.searching+ ? 'Searching'+ : snapshot.hiddenCount+ ? 'Every day is empty here'+ : !snapshot.sources.hls && !snapshot.sources.viirs+ ? 'Sources off'+ : 'No imagery',+ );+ set(stripEmpty, 'hidden', candidates.length > 0);+ if (candidates[snapshot.focusIndex])+ attribute(+ strip,+ 'aria-activedescendant',+ `ri-card-${snapshot.focusIndex}`,+ );+ else strip.removeAttribute('aria-activedescendant');+ toggle(strip, 'searching', snapshot.searching);+ set(hint, 'textContent', hintText(snapshot));+ attribute(hint, 'title', hint.textContent);+ }++ /**+ * Keyboard only: slide the strip until the focused card is in view. Only+ * `strip.scrollLeft` moves — `scrollIntoView` would also scroll the body.+ */+ function scrollFocusedIntoView() {+ const focus = snapshot.candidates[snapshot.focusIndex];+ const card = focus ? cards.get(focus.key)?.card : null;+ const left = Number(card?.offsetLeft) || 0;+ const width = Number(card?.offsetWidth) || 0;+ const viewLeft = Number(strip.scrollLeft) || 0;+ const viewWidth = Number(strip.clientWidth) || 0;+ if (!width || !viewWidth) return;+ if (left < viewLeft) strip.scrollLeft = left;+ else if (left + width > viewLeft + viewWidth)+ strip.scrollLeft = left + width - viewWidth;+ }++ function reportVisibleRange() {+ const width = Number(strip.clientWidth) || 0;+ if (!width || !snapshot.candidates.length) return;+ const left = Number(strip.scrollLeft) || 0;+ let first = null;+ let last = null;+ snapshot.candidates.forEach((candidate, index) => {+ const card = cards.get(candidate.key)?.card;+ const start = Number(card?.offsetLeft) || 0;+ const end = start + (Number(card?.offsetWidth) || 0);+ if (!card || end < left || start > left + width) return;+ first ??= index;+ last = index;+ });+ if (first !== null) layer.setVisibleRange(first, last);+ }++ // ---- selection bar ----------------------------------------------------+ /** What slot `slotId` holds: its pin, else the preview filling it. */+ function slotImage(slotId) {+ const pin = snapshot.pins[slotId];+ if (pin.key) return { ...pin, preview: false };+ if (snapshot.preview.slot === slotId && snapshot.preview.key)+ return { ...snapshot.preview, preview: true };+ return null;+ }++ function renderSelection() {+ const { mode } = snapshot;+ set(selection.dataset, 'mode', mode);+ for (const [id, node] of modeButtons) {+ const on = id === mode;+ attribute(node, 'aria-checked', String(on));+ toggle(node, 'active', on);+ set(node, 'tabIndex', on ? 0 : -1);+ }+ const ab = mode === 'ab';+ for (const slotId of ['a', 'b']) {+ const { row, tag, value, unpin } = slotRows[slotId];+ const basemapRow = slotId === 'b' && !ab;+ const image = basemapRow ? null : slotImage(slotId);+ const pinned = Boolean(image && !image.preview);+ set(+ tag,+ 'textContent',+ ab ? slotId.toUpperCase() : slotId === 'a' ? 'IMAGE' : 'VS',+ );+ let text = 'Not set';+ if (basemapRow) text = 'Basemap';+ else if (image?.label)+ text = `${image.sourceOff ? 'Source off · ' : ''}${image.label}${+ image.preview+ ? ' · preview'+ : image.candidate && !image.drapable && !image.sourceOff+ ? ' · loading'+ : ''+ }`;+ set(value, 'textContent', text);+ attribute(value, 'title', text);+ const lit = basemapRow+ ? mode === 'basemap'+ : Boolean(image) && !image.sourceOff;+ set(+ row.dataset,+ 'state',+ pinned ? 'pinned' : image ? 'preview' : 'empty',+ );+ toggle(row, 'lit', lit);+ set(unpin, 'disabled', !pinned);+ toggle(unpin, 'is-reserved', !pinned);+ attribute(unpin, 'aria-hidden', String(!pinned));+ attribute(+ unpin,+ 'aria-label',+ ab ? `Unpin ${slotId.toUpperCase()}` : 'Unpin the image',+ );+ set(unpin, 'title', unpin.getAttribute('aria-label'));+ }+ }++ // ---- opacity and export -----------------------------------------------+ /** The image a slot's EXPORT downloads: its pin, else its preview. */+ function exportTarget(slotId) {+ if (slotId === 'b' && snapshot.mode !== 'ab') return null;+ const image = slotImage(slotId);+ return image?.candidate && !image.sourceOff ? image.candidate : null;+ }++ function renderControls() {+ const anything = Boolean(snapshot.shown.a || snapshot.shown.b);+ set(opacity, 'disabled', !anything);+ const alphaValue = String(Math.round(snapshot.alpha * 100));+ if (opacity.value !== alphaValue) opacity.value = alphaValue;+ set(opacityValue, 'textContent', `${alphaValue}%`);+ const swipe = snapshot.comparison.active;+ toggle(swap, 'is-reserved', !swipe);+ set(swap, 'disabled', !swipe);+ attribute(swap, 'aria-hidden', String(!swipe));+ toggle(swap, 'active', swipe && snapshot.swapped);+ attribute(swap, 'aria-pressed', String(swipe && snapshot.swapped));+ const ab = snapshot.mode === 'ab';+ exports.update([+ {+ id: 'export',+ type: 'actions',+ actions: ['a', 'b'].map((slotId) => ({+ id: `export-${slotId}`,+ label: ab ? `EXPORT ${slotId.toUpperCase()}` : 'EXPORT',+ title: `Download ${ab ? slotId.toUpperCase() : 'the image'} as a PNG`,+ disabled: !exportTarget(slotId) || exporting.has(slotId),+ onClick: () => void exportImage(slotId),+ })),+ },+ ]);+ const exportB = findIn(+ exportHost,+ (node) => node.dataset?.actionId === 'export-b',+ );+ if (exportB) {+ toggle(exportB, 'is-reserved', !ab);+ attribute(exportB, 'aria-hidden', String(!ab));+ }+ }++ // ---- details ----------------------------------------------------------+ function detailLines() {+ const focus = snapshot.focus;+ const lines = [];+ if (snapshot.box)+ lines.push({+ id: 'box',+ text: `Box ${kmText(snapshot.boxSizeKm?.width)} × ${kmText(snapshot.boxSizeKm?.height)} km`,+ });+ if (focus) {+ lines.push({ id: 'readout', text: snapshot.readout || '' });+ const times = [];+ if (focus.timeRange?.start) {+ const start = utcTime(focus.timeRange.start);+ const end = utcTime(focus.timeRange.end || focus.timeRange.start);+ times.push(`Acquired ${start === end ? start : `${start}–${end}`}`);+ } else if (focus.thumbnail?.acquisitionTime)+ times.push(`Acquired ${utcTime(focus.thumbnail.acquisitionTime)}`);+ times.push(`Coverage ${focus.coverage || 'unknown'}`);+ lines.push({ id: 'acquired', text: times.join(' · ') });+ (focus.granules || []).forEach((granule, index) => {+ const cloud = Number.isFinite(granule.cloud)+ ? ` · ${Math.round(granule.cloud)}% cloud`+ : '';+ lines.push({+ id: `granule-${index}`,+ text: `${granule.id || granule.product} · ${utcTime(granule.timeStart)}${cloud}`,+ muted: true,+ });+ });+ }+ const reason = START_HERE_REASONS[snapshot.recommended?.reason];+ if (reason) lines.push({ id: 'start', text: `START HERE · ${reason}` });+ for (const [index, note] of snapshot.notes.entries())+ lines.push({ id: `note-${index}`, text: note, muted: true });+ if (+ snapshot.sources.viirs &&+ snapshot.box &&+ longerSideKm(snapshot.boxSizeKm) > 0 &&+ longerSideKm(snapshot.boxSizeKm) < OVERVIEW_MIN_BOX_KM+ )+ lines.push({+ id: 'overview-scale',+ text: 'Daily overview shows little detail in a box this small',+ muted: true,+ });+ lines.push({+ id: 'credit',+ text: 'Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS',+ muted: true,+ });+ return lines;+ }++ function renderDetails() {+ const hidden = snapshot.hiddenCount;+ const showing = snapshot.showUnavailable;+ details.update([+ {+ id: 'details',+ title: 'Details',+ open: detailsOpen,+ compact: snapshot.focus ? snapshot.readout : 'Times, coverage, sources',+ blocks: [+ { id: 'lines', type: 'lines', lines: detailLines() },+ {+ id: 'empty-days',+ type: 'actions',+ actions: [+ {+ id: 'toggle-empty',+ label: showing+ ? 'HIDE EMPTY DAYS'+ : `SHOW EMPTY DAYS · ${hidden}`,+ title: 'Days the probe found empty in this box',+ disabled: !showing && !hidden,+ onClick: () => layer.setShowUnavailable(!showing),+ },+ ],+ },+ ],+ },+ ]);+ if (detailsOpen && !detailsShownOpen)+ revealCard(container, detailsHost.children[0]);+ detailsShownOpen = detailsOpen;+ }++ // ---- divider ----------------------------------------------------------+ function renderSplit() {+ const live = snapshot.comparison.active;+ const basemap = snapshot.shown.swipe === 'basemap';+ const swapped = Boolean(snapshot.swapped);+ const a = snapshot.candidates.find((c) => c.key === snapshot.shown.a);+ const b = snapshot.candidates.find((c) => c.key === snapshot.shown.b);+ const describe = (c) => (c ? `${sensorLine(c.product)} · ${c.day}` : '');+ // The two sides as [label, title, spoken name]; SWAP trades them.+ const sides = [+ basemap ? ['IMAGE', describe(a), 'image'] : ['A', describe(a), 'A'],+ basemap ? ['BASEMAP', 'The basemap', 'basemap'] : ['B', describe(b), 'B'],+ ];+ const [before, after] = swapped ? [sides[1], sides[0]] : sides;+ const signature = live+ ? `${snapshot.shown.swipe}|${swapped}|${describe(a)}|${describe(b)}`+ : '';+ if (signature !== splitSignature) {+ split?.destroy();+ split = null;+ splitSignature = signature;+ }+ if (!live || split || destroyed) return;+ split = createSplit({+ scene: viewer?.scene,+ parent: document.body,+ initialValue: snapshot.split,+ id: 'recent-imagery-split-line',+ handleClass: 'recent-imagery-split-handle',+ cssTarget: document.documentElement,+ cssProperty: '--recent-imagery-split',+ beforeLabel: before[0],+ afterLabel: after[0],+ beforeTitle: before[1],+ afterTitle: after[1],+ ariaLabel: basemap+ ? 'Recent imagery against the basemap divider'+ : 'Recent imagery A and B divider',+ formatValueText: (leftPercent, rightPercent) =>+ `${before[2][0].toUpperCase()}${before[2].slice(1)} ${leftPercent} percent, ${after[2]} ${rightPercent} percent`,+ getViewportWidth: () =>+ Number(viewer?.scene?.canvas?.clientWidth) ||+ Number(document.documentElement?.clientWidth) ||+ 0,+ onChange: (value) => layer.setSplit(value),+ requestRender,+ });+ split?.setValue(snapshot.split);+ }++ // ---- panel ------------------------------------------------------------+ function renderPanel() {+ const hidden = !snapshot.enabled;+ if (panel) set(panel, 'hidden', hidden);+ set(root, 'hidden', hidden);+ if (count) set(count, 'textContent', hidden ? '' : countText(snapshot));+ if (hidden || !panel || appearedDocuments.has(document)) return;+ appearedDocuments.add(document);+ // First appearance opens the panel unless a stored or shared collapse+ // choice exists (marked by the panel chrome when it restored the state).+ const preference = panel.dataset?.collapsedPreference;+ if (+ panel.classList.contains('collapsed') &&+ (preference === undefined || preference === 'default')+ )+ panel.querySelector?.(`[data-collapse-target="${PANEL_ID}"]`)?.click();+ }++ function render() {+ if (destroyed) return;+ preserveScroll(() => {+ set(root.dataset, 'mode', snapshot.mode);+ renderPanel();+ renderActions();+ renderNotice();+ renderStrip();+ renderSelection();+ renderControls();+ renderDetails();+ renderSplit();+ reportVisibleRange();+ });+ }++ // ---- export -----------------------------------------------------------+ async function exportImage(slotId = 'a') {+ const candidate = exportTarget(slotId);+ if (!candidate || !snapshot.box || exporting.has(slotId)) return false;+ exporting.add(slotId);+ exportError = null;+ preserveScroll(renderControls);+ // The snapshot is plate carrée: keep the box's degree aspect, with the+ // longer side at the size limit.+ const size = longerSideKm(snapshot.boxSizeKm) > 25 ? 2048 : 1024;+ const spanLon = Math.abs(snapshot.box.east - snapshot.box.west) || 1;+ const spanLat = Math.abs(snapshot.box.north - snapshot.box.south) || 1;+ const width = Math.max(+ 1,+ Math.round(size * Math.min(1, spanLon / spanLat)),+ );+ const height = Math.max(+ 1,+ Math.round(size * Math.min(1, spanLat / spanLon)),+ );+ try {+ const response = await fetchImpl(+ wvsSnapshotUrl({+ product: candidate.product,+ day: candidate.day,+ box: snapshot.box,+ width,+ height,+ }),+ );+ if (!response?.ok) throw new Error(`HTTP ${response?.status ?? 'error'}`);+ const blob = await response.blob();+ if (destroyed) return false;+ const href = createObjectUrl(blob);+ const anchor = document.createElement('a');+ anchor.href = href;+ anchor.download = `recent-imagery-${candidate.product}-${candidate.day}.png`;+ anchor.hidden = true;+ document.body.appendChild(anchor);+ try {+ anchor.click();+ } finally {+ anchor.remove();+ revokeObjectUrl(href);+ }+ return true;+ } catch (error) {+ if (!destroyed)+ exportError = `Export failed · ${error?.message || error}`;+ return false;+ } finally {+ exporting.delete(slotId);+ if (!destroyed)+ preserveScroll(() => {+ renderControls();+ renderNotice();+ });+ }+ }++ // ---- input ------------------------------------------------------------+ /** Escape clears the preview, then cancels the box tool, then blurs. */+ function escape() {+ if (layer.clearPreview()) return true;+ if (tool?.isActive()) {+ tool.cancel('escape');+ return true;+ }+ strip.blur();+ return false;+ }++ function pin(slotId, key) {+ if (!key) return;+ if (slotId === 'b' && snapshot.mode !== 'ab') return;+ exportError = null;+ layer.toggleAssignment(slotId, key);+ }++ listen(root, 'click', (event) => {+ const target = event.target;+ const chip = target?.closest?.('.ri-chip');+ const card = target?.closest?.('.ri-card');+ if (chip && card) {+ if (!chip.disabled) pin(chip.dataset.slot, card.dataset.key);+ strip.focus({ preventScroll: true });+ return;+ }+ if (card) {+ exportError = null;+ layer.preview(card.dataset.key);+ strip.focus({ preventScroll: true });+ return;+ }+ const mode = target?.closest?.('.ri-mode-btn');+ if (mode) {+ layer.setMode(mode.dataset.mode);+ return;+ }+ if (target?.closest?.('.ri-swap') && !swap.disabled) {+ layer.swapSides?.();+ return;+ }+ const unpin = target?.closest?.('.ri-unpin');+ if (unpin && !unpin.disabled)+ layer.setAssignment(unpin.dataset.unpin, null);+ // The layer owns the camera flight; the panel only asks.+ if (target?.closest?.('.ri-zoom-in') && !zoomIn.disabled)+ layer.zoomToFit?.();+ });++ listen(root, 'input', (event) => {+ if (event.target === opacity) layer.setAlpha(Number(opacity.value) / 100);+ });++ listen(modeGroup, 'keydown', (event) => {+ const order = MODE_LABELS.map(([mode]) => mode);+ const step =+ { ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1 }[event.key] ||+ 0;+ if (!step) return;+ event.preventDefault();+ const next =+ order[+ (order.indexOf(snapshot.mode) + step + order.length) % order.length+ ];+ layer.setMode(next);+ modeButtons.get(next)?.focus?.();+ });++ listen(strip, 'keydown', (event) => {+ const total = snapshot.candidates.length;+ const index = snapshot.focusIndex || 0;+ const focus = snapshot.candidates[index];+ if (event.key === 'Escape') {+ event.preventDefault();+ escape();+ return;+ }+ if (event.ctrlKey || event.metaKey || event.altKey) return;+ if (event.key === 'Enter') {+ event.preventDefault();+ // Enter is a click on the focused card; key repeat must not re-fire.+ if (focus && !event.repeat) layer.preview(focus.key);+ return;+ }+ const letter = String(event.key || '').toLowerCase();+ const slotId =+ letter === 'a' || (letter === 's' && snapshot.mode !== 'ab')+ ? 'a'+ : letter === 'b'+ ? 'b'+ : null;+ if (slotId) {+ event.preventDefault();+ if (!event.repeat && focus && focus.thumbnail?.status !== 'empty')+ pin(slotId, focus.key);+ return;+ }+ const step = KEY_STEPS[event.key];+ if (!step || !total) return;+ event.preventDefault();+ layer.focus(Math.max(0, Math.min(total - 1, step(index, total))));+ preserveScroll(scrollFocusedIntoView);+ });++ listen(root, 'keydown', (event) => {+ if (event.key === 'Escape' && event.target !== strip) {+ if (+ snapshot.preview.key ||+ snapshot.preview.pending ||+ tool?.isActive()+ ) {+ event.preventDefault();+ escape();+ }+ }+ });++ listen(strip, 'scroll', reportVisibleRange, { passive: true });++ // ---- wiring -----------------------------------------------------------+ layer.setToolHandler?.(() => {+ if (tool?.isActive()) tool.cancel('layer');+ });+ const unsubscribe = layer.subscribe((next, reason) => {+ if (destroyed) return;+ snapshot = next || layer.getSnapshot();+ if (reason === 'split') {+ split?.setValue(snapshot.split);+ } else if (reason === 'alpha') {+ preserveScroll(renderControls);+ } else if (+ reason === 'thumbnail' &&+ snapshot.candidates.map((candidate) => candidate.key).join('|') ===+ stripKeys+ ) {+ // A probe that emptied a day hides its card; only an unchanged strip+ // takes this in-place path.+ preserveScroll(() => {+ snapshot.candidates.forEach(updateCard);+ renderDetails();+ });+ } else {+ render();+ }+ });+ render();++ return {+ root,+ exportImage,+ destroy() {+ if (destroyed) return;+ destroyed = true;+ unsubscribe();+ layer.setToolHandler?.(null);+ split?.destroy();+ split = null;+ for (const [target, type, handler, options] of listeners.splice(0))+ target.removeEventListener(type, handler, options);+ for (const entry of cards.values()) {+ if (entry.image) entry.image.src = '';+ }+ cards.clear();+ actions.destroy();+ exports.destroy();+ details.destroy();+ root.remove();+ if (count) count.textContent = '';+ if (panel) panel.hidden = true;+ },+ };+}diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjsnew file mode 100644index 000000000..b91169739--- /dev/null+++ b/src/ui/recentImagery.test.mjs@@ -0,0 +1,1153 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { createRecentImageryPanel } from './recentImagery.js';+import { createRecentImageryLayer } from '../layers/recentImagery/index.js';+import {+ BOX,+ fakeCatalog,+ fakeController,+ fakeRenderer,+ fakeThumbnails,+ manualTimers,+ response,+ settle,+} from '../layers/recentImagery/testDoubles.mjs';++const S18 = 'S30:2026-09-18';+const L16 = 'L30:2026-09-16';+const V21 = 'VIIRS:2026-09-21';++// ---- a small DOM double ------------------------------------------------------+class FakeClassList {+ constructor(node) {+ this.node = node;+ }+ get names() {+ return new Set(+ String(this.node.className || '')+ .split(/\s+/)+ .filter(Boolean),+ );+ }+ contains(name) {+ return this.names.has(name);+ }+ toggle(name, force) {+ const names = this.names;+ const on = force === undefined ? !names.has(name) : Boolean(force);+ if (on) names.add(name);+ else names.delete(name);+ this.node.className = [...names].join(' ');+ return on;+ }+ add(...list) {+ for (const name of list) this.toggle(name, true);+ }+ remove(...list) {+ for (const name of list) this.toggle(name, false);+ }+}++function matches(node, selector) {+ if (selector.startsWith('.'))+ return node.classList.contains(selector.slice(1));+ if (selector.startsWith('#')) return node.id === selector.slice(1);+ const attr = /^\[([\w-]+)(?:="([^"]*)")?\]$/.exec(selector);+ if (!attr) return false;+ const key = attr[1].startsWith('data-')+ ? attr[1].slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())+ : null;+ const value = key ? node.dataset[key] : node.getAttribute(attr[1]);+ return attr[2] === undefined ? value != null : value === attr[2];+}++class FakeElement {+ constructor(tagName, ownerDocument) {+ this.tagName = String(tagName).toUpperCase();+ this.ownerDocument = ownerDocument;+ this.children = [];+ this.parentNode = null;+ this.className = '';+ this.dataset = {};+ this.style = {};+ this.attributes = new Map();+ this.listeners = new Map();+ this.hidden = false;+ this.disabled = false;+ this.id = '';+ this.title = '';+ this._text = '';+ this.scrollTop = 0;+ this.scrollLeft = 0;+ this.focused = 0;+ this.blurred = 0;+ }+ get classList() {+ return new FakeClassList(this);+ }+ get textContent() {+ return this.children.length+ ? this.children.map((child) => child.textContent).join('')+ : this._text;+ }+ set textContent(value) {+ for (const child of this.children) child.parentNode = null;+ this.children = [];+ this._text = String(value);+ }+ setAttribute(name, value) {+ this.attributes.set(name, String(value));+ }+ getAttribute(name) {+ return this.attributes.get(name) ?? null;+ }+ removeAttribute(name) {+ this.attributes.delete(name);+ }+ appendChild(child) {+ return this.insertBefore(child, null);+ }+ insertBefore(child, reference) {+ child.parentNode?.removeChild(child);+ const index = reference ? this.children.indexOf(reference) : -1;+ if (index < 0) this.children.push(child);+ else this.children.splice(index, 0, child);+ child.parentNode = this;+ return child;+ }+ append(...children) {+ for (const child of children) this.appendChild(child);+ }+ removeChild(child) {+ this.children.splice(this.children.indexOf(child), 1);+ child.parentNode = null;+ }+ remove() {+ this.parentNode?.removeChild(this);+ }+ addEventListener(type, handler) {+ if (!this.listeners.has(type)) this.listeners.set(type, new Set());+ this.listeners.get(type).add(handler);+ }+ removeEventListener(type, handler) {+ this.listeners.get(type)?.delete(handler);+ }+ /** Bubble an event from this node to the root. */+ dispatch(type, init = {}) {+ const event = {+ type,+ target: this,+ defaultPrevented: false,+ preventDefault() {+ this.defaultPrevented = true;+ },+ ...init,+ };+ for (let node = this; node; node = node.parentNode)+ for (const handler of [...(node.listeners.get(type) || [])])+ handler(event);+ return event;+ }+ click() {+ if (!this.disabled) this.dispatch('click');+ }+ matches(selector) {+ return matches(this, selector);+ }+ closest(selector) {+ for (let node = this; node; node = node.parentNode)+ if (matches(node, selector)) return node;+ return null;+ }+ querySelector(selector) {+ return this.find((node) => matches(node, selector));+ }+ find(predicate) {+ for (const child of this.children) {+ if (predicate(child)) return child;+ const inner = child.find(predicate);+ if (inner) return inner;+ }+ return null;+ }+ findAll(predicate, out = []) {+ for (const child of this.children) {+ if (predicate(child)) out.push(child);+ child.findAll(predicate, out);+ }+ return out;+ }+ focus(options) {+ this.focused += 1;+ this.focusOptions = options;+ }+ blur() {+ this.blurred += 1;+ }+ listenerCount() {+ return [...this.listeners.values()].reduce((n, set) => n + set.size, 0);+ }+}++/** The static rail panel skeleton from templates/context.html. */+function fakeDocument() {+ const document = {+ documentElement: { clientWidth: 1200 },+ createElement: (tag) => new FakeElement(tag, document),+ getElementById: (id) => document.body.find((node) => node.id === id),+ };+ document.body = new FakeElement('body', document);+ const panel = document.createElement('div');+ panel.id = 'recent-imagery-panel';+ panel.className = 'panel-collapsible collapsed';+ panel.hidden = true;+ const count = document.createElement('span');+ count.id = 'recent-imagery-panel-count';+ const collapse = document.createElement('button');+ collapse.dataset.collapseTarget = 'recent-imagery-panel';+ collapse.clicked = 0;+ collapse.click = () => {+ collapse.clicked += 1;+ panel.classList.toggle('collapsed');+ };+ const body = document.createElement('div');+ body.id = 'recent-imagery-panel-body';+ panel.append(count, collapse, body);+ document.body.appendChild(panel);+ return { document, panel, count, collapse, body };+}++// ---- the real layer, with fakes for everything it injects ------------------+function fixture({ fetchImpl, controller = fakeController() } = {}) {+ const dom = fakeDocument();+ const renderer = fakeRenderer();+ const thumbnails = fakeThumbnails();+ const catalog = fakeCatalog();+ const timers = manualTimers();+ const layer = createRecentImageryLayer({+ catalog,+ renderer,+ thumbnails,+ host: () => ({ collection: {}, kind: 'globe' }),+ now: () => new Date('2026-09-21T15:00:00Z'),+ setTimeoutImpl: timers.setTimeoutImpl,+ clearTimeoutImpl: timers.clearTimeoutImpl,+ });+ layer.setSources({ viirs: true });+ const viewer = {+ camera: {},+ scene: { canvas: { clientWidth: 1000 }, requestRender() {} },+ };+ layer.init(viewer);+ layer.attachMapStackController(controller);+ let active = false;+ const tool = {+ calls: [],+ start() {+ active = true;+ this.calls.push('start');+ layer.setToolActive(true);+ },+ cancel(reason) {+ active = false;+ this.calls.push(`cancel:${reason}`);+ layer.setToolActive(false);+ },+ isActive: () => active,+ };+ const splits = [];+ const fetches = [];+ const urls = { created: [], revoked: [] };+ const readout = createRecentImageryPanel({+ container: dom.body,+ layer,+ viewer,+ tool,+ createSplit: (options) => {+ const split = {+ options,+ value: options.initialValue,+ values: [],+ destroyed: false,+ setValue(next) {+ this.value = next;+ this.values.push(next);+ },+ destroy() {+ this.destroyed = true;+ },+ };+ splits.push(split);+ return split;+ },+ fetchImpl:+ fetchImpl ||+ (async (url) => {+ fetches.push(url);+ return response();+ }),+ createObjectUrl: () => {+ urls.created.push('blob:export');+ return 'blob:export';+ },+ revokeObjectUrl: (url) => urls.revoked.push(url),+ });+ const root = readout.root;+ const byId = (id) => root.find((node) => node.id === id);+ const byAction = (id) => root.find((node) => node.dataset.actionId === id);+ const cards = () =>+ root.findAll((node) => node.classList.contains('ri-card'));+ const card = (key) => cards().find((node) => node.dataset.key === key);+ const chip = (key, slot) =>+ card(key).find((node) => node.dataset.slot === slot);+ const part = (node, name) =>+ node.find((child) => child.classList.contains(name));+ const strip = byId('ri-strip');+ const key = (name, extra = {}) =>+ strip.dispatch('keydown', { key: name, ...extra });+ /** Enable, select BOX and land the catalog. */+ const ready = async () => {+ layer.enable();+ layer.setBox(BOX);+ catalog.resolveLast();+ await settle();+ };+ const settleLease = async () => {+ controller.lease?.settle();+ await settle();+ };+ return {+ ...dom,+ layer,+ viewer,+ renderer,+ thumbnails,+ catalog,+ controller,+ timers,+ tool,+ splits,+ fetches,+ urls,+ readout,+ root,+ byId,+ byAction,+ cards,+ card,+ chip,+ part,+ strip,+ key,+ ready,+ settleLease,+ snap: () => layer.getSnapshot(),+ };+}++const rowText = (f, slotId) =>+ [+ part(f, `ri-slot-${slotId}`, 'ri-slot-tag').textContent,+ part(f, `ri-slot-${slotId}`, 'ri-slot-value').textContent,+ ].join(' | ');+function part(f, id, name) {+ return f.byId(id).find((node) => node.classList.contains(name));+}++// ---- tests ---------------------------------------------------------------------+test('the readout mounts in the rail body, hides while the layer is off and opens the panel once on first appearance', async () => {+ const f = fixture();+ assert.equal(f.root.parentNode, f.body);+ assert.equal(f.panel.hidden, true);+ assert.equal(f.count.textContent, '');+ await f.ready();+ const panel = f.document.getElementById('recent-imagery-panel');+ assert.equal(panel.hidden, false);+ assert.equal(f.collapse.clicked, 1, 'first appearance expands');+ assert.equal(panel.classList.contains('collapsed'), false);+ assert.equal(f.count.textContent, '4 DAYS');+ f.collapse.click();+ f.layer.disable();+ f.layer.enable();+ assert.equal(f.collapse.clicked, 2, 'never again: the user collapsed it');+ f.layer.disable();+ assert.equal(panel.hidden, true);+ assert.equal(f.count.textContent, '');+ // A stored or shared collapse choice wins over the first appearance.+ const g = fixture();+ g.document.getElementById(+ 'recent-imagery-panel',+ ).dataset.collapsedPreference = 'stored';+ g.layer.enable();+ assert.equal(g.collapse.clicked, 0);+});++test('the body is a fixed stack of seven blocks in a fixed order, each with a fixed height in the stylesheet', () => {+ const f = fixture();+ assert.deepEqual(+ f.root.children.map((node) => node.id || node.className),+ [+ 'ri-actions',+ 'ri-notice',+ 'ri-strip',+ 'ri-hint',+ 'ri-selection',+ 'ri-controls',+ 'ri-details',+ ],+ );+ const css = readFileSync(+ new URL('./styles/recent-imagery.css', import.meta.url),+ 'utf8',+ );+ const rule = (selector) => {+ const start = css.indexOf(`${selector} {`);+ assert.ok(start >= 0, selector);+ return css.slice(start, css.indexOf('}', start));+ };+ assert.match(rule('.recent-imagery-readout .ri-actions-row'), /height: 22px/);+ assert.match(rule('.recent-imagery-readout .ri-line'), /height: 14px/);+ assert.match(rule('.recent-imagery-readout .ri-strip'), /height: 120px/);+ assert.match(rule('.recent-imagery-readout .ri-card'), /height: 112px/);+ assert.match(+ rule('.recent-imagery-readout .ri-selection'),+ /grid-template-rows: 20px 20px 20px/,+ );+ assert.match(rule('.recent-imagery-readout .ri-slot'), /height: 20px/);+ assert.match(rule('.recent-imagery-readout .ri-controls'), /height: 22px/);+ assert.match(+ rule('.recent-imagery-readout .is-reserved'),+ /visibility: hidden/,+ );+});++/*+ * A DOM-structure guard, not a layout-shift check: the fake DOM has no+ * layout, so this pins what the layout rests on (every control keeps its+ * place in the tree, nothing is hidden, and every block that must not change+ * height keeps the class the stylesheet fixes it by). The live gate+ * `scripts/qa-recent-imagery.mjs` measures the real rectangles.+ */+test('no control changes place in the tree, no block is hidden and every fixed-height block keeps its height class across every state (DOM-structure guard)', async () => {+ const f = fixture();+ const cssRule = (file, selector) => {+ const css = readFileSync(new URL(file, import.meta.url), 'utf8');+ const start = css.indexOf(`${selector} {`);+ assert.ok(start >= 0, `${file} has ${selector}`);+ return css.slice(start, css.indexOf('}', start));+ };+ const readout = (selector) =>+ cssRule(+ './styles/recent-imagery.css',+ `.recent-imagery-readout ${selector}`,+ );+ /**+ * Every block that must keep its height: the node carrying the class, that+ * class, and the rule it gets its height from. The mode row is the first+ * 20 px track of the selection grid. The details header has no height of+ * its own: it is the last block, so it moves nothing below it, and its+ * title is held to one line.+ */+ const fixedHeightBlocks = () => {+ const mode = f.byId('ri-mode');+ const header = f+ .byId('ri-details')+ .find((node) => node.classList.contains('rail-card-header'));+ return {+ 'ri-actions': [+ f.byId('ri-actions'),+ 'ri-actions-row',+ readout('.ri-actions-row'),+ /height: 22px/,+ ],+ 'ri-notice': [+ f.byId('ri-notice'),+ 'ri-line',+ readout('.ri-line'),+ /height: 14px/,+ ],+ 'ri-zoom-in': [+ f.byId('ri-zoom-in')?.parentNode === f.byId('ri-notice')+ ? f.byId('ri-zoom-in')+ : null,+ 'ri-zoom-in',+ readout('.ri-zoom-in'),+ /height: 14px/,+ ],+ 'ri-strip': [+ f.byId('ri-strip'),+ 'ri-strip',+ readout('.ri-strip'),+ /height: 120px/,+ ],+ 'ri-hint': [+ f.byId('ri-hint'),+ 'ri-line',+ readout('.ri-line'),+ /height: 14px/,+ ],+ 'ri-mode': [+ mode.parentNode.children[0] === mode ? mode.parentNode : null,+ 'ri-selection',+ readout('.ri-selection'),+ /grid-template-rows: 20px 20px 20px/,+ ],+ 'ri-slot-a': [+ f.byId('ri-slot-a'),+ 'ri-slot',+ readout('.ri-slot'),+ /height: 20px/,+ ],+ 'ri-slot-b': [+ f.byId('ri-slot-b'),+ 'ri-slot',+ readout('.ri-slot'),+ /height: 20px/,+ ],+ 'ri-controls': [+ f.byId('ri-controls'),+ 'ri-controls',+ readout('.ri-controls'),+ /height: 22px/,+ ],+ 'ri-swap': [+ f.byId('ri-swap')?.parentNode === f.byId('ri-controls')+ ? f.byId('ri-swap')+ : null,+ 'data-toggle-chip',+ readout('.data-toggle-chip'),+ /height: 22px/,+ ],+ 'details header': [+ f.root.children.at(-1) === f.byId('ri-details')+ ? header?.find((node) => node.classList.contains('rail-card-title'))+ : null,+ 'rail-card-nowrap',+ cssRule('./styles/weather.css', '.rail-card-nowrap'),+ /white-space: nowrap/,+ ],+ };+ };+ const assertFixedHeights = (label) => {+ for (const [name, [node, className, rule, fixed]] of Object.entries(+ fixedHeightBlocks(),+ )) {+ assert.ok(node, `${name} is in place (${label})`);+ assert.ok(+ node.classList.contains(className),+ `${name} carries .${className} (${label})`,+ );+ assert.match(rule, fixed, `.${className} fixes ${name}`);+ }+ };+ const controls = () => ({+ 'select-box': f.byAction('select-box'),+ 'use-view': f.byAction('use-view'),+ clear: f.byAction('clear'),+ notice: f.byId('ri-notice'),+ 'zoom-in': f.byId('ri-zoom-in'),+ strip: f.strip,+ hint: f.byId('ri-hint'),+ 'mode-image': f.root.find(+ (node) =>+ node.classList.contains('ri-mode-btn') && node.dataset.mode === 'image',+ ),+ 'mode-basemap': f.root.find(+ (node) =>+ node.classList.contains('ri-mode-btn') &&+ node.dataset.mode === 'basemap',+ ),+ 'mode-ab': f.root.find(+ (node) =>+ node.classList.contains('ri-mode-btn') && node.dataset.mode === 'ab',+ ),+ 'row-a': f.byId('ri-slot-a'),+ 'row-b': f.byId('ri-slot-b'),+ 'unpin-a': f.byId('ri-unpin-a'),+ 'unpin-b': f.byId('ri-unpin-b'),+ opacity: f.byId('ri-opacity'),+ swap: f.byId('ri-swap'),+ 'export-a': f.byAction('export-a'),+ 'export-b': f.byAction('export-b'),+ details: f+ .byId('ri-details')+ .find((node) => node.classList.contains('rail-card-header')),+ });+ /** Tag and index from the root down, plus every hidden flag on the way. */+ const layout = () => {+ const out = {};+ for (const [name, node] of Object.entries(controls())) {+ assert.ok(node, name);+ const path = [];+ for (let at = node; at && at !== f.root; at = at.parentNode) {+ assert.equal(at.hidden, false, `${name} is never hidden`);+ path.unshift(`${at.tagName}${at.parentNode.children.indexOf(at)}`);+ }+ out[name] = path.join('/');+ }+ return out;+ };+ const baseline = layout();+ assertFixedHeights('built');+ const states = [];+ const record = (label) => {+ assert.deepEqual(layout(), baseline, label);+ assertFixedHeights(label);+ states.push(label);+ };+ f.layer.enable();+ record('enabled, no box');+ f.layer.setBox(BOX);+ record('searching');+ f.catalog.resolveLast();+ await settle();+ await f.settleLease();+ record('preview');+ f.chip(S18, 'a').click();+ record('pinned');+ f.byId('ri-opacity').value = '40';+ f.byId('ri-opacity').dispatch('input');+ record('opacity');+ f.root+ .find(+ (node) =>+ node.classList.contains('ri-mode-btn') &&+ node.dataset.mode === 'basemap',+ )+ .click();+ record('vs basemap');+ f.root+ .find(+ (node) =>+ node.classList.contains('ri-mode-btn') && node.dataset.mode === 'ab',+ )+ .click();+ f.chip(L16, 'b').click();+ record('A / B');+ f.byId('ri-swap').click();+ record('swapped');+ f.byId('ri-unpin-b').click();+ record('B unpinned');+ f.byId('ri-unpin-a').click();+ record('A unpinned');+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });+ record('refused');+ f.byAction('clear').click();+ record('cleared');+ assert.equal(states.length, 12);+});++test('cards carry thumbnail, date, sensor, cloud, START HERE and PREVIEW; the chips follow the mode without moving', async () => {+ const f = fixture();+ await f.ready();+ f.thumbnails.setStatus(S18, 'present');+ f.layer.setVisibleRange(0, 3);+ f.layer.focus(1);+ const s18 = f.card(S18);+ assert.equal(f.part(s18, 'ri-card-date').textContent, 'Sep 18');+ assert.equal(f.part(s18, 'ri-card-sensor').textContent, 'Sentinel-2 · 30 m');+ assert.equal(f.part(s18, 'ri-card-cloud').textContent, '12% cloud');+ assert.equal(f.part(s18, 'ri-card-start').hidden, false);+ assert.match(f.part(s18, 'ri-card-start').title, /Newest low-cloud day/);+ assert.equal(f.part(s18, 'ri-card-flag').textContent, 'PREVIEW');+ assert.equal(+ f.part(f.card(V21), 'ri-card-cloud').textContent,+ 'cloud unknown',+ );+ assert.equal(f.part(f.card(V21), 'ri-thumb-text').textContent, 'Checking');+ assert.equal(+ f.part(f.card(V21), 'ri-card-sensor').textContent,+ 'Daily overview · 250 m',+ );+ assert.equal(+ f.part(f.card(L16), 'ri-card-sensor').textContent,+ 'Landsat 8/9 · 30 m',+ );+ // IMAGE: one SHOW chip; the B chip keeps its box but is invisible.+ const [a, b] = [f.chip(S18, 'a'), f.chip(S18, 'b')];+ assert.deepEqual(+ [+ a.textContent,+ a.getAttribute('aria-pressed'),+ b.classList.contains('is-reserved'),+ b.disabled,+ ],+ ['SHOW', 'false', true, true],+ );+ assert.equal(a.getAttribute('aria-label'), 'Show Sep 18');+ a.click();+ assert.equal(a.getAttribute('aria-pressed'), 'true');+ assert.equal(a.classList.contains('active'), true);+ assert.equal(+ f.part(s18, 'ri-card-flag').hidden,+ true,+ 'pinned, not previewed',+ );+ assert.match(s18.getAttribute('aria-label'), /· shown$/);+ // A / B: the same chip slots, relabelled.+ f.root+ .find(+ (node) =>+ node.classList.contains('ri-mode-btn') && node.dataset.mode === 'ab',+ )+ .click();+ assert.deepEqual(+ [+ a.textContent,+ b.textContent,+ b.classList.contains('is-reserved'),+ b.disabled,+ ],+ ['A', 'B', false, false],+ );+ assert.equal(a.parentNode.children.indexOf(a), 0);+ assert.equal(b.getAttribute('aria-label'), 'Pin Sep 18 as B');+ // A day is one slot only: B moves it.+ b.click();+ assert.deepEqual(+ [a.getAttribute('aria-pressed'), b.getAttribute('aria-pressed')],+ ['false', 'true'],+ );+ // An empty day cannot be pinned.+ f.thumbnails.probe(V21, 'empty');+ f.layer.setShowUnavailable(true);+ assert.equal(f.chip(V21, 'a').disabled, true);+ assert.equal(f.part(f.card(V21), 'ri-card-cloud').textContent, 'no imagery');+});++test('the selection bar reads the mode, both rows and a preview, with × reserved when empty', async () => {+ const f = fixture();+ await f.ready();+ const modes = f.root.findAll((node) =>+ node.classList.contains('ri-mode-btn'),+ );+ assert.deepEqual(+ modes.map((node) => [+ node.textContent,+ node.getAttribute('role'),+ node.getAttribute('aria-checked'),+ ]),+ [+ ['IMAGE', 'radio', 'true'],+ ['VS BASEMAP', 'radio', 'false'],+ ['A / B', 'radio', 'false'],+ ],+ );+ assert.equal(rowText(f, 'a'), 'IMAGE | Sep 18 · Sentinel-2 · 30 m · preview');+ assert.equal(f.byId('ri-slot-a').dataset.state, 'preview');+ assert.equal(rowText(f, 'b'), 'VS | Basemap');+ assert.equal(f.byId('ri-slot-b').classList.contains('lit'), false, 'dimmed');+ const unpinA = f.byId('ri-unpin-a');+ assert.deepEqual(+ [+ unpinA.disabled,+ unpinA.classList.contains('is-reserved'),+ unpinA.textContent,+ ],+ [true, true, '×'],+ );+ f.key('s');+ assert.equal(rowText(f, 'a'), 'IMAGE | Sep 18 · Sentinel-2 · 30 m');+ assert.equal(f.byId('ri-slot-a').dataset.state, 'pinned');+ assert.equal(unpinA.disabled, false);+ assert.equal(unpinA.getAttribute('aria-label'), 'Unpin the image');+ modes[1].click();+ assert.equal(f.snap().mode, 'basemap');+ assert.equal(modes[1].getAttribute('aria-checked'), 'true');+ assert.equal(f.byId('ri-slot-b').classList.contains('lit'), true, 'lit');+ modes[2].click();+ assert.equal(rowText(f, 'a'), 'A | Sep 18 · Sentinel-2 · 30 m');+ assert.equal(rowText(f, 'b'), 'B | Not set');+ assert.equal(f.byId('ri-slot-b').dataset.state, 'empty');+ assert.equal(f.byId('ri-unpin-b').classList.contains('is-reserved'), true);+ f.chip(L16, 'b').click();+ assert.equal(rowText(f, 'b'), 'B | Sep 16 · Landsat 8/9 · 30 m');+ f.byId('ri-unpin-b').click();+ assert.equal(f.snap().pins.b.key, null);+ unpinA.click();+ assert.equal(f.snap().pins.a.key, null);+ assert.equal(f.renderer.ownedCount(), 0, 'unpinning drops the layer');+ // Mode keys move the radio selection.+ f.byId('ri-mode').dispatch('keydown', { key: 'ArrowRight' });+ assert.equal(f.snap().mode, 'image');+});++test('strip keys: arrows preview after the debounce, S / A / B pin, Enter previews, repeats are ignored', async () => {+ const f = fixture();+ await f.ready();+ f.key('ArrowRight');+ assert.equal(f.snap().focus.key, L16);+ f.timers.flush();+ assert.equal(f.snap().preview.key, L16);+ f.key('Home');+ assert.equal(f.snap().focus.key, V21);+ f.key('End');+ assert.equal(f.snap().focus.index, 3);+ f.key('ArrowLeft');+ f.timers.flush();+ f.key('a', { repeat: true });+ assert.equal(f.snap().pins.a.key, null, 'key repeat never pins');+ f.key('b');+ assert.equal(f.snap().pins.b.key, null, 'no B outside A / B');+ f.key('A');+ assert.equal(f.snap().pins.a.key, L16);+ f.key('a');+ assert.equal(f.snap().pins.a.key, null, 'A again unpins');+ f.layer.setMode('ab');+ f.key('a');+ f.key('ArrowLeft');+ f.key('b');+ assert.deepEqual([f.snap().pins.a.key, f.snap().pins.b.key], [L16, S18]);+ f.key('a', { metaKey: true });+ assert.equal(f.snap().pins.a.key, L16, 'modified keys are not ours');+ f.layer.setAssignment('a', null);+ f.layer.setAssignment('b', null);+ f.key('Enter');+ assert.equal(f.snap().preview.key, S18, 'Enter previews the focused day');+});++test('clicks: a card previews and focuses the strip, a chip pins, SELECT BOX toggles the tool, USE VIEW and CLEAR drive the layer', async () => {+ const f = fixture();+ await f.ready();+ f.card(L16).click();+ assert.equal(f.snap().preview.key, L16);+ assert.equal(f.strip.focused, 1);+ assert.deepEqual(f.strip.focusOptions, { preventScroll: true });+ f.chip(S18, 'a').click();+ assert.equal(f.snap().pins.a.key, S18);+ const selectBox = f.byAction('select-box');+ selectBox.click();+ assert.deepEqual(f.tool.calls, ['start']);+ assert.equal(selectBox.getAttribute('aria-pressed'), 'true');+ selectBox.click();+ assert.deepEqual(f.tool.calls, ['start', 'cancel:toggle']);+ assert.equal(selectBox.getAttribute('aria-pressed'), 'false');+ f.byAction('use-view').click();+ assert.equal(+ f.snap().boxError,+ 'Point the camera at the ground to use the view',+ );+ assert.equal(f.byAction('clear').disabled, false);+ f.byAction('clear').click();+ assert.equal(f.snap().box, null);+ assert.equal(f.byAction('clear').disabled, true);+});++test('Escape clears the preview first, then cancels the box tool, then blurs the strip', async () => {+ const f = fixture();+ await f.ready();+ f.tool.start();+ f.key('Escape');+ assert.equal(f.snap().preview.key, null);+ assert.equal(f.tool.isActive(), true);+ f.key('Escape');+ assert.equal(f.tool.isActive(), false);+ f.key('Escape');+ assert.equal(f.strip.blurred, 1);+ // From elsewhere in the panel Escape only acts when there is something to undo.+ f.card(L16).click();+ const escape = f.byId('ri-opacity').dispatch('keydown', { key: 'Escape' });+ assert.equal(escape.defaultPrevented, true);+ assert.equal(f.snap().preview.key, null);+ const idle = f.byId('ri-opacity').dispatch('keydown', { key: 'Escape' });+ assert.equal(idle.defaultPrevented, false);+});++test('the notice line shows the refusal, then errors, then CLEAR, then the Esri note; the hint names the next step and that SWAP trades the sides', async () => {+ const controller = fakeController();+ let active = 'photoreal';+ controller.getActiveId = () => active;+ const f = fixture({ controller });+ const notice = f.byId('ri-notice');+ const noticeText = f.byId('ri-notice-text');+ const hint = f.byId('ri-hint');+ f.layer.enable();+ assert.equal(noticeText.textContent, '');+ assert.equal(hint.textContent, 'Select a box or use the view');+ f.layer.setBox(BOX);+ assert.equal(hint.textContent, 'Searching the last 30 days');+ f.catalog.resolveLast();+ await settle();+ assert.equal(hint.textContent, '← → preview · S shows the focused day');+ active = 'esri-imagery';+ controller.lease.settle({ status: 'ready', activeId: active });+ await settle();+ assert.equal(+ noticeText.textContent,+ 'Imagery on Esri · Google 3D returns when cleared',+ );+ assert.equal(notice.classList.contains('info'), true);+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });+ assert.equal(noticeText.textContent, 'Box is 2,226 km wide · limit 1,000 km');+ assert.equal(notice.classList.contains('warn'), true);+ assert.equal(hint.textContent, 'Zoom in or draw a smaller box');+ f.layer.setBox(BOX);+ f.chip(S18, 'a').click();+ assert.equal(hint.textContent, 'S on another day replaces it · × unpins');+ f.layer.setMode('basemap');+ assert.equal(hint.textContent, 'Drag the divider · SWAP trades sides');+ f.layer.setMode('ab');+ assert.equal(hint.textContent, '← → preview the other side · A or B pins it');+ f.chip(L16, 'b').click();+ assert.equal(hint.textContent, 'Drag the divider · SWAP trades sides');+ f.layer.setAssignment('b', null);+ f.layer.setAssignment('a', null);+ assert.equal(hint.textContent, '← → preview · A or B pins the focused day');+ f.byAction('clear').click();+ assert.equal(noticeText.textContent, 'Box and images cleared');+ assert.equal(notice.classList.contains('info'), true);+});++test('an oversized box offers ZOOM IN in a fixed slot at the end of the notice line; it asks the layer to fit', async () => {+ const f = fixture();+ const flights = [];+ f.viewer.scene.canvas.clientHeight = 500;+ f.viewer.scene.ellipsoid = {+ cartographicToCartesian: (c) => ({ ...c }),+ };+ Object.assign(f.viewer.camera, {+ frustum: { fovy: 2 * Math.atan(Math.tan(Math.PI / 6) / 2) },+ flyTo: (options) => flights.push(options),+ });+ const notice = f.byId('ri-notice');+ const zoom = f.byId('ri-zoom-in');+ assert.equal(zoom.tagName, 'BUTTON');+ assert.equal(zoom.textContent, 'ZOOM IN');+ assert.equal(notice.children.at(-1), zoom, 'the right end of the line');+ const reserved = () => [+ zoom.classList.contains('is-reserved'),+ zoom.disabled,+ zoom.getAttribute('aria-hidden'),+ notice.classList.contains('has-action'),+ ];+ await f.ready();+ assert.deepEqual(reserved(), [true, true, 'true', false]);+ zoom.click();+ assert.equal(flights.length, 0);+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });+ assert.deepEqual(reserved(), [false, false, 'false', true]);+ assert.equal(+ f.byId('ri-notice-text').textContent,+ 'Box is 2,226 km wide · limit 1,000 km',+ );+ assert.equal(f.byId('ri-hint').textContent, 'Zoom in or draw a smaller box');+ assert.equal(zoom.title, 'Fly in until the view fits the 1,000 km limit');+ zoom.click();+ assert.equal(flights.length, 1);+ assert.ok(+ Math.abs(+ flights[0].destination.height - 400_000 / (2 * Math.tan(Math.PI / 6)),+ ) < 1e-6,+ );+ // Another refusal has nothing to fit; a box that succeeds hides it again.+ f.layer.reportBoxRefusal('Select one side of the dateline');+ assert.deepEqual(reserved(), [true, true, 'true', false]);+ f.layer.setBox({ west: 0, south: 0, east: 20, north: 20 });+ f.layer.setBox(BOX);+ assert.deepEqual(reserved(), [true, true, 'true', false]);+});++test('the divider exists only while a swipe is live, labelled A / B or IMAGE / BASEMAP; SWAP trades its sides and Space does nothing', async () => {+ const f = fixture();+ const swap = f.byId('ri-swap');+ const swapState = () => [+ swap.disabled,+ swap.classList.contains('is-reserved'),+ swap.getAttribute('aria-hidden'),+ swap.getAttribute('aria-pressed'),+ ];+ const labels = () => {+ const { beforeLabel, afterLabel } = f.splits.at(-1).options;+ return [beforeLabel, afterLabel];+ };+ const directions = () => {+ const owned = f.renderer.getOwned();+ return [owned.a?.splitDirection, owned.b?.splitDirection];+ };+ assert.equal(swap.tagName, 'BUTTON');+ assert.equal(swap.textContent, 'SWAP');+ assert.equal(swap.parentNode, f.byId('ri-controls'));+ await f.ready();+ await f.settleLease();+ assert.equal(f.splits.length, 0, 'one image, no divider');+ assert.deepEqual(swapState(), [true, true, 'true', 'false']);+ swap.click();+ assert.equal(f.snap().swapped, false, 'no swipe, nothing to swap');+ f.layer.setMode('basemap');+ assert.equal(f.splits.length, 1);+ assert.deepEqual(labels(), ['IMAGE', 'BASEMAP']);+ assert.equal(f.splits[0].options.id, 'recent-imagery-split-line');+ assert.deepEqual(swapState(), [false, false, 'false', 'false']);+ assert.deepEqual(directions(), ['left', undefined]);+ // VS BASEMAP: SWAP puts the image right of the basemap, and back.+ swap.click();+ assert.equal(f.snap().swapped, true);+ assert.deepEqual(labels(), ['BASEMAP', 'IMAGE']);+ assert.deepEqual(directions(), ['right', undefined]);+ assert.deepEqual(swapState(), [false, false, 'false', 'true']);+ swap.click();+ assert.deepEqual(labels(), ['IMAGE', 'BASEMAP']);+ assert.deepEqual(directions(), ['left', undefined]);+ f.layer.setMode('ab');+ f.layer.setAssignment('a', S18);+ f.layer.setAssignment('b', L16);+ assert.equal(f.splits[0].destroyed, true);+ const split = f.splits.at(-1);+ assert.deepEqual(+ [split.options.beforeLabel, split.options.afterLabel],+ ['A', 'B'],+ );+ assert.equal(split.options.afterTitle, 'Landsat 8/9 · 30 m · 2026-09-16');+ split.options.onChange(0.3);+ assert.equal(f.snap().split, 0.3);+ assert.deepEqual(directions(), ['left', 'right']);+ // Space is push-to-talk: the panel never takes it.+ for (const target of [f.strip, f.byId('ri-opacity'), f.root]) {+ const space = target.dispatch('keydown', { key: ' ' });+ assert.equal(space.defaultPrevented, false);+ }+ assert.equal(f.splits.at(-1), split, 'the divider is untouched');+ assert.equal(f.snap().swapped, false);+ // SWAP: A moves right and B left, the labels follow; the divider stays.+ swap.click();+ assert.equal(split.destroyed, true);+ assert.deepEqual(labels(), ['B', 'A']);+ assert.equal(+ f.splits.at(-1).options.beforeTitle,+ 'Landsat 8/9 · 30 m · 2026-09-16',+ );+ assert.equal(f.splits.at(-1).options.initialValue, 0.3);+ assert.deepEqual(directions(), ['right', 'left']);+ assert.equal(swap.getAttribute('aria-pressed'), 'true');+ assert.equal(f.layer.getParams().swapped, undefined, 'not in the link');+ // Again restores.+ swap.click();+ assert.deepEqual(labels(), ['A', 'B']);+ assert.deepEqual(directions(), ['left', 'right']);+ assert.equal(swap.getAttribute('aria-pressed'), 'false');+ // Unpinning B ends the swipe and SWAP goes back to its reserved slot.+ f.byId('ri-unpin-b').click();+ assert.equal(f.splits.at(-1).destroyed, true);+ assert.deepEqual(swapState(), [true, true, 'true', 'false']);+});++test('opacity drives both images; EXPORT downloads the pin or the preview and EXPORT B only exists in A / B', async () => {+ const f = fixture();+ await f.ready();+ const exportA = f.byAction('export-a');+ const exportB = f.byAction('export-b');+ assert.deepEqual(+ [+ exportA.textContent,+ exportA.disabled,+ exportB.classList.contains('is-reserved'),+ exportB.disabled,+ ],+ ['EXPORT', false, true, true],+ );+ f.byId('ri-opacity').value = '40';+ f.byId('ri-opacity').dispatch('input');+ assert.equal(f.snap().alpha, 0.4);+ assert.equal(+ f.part(f.byId('ri-controls'), 'ri-opacity-value').textContent,+ '40%',+ );+ assert.equal(await f.readout.exportImage('a'), true);+ assert.match(f.fetches[0], /LAYERS=HLS_S30_Nadir_BRDF_Adjusted_Reflectance/);+ assert.match(f.fetches[0], /WIDTH=1024/);+ assert.deepEqual(f.urls, {+ created: ['blob:export'],+ revoked: ['blob:export'],+ });+ assert.equal(await f.readout.exportImage('b'), false, 'no B outside A / B');+ // A wide box exports wide: the longer side at the limit, degrees kept.+ f.layer.setBox({ ...BOX, east: -97.6 });+ f.catalog.resolveLast();+ await settle();+ assert.equal(await f.readout.exportImage('a'), true);+ assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/);+ f.layer.setMode('ab');+ assert.deepEqual(+ [+ exportA.textContent,+ exportB.textContent,+ exportB.classList.contains('is-reserved'),+ ],+ ['EXPORT A', 'EXPORT B', false],+ );+ const failing = fixture({+ fetchImpl: async () => response({ ok: false, status: 503 }),+ });+ await failing.ready();+ assert.equal(await failing.readout.exportImage('a'), false);+ assert.equal(+ failing.byId('ri-notice-text').textContent,+ 'Export failed · HTTP 503',+ );+});++test('DETAILS is a collapsed rail card holding every note, and the empty-days toggle', async () => {+ const f = fixture();+ await f.ready();+ const header = f+ .byId('ri-details')+ .find((node) => node.classList.contains('rail-card-header'));+ const article = header.parentNode;+ assert.equal(article.dataset.open, 'false');+ assert.equal(header.getAttribute('aria-expanded'), 'false');+ header.click();+ assert.equal(article.dataset.open, 'true');+ const text = f.byId('ri-details').textContent;+ assert.match(text, /Box \d+\.\d × \d+\.\d km/);+ assert.match(text, /Sep 18, 2026 17:12Z/);+ assert.match(text, /Acquired 17:12Z–17:14Z · Coverage full/);+ assert.match(text, /S30-2026-09-18 · 17:12Z · 12% cloud/);+ assert.match(text, /START HERE · newest clear day/);+ assert.match(+ text,+ /Daily overview for today may still be empty until the pass/,+ );+ assert.match(text, /Daily overview shows little detail in a box this small/);+ assert.match(text, /NASA GIBS/);+ const toggle = f.byAction('toggle-empty');+ assert.equal(toggle.disabled, true, 'nothing hidden yet');+ f.thumbnails.probe(L16, 'empty');+ assert.equal(toggle.textContent, 'SHOW EMPTY DAYS · 1');+ toggle.click();+ assert.equal(f.snap().showUnavailable, true);+ assert.equal(toggle.textContent, 'HIDE EMPTY DAYS');+ header.click();+ assert.equal(article.dataset.open, 'false');+});++test('the body scroll position survives renders even when DOM mutations reset it', async () => {+ const f = fixture();+ await f.ready();+ f.body.scrollTop = 120;+ const insert = f.strip.insertBefore.bind(f.strip);+ f.strip.insertBefore = (...args) => {+ f.body.scrollTop = 0;+ return insert(...args);+ };+ f.thumbnails.probe(L16, 'empty');+ f.layer.setShowUnavailable(true);+ assert.equal(f.body.scrollTop, 120);+});++test('destroy returns every listener, the divider and the panel state', async () => {+ const f = fixture();+ await f.ready();+ await f.settleLease();+ f.layer.setMode('basemap');+ const split = f.splits.at(-1);+ f.readout.destroy();+ assert.equal(split.destroyed, true);+ assert.equal(f.root.listenerCount(), 0);+ assert.equal(f.strip.listenerCount(), 0);+ assert.equal(f.root.parentNode, null);+ assert.equal(f.document.getElementById('recent-imagery-panel').hidden, true);+ f.layer.setMode('ab');+ assert.equal(f.splits.length, 1, 'no renders after destroy');+ f.readout.destroy();+});diff --git a/src/ui/styles/layers.css b/src/ui/styles/layers.cssindex 518aeef98..2f53ae33d 100644--- a/src/ui/styles/layers.css+++ b/src/ui/styles/layers.css@@ -163,6 +163,7 @@#right-context-rail > #pp-toggles,#right-context-rail > #cctv-panel,#right-context-rail > #weather-panel,+#right-context-rail > #recent-imagery-panel,#right-context-rail > #global-context-panel {position: relative;inset: auto;@@ -175,19 +176,23 @@pointer-events: auto;}#right-context-rail #cctv-panel,-#right-context-rail #weather-panel {+#right-context-rail #weather-panel,+#right-context-rail #recent-imagery-panel {width: 100%;max-height: 100%;pointer-events: auto;}-#right-context-rail > #weather-panel {+#right-context-rail > #weather-panel,+/* Collapsed, it must stay hideable by the rail's exclusive layout. */+#right-context-rail > #recent-imagery-panel:not(.collapsed) {display: flex;flex-direction: column;flex-shrink: 1;min-height: 0;}#right-context-rail #cctv-panel.collapsed,-#right-context-rail #weather-panel.collapsed {+#right-context-rail #weather-panel.collapsed,+#right-context-rail #recent-imagery-panel.collapsed {width: var(--right-display-collapsed-width);margin-left: auto;}@@ -201,6 +206,7 @@#right-context-rail > #pp-toggles.collapsed .pp-header-row,#right-context-rail #cctv-panel.collapsed .cctv-panel-inner,#right-context-rail #weather-panel.collapsed .weather-panel-inner,+#right-context-rail #recent-imagery-panel.collapsed .recent-imagery-panel-inner,#right-context-rail#global-context-panel.collapsed.global-context-panel-inner {@@ -257,6 +263,7 @@#right-context-rail.layout-focus > #pp-toggles:not(.collapsed),#right-context-rail.layout-focus > #cctv-panel:not(.collapsed),#right-context-rail.layout-focus > #weather-panel:not(.collapsed),+#right-context-rail.layout-focus > #recent-imagery-panel:not(.collapsed),#right-context-rail.layout-focus > #global-context-panel:not(.collapsed) {flex: 0 1 var(--right-panel-allocated-height);height: var(--right-panel-allocated-height);@@ -275,6 +282,9 @@#right-context-rail.layout-focus> #cctv-panel:not(.collapsed).cctv-panel-inner,+#right-context-rail.layout-focus+ > #recent-imagery-panel:not(.collapsed)+ .recent-imagery-panel-inner,#right-context-rail.layout-focus> #global-context-panel:not(.collapsed).global-context-panel-inner {@@ -321,6 +331,9 @@#right-context-rail[data-rail-measuring]> [data-panel-id]:not(.collapsed)> .weather-panel-inner,+#right-context-rail[data-rail-measuring]+ > [data-panel-id]:not(.collapsed)+ > .recent-imagery-panel-inner,#right-context-rail[data-rail-measuring]> [data-panel-id]:not(.collapsed)> .global-context-panel-inner {@@ -1364,7 +1377,8 @@ body.recording-mode #right-context-rail > [data-panel-id] {pointer-events: none !important;}@media (max-width: 720px) {- #right-context-rail #weather-panel.collapsed {+ #right-context-rail #weather-panel.collapsed,+ #right-context-rail #recent-imagery-panel.collapsed {width: 100%;}}diff --git a/src/ui/styles/recent-imagery.css b/src/ui/styles/recent-imagery.cssnew file mode 100644index 000000000..f1e2e20e5--- /dev/null+++ b/src/ui/styles/recent-imagery.css@@ -0,0 +1,483 @@+/* Recent Imagery: a right-rail readout laid out by the rail like WEATHER; only+ the body scrolls. Every block has a fixed height, so no click moves a+ control. Card typography comes from the rail-card rules in weather.css. */+.recent-imagery-panel-inner {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 8px;+ min-height: 0;+ max-height: 100%;+ box-sizing: border-box;+ padding: 14px;+ border: 1px solid var(--glass-border);+ border-radius: var(--panel-radius);+ background: var(--glass-bg);+ backdrop-filter: blur(24px) saturate(1.4);+ -webkit-backdrop-filter: blur(24px) saturate(1.4);+ box-shadow:+ 0 8px 32px rgba(0, 0, 0, 0.5),+ 0 0 0 1px rgba(255, 255, 255, 0.03) inset,+ 0 1px 0 rgba(255, 255, 255, 0.06) inset;+}+#recent-imagery-panel .panel-glow {+ position: absolute;+ inset: -18px;+ background: radial-gradient(+ ellipse at center,+ rgba(0, 212, 255, 0.16) 0%,+ transparent 65%+ );+ filter: blur(16px);+ opacity: 0.25;+ pointer-events: none;+}+#recent-imagery-panel .panel-header {+ flex: 0 0 auto;+}+#recent-imagery-panel-count {+ color: var(--text-secondary);+ font: 9px var(--font-mono);+ letter-spacing: 1px;+ white-space: nowrap;+}+#recent-imagery-panel-body {+ min-height: 0;+ max-height: calc(var(--right-stack-max-height, 50svh) - 64px);+ overflow-y: auto;+ overscroll-behavior: contain;+ scrollbar-width: thin;+ scrollbar-color: rgba(0, 212, 255, 0.46) transparent;+}+#recent-imagery-panel.collapsed #recent-imagery-panel-body,+#recent-imagery-panel.collapsed #recent-imagery-panel-count,+#recent-imagery-panel[hidden],+#recent-imagery-panel [hidden],+#recent-imagery-split-line[hidden] {+ display: none !important;+}+#recent-imagery-panel.collapsed .panel-title {+ font-size: 8px;+ letter-spacing: 1.8px;+}+#recent-imagery-panel.collapsed .panel-header {+ margin-bottom: 2px;+}+#recent-imagery-panel.collapsed .recent-imagery-panel-inner {+ padding-bottom: 10px;+}++/* ---- the fixed stack ---------------------------------------------------- */+.recent-imagery-readout {+ --weather-card-border: rgba(98, 181, 255, 0.28);+ display: flex;+ flex-direction: column;+ gap: 6px;+ min-width: 0;+ color: var(--text-dim);+ font: 9px/1.45 var(--font-mono);+ letter-spacing: 0.5px;+}+.recent-imagery-readout .ri-block {+ flex: 0 0 auto;+ min-width: 0;+ box-sizing: border-box;+}+/* Reserved controls keep their box; they are only invisible. */+.recent-imagery-readout .is-reserved {+ visibility: hidden;+ pointer-events: none;+}+.recent-imagery-readout .data-toggle-chip {+ box-sizing: border-box;+ min-width: 0;+ height: 22px;+ padding: 0 4px;+ overflow: hidden;+ text-align: center;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.recent-imagery-readout .data-toggle-chip:disabled {+ cursor: default;+ opacity: 0.4;+}++/* 1. SELECT BOX · USE VIEW · CLEAR, three equal cells. */+.recent-imagery-readout .ri-actions-row {+ height: 22px;+}+.recent-imagery-readout .ri-actions-row .rail-card-actions {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 6px;+ margin: 0;+}+.recent-imagery-readout .ri-actions-row .data-toggle-chip {+ height: 22px;+}++/* 2 and 3b. One-line notice and hint: always there, empty or not. */+.recent-imagery-readout .ri-line {+ height: 14px;+ line-height: 14px;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}+/* The notice text yields room to ZOOM IN only while it shows; the chip sits+ in a fixed slot at the line's right end either way. The ellipsis is a+ safety net: every notice is written to fit the panel. */+.recent-imagery-readout .ri-notice {+ position: relative;+}+.recent-imagery-readout .ri-notice-text {+ display: block;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}+.recent-imagery-readout .ri-notice.has-action .ri-notice-text {+ padding-right: 52px;+}+.recent-imagery-readout .ri-zoom-in {+ position: absolute;+ top: 0;+ right: 0;+ width: 46px;+ height: 14px;+ padding: 0 3px;+ font-size: 8px;+ line-height: 12px;+ letter-spacing: 0.4px;+ color: var(--accent);+ border-color: var(--accent);+}+.recent-imagery-readout .ri-notice.warn {+ color: rgba(255, 196, 120, 0.95);+}+.recent-imagery-readout .ri-notice.info {+ color: var(--accent);+}+.recent-imagery-readout .ri-hint {+ color: var(--text-secondary);+}++/* 3. The strip: fixed height, newest day first. */+.recent-imagery-readout .ri-strip {+ display: flex;+ gap: 6px;+ height: 120px;+ padding: 2px 2px 6px;+ overflow-x: auto;+ overflow-y: hidden;+ scroll-snap-type: x proximity;+ scrollbar-width: thin;+ outline: none;+ border-radius: 6px;+}+.recent-imagery-readout .ri-strip:focus-visible {+ box-shadow: 0 0 0 1px var(--accent);+}+.recent-imagery-readout .ri-strip.searching {+ opacity: 0.7;+}+.recent-imagery-readout .ri-strip-empty {+ flex: 1 0 100%;+ align-self: center;+ text-align: center;+ letter-spacing: 1px;+ text-transform: uppercase;+}+.recent-imagery-readout .ri-card {+ position: relative;+ flex: 0 0 94px;+ height: 112px;+ box-sizing: border-box;+ display: grid;+ grid-template-rows: 42px 13px 11px 11px 18px;+ row-gap: 2px;+ padding: 3px 2px;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.03);+ color: var(--text-secondary);+ cursor: pointer;+ scroll-snap-align: start;+ transition:+ border-color var(--transition-fast),+ background-color var(--transition-fast);+}+.recent-imagery-readout .ri-card:hover {+ border-color: var(--glass-border-hover);+}+.recent-imagery-readout .ri-card.focused {+ border-color: var(--accent);+ background: var(--accent-dim);+}+.recent-imagery-readout .ri-card.preview {+ box-shadow: inset 0 0 0 1px rgba(139, 233, 255, 0.35);+}+.recent-imagery-readout .ri-card.pinned {+ box-shadow: inset 0 0 0 1px rgba(139, 233, 255, 0.75);+}+.recent-imagery-readout .ri-thumb {+ position: relative;+ display: grid;+ place-items: center;+ overflow: hidden;+ border-radius: 4px;+ background: rgba(120, 130, 140, 0.18);+}+.recent-imagery-readout .ri-thumb[data-status='empty'] {+ background: rgba(90, 96, 104, 0.22);+}+.recent-imagery-readout .ri-thumb-img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ display: block;+}+.recent-imagery-readout .ri-thumb-text {+ padding: 0 4px;+ text-align: center;+ font-size: 8px;+}+.recent-imagery-readout .ri-card-flag,+.recent-imagery-readout .ri-card-start {+ position: absolute;+ padding: 0 4px;+ border-radius: 3px;+ background: rgba(4, 17, 27, 0.9);+ font-size: 7px;+ font-weight: 700;+ line-height: 12px;+ letter-spacing: 0.8px;+ white-space: nowrap;+}+.recent-imagery-readout .ri-card-flag {+ top: 3px;+ left: 3px;+ color: var(--accent);+}+.recent-imagery-readout .ri-card-start {+ right: 3px;+ bottom: 3px;+ color: rgba(255, 196, 120, 0.95);+}+.recent-imagery-readout .ri-card-date,+.recent-imagery-readout .ri-card-sensor,+.recent-imagery-readout .ri-card-cloud {+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}+.recent-imagery-readout .ri-card-date {+ font-size: 10px;+ line-height: 13px;+ color: var(--text-primary);+}+.recent-imagery-readout .ri-card-sensor,+.recent-imagery-readout .ri-card-cloud {+ font-size: 8px;+ line-height: 11px;+ letter-spacing: 0;+ color: var(--text-dim);+}+.recent-imagery-readout .ri-card-chips {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 4px;+}+.recent-imagery-readout .ri-card-chips .data-toggle-chip {+ height: 18px;+ font-weight: 700;+}++/* 4. The selection bar: mode, then two rows that are always there. */+.recent-imagery-readout .ri-selection {+ display: grid;+ grid-template-rows: 20px 20px 20px;+ row-gap: 4px;+ padding: 5px;+ border: 1px solid var(--weather-card-border);+ border-radius: 6px;+}+.recent-imagery-readout .ri-mode {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 4px;+}+.recent-imagery-readout .ri-selection .data-toggle-chip {+ height: 20px;+}+.recent-imagery-readout .ri-slot {+ display: grid;+ grid-template-columns: 44px minmax(0, 1fr) 22px;+ align-items: center;+ column-gap: 6px;+ height: 20px;+}+.recent-imagery-readout .ri-slot-tag {+ height: 16px;+ line-height: 16px;+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 3px;+ text-align: center;+ font-size: 8px;+ font-weight: 700;+ letter-spacing: 1px;+ white-space: nowrap;+}+.recent-imagery-readout .ri-slot.lit .ri-slot-tag {+ border-color: var(--accent);+ color: var(--accent);+}+.recent-imagery-readout .ri-slot-value {+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ letter-spacing: 0;+ color: var(--text-dim);+}+.recent-imagery-readout .ri-slot.lit .ri-slot-value {+ color: var(--text-primary);+}+.recent-imagery-readout .ri-slot[data-state='preview'] .ri-slot-value {+ color: var(--text-secondary);+ font-style: italic;+}+.recent-imagery-readout .ri-unpin {+ width: 22px;+ padding: 0;+ font-size: 12px;+ letter-spacing: 0;+}++/* 5. Opacity (both images), SWAP and export, one row. SWAP keeps its slot+ while no swipe is live. */+.recent-imagery-readout .ri-controls {+ display: grid;+ grid-template-columns: 76px minmax(0, 1fr) 40px 128px;+ align-items: center;+ column-gap: 6px;+ height: 22px;+}+.recent-imagery-readout .ri-opacity-label {+ display: flex;+ justify-content: space-between;+ gap: 4px;+ font-size: 8px;+ letter-spacing: 1px;+ white-space: nowrap;+}+.recent-imagery-readout .ri-opacity-value {+ font-variant-numeric: tabular-nums;+ color: var(--text-secondary);+}+.recent-imagery-readout .ri-opacity {+ width: 100%;+ min-width: 0;+ margin: 0;+ accent-color: var(--accent);+}+.recent-imagery-readout .ri-opacity:disabled {+ opacity: 0.35;+}+.recent-imagery-readout .ri-swap {+ width: 40px;+ padding: 0 2px;+}+.recent-imagery-readout .ri-exports .rail-card-actions {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 4px;+ margin: 0;+}++/* 6. DETAILS: a collapsed rail card at the bottom, for every note. */+.recent-imagery-readout .ri-details .rail-card {+ border-color: var(--weather-card-border);+}+.recent-imagery-readout .ri-details .rail-card-title {+ font-family: var(--font-mono);+ font-size: 9px;+ letter-spacing: 1.2px;+ text-transform: uppercase;+}+.recent-imagery-readout .ri-details .rail-card-line.muted {+ color: var(--text-dim);+}+.recent-imagery-readout .ri-details .rail-card-actions .data-toggle-chip {+ height: 20px;+ padding: 0 7px;+}++/* ---- box tool cursor ---------------------------------------------------- */+body.gev-imagery-box #cesium-container canvas,+body.gev-imagery-box .cesium-widget canvas {+ cursor: crosshair;+}++/* ---- split line --------------------------------------------------------- */+/* Above the right rail (z-index 110) so the handle can always be grabbed. */+#recent-imagery-split-line {+ position: fixed;+ top: 0;+ bottom: 0;+ left: var(--recent-imagery-split, 50%);+ z-index: 130;+ width: 1px;+ pointer-events: none;+ background: rgba(218, 241, 247, 0.76);+ box-shadow: 0 0 12px rgba(94, 216, 239, 0.72);+}+#recent-imagery-split-line span {+ position: absolute;+ top: 14px;+ padding: 2px 6px;+ border-radius: 3px;+ background: rgba(4, 17, 27, 0.82);+ color: rgba(239, 247, 249, 0.92);+ font: 700 9px/1.4 var(--font-mono);+ letter-spacing: 1.2px;+ white-space: nowrap;+ pointer-events: none;+}+#recent-imagery-split-line span.before {+ right: 8px;+}+#recent-imagery-split-line span.after {+ left: 8px;+}+#recent-imagery-split-line .recent-imagery-split-handle {+ position: absolute;+ top: 50%;+ left: 50%;+ width: 36px;+ height: 36px;+ padding: 0;+ border: 1px solid rgba(180, 215, 222, 0.72);+ border-radius: 50%;+ outline: 0;+ color: rgba(239, 247, 249, 0.96);+ background: rgba(4, 17, 27, 0.96);+ box-shadow:+ 0 0 0 5px rgba(62, 112, 125, 0.3),+ 0 0 13px rgba(94, 216, 239, 0.3);+ font: 700 14px/1 var(--font-mono);+ transform: translate(-50%, -50%);+ pointer-events: auto;+ touch-action: none;+ cursor: ew-resize;+}+#recent-imagery-split-line .recent-imagery-split-handle:focus-visible {+ outline: 2px solid #fff;+ outline-offset: 4px;+}++@media (max-width: 720px) {+ #recent-imagery-panel-body {+ max-height: 48vh;+ }+}diff --git a/src/ui/styles/responsive.css b/src/ui/styles/responsive.cssindex 7763d3641..16817ac10 100644--- a/src/ui/styles/responsive.css+++ b/src/ui/styles/responsive.css@@ -218,6 +218,8 @@#right-context-rail #pp-toggles.collapsed .pp-header-row,#right-context-rail #cctv-panel,#right-context-rail #cctv-panel.collapsed,+ #right-context-rail #recent-imagery-panel,+ #right-context-rail #recent-imagery-panel.collapsed,#right-context-rail #radio-panel,#right-context-rail #radio-panel.collapsed,#right-context-rail #global-context-panel,diff --git a/src/ui/templates/context.html b/src/ui/templates/context.htmlindex cf5efa848..6ce5562a6 100644--- a/src/ui/templates/context.html+++ b/src/ui/templates/context.html@@ -12,6 +12,18 @@<div id="weather-panel-body" data-rail-scroller></div></div></div>+ <div id="recent-imagery-panel" class="panel-collapsible" data-panel-id="recent-imagery-panel" hidden>+ <div class="panel-glow"></div>+ <div class="recent-imagery-panel-inner">+ <div class="panel-header">+ <span class="panel-title">RECENT IMAGERY</span>+ <span id="recent-imagery-panel-count" aria-label="Imagery days in the box"></span>+ <span class="panel-divider"></span>+ <button class="panel-collapse-btn" data-collapse-target="recent-imagery-panel" type="button" title="Collapse panel">▼</button>+ </div>+ <div id="recent-imagery-panel-body" data-rail-scroller></div>+ </div>+ </div><div id="global-context-panel" class="panel-collapsible collapsed" data-panel-id="global-context-panel"><div class="panel-glow"></div><div class="global-context-panel-inner">diff --git a/style.css b/style.cssindex 16a27042b..95cdd1d89 100644--- a/style.css+++ b/style.css@@ -10,6 +10,7 @@@import './src/ui/styles/cctv.css';@import './src/ui/styles/scenes.css';@import './src/ui/styles/bhote-koshi.css';+@import './src/ui/styles/recent-imagery.css';@import './src/ui/styles/recording.css';@import './src/ui/styles/responsive.css';@import './src/ui/styles/command-dock.css';