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

+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'));
});