fix(recent-imagery): keep HLS drapes and empty halves steady when a probe gives no answer

- A Worldview 200 without Data-Present no longer takes an HLS day already on
  the map off it: the source reports only the halves that answered, and the
  renderer drapes a PNG on every part not confirmed empty.
- A re-probe keeps the last explicit answer for each half, so a side confirmed
  empty stays undraped when it does not answer again.
- A host change noticed while rendering after a probe sends a full
  notification, so the panel updates the divider.
- Tests: the short-arc refusal asserts the measured box, the widening test
  expects slot B on top on both sides, and the drape-policy cases are one
  table; the widening test moves into rendering.test.mjs.
- Shared box key and Data-Present parsing; transport errors pass through
  unchanged; unreachable guards and repeated comments removed; docs describe
  partial vs. unknown coverage.
This commit is contained in:
German Khokhlov committed 2026-11-20 19:20:49 +04:00
1 parent 8fd0a35f6a
commit 1f64a9ce44
19 files changed
+348 -272

No files matched your search

+3 -3
View File
@@ -8864,10 +8864,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, 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 (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 dateline: Worldview snapshots cannot`) 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.
- 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.** 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 for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when fewer sides drape than the box contains. 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.
- **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).
@@ -0,0 +1,71 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { until } from '../../testSupport/kartaViewFakes.mjs';
import { createRecentImagerySource } from './source.js';
import { createThumbnailLoader } from './thumbnails.js';
import { createRecentImageryLayer } from './index.js';
import { createRecentImageryRenderer } from './rendering.js';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { candidate } from './testDoubles.mjs';
const PLAIN = { west: -98, south: 30, east: -97, north: 31 };
const answer = (present) =>
new Response('img', {
headers: present === null ? {} : { 'Data-Present': String(present) },
});
function realLayer({ fetchImpl, candidates, maxDecoded = 16 }) {
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs: 5000 });
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('hls-missing-header: a shown HLS day on a plain box stays on the map after a 200 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],
fetchImpl: async () => {
await gate;
return answer(null);
},
});
layer.enable();
layer.setBox(PLAIN);
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 });
const shownA = layer.getSnapshot().shown.a;
assert.equal(
globe.layers.length,
1,
`layers=${globe.layers.length} shown.a=${shownA} availableBoxes=${JSON.stringify(loader.get(day.key).availableBoxes)}`,
);
layer.destroy();
});
@@ -0,0 +1,104 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { until } from '../../testSupport/kartaViewFakes.mjs';
import { createRecentImagerySource } from './source.js';
import { createThumbnailLoader } from './thumbnails.js';
import { nonCrossingBoxes } from './model.js';
import { createRecentImageryLayer } from './index.js';
import { createRecentImageryRenderer } from './rendering.js';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
import { FIJI_BOX, candidate } from './testDoubles.mjs';
const sideOf = (url) =>
Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0
? 'west'
: 'east';
const answer = (present) =>
new Response('img', {
headers: present === null ? {} : { 'Data-Present': String(present) },
});
function realLayer({ fetchImpl, candidates, maxDecoded = 16 }) {
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs: 5000 });
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('hls-remembers-empty: a re-probe with one failed half keeps that half confirmed empty', 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,
fetchImpl: async (url) => {
if (new URL(url).searchParams.get('TIME') === day2.day) {
await gate;
return answer(true);
}
if (sideOf(url) === 'east') {
eastCalls += 1;
if (eastCalls === 1) return answer(false);
throw new TypeError('Failed to fetch');
}
return answer(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();
});
+7 -4
View File
@@ -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,8 +590,8 @@ export function createRecentImageryLayer({
: (slotId === 'a') !== _swapped
? 'left'
: 'right',
// The halves the probe lets this product drape, unknown before it answers.
availableBoxes: thumbnails.get(candidate.key)?.availableBoxes,
availableBoxes,
emptyBoxes,
});
} else {
renderer.hideSlot(slotId);
@@ -904,16 +906,17 @@ export function createRecentImageryLayer({
_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],
);
// 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();
+5
View File
@@ -120,10 +120,15 @@ 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<object>}
*/
+5 -1
View File
@@ -528,7 +528,11 @@ test('boxFromPin returns the short-arc box for a pin near the dateline', () => {
(lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half,
),
);
assert.equal(nonCrossingBoxes(box).length, 2, 'splits for tiling and CMR');
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),
+25 -19
View File
@@ -17,6 +17,7 @@ import { markBaseTileset } from '../../render/baseTilesets.js';
import { drawOf } from '../../render/rendererOf.js';
import {
PRODUCTS,
boxKey,
gibsTemplate,
lonSpanDeg,
nonCrossingBoxes,
@@ -34,25 +35,26 @@ 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(';');
/**
* Without per-half evidence a dateline JPEG waits for the probe because
* an empty side would draw black. Other boxes drape all their parts.
* With evidence, only the listed parts of this box drape.
* 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) {
function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) {
const parts = nonCrossingBoxes(box);
if (!Array.isArray(availableBoxes))
return parts.length > 1 && PRODUCTS[candidate.product]?.format === 'jpg'
? []
: parts;
const listed = new Set(availableBoxes.filter(Boolean).map(boxKey));
return parts.filter((part) => listed.has(boxKey(part)));
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)));
}
/**
@@ -157,20 +159,24 @@ export function createRecentImageryRenderer({
return {
/**
* Drape the available parts of a candidate into a slot. On the same day
* and port, keep each surviving layer, add a new part right above it and
* remove dropped parts.
* 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', availableBoxes?: object[] | null }} [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', availableBoxes = null } = {},
{
alpha = 1,
splitDirection = 'none',
availableBoxes = null,
emptyBoxes = null,
} = {},
) {
if (destroyed || !candidate?.key || !box) return false;
if (!host.globe) {
@@ -179,7 +185,7 @@ export function createRecentImageryRenderer({
}
const current = owned[slotId];
const look = { alpha: clampAlpha(alpha), split: splitDirection };
const parts = drapedParts(candidate, box, availableBoxes);
const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes });
if (
current &&
current.globe === host.globe &&
+44 -2
View File
@@ -6,7 +6,7 @@ import {
createRecentImageryRenderer,
} from './rendering.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { nonCrossingBoxes } from './model.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';
@@ -363,13 +363,35 @@ test('evidence going from none to empty removes the drape', () => {
renderer.showSlot('a', S30, FIJI_BOX);
assert.equal(globe.layers.length, 2);
assert.equal(
renderer.showSlot('a', S30, FIJI_BOX, { availableBoxes: [] }),
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();
@@ -390,6 +412,7 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc
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');
@@ -400,6 +423,7 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc
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);
@@ -408,6 +432,24 @@ test('a probe that narrows or widens a dateline drape keeps the layer of the unc
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 };
@@ -1,37 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRecentImageryRenderer } from './rendering.js';
import { nonCrossingBoxes } from './model.js';
import { FIJI_BOX } from './testDoubles.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
const A = { key: 'S30:2026-09-18', product: 'S30', day: '2026-09-18' };
const B = { key: 'L30:2026-09-16', product: 'L30', day: '2026-09-16' };
test('slot order survives widening', () => {
const renderer = createRecentImageryRenderer();
const globe = fakeGlobePort();
renderer.rebind({ collection: {}, kind: 'globe', globe });
const [west, east] = nonCrossingBoxes(FIJI_BOX);
const k = (b) => [b.west, b.south, b.east, b.north].join(',');
const look = { alpha: 1, splitDirection: 'none' };
renderer.showSlot('a', A, FIJI_BOX, { ...look, availableBoxes: [west] });
renderer.showSlot('b', B, FIJI_BOX, {
...look,
availableBoxes: [west, east],
});
renderer.showSlot('a', A, FIJI_BOX, {
...look,
availableBoxes: [west, east],
});
const topOn = (box) => {
const on = globe.layers.filter((l) => k(l.spec.rectangle) === k(box));
return on.at(-1).spec.url.includes('S30') ? 'A' : 'B';
};
assert.equal(
topOn(west),
topOn(east),
`west top ${topOn(west)}, east top ${topOn(east)}`,
);
renderer.destroy();
});
+22 -60
View File
@@ -1,10 +1,5 @@
import { searchHls } from './catalog.js';
import {
PRODUCTS,
gibsTemplate,
nonCrossingBoxes,
wvsSnapshotUrl,
} from './model.js';
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
/**
* Deadline for one half's response headers, so a day whose other half
@@ -15,42 +10,20 @@ 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. Granules do not cross ±180, so a day has data when
* either half does.
* one normalized half. A day has data when either half does.
*/
function requestBoxes(box) {
const halves = nonCrossingBoxes(box);
if (!halves.length) return [box];
return halves.sort((a, b) => b.east - b.west - (a.east - a.west));
return nonCrossingBoxes(box).sort(
(a, b) => b.east - b.west - (a.east - a.west),
);
}
const isPresent = (response) => dataPresent(response) === 'true';
/**
* Which halves a product may drape. The VIIRS JPEG has no alpha and would
* drape an empty side as a black rectangle, so it drapes only a half
* Worldview confirmed present. An HLS PNG drapes every half not confirmed empty.
*/
const drapesOnlyProven = (candidate) =>
PRODUCTS[candidate?.product]?.format === 'jpg';
const dataPresent = (response) =>
/** 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()
: '';
/**
* Of the halves that answered, prefer the first with data (wider wins a
* tie), then the first not confirmed empty so an unreadable answer is
* never called empty, then the first response.
*/
function combineHalves(responses) {
const present = responses.find(isPresent);
if (present) return present;
const unproven = responses.find((r) => dataPresent(r) !== 'false');
return unproven ?? responses[0];
}
/**
* One half's snapshot fetch, raced against its own deadline so a half that
* never answers, even over a transport that ignores AbortSignal, still
@@ -109,12 +82,11 @@ function probeHalf(
}
/**
* Non-enumerable evidence for the box's non-crossing halves. presentBoxes
* lists the halves this product may drape (see drapesOnlyProven).
* emptyBoxes lists the halves Worldview confirmed empty.
* 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 }) {
if (!response) return response;
Object.defineProperties(response, {
presentBoxes: { value: presentBoxes, configurable: true },
emptyBoxes: { value: emptyBoxes, configurable: true },
@@ -172,30 +144,20 @@ export function createRecentImagerySource({
const answers = results.map((result) =>
result.status === 'fulfilled' ? dataPresent(result.value) : null,
);
const responses = results
.filter((result) => result.status === 'fulfilled')
.map((result) => result.value);
const halvesWhere = (keep) => halves.filter((_, i) => keep(answers[i]));
const emptyBoxes = halvesWhere((answer) => answer === 'false');
if (answers.includes('true'))
return withHalves(combineHalves(responses), {
presentBoxes: halvesWhere(
drapesOnlyProven(candidate)
? (answer) => answer === 'true'
: (answer) => answer !== 'false',
),
emptyBoxes,
});
// A missing answer is an error unless another half proved data.
const failure = results.find((result) => result.status === 'rejected');
if (failure) {
if (failure.reason?.name === 'TimeoutError')
throw new DOMException('Thumbnail request timed out', 'TimeoutError');
throw new Error('Thumbnail request failed');
}
return withHalves(combineHalves(responses), {
presentBoxes: [],
emptyBoxes,
if (failure && !answers.includes('true')) 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;
const halvesWhere = (value) =>
halves.filter((_, i) => answers[i] === value);
return withHalves(results[shown].value, {
presentBoxes: halvesWhere('true'),
emptyBoxes: halvesWhere('false'),
});
},
getTileTemplate: (product, day) => tileTemplate(product, day),
+22 -101
View File
@@ -55,6 +55,7 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt
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',
@@ -65,11 +66,11 @@ test('cancelled thumbnail acquisition does not return stale responses or retry',
},
});
await assert.rejects(
source.getThumbnail({}, {}, { signal: controller.signal }),
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
await assert.rejects(
source.getThumbnail({}, {}, { signal: controller.signal }),
source.getThumbnail({}, box, { signal: controller.signal }),
{ name: 'AbortError' },
);
assert.equal(calls, 1);
@@ -197,85 +198,28 @@ test('a rejected half does not hide data on the other half, and never reads as e
});
await assert.rejects(
failing.source.getThumbnail(candidate, NARROW_WEST),
/Thumbnail request failed/,
/network/,
);
});
test('a JPEG product drapes only the half Worldview confirmed present: a rejected half is not draped', async () => {
const { source } = halvesSource({
'-180/-179': new Error('network'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
assert.equal(
response.headers.get('Data-Present'),
'true',
'the day itself stays present',
);
assert.deepEqual(
response.presentBoxes,
[NARROW_BOX],
'the failed half is not draped',
);
});
test('a JPEG product does not drape a half whose probe hung', async () => {
const requested = [];
const source = createRecentImagerySource({
thumbnailUrl: ({ box }) => {
requested.push(box);
return `https://imagery.example/${box.west}/${box.east}`;
},
halfDeadlineMs: 20,
fetchImpl: async (url) => {
const answer = {
'-180/-179': () => new Promise(() => {}),
'179.9/180': () => dated('true', 'narrow'),
}[url.split('imagery.example/')[1]];
return answer();
},
});
const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
assert.equal(requested.length, 2, 'both halves were requested');
assert.equal(
response.headers.get('Data-Present'),
'true',
'the day itself stays present',
);
assert.deepEqual(
response.presentBoxes,
[NARROW_BOX],
'the hung half is not draped',
);
});
test('a JPEG product does not drape a half that answered with an unknown presence', async () => {
const { source } = halvesSource({
'-180/-179': dated('unknown', 'maybe'),
'179.9/180': dated('true', 'narrow'),
});
const response = await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
assert.equal(response.headers.get('Data-Present'), 'true');
assert.deepEqual(
response.presentBoxes,
[NARROW_BOX],
'an unproven half is not draped',
);
});
test('a PNG product keeps an unknown or failed half: alpha hides it', 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');
assert.deepEqual(
response.presentBoxes,
[WIDE_BOX, NARROW_BOX],
'a PNG keeps the unproven half',
);
});
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();
@@ -339,26 +283,3 @@ test('a successful probe leaves no deadline timer behind', async () => {
assert.equal(timers.armed(), 0);
assert.equal(timers.cleared.length, 2);
});
test('transport rejection does not expose untrusted error details', async () => {
const marker = 'synthetic-secret-do-not-expose-ABC123';
const source = createRecentImagerySource({
thumbnailUrl: () => 'https://example.invalid/',
fetchImpl: () => {
throw new Error(marker);
},
});
await assert.rejects(
source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST),
(error) => {
assert.equal(error.message, 'Thumbnail request failed');
assert.equal(
`${error.stack} ${JSON.stringify(error)} ${error.cause}`.includes(
marker,
),
false,
);
return true;
},
);
});
+19 -17
View File
@@ -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,8 +8,8 @@
* 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',
@@ -20,14 +20,16 @@ const EMPTY = Object.freeze({
loading: false,
});
const halfKey = (box) => [box.west, box.south, box.east, box.north].join(',');
/** Keep earlier proof on a re-probe unless the new answer confirms that half empty. */
function keepProvenHalves(previous, next, empty) {
if (!Array.isArray(previous) || !Array.isArray(next) || !Array.isArray(empty))
/** On a re-probe, keep earlier halves of one answer (present or empty) unless the new probe answered them the other way. */
function keepProvenHalves(previous, next, opposite) {
if (
!Array.isArray(previous) ||
!Array.isArray(next) ||
!Array.isArray(opposite)
)
return next;
const drop = new Set([...next, ...empty].map(halfKey));
return [...next, ...previous.filter((half) => !drop.has(halfKey(half)))];
const drop = new Set([...next, ...opposite].map(boxKey));
return [...next, ...previous.filter((half) => !drop.has(boxKey(half)))];
}
/**
@@ -102,7 +104,7 @@ export function createThumbnailLoader({
let status = 'error';
let objectUrl = null;
let acquisitionTime = null;
// The halves the probe lets this product drape, or null without a per-half probe.
// Per-half evidence (see withHalves in source.js), or null without it.
let availableBoxes = null;
let emptyBoxes = null;
let cancelled = false;
@@ -114,9 +116,7 @@ export function createThumbnailLoader({
if (controller.signal.aborted) {
cancelled = true;
} else if (response?.ok) {
const present = String(
response.headers?.get?.('Data-Present') ?? '',
).toLowerCase();
const present = dataPresent(response);
availableBoxes = response.presentBoxes ?? null;
emptyBoxes = response.emptyBoxes ?? null;
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
@@ -147,14 +147,16 @@ export function createThumbnailLoader({
return;
}
// A failed re-fetch of an evicted image keeps what the day proved.
// A re-probe drops a half only on a fresh "empty".
if (status !== 'error' || entry.status !== 'present') {
if (status === 'present' && entry.status === 'present')
if (status === 'present' && entry.status === 'present') {
const fresh = availableBoxes;
availableBoxes = keepProvenHalves(
entry.availableBoxes,
availableBoxes,
fresh,
emptyBoxes,
);
emptyBoxes = keepProvenHalves(entry.emptyBoxes, emptyBoxes, fresh);
}
entry.status = status;
entry.acquisitionTime = acquisitionTime;
entry.availableBoxes = availableBoxes;
+1 -1
View File
@@ -55,7 +55,7 @@ export const getRecentImagery = defineTool({
if (box.west > box.east)
throw new ToolError(
'invalid_arguments',
'The area must not cross the dateline: Worldview snapshots cannot',
'The area must not cross the antimeridian',
);
let latest;
try {
+1 -1
View File
@@ -102,7 +102,7 @@ test('overview fallback, empty results and invalid areas are reported', async ()
wrapped.call('get_recent_imagery', {
area: { bbox: [179, 0, -179, 1] },
}),
/must not cross the dateline/,
/must not cross the antimeridian/,
);
assert.equal(crossing.snapshots.length, 0);
assert.equal(crossing.boxes.length, 0);
+1 -1
View File
@@ -53,7 +53,7 @@ export function initImageryBoxTool({
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.
// the dateline: west gets the larger longitude, east the smaller.
const crosses = hi - lo > 180;
return {
west: crosses ? hi : lo,
+11 -2
View File
@@ -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';
@@ -230,11 +231,19 @@ test('a drag whose short arc is still over the size limit is refused as too larg
lon: nx < 0.5 ? 100 : -100,
lat: ny,
});
const f = fixture({ pickWorld });
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);
assert.equal(f.cancels.at(-1)[0], 'too-large');
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();
});
-7
View File
@@ -529,7 +529,6 @@ export function createRecentImageryPanel({
function exportsView() {
const ab = snapshot.mode === 'ab';
// Worldview Snapshots rejects a crossing BBOX: say so up front.
const crossing = Boolean(
snapshot.box && snapshot.box.west > snapshot.box.east,
);
@@ -781,12 +780,6 @@ 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);
+1 -2
View File
@@ -992,11 +992,10 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX
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');
// The exportImage guard stays as a backstop.
assert.equal(await f.readout.exportImage('a'), false);
assert.equal(
f.byId('ri-notice-text').textContent,
'Select one side of the dateline',
'Export failed · A snapshot cannot cross the dateline',
);
assert.equal(
f.fetches.length,
+6 -14
View File
@@ -13,26 +13,18 @@ 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 }, 'too-large'],
[{ 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 }, 'invalid'],
[{ west: Number.NaN, south: 10, east: 20, north: 20 }, 'invalid'],
].map(([box, reason]) => {
{ 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);
assert.equal(result.reason, reason);
return result.message;
}),
];
test('a dateline box is measured on its short arc', () => {
assert.equal(
validateBox({ west: 179, south: 0, east: -179, north: 1 }).ok,
true,
);
});
test('en: refusals stay English', () => {
setLocale('en');
for (const text of REFUSALS) {