fix(recent-imagery): take the short arc when a box is dragged across the dateline

A drag across ±180° was turned into a min/max box about 360° wide and refused
as "Box is 38,332 km wide", and validateBox() refused any west > east box. A
drag whose corners are more than 180° apart is now the short box (west > east),
and the layer handles it end to end:

- model: lonSpanDeg() and nonCrossingBoxes(); validateBox, boxSideKm,
  boxCentre, boxFromPin and coverageFor read a west > east box as the short arc.
- catalog: CMR reads a west > east bounding_box as the short box, so the box
  is sent as it is.
- rendering: the slot drapes one imagery layer per side of ±180°.
- Worldview Snapshots rejects a west > east BBOX, so snapshot URLs, EXPORT and
  get_recent_imagery refuse a dateline box and request nothing; thumbnail and
  Data-Present probes use the box's wider side.
This commit is contained in:
Byrd-IT committed 2026-11-13 17:12:47 -06:00
1 parent 7df581765d
commit ca14954636
16 files changed
+503 -70

No files matched your search

+3 -3
View File
@@ -7276,10 +7276,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, a box across the dateline sent as one bounding box with west > east, which CMR reads as the short box, 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 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, returned with west > east; its width is the short arc, so only a short arc over the cap is refused as too large. Worldview Snapshots rejects a west > east BBOX, so EXPORT and `get_recent_imagery` refuse a dateline box (`Select one side of the dateline`) without requesting one, and its thumbnails and Data-Present probes use the box's wider side. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
- **Rendering.** `rendering.js` owns at most two slots (a dateline box drapes two GIBS layers in its slot, one each side of ±180) on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes.
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
- **Panel.** `#recent-imagery-panel` is 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).
+18 -2
View File
@@ -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}` }));
+15
View File
@@ -1395,3 +1395,18 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy
assert.equal(f.snap().searching, false);
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°');
});
+85 -21
View File
@@ -76,8 +76,8 @@ 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.
* east are not swapped: west > east is the short arc across the dateline.
* 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) {
@@ -105,8 +105,39 @@ 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 from `west` to `east`. A west > east box is the short
* arc across the antimeridian. A west <= east box is unchanged, even when
* that span is 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;
}
/**
* 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. An invalid box is [].
* @param {object} box Degrees box.
* @returns {Array<object>}
*/
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 +147,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 +157,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 +169,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 +177,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,22 +214,28 @@ 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}
*/
export function boxCentre(box) {
const normalized = normalizeBox(box);
if (!normalized) return null;
let lon = normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2;
if (lon > 180) lon -= 360;
return {
lon: (normalized.west + normalized.east) / 2,
lon,
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 +244,21 @@ 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 wrapLon = (value) =>
value > 180 ? value - 360 : value < -180 ? value + 360 : value;
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;
@@ -444,15 +486,33 @@ 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) => {
if (!crossing) return lon;
if (lon >= west) return lon;
if (lon <= east) return lon + 360;
return west - lon <= lon - east ? lon : lon + 360;
};
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';
@@ -601,6 +661,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,
+116 -9
View File
@@ -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.1), ring(-180.1, -178.9)), box),
'full',
'a pair split 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,48 @@ 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 CMR');
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);
});
+44 -19
View File
@@ -1,13 +1,16 @@
/**
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
* imagery layers (slot `a`, left of a swipe; slot `b`, right) on whichever
* host the map stack offers. Against the basemap slot `a` splits left and
* slot `b` stays empty. Every layer is removed from the collection that owns it, so a
* host switch or a replaced image never strands one. Tile requests pass a
* small semaphore of our own; Cesium's global request limits stay untouched.
* Draped-imagery renderer for the Recent Imagery layer: at most two slots
* (slot `a`, left of a swipe; slot `b`, right) on whichever host the map
* stack offers. A box that crosses the dateline drapes two imagery layers
* in that slot, one on each side of ±180, each a plain west <= east
* rectangle (see `nonCrossingBoxes`). Against the
* basemap slot `a` splits left and slot `b` stays empty. Every layer is
* removed from the collection that owns it, so a host switch or a replaced
* image never strands one. Tile requests pass a small semaphore of our own;
* Cesium's global request limits stay untouched.
*/
import * as Cesium from 'cesium';
import { PRODUCTS, gibsTemplate } from './model.js';
import { PRODUCTS, gibsTemplate, nonCrossingBoxes } from './model.js';
const SLOT_IDS = ['a', 'b'];
const SPLIT_ENUM = { left: 'LEFT', right: 'RIGHT', none: 'NONE' };
@@ -80,7 +83,7 @@ export function createRecentImageryRenderer({
let host = NO_HOST;
let destroyed = false;
const admission = { limit: maxTileRequests, inFlight: 0 };
/** @type {Record<'a'|'b', null | { layer: object, collection: object, candidate: object, box: object, alpha: number, split: string }>} */
/** @type {Record<'a'|'b', null | { layers: Array<object>, collection: object, candidate: object, box: object, alpha: number, split: string }>} */
const owned = { a: null, b: null };
// One timer for both slots: any number of upstream deferrals while it is
@@ -124,26 +127,48 @@ export function createRecentImageryRenderer({
const record = owned[slotId];
if (!record) return false;
owned[slotId] = null;
try {
record.collection.remove(record.layer, true);
} catch {
/* the collection is already gone */
for (const layer of record.layers) {
try {
record.collection.remove(layer, true);
} catch {
/* the collection is already gone */
}
}
return true;
}
function applyLook(record) {
record.layer.alpha = record.alpha;
record.layer.splitDirection =
const alpha = record.alpha;
const splitDirection =
cesium.SplitDirection?.[SPLIT_ENUM[record.split] || 'NONE'] ?? 0;
for (const layer of record.layers) {
layer.alpha = alpha;
layer.splitDirection = splitDirection;
}
}
function mount(slotId, { candidate, box, alpha, split }) {
const layer = host.collection.addImageryProvider(
createProvider(candidate, box),
);
const rectangles = nonCrossingBoxes(box);
const parts = rectangles.length ? rectangles : [box];
// Build every provider before adding any layer, so a throw on the second
// half of a dateline box cannot leave the first layer untracked.
const providers = parts.map((part) => createProvider(candidate, part));
const layers = [];
try {
for (const provider of providers)
layers.push(host.collection.addImageryProvider(provider));
} catch (error) {
for (const layer of layers) {
try {
host.collection.remove(layer, true);
} catch {
/* the collection is already gone */
}
}
throw error;
}
owned[slotId] = {
layer,
layers,
collection: host.collection,
candidate,
box,
@@ -248,7 +273,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 two imagery layers in its slot. */
ownedCount() {
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
},
@@ -227,3 +227,63 @@ test('replacement imagery uses source-owned tile URLs and credit and tears down
assert.equal(globe.layers.length, 0);
assert.equal(layer.destroyed, true);
});
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.provider.options.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].splitDirection, -1);
assert.equal(globe.layers[1].splitDirection, -1);
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.layers.length, 2, 'the same box does not remount');
renderer.hideSlot('a');
assert.equal(globe.layers.length, 0);
});
test('a dateline provider that fails on the second half adds no layer', () => {
let built = 0;
const base = fakeCesium();
const Provider = base.UrlTemplateImageryProvider;
base.UrlTemplateImageryProvider = class extends Provider {
constructor(options) {
built += 1;
if (built === 2) throw new Error('provider failed');
super(options);
}
};
const renderer = createRecentImageryRenderer({
cesium: base,
requestRender: () => {},
});
const globe = fakeCollection();
renderer.rebind({ collection: globe, kind: 'globe' });
assert.throws(
() =>
renderer.showSlot('a', S30, {
west: 179,
south: 0,
east: -179,
north: 1,
}),
/provider failed/,
);
assert.equal(globe.layers.length, 0);
assert.equal(renderer.ownedCount(), 0);
});
+17 -2
View File
@@ -1,5 +1,20 @@
import { searchHls } from './catalog.js';
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
/**
* Worldview Snapshots rejects a BBOX with west > east, so a dateline box is
* probed on its wider side. That is enough for the Data-Present answer, and
* the thumbnail shows that side.
*/
function requestBox(box) {
if (!(box?.west > box?.east)) return box;
const halves = nonCrossingBoxes(box);
return halves.reduce(
(wider, half) =>
half.east - half.west > wider.east - wider.west ? half : wider,
halves[0] ?? box,
);
}
/**
* NASA-compatible imagery acquisition; transport and URL builders are replaceable.
@@ -22,7 +37,7 @@ export function createRecentImagerySource({
thumbnailUrl({
product: candidate.product,
day: candidate.day,
box,
box: requestBox(box),
width: size,
height: size,
}),
+37
View File
@@ -40,3 +40,40 @@ test('cancelled thumbnail acquisition does not return stale responses or retry',
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
assert.equal(calls, 1);
});
test('a dateline thumbnail is requested for the wider side, 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.at(-1), {
west: -180,
south: 0,
east: -179,
north: 1,
});
await source.getThumbnail(candidate, {
west: 179,
south: 0,
east: -179.9,
north: 1,
});
assert.deepEqual(requested.at(-1), {
west: 179,
south: 0,
east: 180,
north: 1,
});
assert.ok(requested.every((box) => box.west <= box.east));
});
+7 -5
View File
@@ -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',
'A snapshot cannot cross the dateline',
);
let latest;
try {
latest = await services.imagery.latest({ box, signal });
+22 -1
View File
@@ -82,8 +82,29 @@ 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] },
}),
/snapshot cannot cross the dateline/,
);
assert.equal(crossing.snapshots.length, 0);
await assert.rejects(
none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }),
/±85° latitude/,
+13 -4
View File
@@ -23,6 +23,8 @@ export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps
* `onEscape` runs before the tool cancels on Escape; returning `true` claims
* the key (it is still consumed) and leaves the tool armed.
* A drag whose corners are more than 180 degrees of longitude apart is the
* short box across the dateline, returned with west > east.
* @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise<void> } | null}
*/
export function initImageryBoxTool({
@@ -48,13 +50,20 @@ export function initImageryBoxTool({
let savedDoubleClick = null;
let savedCameraInputs = 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 is the eastern corner and east the western one.
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 dataSource = new cesium.CustomDataSource(
'gev-recent-imagery-box-preview',
+29
View File
@@ -152,3 +152,32 @@ 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 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.equal(f.boxes.length, 0);
assert.equal(f.cancels.at(-1)[0], 'too-large');
await f.tool.destroy();
});
+8 -1
View File
@@ -22,6 +22,7 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
import {
PRODUCTS,
hhmm,
lonSpanDeg,
wvsSnapshotUrl,
} from '../layers/recentImagery/model.js';
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
@@ -766,13 +767,19 @@ export function createRecentImageryPanel({
const candidate = exportTarget(slotId);
if (destroyed || !candidate || !snapshot.box || exporting.has(slotId))
return false;
// Worldview Snapshots rejects a west > east BBOX: say so, request nothing.
if (snapshot.box.west > snapshot.box.east) {
exportError = t('Select one side of the dateline');
preserveScroll(paint);
return false;
}
exporting.add(slotId);
exportError = null;
preserveScroll(paint);
// The snapshot is plate carrée: keep the box's degree aspect, with the
// longer side at the size limit.
const size = longerSideKm(snapshot.boxSizeKm) > 25 ? 2048 : 1024;
const spanLon = Math.abs(snapshot.box.east - snapshot.box.west) || 1;
const spanLon = lonSpanDeg(snapshot.box.west, snapshot.box.east) || 1;
const spanLat = Math.abs(snapshot.box.north - snapshot.box.south) || 1;
const width = Math.max(
1,
+20
View File
@@ -968,6 +968,26 @@ 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',
);
assert.equal(await f.readout.exportImage('a'), false);
assert.equal(
f.byId('ri-notice-text').textContent,
'Select one side of the dateline',
);
assert.equal(
f.fetches.length,
before,
'export does not request a crossing BBOX',
);
f.layer.setMode('ab');
assert.deepEqual(
[
+9 -3
View File
@@ -14,7 +14,7 @@ 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: 170, south: 10, east: -170, north: 20 }, // too large (dateline arc)
{ 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
@@ -37,8 +37,14 @@ const SHOWN_EN = new Map([
test('en: refusals stay English', () => {
setLocale('en');
for (const text of REFUSALS)
assert.equal(localizeNotice(text), SHOWN_EN.get(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')
: (SHOWN_EN.get(text) ?? text);
assert.equal(shown, expected);
}
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
});