diff --git a/changelog.d/1540-recent-imagery-dateline.md b/changelog.d/1540-recent-imagery-dateline.md new file mode 100644 index 0000000000..227db9ca93 --- /dev/null +++ b/changelog.d/1540-recent-imagery-dateline.md @@ -0,0 +1,6 @@ +- Recent Imagery takes a box dragged across the dateline as the short box across + ±180° instead of refusing it as about 360° wide. A day counts when either side + has imagery. A side confirmed empty is not draped, and the VIIRS overview + drapes only a side confirmed to have data. Voice accepts named areas across + the dateline. EXPORT and `get_recent_imagery` refuse such a box, since + Worldview Snapshots cannot draw one (Byrd-IT, #1540). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ada8897b97..a64a03cb25 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -8890,10 +8890,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool, pins and share links already supply complete boxes. - 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. +- 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. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. 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 and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. 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. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. 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: the globe port's imagery while the globe shows, the shown photoreal tileset 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. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe. +- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `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. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), 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. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe. - **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 rail markup in the Context view (`src/ui/views/ContextView.vue`) 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`; opening DETAILS then scrolls its card into view once. - **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). diff --git a/src/layers/recentImagery/catalog.test.mjs b/src/layers/recentImagery/catalog.test.mjs index 462e262162..4866384829 100644 --- a/src/layers/recentImagery/catalog.test.mjs +++ b/src/layers/recentImagery/catalog.test.mjs @@ -239,10 +239,10 @@ test('an invalid box or clock is refused before any request', async () => { }; await assert.rejects( searchHls({ - box: { west: 179, south: 0, east: -179, north: 1 }, + box: { west: -181, south: 0, east: -179, north: 1 }, fetchImpl, }), - /dateline/, + /±180/, ); await assert.rejects( searchHls({ box: BOX, now: 'never', fetchImpl }), @@ -251,6 +251,22 @@ test('an invalid box or clock is refused before any request', async () => { assert.equal(called, false); }); +test('a dateline box goes to CMR as it is: CMR reads west > east as the short box', async () => { + const calls = []; + const result = await searchHls({ + box: { west: 179, south: 0, east: -179, north: 1 }, + days: 2, + now: '2026-09-21T00:00:00Z', + fetchImpl: async (url) => { + calls.push(url); + return response({ json: { hits: 1, items: [ummItem({})] } }); + }, + }); + assert.equal(calls.length, 2, 'one search per product'); + assert.ok(calls.every((url) => url.includes('bounding_box=179,0,-179,1'))); + assert.ok(result.candidates.some((candidate) => candidate.product === 'S30')); +}); + 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}` })); diff --git a/src/layers/recentImagery/index.js b/src/layers/recentImagery/index.js index 5fff3e29ac..ace8d8d7cb 100644 --- a/src/layers/recentImagery/index.js +++ b/src/layers/recentImagery/index.js @@ -581,6 +581,8 @@ export function createRecentImageryLayer({ for (const slotId of SLOT_IDS) { const candidate = candidateFor(shown[slotId]); if (candidate && _hostInfo.collection) { + const { availableBoxes, emptyBoxes } = + thumbnails.get(candidate.key) ?? {}; renderer.showSlot(slotId, candidate, _box, { alpha: _alpha, splitDirection: !live @@ -588,6 +590,8 @@ export function createRecentImageryLayer({ : (slotId === 'a') !== _swapped ? 'left' : 'right', + availableBoxes, + emptyBoxes, }); } else { renderer.hideSlot(slotId); @@ -897,21 +901,22 @@ export function createRecentImageryLayer({ // The new automatic day's probe may have been cancelled off-screen. requestThumbnails(); } - 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(); + // One render per probe: the key can stay the same while its halves change. + // A host found moved changes the divider, so the panel renders in full. + const moved = !followed && syncHost(); + if (!followed) syncRender(); notify('thumbnail'); - if (pruned || followed || drapesChanged) notify(); + if (pruned || followed || drapesChanged || moved) notify(); }); syncHost(); if (_box && !_candidates.length) void runSearch(); diff --git a/src/layers/recentImagery/index.test.mjs b/src/layers/recentImagery/index.test.mjs index 922783ec0d..b226bb3d73 100644 --- a/src/layers/recentImagery/index.test.mjs +++ b/src/layers/recentImagery/index.test.mjs @@ -1,6 +1,10 @@ import test from 'node:test'; import * as Cesium from 'cesium'; import assert from 'node:assert/strict'; +import { until } from '../../testSupport/kartaViewFakes.mjs'; +import { createRecentImagerySource } from './source.js'; +import { createThumbnailLoader } from './thumbnails.js'; +import { boxKey, nonCrossingBoxes } from './model.js'; import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js'; import { acquireImageryComparison } from '../../maps/imageryComparison.js'; import { MapSourceController } from '../../maps/controller.js'; @@ -14,11 +18,16 @@ import { SPLIT_PUBLISH_MS, createRecentImageryLayer, } from './index.js'; -import { createImageryBoxPreview } from './rendering.js'; +import { + createImageryBoxPreview, + createRecentImageryRenderer, +} from './rendering.js'; +import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; import { BOX, CANDIDATES, + FIJI_BOX, boxToolFakes, candidate, fakeCatalog, @@ -1564,6 +1573,424 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy assert.equal(f.snap().notice, 'Search cancelled'); }); +test('a box dragged across the dateline is searched, listed and draped as one box', async () => { + const f = fixture(); + const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 }; + f.layer.enable(); + assert.equal(f.layer.setBox(box), true); + assert.equal(f.snap().boxError, null); + assert.deepEqual(f.catalog.searches.at(-1).request.box, box); + f.catalog.resolveLast(); + await settle(); + assert.equal(f.snap().candidates.length, 4); + assert.equal(f.snap().preview.key, S18); + assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped'); + assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°'); +}); + +test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => { + const f = fixture(); + const priorGet = f.thumbnails.get; + const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 }; + const [west, east] = nonCrossingBoxes(box); + let boxes = [west]; + f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes }); + f.layer.enable(); + f.layer.setBox(box); + f.catalog.resolveLast(); + await settle(); + f.thumbnails.probeRequested(); + const slot = Object.keys(f.owned()).find((id) => f.owned()[id]); + assert.ok(slot, 'a day is already on the map'); + const key = f.owned()[slot].key; + assert.deepEqual(f.owned()[slot].availableBoxes, [west]); + boxes = [west, east]; + f.thumbnails.probe(key, 'present'); + assert.deepEqual(f.owned()[slot].availableBoxes, boxes); + f.layer.destroy(); +}); + +const sideOf = (url) => + Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0 + ? 'west' + : 'east'; +/** A snapshot response; `present: null` sends no Data-Present header. */ +const snapshotAnswer = (present, status = 200) => + new Response('img', { + status, + headers: present === null ? {} : { 'Data-Present': String(present) }, + }); + +function realLayer({ + fetchImpl, + candidates, + maxDecoded = 16, + halfDeadlineMs = 50, +}) { + const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs }); + let nextUrl = 0; + const loader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + createObjectUrl: () => `blob:${++nextUrl}`, + revokeObjectUrl: () => {}, + maxDecoded, + }); + const globe = fakeGlobePort(); + const layer = createRecentImageryLayer({ + catalog: { + searchHls: async () => ({ candidates, truncated: false, errors: [] }), + }, + renderer: createRecentImageryRenderer(), + thumbnails: loader, + host: () => ({ collection: globe.imagery, kind: 'globe' }), + globeOf: () => globe, + now: () => new Date('2026-11-13T15:00:00Z'), + }); + layer.init({ camera: {} }); + return { layer, loader, globe }; +} + +test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => { + const day = candidate('VIIRS', '2026-11-10'); + const sides = []; + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async (url) => { + const side = sideOf(url); + sides.push(side); + return snapshotAnswer(side === 'east'); + }, + }); + layer.setSources({ viirs: true }); + layer.enable(); + assert.equal(layer.setBox(FIJI_BOX), true); + // The probe asks about both halves, wider first. The layer drapes the one with data. + assert.equal( + await until(() => globe.layers.length > 0, { ticks: 2000 }), + true, + ); + assert.deepEqual(sides, ['east', 'west']); + assert.deepEqual( + globe.layers.map((layer) => layer.spec.rectangle), + [nonCrossingBoxes(FIJI_BOX)[1]], + ); + assert.equal(loader.get(day.key).status, 'present'); + const snapshot = layer.getSnapshot(); + assert.equal(snapshot.candidates[0].thumbnail.status, 'present'); + assert.equal(snapshot.candidates[0].drapable, true); + assert.equal(snapshot.auto?.key, day.key); + layer.destroy(); + assert.equal(globe.layers.length, 0); +}); + +test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => { + const day = candidate('VIIRS', '2026-11-10'); + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async () => snapshotAnswer(false), + }); + layer.setSources({ viirs: true }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }), + true, + ); + assert.equal(globe.layers.length, 0); + assert.equal( + layer.getSnapshot().candidates.some((c) => c.key === day.key), + false, + 'an empty day leaves the strip', + ); + layer.destroy(); +}); + +for (const [label, box] of [ + ['a plain box', { west: -98, south: 30, east: -97, north: 31 }], + ['a dateline box', FIJI_BOX], +]) { + test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => { + const day = candidate('S30', '2026-11-10'); + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + const { layer, loader, globe } = realLayer({ + candidates: [day], + halfDeadlineMs: 5000, + fetchImpl: async () => { + await gate; + return snapshotAnswer(true); + }, + }); + layer.enable(); + layer.setBox(box); + assert.equal( + await until(() => globe.layers.length === nonCrossingBoxes(box).length, { + ticks: 2000, + }), + true, + ); + const before = [...globe.layers]; + const added = globe.added.length; + release(); + assert.equal( + await until(() => loader.get(day.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(globe.added.length, added); + assert.deepEqual(globe.layers, before); + layer.destroy(); + }); +} + +test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => { + const day1 = candidate('VIIRS', '2026-11-10'); + const day2 = candidate('VIIRS', '2026-11-11'); + let eastCalls = 0; + let releaseDay2; + const gate = new Promise((resolve) => { + releaseDay2 = resolve; + }); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + halfDeadlineMs: 5000, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) await gate; + else if (sideOf(url) === 'east' && ++eastCalls === 2) + throw new TypeError('Failed to fetch'); + return snapshotAnswer(true); + }, + }); + layer.setSources({ hls: false, viirs: true }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).availableBoxes.length, 2); + releaseDay2(); + assert.equal( + await until(() => loader.get(day2.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).objectUrl, null); + layer.setAssignment('a', day1.key); + assert.equal( + await until(() => eastCalls === 2 && !loader.get(day1.key).loading, { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).status, 'present'); + assert.equal(loader.get(day1.key).availableBoxes.length, 2); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + globe.layers.map((layer) => layer.spec.rectangle), + [west, east], + 'a half that failed on the re-probe stays draped', + ); + layer.destroy(); +}); + +test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => { + const day1 = candidate('S30', '2026-11-10'); + const day2 = candidate('S30', '2026-11-11'); + let eastCalls = 0; + let releaseDay2; + const gate = new Promise((r) => (releaseDay2 = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + halfDeadlineMs: 5000, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) { + await gate; + return snapshotAnswer(true); + } + if (sideOf(url) === 'east') { + eastCalls += 1; + if (eastCalls === 1) return snapshotAnswer(false); + throw new TypeError('Failed to fetch'); + } + return snapshotAnswer(true); + }, + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key).status === 'present', { + ticks: 2000, + }), + true, + ); + const [west] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual(loader.get(day1.key).availableBoxes, [west]); + assert.equal(loader.get(day1.key).emptyBoxes.length, 1); + releaseDay2(); + assert.equal( + await until(() => loader.get(day2.key).status === 'present', { + ticks: 2000, + }), + true, + ); + assert.equal(loader.get(day1.key).objectUrl, null); + layer.setAssignment('a', day1.key); + assert.equal( + await until(() => eastCalls === 2 && !loader.get(day1.key).loading, { + ticks: 2000, + }), + true, + ); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day1.key); + assert.deepEqual( + { + available: entry.availableBoxes.length, + empty: entry.emptyBoxes.length, + layers: globe.layers.length, + }, + { available: 1, empty: 1, layers: 1 }, + ); + layer.destroy(); +}); + +test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => { + const day = candidate('S30', '2026-11-10'); + let release; + const gate = new Promise((r) => (release = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day], + halfDeadlineMs: 5000, + fetchImpl: async () => { + await gate; + return snapshotAnswer(null); + }, + }); + layer.enable(); + layer.setBox({ west: -98, south: 30, east: -97, north: 31 }); + assert.equal( + await until(() => globe.layers.length === 1, { ticks: 2000 }), + true, + ); + release(); + assert.equal( + await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }), + true, + ); + await until(() => false, { ticks: 50 }); + assert.equal(globe.layers.length, 1); + layer.destroy(); +}); + +for (const [label, failEast] of [ + ['answers 503', async () => snapshotAnswer(null, 503)], + [ + 'rejects', + async () => { + throw new TypeError('Failed to fetch'); + }, + ], + ['never answers', () => new Promise(() => {})], +]) { + test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => { + const day = candidate('S30', '2026-11-10'); + const { layer, loader, globe } = realLayer({ + candidates: [day], + fetchImpl: async (url) => + sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(), + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day.key)?.status === 'error', { + ticks: 2000, + }), + true, + ); + layer.setAssignment('a', day.key); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day.key); + const [west] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + { + empty: (entry.emptyBoxes ?? []).map(boxKey), + layers: globe.layers.length, + }, + { empty: [boxKey(west)], layers: 1 }, + ); + layer.destroy(); + }); +} + +test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => { + const day1 = candidate('S30', '2026-11-10'); + const day2 = candidate('S30', '2026-11-11'); + let round = 0; + let releaseDay2; + const gate = new Promise((r) => (releaseDay2 = r)); + const { layer, loader, globe } = realLayer({ + candidates: [day2, day1], + maxDecoded: 1, + halfDeadlineMs: 5000, + fetchImpl: async (url) => { + if (new URL(url).searchParams.get('TIME') === day2.day) { + await gate; + return snapshotAnswer(true); + } + if (round === 0) + return sideOf(url) === 'west' + ? snapshotAnswer(true) + : snapshotAnswer(null); + return sideOf(url) === 'west' + ? snapshotAnswer(null) + : snapshotAnswer(false); + }, + }); + layer.enable(); + layer.setBox(FIJI_BOX); + assert.equal( + await until(() => loader.get(day1.key)?.status === 'present', { + ticks: 2000, + }), + true, + ); + round = 1; + releaseDay2(); + assert.equal( + await until( + () => + loader.get(day2.key)?.status === 'present' && + loader.get(day1.key).objectUrl === null, + { ticks: 2000 }, + ), + true, + ); + layer.setAssignment('a', day1.key); + await until(() => false, { ticks: 50 }); + await until(() => !loader.get(day1.key).loading, { ticks: 2000 }); + await until(() => false, { ticks: 50 }); + const entry = loader.get(day1.key); + const [, east] = nonCrossingBoxes(FIJI_BOX); + assert.deepEqual( + { + status: entry.status, + empty: (entry.emptyBoxes ?? []).map(boxKey), + layers: globe.layers.length, + }, + { status: 'present', empty: [boxKey(east)], layers: 1 }, + ); + layer.destroy(); +}); + test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => { for (const order of [ [S18, V15], diff --git a/src/layers/recentImagery/model.js b/src/layers/recentImagery/model.js index 59f48cd847..2ef7255b32 100644 --- a/src/layers/recentImagery/model.js +++ b/src/layers/recentImagery/model.js @@ -72,13 +72,11 @@ export const PRODUCTS = Object.freeze({ const finite = (value) => typeof value === 'number' && Number.isFinite(value); const toRadians = (degrees) => (degrees * Math.PI) / 180; +/** A longitude brought back into ±180 after one step past it. */ +const wrapLon = (value) => + value > 180 ? value - 360 : value < -180 ? value + 360 : value; 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. - */ /** A box edge as a number, or null when it is missing, blank or not numeric. */ function edgeNumber(value) { if (typeof value === 'number') return Number.isFinite(value) ? value : null; @@ -87,6 +85,11 @@ function edgeNumber(value) { return Number.isFinite(number) ? number : null; } +/** + * Coerce a box to `{ west, south, east, north }` with south ≤ north. West and + * east are not swapped: west > east is the short arc across the dateline. + * Null when any edge is nonfinite. + */ function normalizeBox(box) { if (!box || typeof box !== 'object') return null; const [west, south, east, north] = [ @@ -105,8 +108,45 @@ function normalizeBox(box) { } /** - * 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. + * Degrees of longitude going east from `west` to `east`. A west > east pair + * wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and + * `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`, + * even the long way round. + * @param {number} west Degrees. + * @param {number} east Degrees. + * @returns {number} + */ +export function lonSpanDeg(west, east) { + return east >= west ? east - west : east + 360 - west; +} + +/** A comparable key for a degrees box. */ +export const boxKey = (box) => + [box.west, box.south, box.east, box.north].map(Number).join(','); + +/** + * One or two boxes with west <= east that cover the same area. A dateline + * box is split at ±180 so each side is a plain rectangle for a draped layer + * or a Worldview request. A box with a missing or nonfinite edge is []. + * So is a dateline box of zero width (west 180, east -180). + * @param {object} box Degrees box. + * @returns {Array} + */ +export function nonCrossingBoxes(box) { + const normalized = normalizeBox(box); + if (!normalized) return []; + const { west, south, east, north } = normalized; + if (!(west > east)) return [normalized]; + const parts = []; + if (west < 180) parts.push({ west, south, east: 180, north }); + if (east > -180) parts.push({ west: -180, south, east, north }); + return parts; +} + +/** + * Side lengths of a box in km: the longitude span at its mid-latitude (the + * short arc when the box crosses the dateline; a west <= east box is not + * shortened), and its latitude span. * @param {object} box Degrees box. * @returns {{ width: number, height: number }} */ @@ -116,7 +156,7 @@ export function boxSideKm(box) { const midLat = (normalized.south + normalized.north) / 2; return { width: - (normalized.east - normalized.west) * + lonSpanDeg(normalized.west, normalized.east) * KM_PER_DEG_LAT * Math.cos(toRadians(midLat)), height: (normalized.north - normalized.south) * KM_PER_DEG_LAT, @@ -126,9 +166,11 @@ export function boxSideKm(box) { const refuse = (reason, message) => ({ ok: false, reason, message }); /** - * Validate a selection box for the catalog and the tile providers. + * Validate a selection box for the catalog and the tile providers. A box + * with west > east is the short arc across the dateline and is accepted + * when that arc is under the size cap. * @param {object} box Degrees box. - * @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }} + * @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }} */ export function validateBox(box) { const normalized = normalizeBox(box); @@ -136,8 +178,6 @@ export function validateBox(box) { const { west, south, east, north } = normalized; if (Math.abs(west) > 180 || Math.abs(east) > 180) return refuse('invalid', msg('Longitudes must be within ±180°')); - if (west > east) - return refuse('dateline', msg('Select one side of the dateline')); if ( Math.abs(south) > MERCATOR_LAT_LIMIT || Math.abs(north) > MERCATOR_LAT_LIMIT @@ -146,7 +186,7 @@ export function validateBox(box) { 'polar', `Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`, ); - if (east === west || north === south) + if (lonSpanDeg(west, east) === 0 || north === south) return refuse('degenerate', msg('Box must enclose an area')); const { width, height } = boxSideKm(normalized); if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM) @@ -183,7 +223,9 @@ export function fitViewHeightM({ width, height, fovy } = {}) { } /** - * The centre of a box that does not cross the dateline, in degrees. + * The centre of a box, in degrees. A dateline box (west > east) is centred + * on the short arc, not the arithmetic mean, which would be the other side + * of the globe. * @param {object} box Degrees box. * @returns {{ lon: number, lat: number } | null} */ @@ -191,14 +233,18 @@ export function boxCentre(box) { const normalized = normalizeBox(box); if (!normalized) return null; return { - lon: (normalized.west + normalized.east) / 2, + lon: wrapLon( + normalized.west + lonSpanDeg(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. + * widens by 1/cos(lat)); null when the result would not validate. A pin whose + * box passes ±180 gets the short-arc box (west > east), the same convention + * as a dragged dateline box, with edges wrapped into ±180. * @param {number} lon Degrees. * @param {number} lat Degrees. * @param {number} [sideKm] @@ -207,16 +253,19 @@ export function boxCentre(box) { export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) { if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0) return null; + if (Math.abs(lon) > 180) 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); + // A half-width of 90° or more is not a short arc; refuse rather than wrap. + if (halfLon >= 90) return null; const clampLat = (value) => Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value)); const result = validateBox({ - west: lon - halfLon, + west: wrapLon(lon - halfLon), south: clampLat(lat - halfLat), - east: lon + halfLon, + east: wrapLon(lon + halfLon), north: clampLat(lat + halfLat), }); return result.ok ? result.box : null; @@ -449,15 +498,31 @@ export function coverageFor(candidate, box) { .filter((ring) => Array.isArray(ring) && ring.length >= 3); if (!normalized || !footprints.length) return 'unknown'; const { west, south, east, north } = normalized; + const centre = boxCentre(normalized); + // A dateline box is one continuous range starting at its west edge. A + // longitude on the east side (at or past ±180) shifts by 360. One just + // outside the west corner stays put: shifting every value below west would + // send that corner the long way round and miss a footprint that covers it. + const crossing = west > east; + const project = (lon) => + crossing && lon < west && (lon <= east || lon - east < west - lon) + ? lon + 360 + : lon; const samples = [ - [west, south], - [east, south], - [east, north], - [west, north], - [(west + east) / 2, (south + north) / 2], + [project(west), south], + [project(east), south], + [project(east), north], + [project(west), north], + [project(centre.lon), centre.lat], ]; return samples.every(([lon, lat]) => - footprints.some((ring) => pointInPolygon(lon, lat, ring)), + footprints.some((ring) => + pointInPolygon( + lon, + lat, + crossing ? ring.map(([x, y]) => [project(x), y]) : ring, + ), + ), ) ? 'full' : 'partial'; @@ -606,6 +671,10 @@ export function wvsSnapshotUrl({ const normalized = normalizeBox(box); if (!spec) throw new TypeError(`Unknown imagery product: ${product}`); if (!normalized) throw new TypeError('A finite box is required'); + // Worldview Snapshots rejects a BBOX whose west is greater than its east + // (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse. + if (normalized.west > normalized.east) + throw new TypeError('A snapshot cannot cross the dateline'); const bbox = [ normalized.south, normalized.west, diff --git a/src/layers/recentImagery/model.test.mjs b/src/layers/recentImagery/model.test.mjs index 7de9e0e7cb..f99a20ef54 100644 --- a/src/layers/recentImagery/model.test.mjs +++ b/src/layers/recentImagery/model.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import { boxFromPin, + lonSpanDeg, + nonCrossingBoxes, boxFromRectangle, boxSideKm, coverageFor, @@ -51,11 +53,20 @@ function hls(product, day, clouds, extra = {}) { return { ...groupGranulesByDay(granules)[0], ...extra }; } -test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => { +test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => { const reason = (box) => validateBox(box).reason; + const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 }); + assert.equal(dateline.ok, true); + assert.equal(dateline.box.west, 179); + assert.equal(dateline.box.east, -179); assert.equal( - reason({ west: 179, south: 0, east: -179, north: 1 }), - 'dateline', + reason({ west: 170, south: 0, east: -170, north: 1 }), + 'too-large', + 'a 20° dateline arc is still over the 1,000 km cap', + ); + assert.equal( + reason({ west: 180, south: 0, east: -180, north: 1 }), + 'degenerate', ); assert.equal( reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }), @@ -70,10 +81,6 @@ test('validateBox refuses dateline, polar, degenerate, invalid and oversized box 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, @@ -137,10 +144,14 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400 lon: 10, lat: 5, }); + assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), { + lon: 180, + lat: 1, + }); assert.equal(boxCentre(null), null); }); -test('box width is the longitude span at the mid-latitude, never the shortest arc', () => { +test('box width is the longitude span at the mid-latitude; a dateline box uses the short 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); @@ -149,6 +160,13 @@ test('box width is the longitude span at the mid-latitude, never the shortest ar 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'); + const crossing = boxSideKm({ + west: 179, + south: -0.5, + east: -179, + north: 0.5, + }); + assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width)); }); test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => { @@ -167,7 +185,12 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha 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(181, 0), null, 'longitude out of range'); + assert.equal( + boxFromPin(0, 0, 400000), + null, + 'half-width of 90 degrees or more', + ); assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box'); assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid'); }); @@ -298,6 +321,34 @@ test('coverage samples the box corners and centre against the union of footprint assert.equal(coverageFor(withRings(null), BOX), 'unknown'); }); +test('coverage of a dateline box uses the short arc, not the long way', () => { + const box = { west: 179, south: 0, east: -179, north: 1 }; + const ring = (west, east, south = -0.1, north = 1.1) => [ + [west, south], + [east, south], + [east, north], + [west, north], + ]; + const withRings = (...rings) => ({ + granules: rings.map((footprint) => granule({ footprint })), + }); + assert.equal( + coverageFor(withRings(ring(178.5, -178.5)), box), + 'full', + 'one footprint that crosses ±180', + ); + assert.equal( + coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box), + 'full', + 'a pair split exactly at ±180', + ); + assert.equal( + coverageFor(withRings(ring(179, 180)), box), + 'partial', + 'one side does not cover the other', + ); +}); + test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => { const candidates = [ hls('S30', '2026-09-20', [10, null]), @@ -429,6 +480,17 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e () => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }), TypeError, ); + assert.throws( + () => + wvsSnapshotUrl({ + product: 'S30', + day: '2026-09-18', + box: { west: 179, south: 0, east: -179, north: 1 }, + width: 64, + height: 64, + }), + /snapshot cannot cross the dateline/, + ); }); test('thumbnails load the focused card, then the visible cards outward, then the margins', () => { @@ -437,3 +499,52 @@ test('thumbnails load the focused card, then the visible cards outward, then the assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]); assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []); }); + +test('boxFromPin returns the short-arc box for a pin near the dateline', () => { + const near = (a, b) => Math.abs(a - b) < 1e-6; + const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492 + const spanOk = (box) => { + const { width, height } = boxSideKm(box); + assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`); + assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`); + assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span'); + }; + // 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side. + for (const lon of [179.9, -179.9]) { + const box = boxFromPin(lon, 0); + spanOk(box); + assert.ok(box.west < box.east, `no wrap needed at ${lon}`); + assert.ok(near((box.west + box.east) / 2, lon)); + } + // A pin on the line, or close enough that the box passes it, wraps. + for (const lon of [180, -180, 179.99, -179.99]) { + const box = boxFromPin(lon, 0); + spanOk(box); + assert.ok(box.west > box.east, `crossing at ${lon}`); + assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180'); + assert.ok( + near( + box.west, + (lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half, + ), + ); + assert.equal( + nonCrossingBoxes(box).length, + 2, + 'splits for tiling and Worldview', + ); + assert.ok( + Math.abs( + Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon), + ) < 1e-6, + ); + } + // 0 is an ordinary box. + const mid = boxFromPin(0, 0); + spanOk(mid); + assert.ok(mid.west < mid.east && near(mid.west, -half)); + // Off the equator the east-west extent widens but stays a short arc. + const high = boxFromPin(-179.99, 60); + spanOk(high); + assert.ok(high.west > high.east); +}); diff --git a/src/layers/recentImagery/rendering.js b/src/layers/recentImagery/rendering.js index 6edf44ab21..ca18900688 100644 --- a/src/layers/recentImagery/rendering.js +++ b/src/layers/recentImagery/rendering.js @@ -1,7 +1,7 @@ /** - * Draped-imagery renderer for the Recent Imagery layer: at most two GIBS - * imagery layers (slot `a`, left of a swipe; slot `b`, right) through the - * renderer's globe port, draped on whichever surface the map stack draws. + * Recent Imagery drapes two slots through the renderer's globe port, slot + * `a` left of a swipe and slot `b` right. Each slot drapes up to two GIBS + * layers, one per available part, on whichever surface the map stack draws. * Against the basemap slot `a` splits left and slot `b` stays empty. Tile * requests pass a small semaphore of our own, shared by both slots, through * each layer's admission hook; the renderer's own request limits stay @@ -15,7 +15,13 @@ import { fromDegrees } from '../../geo/ellipsoid.js'; import { markBaseTileset } from '../../render/baseTilesets.js'; import { drawOf } from '../../render/rendererOf.js'; -import { PRODUCTS, gibsTemplate } from './model.js'; +import { + PRODUCTS, + boxKey, + gibsTemplate, + lonSpanDeg, + nonCrossingBoxes, +} from './model.js'; const SLOT_IDS = ['a', 'b']; const SPLITS = new Set(['left', 'right', 'none']); @@ -29,8 +35,27 @@ function clampAlpha(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(','); +/** One comparable key for a slot's draped parts. */ +const partsKey = (parts) => parts.map(boxKey).sort().join(';'); + +/** + * The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would + * draw an empty side black, so it drapes only parts Worldview confirmed + * present, and no part of a dateline box before the probe answers. A PNG + * drapes every part not confirmed empty. + */ +function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) { + const parts = nonCrossingBoxes(box); + const keys = (list) => new Set(list.map(boxKey)); + if (PRODUCTS[candidate.product]?.format !== 'jpg') { + if (!Array.isArray(emptyBoxes)) return parts; + const empty = keys(emptyBoxes); + return parts.filter((part) => !empty.has(boxKey(part))); + } + if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts; + const proven = keys(availableBoxes); + return parts.filter((part) => proven.has(boxKey(part))); +} /** * Admit a tile request while the semaphore has room. A request that finds @@ -77,7 +102,7 @@ export function createRecentImageryRenderer({ let host = NO_HOST; let destroyed = false; const admission = { limit: maxTileRequests, inFlight: 0 }; - /** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */ + /** @type {Record<'a'|'b', null | { layers: Array, globe: object, candidate: object, parts: Array, alpha: number, split: string }>} */ const owned = { a: null, b: null }; const admit = admitTileRequests(admission, requestRender); @@ -105,36 +130,53 @@ export function createRecentImageryRenderer({ const record = owned[slotId]; if (!record) return false; owned[slotId] = null; - record.layer.remove(); + for (const layer of record.layers) layer.remove(); return true; } function applyLook(record) { - record.layer.alpha = record.alpha; - record.layer.split = SPLITS.has(record.split) ? record.split : 'none'; + for (const layer of record.layers) { + layer.alpha = record.alpha; + layer.split = SPLITS.has(record.split) ? record.split : 'none'; + } } - function mount(slotId, { candidate, box, alpha, split }) { - const layer = host.globe.imagery.add(specFor(candidate, box)); - owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split }; + function mount(slotId, { candidate, parts, alpha, split }) { + if (!parts.length) return false; + owned[slotId] = { + layers: parts.map((part) => + host.globe.imagery.add(specFor(candidate, part)), + ), + globe: host.globe, + candidate, + parts, + alpha, + split, + }; applyLook(owned[slotId]); + return true; } 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. + * Drape the parts of a candidate's box that the evidence allows (see drapedParts). + * The same candidate on the same port keeps the layer of each unchanged part. * @param {'a'|'b'} slotId * @param {object} candidate * @param {object} box Degrees box. - * @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look] + * @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look] * @returns {boolean} Whether a layer is now draped for the slot. */ showSlot( slotId, candidate, box, - { alpha = 1, splitDirection = 'none' } = {}, + { + alpha = 1, + splitDirection = 'none', + availableBoxes = null, + emptyBoxes = null, + } = {}, ) { if (destroyed || !candidate?.key || !box) return false; if (!host.globe) { @@ -143,21 +185,52 @@ export function createRecentImageryRenderer({ } const current = owned[slotId]; const look = { alpha: clampAlpha(alpha), split: splitDirection }; + const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes }); if ( current && current.globe === host.globe && current.candidate.key === candidate.key && - boxKey(current.box) === boxKey(box) + parts.length ) { - if (current.alpha !== look.alpha || current.split !== look.split) { + if (partsKey(current.parts) !== partsKey(parts)) { + const previous = new Map( + current.parts.map((part, i) => [boxKey(part), current.layers[i]]), + ); + // A new half goes right above the slot's surviving half, so both + // halves keep the same place against the other slot. + const survivor = parts + .map((part) => previous.get(boxKey(part))) + .find(Boolean); + const at = survivor + ? host.globe.imagery.list().indexOf(survivor) + 1 + : undefined; + const layers = parts.map((part) => { + const key = boxKey(part); + const layer = previous.get(key); + previous.delete(key); + return ( + layer ?? host.globe.imagery.add(specFor(candidate, part), at) + ); + }); + for (const layer of previous.values()) layer.remove(); + Object.assign(current, { layers, parts, ...look }); + applyLook(current); + requestRender('recent-imagery-show'); + } else 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 }); + const removed = removeOwned(slotId); + if (!mount(slotId, { candidate, parts, ...look })) { + if (removed) requestRender('recent-imagery-hide'); + return false; + } requestRender('recent-imagery-show'); return true; }, @@ -221,7 +294,7 @@ export function createRecentImageryRenderer({ return out; }, - /** Number of layers this renderer owns (never above two). */ + /** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */ ownedCount() { return SLOT_IDS.filter((slotId) => owned[slotId]).length; }, @@ -247,11 +320,11 @@ let previewSeq = 0; /** A box with no area has no fill: a press, or a drag along one axis. */ const hasArea = (box) => - Boolean(box) && box.east > box.west && box.north > box.south; + Boolean(box) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south; /** A box with no extent draws nothing: a press that has not moved yet. */ const hasExtent = (box) => - Boolean(box) && (box.east > box.west || box.north > box.south); + Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south); /** * The box tool's preview: the box being dragged, a translucent fill and a diff --git a/src/layers/recentImagery/rendering.test.mjs b/src/layers/recentImagery/rendering.test.mjs index 70028d43e7..804c73a88f 100644 --- a/src/layers/recentImagery/rendering.test.mjs +++ b/src/layers/recentImagery/rendering.test.mjs @@ -5,7 +5,9 @@ import { createImageryBoxPreview, createRecentImageryRenderer, } from './rendering.js'; -import { BOX } from './testDoubles.mjs'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { boxKey, nonCrossingBoxes } from './model.js'; +import { BOX, FIJI_BOX } from './testDoubles.mjs'; import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs'; import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs'; @@ -271,3 +273,210 @@ test('the box preview draws a ground fill and a draped dashed edge, hidden rathe box = { west: -96, south: 32, east: -95, north: 33 }; assert.doesNotThrow(() => preview.changed()); }); + +test('a dateline box drapes one layer on each side of ±180 and removes both', () => { + const { renderer, globe } = fixture(); + const box = { west: 179, south: 0, east: -179, north: 1 }; + assert.equal( + renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }), + true, + ); + assert.equal(renderer.ownedCount(), 1); + assert.equal(globe.layers.length, 2); + assert.deepEqual( + globe.layers.map((item) => item.spec.rectangle), + [ + { west: 179, south: 0, east: 180, north: 1 }, + { west: -180, south: 0, east: -179, north: 1 }, + ], + ); + assert.equal(globe.layers[0].alpha, 0.4); + assert.equal(globe.layers[1].alpha, 0.4); + assert.equal(globe.layers[0].split, 'left'); + assert.equal(globe.layers[1].split, 'left'); + renderer.setAlpha('a', 0.2); + assert.equal(globe.layers[0].alpha, 0.2); + assert.equal(globe.layers[1].alpha, 0.2); + renderer.showSlot('a', S30, box, { alpha: 0.2 }); + assert.equal(globe.added.length, 2, 'the same box does not remount'); + renderer.hideSlot('a'); + assert.equal(globe.layers.length, 0); +}); + +test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => { + const { renderer, globe } = fixture(); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + assert.equal( + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }), + true, + ); + assert.deepEqual( + globe.layers.map((layer) => layer.spec.rectangle), + [east], + ); + renderer.showSlot('b', VIIRS, FIJI_BOX, { + availableBoxes: [east, west], + splitDirection: 'right', + }); + assert.deepEqual( + globe.layers.map((layer) => layer.split), + ['none', 'right', 'right'], + ); + assert.equal(globe.layers.length, 3); + + const next = fakeGlobePort(); + renderer.rebind({ collection: {}, kind: 'globe', globe: next }); + assert.deepEqual( + next.layers.map((layer) => layer.spec.rectangle), + [east, west, east], + ); + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] }); + assert.equal(next.layers.length, 4); + renderer.destroy(); + assert.equal(next.layers.length, 0); +}); + +test('no allowed half, or halves of another box, drapes nothing', () => { + const { renderer, globe } = fixture(); + for (const availableBoxes of [[], [BOX]]) { + assert.equal( + renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }), + false, + ); + assert.equal(globe.layers.length, 0); + } +}); + +test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => { + const { renderer, globe } = fixture(); + assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false); + assert.equal(globe.layers.length, 0); + assert.equal(renderer.showSlot('a', VIIRS, BOX), true); + assert.equal(globe.layers.length, 1); + assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true); + assert.equal(globe.layers.length, 3); + renderer.destroy(); +}); + +test('evidence going from none to empty removes the drape', () => { + const { renderer, globe } = fixture(); + renderer.showSlot('a', S30, FIJI_BOX); + assert.equal(globe.layers.length, 2); + assert.equal( + renderer.showSlot('a', S30, FIJI_BOX, { + availableBoxes: [], + emptyBoxes: nonCrossingBoxes(FIJI_BOX), + }), + false, + ); + assert.equal(globe.layers.length, 0); + renderer.destroy(); +}); + +test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => { + const [west, east] = nonCrossingBoxes(FIJI_BOX); + for (const [product, expected] of [ + [S30, [west, east]], + [VIIRS, [east]], + ]) { + const { renderer, globe } = fixture(); + renderer.showSlot('a', product, FIJI_BOX, { + availableBoxes: [east], + emptyBoxes: [], + }); + assert.deepEqual( + globe.layers.map((layer) => layer.spec.rectangle), + expected, + ); + renderer.destroy(); + } +}); + +test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => { + const renderer = createRecentImageryRenderer(); + const globe = fakeGlobePort(); + renderer.rebind({ collection: {}, kind: 'globe', globe }); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + const layerFor = (box) => + globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box)); + + // An HLS day drapes both halves before its probe answers. + renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' }); + const kept = layerFor(west); + assert.ok(kept); + const added = globe.added.length; + + // The probe confirms the east half empty: only the east layer goes. + renderer.showSlot('a', S30, FIJI_BOX, { + alpha: 0.4, + splitDirection: 'left', + availableBoxes: [west], + emptyBoxes: [east], + }); + assert.equal(kept.removed, false, 'the west layer survives the narrowing'); + assert.equal(globe.added.length, added, 'narrowing adds no layer'); + assert.equal(layerFor(east), undefined); + + // A later probe admits east again: only the east layer is added. + renderer.showSlot('a', S30, FIJI_BOX, { + alpha: 0.4, + splitDirection: 'left', + availableBoxes: [west, east], + emptyBoxes: [], + }); + assert.equal(kept.removed, false, 'the west layer survives the widening'); + assert.equal(globe.added.length, added + 1); + assert.equal(kept.alpha, 0.4); + assert.equal(kept.split, 'left'); + renderer.destroy(); +}); + +test('widening slot a over the dateline keeps it below slot b on both sides', () => { + const { renderer, globe } = fixture(); + const [west, east] = nonCrossingBoxes(FIJI_BOX); + const topOn = (box) => + globe.layers + .filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box)) + .at(-1) + .spec.url.includes('S30') + ? 'A' + : 'B'; + renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] }); + renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] }); + assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']); + renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] }); + assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']); + renderer.destroy(); +}); + +test('the drag preview draws a wrapped fill and outline across the dateline', async () => { + const draw = fakeDrawPort(); + let box = { west: 179, south: 0, east: 179, north: 0 }; + const preview = createImageryBoxPreview({}, () => box, { draw }); + const [fills, outlines] = draw.sets.values(); + preview.setVisible(true); + + box = { ...box, east: -179 }; + preview.changed(); + assert.equal(fills.items.size, 0); + assert.equal(outlines.items.get('edge').show, true); + assert.deepEqual( + outlines.items.get('edge').positions[1], + fromDegrees(-179, 0), + ); + + box = { ...box, north: 1 }; + preview.changed(); + assert.equal(fills.items.get('box').show, true); + assert.deepEqual(fills.items.get('box').geometry.rect, box); + const edge = outlines.items.get('edge'); + assert.equal(edge.show, true); + assert.deepEqual(edge.positions, [ + fromDegrees(179, 0), + fromDegrees(-179, 0), + fromDegrees(-179, 1), + fromDegrees(179, 1), + fromDegrees(179, 0), + ]); + await preview.destroy(); +}); diff --git a/src/layers/recentImagery/source.js b/src/layers/recentImagery/source.js index 9e6749cb72..1e2afa1159 100644 --- a/src/layers/recentImagery/source.js +++ b/src/layers/recentImagery/source.js @@ -1,10 +1,107 @@ import { searchHls } from './catalog.js'; -import { gibsTemplate, wvsSnapshotUrl } from './model.js'; +import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js'; + +/** + * Deadline for one half's response headers, so a day whose other half + * answered is not held at "checking". + */ +const DEFAULT_HALF_DEADLINE_MS = 15_000; + +/** + * Worldview Snapshots rejects a BBOX with west > east, so a dateline box is + * probed as its two non-crossing halves, wider first. A plain box is its + * one normalized half. A day has data when either half does. + */ +function requestBoxes(box) { + return nonCrossingBoxes(box).sort( + (a, b) => b.east - b.west - (a.east - a.west), + ); +} + +/** A response's Data-Present answer in lower case, or '' when it failed or has none. */ +export const dataPresent = (response) => + response?.ok + ? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase() + : ''; + +/** + * One half's snapshot fetch, raced against its own deadline so a half that + * never answers, even over a transport that ignores AbortSignal, still + * settles. Its deadline cancels only this half. The caller can cancel it + * at any time, including while its body is being read. + */ +function probeHalf( + url, + { fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl }, +) { + const controller = new AbortController(); + return new Promise((resolve, reject) => { + let timer = null; + const finishTimeout = () => { + if (timer !== null) clearTimeoutImpl(timer); + timer = null; + }; + const stop = (reason) => { + controller.abort(reason); + finishTimeout(); + // Settle even if the transport ignores abort. + reject(reason); + }; + if (signal?.aborted) { + stop(signal.reason); + return; + } + signal?.addEventListener('abort', () => stop(signal.reason), { + once: true, + }); + if (deadlineMs > 0) + timer = setTimeoutImpl( + () => + stop(new DOMException('Thumbnail half timed out', 'TimeoutError')), + deadlineMs, + ); + let promise; + try { + promise = Promise.resolve(fetchImpl(url, { signal: controller.signal })); + } catch (error) { + finishTimeout(); + reject(error); + return; + } + promise.then( + (value) => { + finishTimeout(); + resolve(value); + }, + (error) => { + finishTimeout(); + reject(error); + }, + ); + }); +} + +/** + * Non-enumerable per-half evidence for the box's non-crossing halves: + * presentBoxes lists the halves Worldview confirmed present, emptyBoxes + * the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js. + */ +function withHalves(response, { presentBoxes, emptyBoxes }) { + Object.defineProperties(response, { + presentBoxes: { value: presentBoxes, configurable: true }, + emptyBoxes: { value: emptyBoxes, configurable: true }, + }); + return response; +} /** * NASA-compatible imagery acquisition; transport and URL builders are replaceable. * Thumbnail responses must expose Data-Present: true for image admission, or * false for confirmed empty coverage, including injected getThumbnail sources. + * getThumbnail also sets presentBoxes and emptyBoxes (see withHalves), + * also on the error it throws when another half was confirmed empty. + * Without per-half evidence the renderer drapes every side of an HLS + * dateline box and no side of a VIIRS one. */ export function createRecentImagerySource({ fetchImpl = (...args) => globalThis.fetch(...args), @@ -12,24 +109,68 @@ export function createRecentImagerySource({ thumbnailUrl = wvsSnapshotUrl, tileTemplate = gibsTemplate, credit = 'NASA GIBS', + halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS, + setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms), + clearTimeoutImpl = (id) => globalThis.clearTimeout(id), } = {}) { return { credit, searchHls: (query) => search({ ...query, fetchImpl }), async getThumbnail(candidate, box, { size = 256, signal } = {}) { signal?.throwIfAborted(); - const response = await fetchImpl( - thumbnailUrl({ - product: candidate.product, - day: candidate.day, - box, - width: size, - height: size, - }), - { signal }, + const halves = requestBoxes(box); + const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0; + const results = await Promise.allSettled( + halves.map((half) => + probeHalf( + thumbnailUrl({ + product: candidate.product, + day: candidate.day, + box: half, + width: size, + height: size, + }), + { + fetchImpl, + signal, + deadlineMs, + setTimeoutImpl, + clearTimeoutImpl, + }, + ), + ), ); signal?.throwIfAborted(); - return response; + // Per half, its Data-Present answer or null when it did not answer. + const answers = results.map((result) => + result.status === 'fulfilled' ? dataPresent(result.value) : null, + ); + const halvesWhere = (value) => + halves.filter((_, i) => answers[i] === value); + // A missing answer is an error unless another half proved data. The + // error keeps a half confirmed empty (see withHalves). + const failure = results.find((result) => result.status === 'rejected'); + if (failure && !answers.includes('true')) { + const emptyBoxes = halvesWhere('false'); + if (Object.isExtensible(failure.reason)) + withHalves( + failure.reason, + emptyBoxes.length + ? { presentBoxes: [], emptyBoxes } + : { presentBoxes: null, emptyBoxes: null }, + ); + throw failure.reason; + } + // Show the first half with data (the wider wins a tie), else the first + // not confirmed empty, so an unreadable answer is never called empty. + // Every half answered here unless one proved data. + let shown = answers.indexOf('true'); + if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false'); + if (shown < 0) shown = 0; + return withHalves(results[shown].value, { + presentBoxes: halvesWhere('true'), + emptyBoxes: halvesWhere('false'), + }); }, getTileTemplate: (product, day) => tileTemplate(product, day), }; diff --git a/src/layers/recentImagery/source.test.mjs b/src/layers/recentImagery/source.test.mjs index d3cafc5b0d..f573c1f711 100644 --- a/src/layers/recentImagery/source.test.mjs +++ b/src/layers/recentImagery/source.test.mjs @@ -1,13 +1,20 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { manualTimers } from './testDoubles.mjs'; import { createRecentImagerySource } from './source.js'; test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => { const controller = new AbortController(); - const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal }; + const query = { + box: { west: 0, east: 1, south: 0, north: 1 }, + signal: controller.signal, + }; const candidate = { product: 'S30', day: '2026-10-01' }; const calls = []; - const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); }; + const fetchImpl = async (...args) => { + calls.push(args); + return new Response('image'); + }; const source = createRecentImagerySource({ fetchImpl, search: async (request) => { @@ -16,27 +23,263 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt assert.equal(request.box, query.box); return [candidate]; }, - thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`, - tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`, + thumbnailUrl: ({ product, day, width }) => + `https://imagery.example/${product}/${day}/${width}`, + tileTemplate: (product, day) => + `https://tiles.example/${product}/${day}/{z}/{x}/{y}`, credit: 'Example imagery', }); assert.deepEqual(await source.searchHls(query), [candidate]); - assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image'); + assert.equal( + await ( + await source.getThumbnail(candidate, query.box, { + signal: controller.signal, + }) + ).text(), + 'image', + ); assert.equal(calls.length, 1); assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256'); - assert.equal(calls[0][1].signal, controller.signal); - assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}'); + // The fetch gets a private signal chained to the caller's. + const halfSignal = calls[0][1].signal; + assert.notEqual(halfSignal, controller.signal); + assert.equal(halfSignal.aborted, false); + controller.abort(); + assert.equal(halfSignal.aborted, true); + assert.equal( + source.getTileTemplate(candidate.product, candidate.day), + 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}', + ); assert.equal(source.credit, 'Example imagery'); }); test('cancelled thumbnail acquisition does not return stale responses or retry', async () => { const controller = new AbortController(); + const box = { west: 0, south: 0, east: 1, north: 1 }; let calls = 0; const source = createRecentImagerySource({ thumbnailUrl: () => 'https://imagery.example/thumbnail', - fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); }, + fetchImpl: async () => { + calls++; + controller.abort(); + return new Response('image'); + }, }); - await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' }); - await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' }); + await assert.rejects( + source.getThumbnail({}, box, { signal: controller.signal }), + { name: 'AbortError' }, + ); + await assert.rejects( + source.getThumbnail({}, box, { signal: controller.signal }), + { name: 'AbortError' }, + ); assert.equal(calls, 1); }); + +test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => { + const requested = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => { + requested.push(box); + return 'https://imagery.example/thumbnail'; + }, + fetchImpl: async () => new Response('image'), + }); + const candidate = { product: 'S30', day: '2026-10-01' }; + await source.getThumbnail(candidate, { + west: 179.9, + south: 0, + east: -179, + north: 1, + }); + assert.deepEqual(requested, [ + { west: -180, south: 0, east: -179, north: 1 }, + { west: 179.9, south: 0, east: 180, north: 1 }, + ]); + requested.length = 0; + await source.getThumbnail(candidate, { + west: 179, + south: 0, + east: -179.9, + north: 1, + }); + assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 }); + assert.equal(requested.length, 2); + assert.ok(requested.every((box) => box.west <= box.east)); +}); + +const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 }; +// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG. +const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' }; +const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 }; +const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 }; + +const dated = (present, body = 'image') => + new Response(body, { headers: { 'Data-Present': present } }); +function halvesSource(answers, options = {}) { + const requested = []; + const source = createRecentImagerySource({ + ...options, + thumbnailUrl: ({ box }) => + `https://imagery.example/${box.west}/${box.east}`, + fetchImpl: async (url) => { + requested.push(url); + const answer = answers[url.split('imagery.example/')[1]]; + if (answer instanceof Error) throw answer; + return answer.clone ? answer : answer(); + }, + }); + return { source, requested }; +} +const candidate = { product: 'S30', day: '2026-10-01' }; + +test('a crossing box probes both halves and is present when only the narrow half has data', async () => { + const { source, requested } = halvesSource({ + '-180/-179': dated('false'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(requested.length, 2); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.equal(await response.text(), 'narrow'); + assert.deepEqual(response.presentBoxes, [NARROW_BOX]); + assert.deepEqual(response.emptyBoxes, [WIDE_BOX]); +}); + +test('a crossing box with data only on the wider half is present and shows the wider side', async () => { + const { source } = halvesSource({ + '-180/-179': dated('true', 'wide'), + '179.9/180': dated('false'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'wide'); +}); + +test('a crossing box is empty only when both halves are confirmed empty', async () => { + const { source } = halvesSource({ + '-180/-179': dated('false'), + '179.9/180': dated('false'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(response.headers.get('Data-Present'), 'false'); + assert.deepEqual(response.presentBoxes, []); + assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]); +}); + +test('a crossing box is not called empty when the other half failed', async () => { + const { source } = halvesSource({ + '-180/-179': dated('false'), + '179.9/180': () => new Response('x', { status: 503 }), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(response.ok, false); +}); + +test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => { + const { source } = halvesSource({ + '-180/-179': dated('true', 'wide'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'wide'); + assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]); +}); + +test('a rejected half does not hide data on the other half, and never reads as empty', async () => { + const { source } = halvesSource({ + '-180/-179': new Error('network'), + '179.9/180': dated('true', 'narrow'), + }); + const response = await source.getThumbnail(candidate, NARROW_WEST); + assert.equal(await response.text(), 'narrow'); + const failing = halvesSource({ + '-180/-179': new Error('network'), + '179.9/180': dated('false'), + }); + await assert.rejects( + failing.source.getThumbnail(candidate, NARROW_WEST), + /network/, + ); +}); + +for (const [label, answer] of [ + ['rejected', new Error('network')], + ['hung', () => new Promise(() => {})], + ['answered without a presence', () => dated('unknown', 'maybe')], +]) { + for (const product of [JPEG_CANDIDATE, candidate]) { + test(`a ${product.product} half that ${label} is neither present nor empty`, async () => { + const { source } = halvesSource( + { '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') }, + { halfDeadlineMs: 20 }, + ); + const response = await source.getThumbnail(product, NARROW_WEST); + assert.equal(response.headers.get('Data-Present'), 'true'); + assert.deepEqual(response.presentBoxes, [NARROW_BOX]); + assert.deepEqual(response.emptyBoxes, []); + }); + } +} + +test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => { + const controller = new AbortController(); + const source = createRecentImagerySource({ + thumbnailUrl: () => 'https://example.invalid/', + halfDeadlineMs: 10000, + fetchImpl: () => { + controller.abort(); + return new Promise(() => {}); + }, + }); + const outcome = await Promise.race([ + source + .getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal }) + .then( + () => 'resolved', + (error) => error.name, + ), + new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)), + ]); + assert.equal(outcome, 'AbortError'); +}); + +test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => { + const hang = () => new Promise(() => {}); + const { source, requested } = halvesSource( + { '-180/-179': hang, '179.9/180': hang }, + { halfDeadlineMs: 10 }, + ); + await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), { + name: 'TimeoutError', + }); + assert.equal(requested.length, 2); +}); + +test("the caller's cancellation rejects at once and stops every half", async () => { + const aborted = []; + const source = createRecentImagerySource({ + thumbnailUrl: ({ box }) => String(box.west), + fetchImpl: (url, { signal }) => { + signal.addEventListener('abort', () => aborted.push(url), { once: true }); + return new Promise(() => {}); + }, + }); + const controller = new AbortController(); + const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { + signal: controller.signal, + }); + controller.abort(); + await assert.rejects(result, { name: 'AbortError' }); + assert.deepEqual(aborted, ['-180', '179.9']); +}); + +test('a successful probe leaves no deadline timer behind', async () => { + const timers = manualTimers(); + const { source } = halvesSource( + { '-180/-179': dated('true'), '179.9/180': dated('false') }, + timers, + ); + await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST); + assert.equal(timers.armed(), 0); + assert.equal(timers.cleared.length, 2); +}); diff --git a/src/layers/recentImagery/testDoubles.mjs b/src/layers/recentImagery/testDoubles.mjs index 75f660553c..d38d207034 100644 --- a/src/layers/recentImagery/testDoubles.mjs +++ b/src/layers/recentImagery/testDoubles.mjs @@ -16,6 +16,13 @@ export const BOX = Object.freeze({ north: 30.3, }); +export const FIJI_BOX = Object.freeze({ + west: 179, + south: -18, + east: -177, + north: -17, +}); + export const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); /** Timers that fire only when the test says so. */ diff --git a/src/layers/recentImagery/thumbnails.js b/src/layers/recentImagery/thumbnails.js index 190836fefd..70e00526d3 100644 --- a/src/layers/recentImagery/thumbnails.js +++ b/src/layers/recentImagery/thumbnails.js @@ -1,6 +1,6 @@ /** * Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per - * candidate day. The response's `Data-Present` header is the only proof that + * candidate day (one per side of a dateline box). 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 @@ -8,16 +8,28 @@ * 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 } from './model.js'; -import { createRecentImagerySource } from './source.js'; +import { boxKey, thumbnailOrder } from './model.js'; +import { createRecentImagerySource, dataPresent } from './source.js'; const EMPTY = Object.freeze({ status: 'unknown', objectUrl: null, acquisitionTime: null, + availableBoxes: null, + emptyBoxes: null, loading: false, }); +/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */ +function keepProvenHalves(previous, next, opposite) { + if (!Array.isArray(next) || !Array.isArray(opposite)) return previous; + const drop = new Set([...next, ...opposite].map(boxKey)); + return [ + ...next, + ...(previous ?? []).filter((half) => !drop.has(boxKey(half))), + ]; +} + /** * @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options] */ @@ -90,18 +102,22 @@ export function createThumbnailLoader({ let status = 'error'; let objectUrl = null; let acquisitionTime = null; + // Per-half evidence (see withHalves in source.js), or null without it. + let availableBoxes = null; + let emptyBoxes = null; let cancelled = false; try { const response = await requestThumbnail(entry.candidate, entry.box, { size, signal: controller.signal, }); + // Each half's explicit answer counts even when the shown response fails. + availableBoxes = response?.presentBoxes ?? null; + emptyBoxes = response?.emptyBoxes ?? null; if (controller.signal.aborted) { cancelled = true; } else if (response?.ok) { - const present = String( - response.headers?.get?.('Data-Present') ?? '', - ).toLowerCase(); + const present = dataPresent(response); acquisitionTime = response.headers?.get?.('Acquisition-Time') || null; if (present === 'false') { status = 'empty'; @@ -117,7 +133,11 @@ export function createThumbnailLoader({ } catch (error) { if (controller.signal.aborted || error?.name === 'AbortError') cancelled = true; - else status = 'error'; + else { + status = 'error'; + availableBoxes = error?.presentBoxes ?? availableBoxes; + emptyBoxes = error?.emptyBoxes ?? emptyBoxes; + } } finally { inFlight -= 1; entry.loading = false; @@ -129,6 +149,17 @@ export function createThumbnailLoader({ pump(); return; } + // Each half keeps its latest explicit answer. + entry.availableBoxes = keepProvenHalves( + entry.availableBoxes, + availableBoxes, + emptyBoxes, + ); + entry.emptyBoxes = keepProvenHalves( + entry.emptyBoxes, + emptyBoxes, + availableBoxes, + ); // A failed re-fetch of an evicted image keeps what the day proved. if (status !== 'error' || entry.status !== 'present') { entry.status = status; @@ -196,6 +227,8 @@ export function createThumbnailLoader({ status: 'unknown', objectUrl: null, acquisitionTime: null, + availableBoxes: null, + emptyBoxes: null, loading: false, controller: null, touched: 0, @@ -272,7 +305,7 @@ export function createThumbnailLoader({ /** * 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 }} + * @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array | null, emptyBoxes: Array | null, loading: boolean }} */ get(key) { const entry = entries.get(key); @@ -281,6 +314,8 @@ export function createThumbnailLoader({ status: entry.status, objectUrl: entry.objectUrl, acquisitionTime: entry.acquisitionTime, + availableBoxes: entry.availableBoxes, + emptyBoxes: entry.emptyBoxes, loading: entry.loading, }; }, diff --git a/src/layers/recentImagery/thumbnails.test.mjs b/src/layers/recentImagery/thumbnails.test.mjs index a9df5e0861..e5843dea6e 100644 --- a/src/layers/recentImagery/thumbnails.test.mjs +++ b/src/layers/recentImagery/thumbnails.test.mjs @@ -1,13 +1,9 @@ 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, -}); +import { createRecentImagerySource } from './source.js'; +import { nonCrossingBoxes } from './model.js'; +import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs'; /** A fetch whose responses the test releases, in any order. */ function fakeFetch() { @@ -68,6 +64,8 @@ test('Data-Present decides the day: present with an object URL and sensing time, status: 'present', objectUrl: 'blob:1', acquisitionTime: '2026-09-18T17:12:00Z', + availableBoxes: [BOX], + emptyBoxes: [], loading: false, }); assert.equal(loader.get('L30:2026-09-16').status, 'empty'); @@ -337,6 +335,75 @@ test('injected thumbnail acquisition owns requests while the loader releases obj assert.deepEqual(revoked, ['blob:1']); }); +test('the loader proves a dateline day present from one half and hands that half on', async () => { + const day = candidate('VIIRS', '2026-11-04'); + const time = day.day + 'T22:10:00Z'; + const { loader } = fixture({ + fetchImpl: async (url) => { + const east = + new URL(url).searchParams.get('BBOX').split(',')[1] === '-180'; + return response({ + headers: east + ? { 'Data-Present': 'true', 'Acquisition-Time': time } + : { 'Data-Present': 'false' }, + }); + }, + }); + loader.request(day, FIJI_BOX); + await settle(); + const entry = loader.get(day.key); + assert.equal(entry.status, 'present'); + assert.equal(entry.acquisitionTime, time); + assert.ok(entry.objectUrl); + assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]); + loader.destroy(); +}); + +test('a dateline day whose halves both hang is an error, not "checking" forever', async () => { + const source = createRecentImagerySource({ + fetchImpl: () => new Promise(() => {}), + halfDeadlineMs: 20, + }); + const loader = createThumbnailLoader({ + requestThumbnail: source.getThumbnail, + }); + const day = candidate('VIIRS', '2026-11-04'); + const settled = new Promise((resolve) => loader.subscribe(resolve)); + loader.request(day, FIJI_BOX); + await settled; + assert.equal(loader.get(day.key).status, 'error'); + loader.destroy(); +}); + +test('a re-probe of a present day drops a half only when it is confirmed empty', async () => { + const box = { west: 179, south: 0, east: -179, north: 1 }; + const [west, east] = nonCrossingBoxes(box); + const answers = [ + { presentBoxes: [west, east], emptyBoxes: [] }, + { presentBoxes: [west, east], emptyBoxes: [] }, + { presentBoxes: [west], emptyBoxes: [east] }, + ]; + const { loader } = fixture({ + maxDecoded: 1, + requestThumbnail: async () => + Object.assign( + response({ headers: { 'Data-Present': 'true' } }), + answers.shift(), + ), + }); + const day1 = candidate('VIIRS', '2026-11-04'); + const day2 = candidate('VIIRS', '2026-11-05'); + loader.request(day1, box); + await settle(); + loader.request(day2, box); + await settle(); + assert.equal(loader.get(day1.key).objectUrl, null); + loader.request(day1, box); + await settle(); + assert.deepEqual(loader.get(day1.key).availableBoxes, [west]); + loader.destroy(); +}); + test('retain aborts stale acquisition while allowing the current intent to start', async () => { const { loader, fetch } = fixture({ maxInFlight: 1 }); const stale = candidate('S30', '2026-09-10'); diff --git a/src/tools/queries/imagery.js b/src/tools/queries/imagery.js index 310f270569..2615d1a212 100644 --- a/src/tools/queries/imagery.js +++ b/src/tools/queries/imagery.js @@ -31,11 +31,6 @@ export const getRecentImagery = defineTool({ requires: ['imagery'], async run(args, { services, signal }) { const area = await resolveArea(args.area, { services, signal }); - if (area.west > area.east) - throw new ToolError( - 'invalid_arguments', - 'The area must not cross the antimeridian', - ); if ( Math.abs(area.south) > MAX_LATITUDE || Math.abs(area.north) > MAX_LATITUDE @@ -55,6 +50,13 @@ export const getRecentImagery = defineTool({ east: area.east, north: area.north, }; + // Worldview Snapshots rejects a west > east BBOX, so a dateline area can + // never produce the image this tool returns: refuse before searching. + if (box.west > box.east) + throw new ToolError( + 'invalid_arguments', + 'The area must not cross the antimeridian', + ); let latest; try { latest = await services.imagery.latest({ box, signal }); diff --git a/src/tools/queries/imagery.test.mjs b/src/tools/queries/imagery.test.mjs index 75ef94312d..e450d57929 100644 --- a/src/tools/queries/imagery.test.mjs +++ b/src/tools/queries/imagery.test.mjs @@ -82,8 +82,30 @@ test('overview fallback, empty results and invalid areas are reported', async () ); await assert.rejects( none.call('get_recent_imagery', { area: { bbox: [170, 0, -170, 5] } }), - /antimeridian/, + /too large for imagery/, ); + const crossing = imagery({ + candidate: { + product: 'S30', + day: '2026-10-01', + cloud: { min: 1, max: 2 }, + coverage: 'full', + }, + reason: 'clear', + errors: [], + }); + const wrapped = composeCatalog({ + tools: coreTools, + services: { imagery: crossing }, + }); + await assert.rejects( + wrapped.call('get_recent_imagery', { + area: { bbox: [179, 0, -179, 1] }, + }), + /must not cross the antimeridian/, + ); + assert.equal(crossing.snapshots.length, 0); + assert.equal(crossing.boxes.length, 0); await assert.rejects( none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }), /±85° latitude/, diff --git a/src/ui/imageryBoxTool.js b/src/ui/imageryBoxTool.js index 9305a95129..df2c5e08ed 100644 --- a/src/ui/imageryBoxTool.js +++ b/src/ui/imageryBoxTool.js @@ -48,13 +48,20 @@ export function initImageryBoxTool({ let lease = null; let releaseCamera = null; - const dragBox = () => - anchor && { - west: Math.min(anchor.lon, corner.lon), + const dragBox = () => { + if (!anchor) return null; + const lo = Math.min(anchor.lon, corner.lon); + const hi = Math.max(anchor.lon, corner.lon); + // Corners more than half the globe apart are the short way round, over + // the dateline: west gets the larger longitude, east the smaller. + const crosses = hi - lo > 180; + return { + west: crosses ? hi : lo, south: Math.min(anchor.lat, corner.lat), - east: Math.max(anchor.lon, corner.lon), + east: crosses ? lo : hi, north: Math.max(anchor.lat, corner.lat), }; + }; const preview = createPreview(viewer, dragBox); const setPreview = (visible) => preview.setVisible(visible); diff --git a/src/ui/imageryBoxTool.test.mjs b/src/ui/imageryBoxTool.test.mjs index 4f52ff1dc1..ffefdc5dad 100644 --- a/src/ui/imageryBoxTool.test.mjs +++ b/src/ui/imageryBoxTool.test.mjs @@ -10,6 +10,7 @@ import { IMAGERY_BOX_POINTER_OWNER, initImageryBoxTool, } from './imageryBoxTool.js'; +import { lonSpanDeg, validateBox } from '../layers/recentImagery/model.js'; import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs'; import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js'; import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; @@ -209,3 +210,40 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the assert.equal(f.tool.start(), false); assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null); }); + +test('a drag across the dateline is the short box, not a box round the world', async () => { + const pickWorld = (_viewer, nx, ny) => + ny < 0.05 ? null : { lon: nx < 0.5 ? 179.99 : -179.99, lat: ny }; + const f = fixture({ pickWorld }); + f.tool.start(); + f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } }); + f.fire('LEFT_UP', { position: { x: 800, y: 250 } }); + assert.deepEqual(f.cancels, []); + assert.equal(f.boxes.length, 1); + const { west, east } = f.boxes[0]; + assert.ok(west > east, `west ${west} is east of east ${east}`); + assert.ok(Math.abs(east + 360 - west - 0.02) < 1e-9, 'a 0.02 degree span'); + await f.tool.destroy(); +}); + +test('a drag whose short arc is still over the size limit is refused as too large', async () => { + const pickWorld = (_viewer, nx, ny) => ({ + lon: nx < 0.5 ? 100 : -100, + lat: ny, + }); + const refused = []; + const f = fixture({ + pickWorld, + onCancel: (reason, message, box) => refused.push({ reason, message, box }), + }); + f.tool.start(); + f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } }); + f.fire('LEFT_UP', { position: { x: 800, y: 250 } }); + assert.equal(f.boxes.length, 0); + const { reason, message, box } = refused.at(-1); + assert.equal(reason, 'too-large'); + assert.deepEqual([box.west, box.east], [100, -100], 'the short arc'); + assert.equal(lonSpanDeg(box.west, box.east), 160); + assert.equal(message, validateBox(box).message); + await f.tool.destroy(); +}); diff --git a/src/ui/recentImagery.js b/src/ui/recentImagery.js index 623ac4e085..4d1bf989e5 100644 --- a/src/ui/recentImagery.js +++ b/src/ui/recentImagery.js @@ -22,6 +22,7 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue'; import { PRODUCTS, hhmm, + nonCrossingBoxes, wvsSnapshotUrl, } from '../layers/recentImagery/model.js'; import { displayDay, displayMetres } from '../layers/recentImagery/display.js'; @@ -135,6 +136,20 @@ function coverageText(coverage) { return t('unknown'); } +/** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */ +function shownCoverage(candidate, box) { + const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {}; + const halves = nonCrossingBoxes(box).length; + if (emptyBoxes?.length && emptyBoxes.length < halves) return 'partial'; + if ( + status !== 'present' || + !Array.isArray(availableBoxes) || + availableBoxes.length >= halves + ) + return candidate.coverage; + return 'unknown'; +} + function cloudText(candidate) { if (candidate.thumbnail?.status === 'empty') return t('no imagery'); if (!candidate.cloud) return t('cloud unknown'); @@ -516,6 +531,9 @@ export function createRecentImageryPanel({ function exportsView() { const ab = snapshot.mode === 'ab'; + const crossing = Boolean( + snapshot.box && snapshot.box.west > snapshot.box.east, + ); return [ { id: 'export', @@ -525,10 +543,12 @@ export function createRecentImageryPanel({ label: ab ? t('EXPORT {slot}', { slot: slotId.toUpperCase() }) : t('EXPORT'), - title: ab - ? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() }) - : t('Download the image as a PNG'), - disabled: !exportTarget(slotId) || exporting.has(slotId), + title: crossing + ? t('Select one side of the dateline') + : ab + ? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() }) + : t('Download the image as a PNG'), + disabled: crossing || !exportTarget(slotId) || exporting.has(slotId), reserved: slotId === 'b' ? !ab : undefined, onClick: () => void exportImage(slotId), })), @@ -566,7 +586,9 @@ export function createRecentImageryPanel({ }), ); times.push( - t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }), + t('Coverage {coverage}', { + coverage: coverageText(shownCoverage(focus, snapshot.box)), + }), ); lines.push({ id: 'acquired', text: times.join(' · ') }); (focus.granules || []).forEach((granule, index) => { diff --git a/src/ui/recentImagery.test.mjs b/src/ui/recentImagery.test.mjs index b1336940f1..06f6eabe20 100644 --- a/src/ui/recentImagery.test.mjs +++ b/src/ui/recentImagery.test.mjs @@ -5,9 +5,11 @@ import assert from 'node:assert/strict'; import { assertSameNode } from '../testSupport/domAssert.mjs'; import { readFileSync } from 'node:fs'; import { createRecentImageryPanel } from './recentImagery.js'; +import { nonCrossingBoxes } from '../layers/recentImagery/model.js'; import { createRecentImageryLayer } from '../layers/recentImagery/index.js'; import { BOX, + FIJI_BOX, fakeCatalog, fakeController, fakeRenderer, @@ -977,6 +979,29 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX await settle(); assert.equal(await f.readout.exportImage('a'), true); assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/); + // A dateline box is drawn on the map, but Worldview rejects a crossing BBOX. + const before = f.fetches.length; + f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 }); + f.catalog.resolveLast(); + await settle(); + assert.notEqual( + f.byId('ri-notice-text').textContent, + 'Select one side of the dateline', + 'the drawn box is not a warning until an export is tried', + ); + const crossingExport = f.byAction('export-a'); + assert.equal(crossingExport.disabled, true, 'EXPORT is off up front'); + assert.equal(crossingExport.title, 'Select one side of the dateline'); + assert.equal(await f.readout.exportImage('a'), false); + assert.equal( + f.byId('ri-notice-text').textContent, + 'Export failed · A snapshot cannot cross the dateline', + ); + assert.equal( + f.fetches.length, + before, + 'export does not request a crossing BBOX', + ); f.layer.setMode('ab'); assert.deepEqual( [ @@ -1040,6 +1065,31 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to assert.equal(article.dataset.open, 'false'); }); +test('DETAILS shows partial coverage for a dateline day with one side empty, unknown when a side did not answer', async () => { + const f = fixture(); + f.layer.enable(); + f.layer.setBox(FIJI_BOX); + f.catalog.resolveLast(); + await settle(); + assert.match(f.byId('ri-details').textContent, /Coverage full/); + const get = f.thumbnails.get; + const [west, east] = nonCrossingBoxes(FIJI_BOX); + f.thumbnails.get = (key) => ({ + ...get(key), + availableBoxes: [west], + emptyBoxes: [east], + }); + f.thumbnails.probe(f.snap().focus.key, 'present'); + assert.match(f.byId('ri-details').textContent, /Coverage partial/); + f.thumbnails.get = (key) => ({ + ...get(key), + availableBoxes: [west], + emptyBoxes: [], + }); + f.thumbnails.probe(f.snap().focus.key, 'present'); + assert.match(f.byId('ri-details').textContent, /Coverage unknown/); +}); + test('the body scroll position survives renders even when DOM mutations reset it', async () => { const f = fixture(); await f.ready(); diff --git a/src/ui/recentImageryNotice.test.mjs b/src/ui/recentImageryNotice.test.mjs index af14de4694..a7dffa7176 100644 --- a/src/ui/recentImageryNotice.test.mjs +++ b/src/ui/recentImageryNotice.test.mjs @@ -13,11 +13,11 @@ const REFUSALS = [ 'Point the camera at the ground to use the view', // layers/recentImagery/index.js 'That point cannot anchor a box', // layers/recentImagery/index.js ...[ - { west: 170, south: 10, east: -170, north: 20 }, // dateline - { west: 10, south: 80, east: 20, north: 89 }, // polar - { west: 10, south: 10, east: 10, north: 20 }, // degenerate - { west: 10, south: 10, east: 200, north: 20 }, // longitude range - { west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite + { west: 170, south: 10, east: -170, north: 20 }, // dateline, over the size cap + { west: 10, south: 80, east: 20, north: 89 }, + { west: 10, south: 10, east: 10, north: 20 }, + { west: 10, south: 10, east: 200, north: 20 }, + { west: Number.NaN, south: 10, east: 20, north: 20 }, ].map((box) => { const result = validateBox(box); assert.equal(result.ok, false); @@ -27,7 +27,14 @@ const REFUSALS = [ test('en: refusals stay English', () => { setLocale('en'); - for (const text of REFUSALS) assert.equal(localizeNotice(text), text); + for (const text of REFUSALS) { + const shown = localizeNotice(text); + // Size refusals are rewritten with a non-breaking space before the unit. + const expected = / km wide/.test(text) + ? text.replaceAll(' km', '\u00a0km') + : text; + assert.equal(shown, expected); + } assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude')); }); diff --git a/src/voice/imageryActions.js b/src/voice/imageryActions.js index 50d361f8f6..1d857cdec4 100644 --- a/src/voice/imageryActions.js +++ b/src/voice/imageryActions.js @@ -17,7 +17,12 @@ * @module voice/imageryActions */ -import { PRODUCTS, rankLatest } from '../layers/recentImagery/model.js'; +import { + PRODUCTS, + boxCentre, + boxSideKm, + rankLatest, +} from '../layers/recentImagery/model.js'; import { displacedLayerResult, watchExplicitLayerOff, @@ -203,19 +208,14 @@ export async function findImagery( `No area "${args.areaId}" on this page — call resolve_area again.`, ); const [west, south, east, north] = record.bbox; - if (west > east) - return fail( - 'DATELINE', - `${record.name} crosses the date line; the imagery box needs one side of it.`, - ); // 30 m pixels over a landmark-sized area show a handful of blobs: a small // area gets the layer's own 10 km box around its centre instead. - const small = - (north - south) * 111 < 5 && - (east - west) * 111 * Math.cos((((north + south) / 2) * Math.PI) / 180) < - 5; + // west > east is the short arc across the date line. The layer's helpers + // measure and centre it. + const { width, height } = boxSideKm({ west, south, east, north }); + const small = width < 5 && height < 5; box = small - ? { pin: { lon: (west + east) / 2, lat: (south + north) / 2 } } + ? { pin: boxCentre({ west, south, east, north }) } : { west, south, east, north }; areaName = record.name; } else if (where === 'point') { diff --git a/src/voice/imageryActions.test.mjs b/src/voice/imageryActions.test.mjs index 8c80fb32c8..12a1162714 100644 --- a/src/voice/imageryActions.test.mjs +++ b/src/voice/imageryActions.test.mjs @@ -236,7 +236,7 @@ test('an area handle searches its bounding box; the view and pointer have their assert.equal(unknown.code, 'AREA_UNKNOWN'); }); -test('a mixed antimeridian area gets the deliberate imagery date-line refusal', async () => { +test('a mixed antimeridian area is searched as its short-arc box', async () => { const square = (w, s, e, n) => [ [w, s], [e, s], @@ -251,6 +251,7 @@ test('a mixed antimeridian area gets the deliberate imagery date-line refusal', [178, 1], [178, 0], ]; + const layer = fakeLayer(); const store = createAreaStore(); const area = store.put({ geometry: [[crossing], [square(-176, 0.2, -174, 0.8)]], @@ -258,11 +259,33 @@ test('a mixed antimeridian area gets the deliberate imagery date-line refusal', source: 'osm', }); assert.deepEqual(area.bbox, [178, 0, -174, 1]); - const result = await findImagery(deps(fakeLayer(), { area }).value, { + const result = await findImagery(deps(layer, { area }).value, { areaId: area.areaId, }); - assert.equal(result.ok, false); - assert.equal(result.code, 'DATELINE'); + assert.equal(result.ok, true, 'the guard is lifted'); + assert.deepEqual(layer.calls.find((c) => c[0] === 'setBox')[1], { + west: 178, + south: 0, + east: -174, + north: 1, + }); +}); + +test('a small area across the date line is pinned at its short-arc centre', async () => { + const layer = fakeLayer(); + await findImagery( + deps(layer, { + area: { + areaId: 'd', + name: 'Dateline Islet', + bbox: [179.998, 0, -179.998, 0.01], + }, + }).value, + { areaId: 'd' }, + ); + const [, lon, lat] = layer.calls.find((c) => c[0] === 'boxFromPinAt'); + assert.ok(Math.abs(Math.abs(lon) - 180) < 1e-9, `pin lon ${lon}, not 0`); + assert.equal(lat, 0.005); }); test('a box the layer refuses is refused with its reason, and the layer is turned on first', async () => {