mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 11:42:21 +00:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b880cf42c0 | ||
|
|
f5b2867752 | ||
|
|
e51853de3d | ||
|
|
46f8ea16c0 | ||
|
|
3973772b83 | ||
|
|
8604968746 | ||
|
|
1f64a9ce44 | ||
|
|
8fd0a35f6a | ||
|
|
e71ed72272 | ||
|
|
5555aba82c | ||
|
|
fc137bef85 | ||
|
|
ccffaeca4d | ||
|
|
154d3388e5 | ||
|
|
fb3f921ac7 | ||
|
|
797bd25841 | ||
|
|
5f1c230b52 | ||
|
|
6b216b3534 | ||
|
|
b2a6aa4d9f | ||
|
|
7b76525528 | ||
|
|
eeda6d51d1 | ||
|
|
9924cb15eb | ||
|
|
d60f2420f4 | ||
|
|
9a34d63f1d | ||
|
|
ca14954636 |
No files matched your search
@@ -51,12 +51,6 @@ GOOGLE_MAPS_SERVER_API_KEY=
|
||||
# Quotas).
|
||||
# GEV_RATELIMIT_GOOGLE_PER_MIN=60 # uncomment to tighten from the default 120
|
||||
|
||||
# Optional: per-IP requests/minute for the keyless adsbdb aircraft-enrichment
|
||||
# proxy (/api/adsbdb). DEFAULTS TO 720: one tab's two enrichment queues
|
||||
# (Flights and Local ADS-B) top out at 600. Same rules as above: 0 disables,
|
||||
# an unreadable value takes the default.
|
||||
# GEV_RATELIMIT_ADSBDB_PER_MIN=720
|
||||
|
||||
# Optional: Google Photorealistic 3D Tiles through Cesium ion, Bing world
|
||||
# imagery, and Cesium World Terrain. The free Community plan is for eligible
|
||||
# personal/non-commercial use and has quotas; check current Cesium terms. A
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
- Recent Imagery takes a box dragged across the dateline as the short box across
|
||||
±180° instead of refusing it as about 360° wide. A day counts when either side
|
||||
has imagery. A side confirmed empty is not draped, and the VIIRS overview
|
||||
drapes only a side confirmed to have data. Voice accepts named areas across
|
||||
the dateline. EXPORT and `get_recent_imagery` refuse such a box, since
|
||||
Worldview Snapshots cannot draw one (Byrd-IT, #1540).
|
||||
@@ -0,0 +1,6 @@
|
||||
- The app opens with the loading screen's logo turning into the globe: the
|
||||
eye's arcs fly out, the planet in the pupil becomes the real globe, which
|
||||
spins, grows and stops with the whole planet in view over your country, taken
|
||||
from the browser's time zone. The title's logo goes back to that view. A
|
||||
share link, a Stories link, reduced motion and `?intro=0` open as before
|
||||
(gekh, #1909).
|
||||
@@ -1,13 +0,0 @@
|
||||
- Bound the adsbdb enrichment proxy. `/api/adsbdb` had no request limit and no
|
||||
cache eviction, so a caller cycling through the callsign or hex keyspace
|
||||
could drive unlimited live requests at the free community API and grow
|
||||
`.gev-cache/adsbdb.json` without end — every distinct key, 404s included, was
|
||||
remembered forever. The route now admits 720 requests/minute per client
|
||||
address (`GEV_RATELIMIT_ADSBDB_PER_MIN`; one tab's two enrichment queues top
|
||||
out at 600), refusing the rest with 429 and `Retry-After` before any cache,
|
||||
disk or upstream work. A refused lookup is asked for again once the refusal
|
||||
has passed instead of leaving that aircraft without metadata for the
|
||||
session. Each cache holds at most 20,000 entries, dropping the
|
||||
least-recently-written first, and entries past the existing 24-hour TTL are
|
||||
discarded when the file is read back. Cached answers and response shapes are
|
||||
unchanged (daikaginza, #689).
|
||||
+3
-22
@@ -4350,25 +4350,6 @@ The existing aircraft normalizer is separately available through the portable
|
||||
`gods-eye-view/sources/adsb-lol` export. Provider URLs, local credentials, cache
|
||||
policy, fallback behavior, response shapes and rendering remain unchanged.
|
||||
|
||||
### ADSBDB enrichment bounds
|
||||
|
||||
`/api/adsbdb` admits 720 requests/minute per client address
|
||||
(`GEV_RATELIMIT_ADSBDB_PER_MIN`; `0` disables), with a global backstop of three
|
||||
times that; a refused request answers 429 with `Retry-After` and reaches
|
||||
neither the cache nor api.adsbdb.com. Each browser enrichment queue drips at
|
||||
most 300/minute and one tab runs two (Flights and Local ADS-B), so an ordinary
|
||||
session never meets the limit. When a lookup is refused anyway, both queues
|
||||
make that key askable again after the refusal's retry-after rather than
|
||||
treating the 429 as an answer.
|
||||
|
||||
Both enrichment caches hold at most 20,000 entries each, dropping the
|
||||
least-recently-written first, and entries past their 24-hour TTL are discarded
|
||||
when `.gev-cache/adsbdb.json` is read back. A cache file above 16 MB is skipped
|
||||
rather than parsed. An evicted key costs one upstream request the next time it
|
||||
is asked for; cached answers are otherwise unchanged.
|
||||
|
||||
Updated: October 23, 2026
|
||||
|
||||
## Control names for assistive technology
|
||||
|
||||
Scope, Bloom, Sharpen and location search have explicit accessible names.
|
||||
@@ -8909,10 +8890,10 @@ coordinates. Valid finite numeric edges remain accepted; the app’s drag tool,
|
||||
pins and share links already supply complete boxes.
|
||||
|
||||
- The layer sits in the Data Layers panel's Cameras group beside Cameras (CCTV); Mapped ALPR Cameras moved to the Infrastructure group to make room.
|
||||
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
|
||||
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
|
||||
- DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. CMR gets a box across the dateline as one bounding box with west > east and reads it as the short box. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes.
|
||||
- **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side and inside the Web-Mercator limit (`validateBox`). A drag whose corners are more than 180° of longitude apart is the short box across the dateline (west > east), measured on that short arc. The draw port previews the wrapped rectangle and its dashed outline during the drag. Worldview Snapshots rejects a west > east BBOX, so EXPORT (`Select one side of the dateline`) and `get_recent_imagery` (`The area must not cross the antimeridian`) refuse a dateline box without requesting one. A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height.
|
||||
- **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. When that day probes empty the next ranked day takes over, and focus still on the empty day moves with it, so the successor drapes once its probe says present; a day the user picked meanwhile, still being probed or debounced, keeps the slot instead (and the Esri lease while it waits), and if that pick probes empty, fails, loses its source or gives way to an empty card the hand-over goes ahead. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied.
|
||||
- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
|
||||
- **Rendering.** Each of the two slots owns up to two GIBS layers through the renderer's globe port, one on each side of ±180° for a dateline box. `src/maps/imageryHost.js` resolves the surface: the globe while it shows, the photoreal tileset while the globe is hidden, or none (the panel says so). The port moves layers between surfaces. A new port rebuilds them. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. A dateline probe requests both sides of ±180 concurrently, starting the wider side first. Each has a 15 s header deadline, and caller cancellation reaches both. Either side with data makes the day present. Only two confirmed-empty sides make it empty. A failed or timed-out request leaves that side unproven. Both products omit confirmed-empty sides. VIIRS drapes only confirmed imagery because its JPEG would show an empty side as black. HLS can also drape an unproven side. A re-probe keeps earlier proof, present or empty, for a side it could not reach and reuses the layers when the draped rectangles stay the same. DETAILS shows coverage `partial` when a side is confirmed empty and `unknown` when a side is only unproven. Thumbnails: three days probed at once (two fetches each for a dateline box), sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. A thumbnail request pass over a non-empty strip ends with `retain()`, which cancels queued and in-flight work for days it no longer wants (focus, visible range, pins, sources, the empty-day filter, a share link); a cancelled day already probed present keeps its status. When an automatic day probes empty, its successor is requested again, since scrolling may have cancelled that probe.
|
||||
- **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape.
|
||||
- **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once.
|
||||
- **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off).
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env node
|
||||
// Writes src/data/homeCountries.js: each time zone's country, and where the
|
||||
// opening stops over that country.
|
||||
//
|
||||
// node scripts/build-home-countries.mjs [path/to/zone.tab]
|
||||
//
|
||||
// Zones come from tzdata's zone.tab (macOS and most Linux systems ship it at
|
||||
// /usr/share/zoneinfo/zone.tab), with the older names ICU still reports for
|
||||
// some of them (Asia/Calcutta for Asia/Kolkata): a browser may give either.
|
||||
// A country's point is the centroid of its largest part in the Natural Earth
|
||||
// countries pack (the contiguous United States, mainland France), or the
|
||||
// zone's own place where the pack has no such country.
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { geometryOf } from '../src/data/adminBoundaries.js';
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const zoneTab = process.argv[2] ?? '/usr/share/zoneinfo/zone.tab';
|
||||
const pack = JSON.parse(
|
||||
readFileSync(
|
||||
new URL('src/data/local_data/natural_earth/countries.json', root),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const out = new URL('src/data/homeCountries.js', root);
|
||||
|
||||
const round = (value) => Math.round(value * 10) / 10;
|
||||
|
||||
/** ISO 6709 `±DDMM[SS]±DDDMM[SS]` → [lat, lon]. */
|
||||
function iso6709(text) {
|
||||
const [, lat, lon] = text.match(/^([+-]\d+)([+-]\d+)$/);
|
||||
const part = (s, degreeDigits) => {
|
||||
const sign = s[0] === '-' ? -1 : 1;
|
||||
const d = s.slice(1);
|
||||
const deg = Number(d.slice(0, degreeDigits));
|
||||
const min = Number(d.slice(degreeDigits, degreeDigits + 2));
|
||||
const sec = Number(d.slice(degreeDigits + 2) || 0);
|
||||
return sign * (deg + min / 60 + sec / 3600);
|
||||
};
|
||||
return [part(lat, 2), part(lon, 3)];
|
||||
}
|
||||
|
||||
const largest = new Map();
|
||||
for (const feature of pack.features) {
|
||||
if (feature.type !== 'Country' || !/^[A-Z]{2}$/.test(feature.iso2)) continue;
|
||||
const geometry = geometryOf({ feature, decimals: pack.meta.decimals });
|
||||
const held = largest.get(feature.iso2);
|
||||
if (!held || geometry.areaKm2 > held.areaKm2)
|
||||
largest.set(feature.iso2, geometry);
|
||||
}
|
||||
|
||||
const zones = new Map();
|
||||
const centres = new Map();
|
||||
const icuName = (zone) => {
|
||||
try {
|
||||
return new Intl.DateTimeFormat('en', { timeZone: zone }).resolvedOptions()
|
||||
.timeZone;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
for (const line of readFileSync(zoneTab, 'utf8').split('\n')) {
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const [country, place, zone] = line.split('\t');
|
||||
zones.set(zone, country);
|
||||
const icu = icuName(zone);
|
||||
if (icu && icu !== zone && !zones.has(icu)) zones.set(icu, country);
|
||||
if (centres.has(country)) continue;
|
||||
const label = largest.get(country)?.label;
|
||||
centres.set(
|
||||
country,
|
||||
label ? [round(label.lat), round(label.lon)] : iso6709(place).map(round),
|
||||
);
|
||||
}
|
||||
|
||||
const sortedEntries = (map) =>
|
||||
[...map].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
const lines = [
|
||||
'// Generated by scripts/build-home-countries.mjs. Do not edit by hand.',
|
||||
'// Sources: tzdata zone.tab (public domain) and the Natural Earth countries',
|
||||
'// pack in src/data/local_data/natural_earth (public domain).',
|
||||
'',
|
||||
'/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */',
|
||||
'export const COUNTRY_CENTRES = {',
|
||||
...sortedEntries(centres).map(
|
||||
([country, [lat, lon]]) => ` ${country}: [${lat}, ${lon}],`,
|
||||
),
|
||||
'};',
|
||||
'',
|
||||
'/** Time zone (tzdata and ICU names) → ISO 3166 country. */',
|
||||
'export const ZONE_COUNTRIES = {',
|
||||
...sortedEntries(zones).map(
|
||||
([zone, country]) => ` '${zone}': '${country}',`,
|
||||
),
|
||||
'};',
|
||||
'',
|
||||
];
|
||||
writeFileSync(out, lines.join('\n'));
|
||||
console.log(
|
||||
`${fileURLToPath(out)}: ${centres.size} countries, ${zones.size} zones`,
|
||||
);
|
||||
@@ -1703,7 +1703,5 @@
|
||||
"src/ui/livePanel.test.mjs",
|
||||
"src/ui/stationPanel.test.mjs",
|
||||
"src/ui/styles/live.css",
|
||||
"src/ui/styles/station.css",
|
||||
"src/adsbdbCacheGovernor.test.mjs",
|
||||
"src/layers/enrichmentRateLimitRetry.test.mjs"
|
||||
"src/ui/styles/station.css"
|
||||
]
|
||||
@@ -392,8 +392,6 @@
|
||||
"server/providers/common/compress.js",
|
||||
"server/providers/common/http.js",
|
||||
"server/providers/common/query.js",
|
||||
"server/providers/common/rate-limit.js",
|
||||
"src/sources/rateLimit.js",
|
||||
"server/providers/aircraft/opensky.js",
|
||||
"server/providers/aircraft/adsb-lol.js",
|
||||
"server/providers/aircraft/enrichment.js",
|
||||
@@ -4305,6 +4303,7 @@
|
||||
"src/render/contract/index.js",
|
||||
"src/sources/sourceSlot.js",
|
||||
"src/app/sources.js",
|
||||
"src/app/openingIntro.js",
|
||||
"src/app/startupChrome.js",
|
||||
"src/app/stateChannel.js",
|
||||
"src/app/surfaceServices.js",
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import path from 'node:path';
|
||||
import { promises as fsp } from 'node:fs';
|
||||
import {
|
||||
makeRateLimiter,
|
||||
clientKey,
|
||||
resolvePerMinuteCap,
|
||||
} from '../common/rate-limit.js';
|
||||
import { readResponseJsonCapped } from '../common/http.js';
|
||||
|
||||
/** Route and aircraft lookups are a few hundred bytes; 1 MiB is a hard bound. */
|
||||
@@ -17,126 +12,29 @@ const ADSBDB_MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
* cached. Adapted from skylight
|
||||
* (MIT) server/src/enrich/routes.ts.
|
||||
*/
|
||||
export function adsbdbProxy(options = {}) {
|
||||
// Destructured in the body, not the signature: `proxyErrorResponses.test.mjs`
|
||||
// extracts these proxies by slicing to the first closing brace in column zero.
|
||||
const {
|
||||
cacheMaxEntries = 20_000,
|
||||
cacheMaxDiskBytes = 16 * 1024 * 1024,
|
||||
cachePath,
|
||||
} = options;
|
||||
export function adsbdbProxy() {
|
||||
const TTL_MS = 24 * 3600_000;
|
||||
const CACHE_PATH =
|
||||
cachePath || path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
|
||||
/**
|
||||
* Entry ceiling per store.
|
||||
*
|
||||
* Both keyspaces are enumerable by the caller — a callsign is 2-8 of
|
||||
* `[A-Z0-9]`, a hex is six of `[0-9a-f]` — and every distinct key that
|
||||
* reaches upstream is cached, 404s included. Without a ceiling the maps, and
|
||||
* the file they are written to, grow for as long as a caller keeps asking.
|
||||
* Sized from a real session's own file: `.gev-cache/adsbdb.json` held 397
|
||||
* aircraft entries (~100 B each) and 3 route entries (~231 B each), so
|
||||
* 20,000 per store is roughly fifty times an ordinary working set and still
|
||||
* bounds the file at about 7 MB.
|
||||
*/
|
||||
const CACHE_MAX_ENTRIES = cacheMaxEntries;
|
||||
const CACHE_MAX_DISK_BYTES = cacheMaxDiskBytes;
|
||||
/**
|
||||
* Requests/minute/IP (`GEV_RATELIMIT_ADSBDB_PER_MIN`; unset takes the
|
||||
* default, `0` disables). Each browser queue drips at most five lookups a
|
||||
* second (`ENRICH_DISPATCH_GAP_MS`, 200 ms), and one tab can run two — the
|
||||
* Flights layer's and Local ADS-B's — so a real session tops out at 600.
|
||||
* The assistant's aviation tools look up through the same source, unqueued
|
||||
* but one at a time per tool call. 720 leaves all of that untouched while
|
||||
* still capping an enumerating caller. The global backstop is the usual
|
||||
* generous multiple.
|
||||
*/
|
||||
const RATE_PER_MIN = resolvePerMinuteCap(
|
||||
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN,
|
||||
720,
|
||||
);
|
||||
const allow =
|
||||
RATE_PER_MIN > 0
|
||||
? makeRateLimiter({
|
||||
windowMs: 60_000,
|
||||
max: RATE_PER_MIN,
|
||||
globalMax: RATE_PER_MIN * 3,
|
||||
})
|
||||
: () => true;
|
||||
// Maps, not plain objects: `size` is O(1), so the ceiling can be enforced on
|
||||
// every write, and iteration is true insertion order (an all-digit callsign
|
||||
// like "1234" would sort ahead of everything else as an object key).
|
||||
let cache = { routes: new Map(), aircraft: new Map() };
|
||||
const CACHE_PATH = path.join(process.cwd(), '.gev-cache', 'adsbdb.json');
|
||||
let cache = { routes: {}, aircraft: {} };
|
||||
let dirty = false;
|
||||
let loaded = false;
|
||||
const inflight = new Map();
|
||||
|
||||
/** Rehydrate one store, dropping entries that expired while we were down. */
|
||||
function toStore(raw) {
|
||||
const store = new Map();
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of Object.entries(raw ?? {})) {
|
||||
const at = Number(entry?.at);
|
||||
if (!Number.isFinite(at) || now - at >= TTL_MS) continue;
|
||||
store.set(key, entry);
|
||||
}
|
||||
prune(store);
|
||||
return store;
|
||||
}
|
||||
|
||||
/** Hold the store at its ceiling, dropping least-recently-written first. */
|
||||
function prune(store) {
|
||||
while (store.size > CACHE_MAX_ENTRIES) {
|
||||
const oldest = store.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
store.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
/** Write `key` as the newest entry, then restore the ceiling. */
|
||||
function remember(store, key, entry) {
|
||||
store.delete(key); // re-insert so insertion order tracks last write
|
||||
store.set(key, entry);
|
||||
prune(store);
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
async function loadOnce() {
|
||||
if (loaded) return;
|
||||
loaded = true;
|
||||
let sizeBytes = null;
|
||||
try {
|
||||
sizeBytes = (await fsp.stat(CACHE_PATH)).size;
|
||||
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
|
||||
cache = { routes: parsed.routes ?? {}, aircraft: parsed.aircraft ?? {} };
|
||||
} catch {
|
||||
sizeBytes = null; // cannot measure it — let the read below decide
|
||||
}
|
||||
if (sizeBytes !== null && sizeBytes > CACHE_MAX_DISK_BYTES) {
|
||||
console.warn('[adsbdb-proxy] cache file above ceiling — starting empty');
|
||||
} else {
|
||||
try {
|
||||
const parsed = JSON.parse(await fsp.readFile(CACHE_PATH, 'utf8'));
|
||||
cache = {
|
||||
routes: toStore(parsed.routes),
|
||||
aircraft: toStore(parsed.aircraft),
|
||||
};
|
||||
} catch {
|
||||
/* first run */
|
||||
}
|
||||
/* first run */
|
||||
}
|
||||
setInterval(async () => {
|
||||
if (!dirty) return;
|
||||
dirty = false;
|
||||
try {
|
||||
await fsp.mkdir(path.dirname(CACHE_PATH), { recursive: true });
|
||||
await fsp.writeFile(
|
||||
CACHE_PATH,
|
||||
JSON.stringify({
|
||||
routes: Object.fromEntries(cache.routes),
|
||||
aircraft: Object.fromEntries(cache.aircraft),
|
||||
}),
|
||||
'utf8',
|
||||
);
|
||||
await fsp.writeFile(CACHE_PATH, JSON.stringify(cache), 'utf8');
|
||||
} catch {
|
||||
dirty = true;
|
||||
} // retry next tick
|
||||
@@ -176,7 +74,7 @@ export function adsbdbProxy(options = {}) {
|
||||
|
||||
function lookup(kind, key) {
|
||||
const store = kind === 'route' ? cache.routes : cache.aircraft;
|
||||
if (fresh(store.get(key))) return Promise.resolve(store.get(key).data);
|
||||
if (fresh(store[key])) return Promise.resolve(store[key].data);
|
||||
const ik = `${kind}:${key}`;
|
||||
if (!inflight.has(ik)) {
|
||||
inflight.set(
|
||||
@@ -197,19 +95,18 @@ export function adsbdbProxy(options = {}) {
|
||||
);
|
||||
const data =
|
||||
kind === 'route' ? parseRoute(payload) : parseAircraft(payload);
|
||||
// data may be null — negative cache
|
||||
remember(store, key, { at: Date.now(), data });
|
||||
store[key] = { at: Date.now(), data }; // data may be null — negative cache
|
||||
dirty = true;
|
||||
return data;
|
||||
}
|
||||
if (res.status === 404) {
|
||||
// known-missing — cache the miss
|
||||
remember(store, key, { at: Date.now(), data: null });
|
||||
store[key] = { at: Date.now(), data: null }; // known-missing — cache the miss
|
||||
dirty = true;
|
||||
}
|
||||
// other statuses: leave uncached so we retry later
|
||||
return fresh(store.get(key)) ? store.get(key).data : null;
|
||||
return fresh(store[key]) ? store[key].data : null;
|
||||
} catch {
|
||||
// network error → stale if any
|
||||
return fresh(store.get(key)) ? store.get(key).data : null;
|
||||
return fresh(store[key]) ? store[key].data : null; // network error → stale if any
|
||||
} finally {
|
||||
inflight.delete(ik);
|
||||
}
|
||||
@@ -221,24 +118,11 @@ export function adsbdbProxy(options = {}) {
|
||||
|
||||
const installMiddleware = (server) => {
|
||||
server.middlewares.use('/api/adsbdb', async (req, res) => {
|
||||
const send = (status, obj, headers = {}) => {
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
});
|
||||
await loadOnce();
|
||||
const send = (status, obj) => {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(obj));
|
||||
};
|
||||
// Before any work: a refused request must not touch the cache, the disk,
|
||||
// or api.adsbdb.com.
|
||||
if (!allow(clientKey(req)))
|
||||
return send(
|
||||
429,
|
||||
{ error: 'Rate limit exceeded' },
|
||||
{
|
||||
'Retry-After': '10',
|
||||
},
|
||||
);
|
||||
await loadOnce();
|
||||
try {
|
||||
const [, kind, rawKey] = String(req.url || '')
|
||||
.split('?')[0]
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
// ADSBDB ENRICHMENT — the keyspace the cache used to remember forever.
|
||||
//
|
||||
// `/api/adsbdb` answers `route/<callsign>` and `type/<hex>`. Both keys come
|
||||
// from the caller: a callsign is 2-8 of [A-Z0-9], a hex is six of [0-9a-f].
|
||||
// Every distinct key that reached upstream was cached — 404s included — and
|
||||
// nothing ever removed one, so a caller walking the keyspace grew both the
|
||||
// in-memory maps and `.gev-cache/adsbdb.json` without bound, at one live
|
||||
// request to the free community API per new key.
|
||||
//
|
||||
// These cases drive the real exported route handler. No network: `fetch` is
|
||||
// stubbed per test and restored afterwards, so a case that reaches upstream
|
||||
// fails loudly rather than making a request.
|
||||
//
|
||||
// Run with: npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { adsbdbProxy } from '../server/providers/aircraft/enrichment.js';
|
||||
|
||||
/** Collect a plugin's routes into a path → handler map. */
|
||||
function install(plugin) {
|
||||
const routes = new Map();
|
||||
plugin.configureServer({
|
||||
middlewares: {
|
||||
use(routePath, handler) {
|
||||
routes.set(routePath, handler);
|
||||
},
|
||||
},
|
||||
});
|
||||
return routes;
|
||||
}
|
||||
|
||||
function request(handler, { url = '/', remoteAddress = '127.0.0.1' } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers = new Map();
|
||||
const req = { method: 'GET', url, headers: {}, socket: { remoteAddress } };
|
||||
const res = {
|
||||
statusCode: 200,
|
||||
writeHead(status, hdrs = {}) {
|
||||
this.statusCode = status;
|
||||
for (const [name, value] of Object.entries(hdrs))
|
||||
headers.set(String(name).toLowerCase(), String(value));
|
||||
},
|
||||
end(body = '') {
|
||||
let parsed = null;
|
||||
try {
|
||||
parsed = body ? JSON.parse(String(body)) : null;
|
||||
} catch {
|
||||
parsed = String(body);
|
||||
}
|
||||
resolve({
|
||||
statusCode: this.statusCode,
|
||||
headers: Object.fromEntries(headers),
|
||||
body: parsed,
|
||||
});
|
||||
},
|
||||
};
|
||||
Promise.resolve(handler(req, res)).catch(reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace global fetch for the duration of one test, counting the calls the
|
||||
* cache failed to absorb. Every hex answers with the same aircraft, so a
|
||||
* second live call for a key we already asked about is a cache miss, nothing
|
||||
* else.
|
||||
*/
|
||||
function stubUpstream(t) {
|
||||
const asked = [];
|
||||
const original = globalThis.fetch;
|
||||
globalThis.fetch = async (url) => {
|
||||
asked.push(String(url));
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
response: {
|
||||
aircraft: {
|
||||
icao_type: 'B738',
|
||||
manufacturer: 'Boeing',
|
||||
type: '737-800',
|
||||
registration: 'N-FIXTURE',
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ status: 200 },
|
||||
);
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.fetch = original;
|
||||
});
|
||||
return asked;
|
||||
}
|
||||
|
||||
/** A cache path inside the OS temp dir: these cases never load or write it. */
|
||||
const scratchCachePath = () =>
|
||||
path.join(os.tmpdir(), `gev-adsbdb-fixture-${process.pid}-absent.json`);
|
||||
|
||||
const hex = (i) => i.toString(16).padStart(6, '0');
|
||||
|
||||
test('an enrichment lookup still answers, and is cached', async (t) => {
|
||||
const asked = stubUpstream(t);
|
||||
const routes = install(
|
||||
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 10 }),
|
||||
);
|
||||
const handler = routes.get('/api/adsbdb');
|
||||
|
||||
const first = await request(handler, { url: '/type/abc123' });
|
||||
assert.equal(first.statusCode, 200);
|
||||
assert.equal(first.body.found, true);
|
||||
assert.equal(first.body.typeCode, 'B738');
|
||||
assert.equal(asked.length, 1);
|
||||
|
||||
const second = await request(handler, { url: '/type/abc123' });
|
||||
assert.equal(second.body.typeCode, 'B738');
|
||||
assert.equal(asked.length, 1, 'a warm key costs no upstream request');
|
||||
});
|
||||
|
||||
test('the cache stops growing, and an evicted key is simply re-fetched', async (t) => {
|
||||
const asked = stubUpstream(t);
|
||||
// A ceiling of 3 exercises the same path 20,000 does, in four keys.
|
||||
const routes = install(
|
||||
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 3 }),
|
||||
);
|
||||
const handler = routes.get('/api/adsbdb');
|
||||
|
||||
for (let i = 1; i <= 4; i += 1)
|
||||
await request(handler, { url: `/type/${hex(i)}` });
|
||||
assert.equal(asked.length, 4, 'four distinct keys, four upstream requests');
|
||||
|
||||
// The newest is still warm...
|
||||
await request(handler, { url: `/type/${hex(4)}` });
|
||||
assert.equal(asked.length, 4);
|
||||
|
||||
// ...and the oldest was evicted, so it costs exactly one re-fetch, and
|
||||
// still answers correctly.
|
||||
const again = await request(handler, { url: `/type/${hex(1)}` });
|
||||
assert.equal(asked.length, 5);
|
||||
assert.match(asked[4], new RegExp(`/aircraft/${hex(1)}$`));
|
||||
assert.equal(again.body.typeCode, 'B738');
|
||||
});
|
||||
|
||||
test('route and aircraft keys are held to the ceiling independently', async (t) => {
|
||||
const asked = stubUpstream(t);
|
||||
const routes = install(
|
||||
adsbdbProxy({ cachePath: scratchCachePath(), cacheMaxEntries: 2 }),
|
||||
);
|
||||
const handler = routes.get('/api/adsbdb');
|
||||
|
||||
await request(handler, { url: '/type/aaaaaa' });
|
||||
await request(handler, { url: '/type/bbbbbb' });
|
||||
// Two callsigns must not push the two hexes out — they are separate stores.
|
||||
await request(handler, { url: '/route/BAW1' });
|
||||
await request(handler, { url: '/route/DLH2' });
|
||||
assert.equal(asked.length, 4);
|
||||
|
||||
await request(handler, { url: '/type/aaaaaa' });
|
||||
assert.equal(asked.length, 4, 'the aircraft store kept its own two keys');
|
||||
});
|
||||
|
||||
test('a caller enumerating the keyspace is refused, and refusal costs nothing', async (t) => {
|
||||
const asked = stubUpstream(t);
|
||||
const routes = install(adsbdbProxy({ cachePath: scratchCachePath() }));
|
||||
const handler = routes.get('/api/adsbdb');
|
||||
|
||||
let refused = null;
|
||||
let served = 0;
|
||||
// Each client queue drips one lookup per ENRICH_DISPATCH_GAP_MS (200 ms),
|
||||
// and one tab runs two (Flights and Local ADS-B): 600/min must fit.
|
||||
for (let i = 0; i < 1000 && !refused; i += 1) {
|
||||
const res = await request(handler, { url: `/type/${hex(i)}` });
|
||||
if (res.statusCode === 429) refused = res;
|
||||
else served += 1;
|
||||
}
|
||||
|
||||
assert.ok(refused, 'an unbounded sweep is eventually refused');
|
||||
assert.equal(refused.body.error, 'Rate limit exceeded');
|
||||
assert.equal(refused.headers['retry-after'], '10');
|
||||
assert.ok(
|
||||
served >= 600,
|
||||
`both client queues together (600/min) must fit; served ${served}`,
|
||||
);
|
||||
assert.equal(
|
||||
asked.length,
|
||||
served,
|
||||
'a refused request never reaches api.adsbdb.com',
|
||||
);
|
||||
});
|
||||
|
||||
test('a different client keeps its own budget', async (t) => {
|
||||
stubUpstream(t);
|
||||
const routes = install(adsbdbProxy({ cachePath: scratchCachePath() }));
|
||||
const handler = routes.get('/api/adsbdb');
|
||||
|
||||
let noisy = 0;
|
||||
for (let i = 0; i < 1000; i += 1) {
|
||||
const res = await request(handler, {
|
||||
url: `/type/${hex(i)}`,
|
||||
remoteAddress: '10.0.0.1',
|
||||
});
|
||||
if (res.statusCode === 200) noisy += 1;
|
||||
}
|
||||
assert.ok(noisy > 0 && noisy < 1000, 'the noisy client was throttled');
|
||||
|
||||
const quiet = await request(handler, {
|
||||
url: '/type/ffffff',
|
||||
remoteAddress: '10.0.0.2',
|
||||
});
|
||||
assert.equal(quiet.statusCode, 200, 'a quiet client is not collateral');
|
||||
});
|
||||
|
||||
test('GEV_RATELIMIT_ADSBDB_PER_MIN sets the cap, and 0 turns it off', async (t) => {
|
||||
stubUpstream(t);
|
||||
const original = process.env.GEV_RATELIMIT_ADSBDB_PER_MIN;
|
||||
t.after(() => {
|
||||
if (original === undefined) delete process.env.GEV_RATELIMIT_ADSBDB_PER_MIN;
|
||||
else process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = original;
|
||||
});
|
||||
|
||||
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '5';
|
||||
const tight = install(adsbdbProxy({ cachePath: scratchCachePath() })).get(
|
||||
'/api/adsbdb',
|
||||
);
|
||||
const statuses = [];
|
||||
for (let i = 0; i < 6; i += 1)
|
||||
statuses.push(
|
||||
(await request(tight, { url: `/type/${hex(i)}` })).statusCode,
|
||||
);
|
||||
assert.deepEqual(statuses, [200, 200, 200, 200, 200, 429]);
|
||||
|
||||
process.env.GEV_RATELIMIT_ADSBDB_PER_MIN = '0';
|
||||
const open = install(adsbdbProxy({ cachePath: scratchCachePath() })).get(
|
||||
'/api/adsbdb',
|
||||
);
|
||||
for (let i = 0; i < 1500; i += 1) {
|
||||
const res = await request(open, { url: `/type/${hex(i)}` });
|
||||
assert.equal(res.statusCode, 200, `request ${i} with the limiter off`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { cameraOf } from '../render/rendererOf.js';
|
||||
|
||||
/**
|
||||
* The opening: once the world has loaded, the loading screen's logo turns
|
||||
* into the globe. The words fade and the logo glides to the centre; the eye's
|
||||
* arcs fly at the viewer; the drawn planet in the pupil gives way to the real
|
||||
* one, drawn the same size behind it; the real one spins and grows, slowing
|
||||
* until it stops, the whole planet in view, over the start view (the
|
||||
* visitor's country). Everything is timed from one clock, in ms.
|
||||
*/
|
||||
export const OPENING = Object.freeze({
|
||||
/** The words fade and the logo moves to the centre. */
|
||||
centreMs: 450,
|
||||
// The rest is timed from the end of the move.
|
||||
/** The arcs grow and fade. */
|
||||
arcsMs: 700,
|
||||
/** The background clears to the globe. */
|
||||
veilMs: Object.freeze([200, 700]),
|
||||
/** The drawn planet fades into the real one. */
|
||||
pupilMs: Object.freeze([500, 1100]),
|
||||
/** The camera's flight in. */
|
||||
flightStartMs: 300,
|
||||
flightMs: 4200,
|
||||
/** How far the globe turns on the way in, degrees. */
|
||||
spinDeg: 360,
|
||||
});
|
||||
|
||||
const EARTH_RADIUS_M = 6371000;
|
||||
// logo.svg: its viewBox width and the drawn planet's radius, in its units.
|
||||
const LOGO_WIDTH = 775;
|
||||
const PUPIL_RADIUS = 120.33;
|
||||
/** Never start further out than this, metres. */
|
||||
const MAX_FAR_HEIGHT_M = 4e8;
|
||||
|
||||
/** Openings in progress on this page. */
|
||||
let playing = 0;
|
||||
|
||||
/**
|
||||
* Whether an opening is playing: the far start shows the globe as a speck,
|
||||
* which the globe-in-view recovery would otherwise turn the camera back to.
|
||||
*/
|
||||
export function openingPlaying() {
|
||||
return playing > 0;
|
||||
}
|
||||
|
||||
const clamp01 = (x) => Math.min(1, Math.max(0, x));
|
||||
const easeInCubic = (x) => x ** 3;
|
||||
const easeOutCubic = (x) => 1 - (1 - x) ** 3;
|
||||
const easeInOutCubic = (x) =>
|
||||
x < 0.5 ? 4 * x ** 3 : 1 - (-2 * x + 2) ** 3 / 2;
|
||||
const span = (t, [from, to]) => clamp01((t - from) / (to - from));
|
||||
|
||||
/**
|
||||
* Where each part of the opening stands `t` ms after it starts.
|
||||
* @param {number} t
|
||||
*/
|
||||
export function openingStage(t, timing = OPENING) {
|
||||
const move = clamp01(t / timing.centreMs);
|
||||
const after = t - timing.centreMs;
|
||||
const arcs = easeInCubic(clamp01(after / timing.arcsMs));
|
||||
const flight = clamp01((after - timing.flightStartMs) / timing.flightMs);
|
||||
return {
|
||||
/** The words' opacity. */
|
||||
text: 1 - move,
|
||||
/** How far the logo has moved to the centre, 0–1. */
|
||||
centre: easeInOutCubic(move),
|
||||
arcsScale: 1 + 5 * arcs,
|
||||
arcsOpacity: 1 - arcs,
|
||||
/** The loading screen's background opacity. */
|
||||
veil: 1 - span(after, timing.veilMs),
|
||||
pupilOpacity: 1 - span(after, timing.pupilMs),
|
||||
/** The flight's progress, 0–1. */
|
||||
flight,
|
||||
done: flight >= 1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera `flight` (0–1) of the way in: from `farHeight` over the
|
||||
* equator, a turn of `spinDeg` west to east that slows to a stop over
|
||||
* `target`, closing in on `target.height`.
|
||||
*/
|
||||
export function openingPose(
|
||||
flight,
|
||||
{ target, farHeight, spinDeg = OPENING.spinDeg },
|
||||
) {
|
||||
const f = clamp01(flight);
|
||||
const closing = easeInOutCubic(f);
|
||||
const height = Math.exp(
|
||||
Math.log(farHeight) +
|
||||
(Math.log(target.height) - Math.log(farHeight)) * closing,
|
||||
);
|
||||
const lon = target.lon + spinDeg * (1 - easeOutCubic(f));
|
||||
return {
|
||||
lon: ((((lon + 180) % 360) + 360) % 360) - 180,
|
||||
lat: target.lat * closing,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The globe's radius on screen, pixels, from `height` metres straight above
|
||||
* it, through a lens of vertical angle `fovy` on a view `viewportHeight`
|
||||
* pixels tall.
|
||||
*/
|
||||
export function globeRadiusPx(height, { fovy, viewportHeight }) {
|
||||
const angle = Math.asin(EARTH_RADIUS_M / (EARTH_RADIUS_M + height));
|
||||
return (Math.tan(angle) / Math.tan(fovy / 2)) * (viewportHeight / 2);
|
||||
}
|
||||
|
||||
/** The height at which the globe's radius on screen is `radiusPx`. */
|
||||
export function heightForGlobeRadius(radiusPx, { fovy, viewportHeight }) {
|
||||
const tangent = (radiusPx * Math.tan(fovy / 2)) / (viewportHeight / 2);
|
||||
return EARTH_RADIUS_M / Math.sin(Math.atan(tangent)) - EARTH_RADIUS_M;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page opens with the opening: not where motion is reduced, not
|
||||
* on a Stories link (Stories opens its own view) and not with `?intro=0`.
|
||||
*/
|
||||
export function openingWanted(win = globalThis.window) {
|
||||
if (!win) return false;
|
||||
if (win.matchMedia?.('(prefers-reduced-motion: reduce)').matches)
|
||||
return false;
|
||||
const params = new URLSearchParams(win.location?.search ?? '');
|
||||
return !(
|
||||
params.get('intro') === '0' ||
|
||||
params.has('story') ||
|
||||
params.has('stories')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Play the opening over `loadingScreen`, from where the camera stands (the
|
||||
* start view). Returns null when it does not play; else `done`, which
|
||||
* settles when the camera has stopped, and `cancel()`. A click, a key or the
|
||||
* wheel skips to the start view; any other camera move stops it where it is. The loading
|
||||
* screen is `hidden` once the real globe shows, or at once on a cancel.
|
||||
* @param {{viewer: object, loadingScreen: HTMLElement, win?: Window,
|
||||
* camera?: object}} options `camera` is the viewer's camera port unless given.
|
||||
*/
|
||||
export function playOpeningIntro({
|
||||
viewer,
|
||||
loadingScreen,
|
||||
win = globalThis.window,
|
||||
camera = null,
|
||||
}) {
|
||||
if (!openingWanted(win)) return null;
|
||||
try {
|
||||
camera ??= cameraOf(viewer);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const target = camera.pose();
|
||||
if (
|
||||
!Number.isFinite(target?.height) ||
|
||||
!Number.isFinite(target.lon) ||
|
||||
!Number.isFinite(target.lat)
|
||||
)
|
||||
return null;
|
||||
const doc = loadingScreen.ownerDocument;
|
||||
const logo = loadingScreen.querySelector('.loader-logo');
|
||||
const svg = logo?.querySelector('svg');
|
||||
const part = (id) => svg?.querySelector(`#${id}`);
|
||||
const arcs = [part('outer_eye'), part('inner_eye')].filter(Boolean);
|
||||
// The drawn planet; the whole logo where it is an <img>.
|
||||
const pupil = svg
|
||||
? [part('globe'), part('globe_cage')].filter(Boolean)
|
||||
: [logo].filter(Boolean);
|
||||
|
||||
loadingScreen.classList.add('opening');
|
||||
playing += 1;
|
||||
// The planet looks out of the middle of the eye again.
|
||||
for (const element of pupil) element.style.transform = 'none';
|
||||
const globe = part('globe');
|
||||
const pupilRect = (globe ?? logo)?.getBoundingClientRect();
|
||||
const view = (
|
||||
doc.getElementById('cesiumContainer') ?? doc.documentElement
|
||||
).getBoundingClientRect();
|
||||
const viewportHeight = view.height || win.innerHeight;
|
||||
const aspect = (view.width || win.innerWidth) / viewportHeight;
|
||||
// Cesium's default lens: 60° across the wider side.
|
||||
const fovy = Number.isFinite(target.fovy)
|
||||
? target.fovy
|
||||
: aspect > 1
|
||||
? 2 * Math.atan(Math.tan(Math.PI / 6) / aspect)
|
||||
: Math.PI / 3;
|
||||
const lens = { fovy, viewportHeight };
|
||||
const pupilRadius = pupilRect
|
||||
? globe
|
||||
? pupilRect.width / 2
|
||||
: (pupilRect.width * PUPIL_RADIUS) / LOGO_WIDTH
|
||||
: 20;
|
||||
const farHeight = Math.min(
|
||||
MAX_FAR_HEIGHT_M,
|
||||
Math.max(target.height * 2, heightForGlobeRadius(pupilRadius, lens)),
|
||||
);
|
||||
const toCentre = pupilRect
|
||||
? {
|
||||
x: view.left + view.width / 2 - (pupilRect.left + pupilRect.width / 2),
|
||||
y: view.top + view.height / 2 - (pupilRect.top + pupilRect.height / 2),
|
||||
}
|
||||
: { x: 0, y: 0 };
|
||||
const startRadius = globeRadiusPx(farHeight, lens);
|
||||
|
||||
let driving = false;
|
||||
const place = (pose, heading = 0, pitch = -Math.PI / 2) => {
|
||||
driving = true;
|
||||
try {
|
||||
camera.setView({
|
||||
destination: pose,
|
||||
orientation: { heading, pitch, roll: 0 },
|
||||
});
|
||||
} finally {
|
||||
driving = false;
|
||||
}
|
||||
};
|
||||
|
||||
let resolveDone;
|
||||
const done = new Promise((resolve) => {
|
||||
resolveDone = resolve;
|
||||
});
|
||||
let frame = 0;
|
||||
let finished = false;
|
||||
const hide = () => loadingScreen.classList.add('hidden');
|
||||
const stopCommands = camera.onCommand?.(() => {
|
||||
if (!driving) finish();
|
||||
});
|
||||
const inputs = ['pointerdown', 'wheel', 'keydown', 'touchstart'];
|
||||
// The person's own input skips to the end; another camera move stops it.
|
||||
const onInput = () => finish({ land: true });
|
||||
for (const type of inputs)
|
||||
win.addEventListener(type, onInput, { capture: true, passive: true });
|
||||
|
||||
function finish({ land = false } = {}) {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
playing -= 1;
|
||||
if (frame) win.cancelAnimationFrame(frame);
|
||||
stopCommands?.();
|
||||
for (const type of inputs)
|
||||
win.removeEventListener(type, onInput, { capture: true });
|
||||
if (land)
|
||||
place(
|
||||
{ lon: target.lon, lat: target.lat, height: target.height },
|
||||
target.heading ?? 0,
|
||||
target.pitch ?? -Math.PI / 2,
|
||||
);
|
||||
hide();
|
||||
resolveDone();
|
||||
}
|
||||
|
||||
const start = win.performance.now();
|
||||
const step = () => {
|
||||
frame = 0;
|
||||
if (finished) return;
|
||||
const stage = openingStage(win.performance.now() - start);
|
||||
if (stage.done) {
|
||||
finish({ land: true });
|
||||
return;
|
||||
}
|
||||
const pose = openingPose(stage.flight, { target, farHeight });
|
||||
place(pose);
|
||||
const scale = globeRadiusPx(pose.height, lens) / startRadius;
|
||||
loadingScreen.style.setProperty('--opening-text', stage.text);
|
||||
loadingScreen.style.setProperty('--opening-veil', stage.veil);
|
||||
if (logo)
|
||||
logo.style.transform = `translate(${toCentre.x * stage.centre}px, ${
|
||||
toCentre.y * stage.centre
|
||||
}px) scale(${scale})`;
|
||||
for (const element of arcs) {
|
||||
element.style.transform = `scale(${stage.arcsScale})`;
|
||||
element.style.opacity = stage.arcsOpacity;
|
||||
}
|
||||
for (const element of pupil) element.style.opacity = stage.pupilOpacity;
|
||||
if (stage.pupilOpacity === 0) hide();
|
||||
frame = win.requestAnimationFrame(step);
|
||||
};
|
||||
step();
|
||||
return { done, cancel: () => finish() };
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Window } from 'happy-dom';
|
||||
import {
|
||||
OPENING,
|
||||
globeRadiusPx,
|
||||
heightForGlobeRadius,
|
||||
openingPlaying,
|
||||
openingPose,
|
||||
openingStage,
|
||||
openingWanted,
|
||||
playOpeningIntro,
|
||||
} from './openingIntro.js';
|
||||
|
||||
const LENS = { fovy: Math.PI / 4, viewportHeight: 800 };
|
||||
const TARGET = { lon: 10.4, lat: 51.1, height: 23e6, heading: 0, pitch: -1 };
|
||||
const LANDED = { lon: TARGET.lon, lat: TARGET.lat, height: TARGET.height };
|
||||
const END_MS = OPENING.centreMs + OPENING.flightStartMs + OPENING.flightMs + 1;
|
||||
|
||||
test('the arcs fly out and the words fade before the globe arrives', () => {
|
||||
const start = openingStage(0);
|
||||
assert.equal(start.text, 1);
|
||||
assert.equal(start.veil, 1);
|
||||
assert.equal(start.pupilOpacity, 1);
|
||||
assert.equal(start.flight, 0);
|
||||
const centred = openingStage(OPENING.centreMs);
|
||||
assert.equal(centred.text, 0);
|
||||
assert.equal(centred.centre, 1);
|
||||
const arcsGone = openingStage(OPENING.centreMs + OPENING.arcsMs);
|
||||
assert.equal(arcsGone.arcsOpacity, 0);
|
||||
assert.ok(arcsGone.arcsScale > 5);
|
||||
const real = openingStage(OPENING.centreMs + OPENING.pupilMs[1]);
|
||||
assert.equal(real.pupilOpacity, 0);
|
||||
assert.equal(real.veil, 0);
|
||||
assert.ok(real.flight > 0 && real.flight < 1);
|
||||
assert.equal(openingStage(END_MS).done, true);
|
||||
});
|
||||
|
||||
test('the flight turns west to east, slows and stops over the target', () => {
|
||||
const far = 4e8;
|
||||
const start = openingPose(0, { target: TARGET, farHeight: far });
|
||||
assert.ok(Math.abs(start.height - far) < 1);
|
||||
assert.equal(start.lat, 0);
|
||||
const end = openingPose(1, { target: TARGET, farHeight: far });
|
||||
assert.ok(Math.abs(end.lon - TARGET.lon) < 1e-9);
|
||||
assert.ok(Math.abs(end.lat - TARGET.lat) < 1e-9);
|
||||
assert.ok(Math.abs(end.height - TARGET.height) < 1e-3);
|
||||
// Unwrapped longitude falls all the way (the camera moves west, so the
|
||||
// surface turns east), fastest at first.
|
||||
let previous = Infinity;
|
||||
let previousStep = Infinity;
|
||||
for (let i = 0; i <= 10; i++) {
|
||||
const f = i / 10;
|
||||
const unwrapped = TARGET.lon + OPENING.spinDeg * (1 - (1 - (1 - f) ** 3));
|
||||
assert.ok(unwrapped <= previous);
|
||||
if (i > 0) {
|
||||
const step = previous - unwrapped;
|
||||
assert.ok(step <= previousStep + 1e-9, 'the turn slows');
|
||||
previousStep = step;
|
||||
}
|
||||
previous = unwrapped;
|
||||
const pose = openingPose(f, { target: TARGET, farHeight: far });
|
||||
assert.ok(pose.lon >= -180 && pose.lon < 180);
|
||||
}
|
||||
});
|
||||
|
||||
test('the far start draws the globe the size of the pupil', () => {
|
||||
for (const radius of [12, 20, 64]) {
|
||||
const height = heightForGlobeRadius(radius, LENS);
|
||||
assert.ok(Math.abs(globeRadiusPx(height, LENS) - radius) < 1e-6);
|
||||
}
|
||||
assert.ok(globeRadiusPx(4e8, LENS) < globeRadiusPx(23e6, LENS));
|
||||
});
|
||||
|
||||
test('reduced motion, Stories links and ?intro=0 open without it', () => {
|
||||
const win = (search, reduced = false) => ({
|
||||
location: { search },
|
||||
matchMedia: () => ({ matches: reduced }),
|
||||
});
|
||||
assert.equal(openingWanted(win('')), true);
|
||||
assert.equal(openingWanted(win('', true)), false);
|
||||
assert.equal(openingWanted(win('?intro=0')), false);
|
||||
assert.equal(openingWanted(win('?story=abc')), false);
|
||||
assert.equal(openingWanted(win('?stories')), false);
|
||||
assert.equal(openingWanted(win('?intro=1')), true);
|
||||
});
|
||||
|
||||
// A loading screen and a camera port; the test runs the frames by hand.
|
||||
function stage() {
|
||||
const window = new Window({ width: 1280, height: 800 });
|
||||
const doc = window.document;
|
||||
doc.body.innerHTML = `
|
||||
<div id="cesiumContainer"></div>
|
||||
<div id="loading-screen"><span class="loader-logo"><svg>
|
||||
<path id="outer_eye"/><path id="inner_eye"/>
|
||||
<path id="globe"/><path id="globe_cage"/>
|
||||
</svg></span></div>`;
|
||||
const screen = doc.getElementById('loading-screen');
|
||||
let now = 0;
|
||||
let frames = [];
|
||||
window.performance.now = () => now;
|
||||
window.requestAnimationFrame = (fn) => frames.push(fn);
|
||||
window.cancelAnimationFrame = () => {
|
||||
frames = [];
|
||||
};
|
||||
window.matchMedia = () => ({ matches: false });
|
||||
const views = [];
|
||||
const commandListeners = new Set();
|
||||
const camera = {
|
||||
pose: () => ({ ...TARGET, fovy: Math.PI / 4 }),
|
||||
setView(spec) {
|
||||
views.push(spec);
|
||||
for (const cb of commandListeners) cb({ kind: 'setView' });
|
||||
},
|
||||
onCommand(cb) {
|
||||
commandListeners.add(cb);
|
||||
return () => commandListeners.delete(cb);
|
||||
},
|
||||
};
|
||||
return {
|
||||
window,
|
||||
screen,
|
||||
views,
|
||||
camera,
|
||||
commandListeners,
|
||||
play: () =>
|
||||
playOpeningIntro({
|
||||
viewer: {},
|
||||
loadingScreen: screen,
|
||||
win: window,
|
||||
camera,
|
||||
}),
|
||||
advance(ms) {
|
||||
now += ms;
|
||||
const run = frames;
|
||||
frames = [];
|
||||
for (const fn of run) fn();
|
||||
},
|
||||
otherMove: () => {
|
||||
for (const cb of [...commandListeners]) cb({ kind: 'flyTo' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the opening runs to the start view, then hides the cover', async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
assert.ok(opening);
|
||||
assert.equal(openingPlaying(), true);
|
||||
assert.ok(s.screen.classList.contains('opening'));
|
||||
assert.ok(s.views[0].destination.height > TARGET.height * 2, 'far start');
|
||||
s.advance(OPENING.centreMs + OPENING.pupilMs[1]);
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
s.advance(OPENING.flightMs);
|
||||
await opening.done;
|
||||
const last = s.views.at(-1);
|
||||
assert.deepEqual(last.destination, LANDED);
|
||||
assert.equal(last.orientation.pitch, TARGET.pitch);
|
||||
assert.equal(openingPlaying(), false);
|
||||
assert.equal(s.commandListeners.size, 0);
|
||||
});
|
||||
|
||||
test("the person's input skips to the start view", async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
s.window.dispatchEvent(new s.window.Event('keydown'));
|
||||
await opening.done;
|
||||
assert.deepEqual(s.views.at(-1).destination, LANDED);
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
assert.equal(openingPlaying(), false);
|
||||
});
|
||||
|
||||
test('another camera move stops it where it is', async () => {
|
||||
const s = stage();
|
||||
const opening = s.play();
|
||||
s.advance(2000);
|
||||
const count = s.views.length;
|
||||
s.otherMove();
|
||||
await opening.done;
|
||||
s.advance(1000);
|
||||
assert.equal(s.views.length, count, 'no more frames');
|
||||
assert.ok(s.screen.classList.contains('hidden'));
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { initFirstRunExperience } from '../firstRunExperience.js';
|
||||
|
||||
/** Reveal welcome controls only after restoration and the loading transition. */
|
||||
/**
|
||||
* Reveal welcome controls only after restoration and the loading transition.
|
||||
* `playOpening` plays the opening on a bare address (src/app/openingIntro.js).
|
||||
*/
|
||||
export function startApplicationChrome({
|
||||
loadingScreen,
|
||||
styleManager,
|
||||
@@ -8,9 +11,11 @@ export function startApplicationChrome({
|
||||
signal,
|
||||
initializeWelcome = initFirstRunExperience,
|
||||
initializeSettings,
|
||||
playOpening = null,
|
||||
}) {
|
||||
let disposed = false;
|
||||
let firstRun;
|
||||
let opening = null;
|
||||
let revealTimer;
|
||||
let resolveDelay;
|
||||
const minimumDelay = new Promise((resolve) => {
|
||||
@@ -29,6 +34,14 @@ export function startApplicationChrome({
|
||||
})
|
||||
.then(() => {
|
||||
if (disposed || signal.aborted) return;
|
||||
// A bare address opens with the opening; welcome waits for its end.
|
||||
opening = styleManager.hasShareState
|
||||
? null
|
||||
: playOpening?.({ viewer: styleManager.viewer, loadingScreen });
|
||||
if (opening) {
|
||||
void opening.done.then(revealFirstRun);
|
||||
return;
|
||||
}
|
||||
loadingScreen.classList.add('hidden');
|
||||
loadingScreen.addEventListener('transitionend', revealFirstRun, {
|
||||
once: true,
|
||||
@@ -44,6 +57,7 @@ export function startApplicationChrome({
|
||||
);
|
||||
return async () => {
|
||||
disposed = true;
|
||||
opening?.cancel();
|
||||
clearTimeout(delayTimer);
|
||||
clearTimeout(revealTimer);
|
||||
resolveDelay();
|
||||
|
||||
+4
-2
@@ -22,6 +22,7 @@ import { initImageryBoxTool } from '../ui/imageryBoxTool.js';
|
||||
import { createRecentImageryPanel } from '../ui/recentImagery.js';
|
||||
import { createDataLibrary } from '../library/controller.js';
|
||||
import { flyToLibraryExtent } from '../library/camera.js';
|
||||
import { openingPlaying } from './openingIntro.js';
|
||||
import { createLibraryBrowser } from '../ui/libraryBrowser.js';
|
||||
import { useDataLibraryStore } from '../ui/stores/dataLibrary.js';
|
||||
import { localGeoJsonServices } from './localGeojsonServices.js';
|
||||
@@ -88,8 +89,9 @@ export function createApplicationTools({
|
||||
installGlobeInViewRecovery(viewer, {
|
||||
// The scope mask hides everything outside its keyhole.
|
||||
keyholeRadius: () => (isScopeMaskEnabled() ? KEYHOLE_OUTER_RADIUS : 0),
|
||||
// An authored scene frames its own shots, holds included.
|
||||
paused: () => sceneDirector.running,
|
||||
// An authored scene frames its own shots, holds included, and the
|
||||
// opening starts with the globe as a speck.
|
||||
paused: () => sceneDirector.running || openingPlaying(),
|
||||
}),
|
||||
);
|
||||
onSceneDirector?.(sceneDirector);
|
||||
|
||||
@@ -0,0 +1,695 @@
|
||||
// Generated by scripts/build-home-countries.mjs. Do not edit by hand.
|
||||
// Sources: tzdata zone.tab (public domain) and the Natural Earth countries
|
||||
// pack in src/data/local_data/natural_earth (public domain).
|
||||
|
||||
/** ISO 3166 country → [lat, lon]: the centroid of its largest part. */
|
||||
export const COUNTRY_CENTRES = {
|
||||
AD: [42.5, 1.6],
|
||||
AE: [23.9, 54.3],
|
||||
AF: [33.8, 66],
|
||||
AG: [17.1, -61.8],
|
||||
AI: [18.2, -63.1],
|
||||
AL: [41.1, 20.1],
|
||||
AM: [40.3, 44.9],
|
||||
AO: [-12.3, 17.6],
|
||||
AQ: [-80.6, 20.8],
|
||||
AR: [-35.2, -65.1],
|
||||
AS: [-14.3, -170.7],
|
||||
AT: [47.6, 14.1],
|
||||
AU: [-25.6, 134.4],
|
||||
AW: [12.5, -70],
|
||||
AX: [60.2, 19.9],
|
||||
AZ: [40.3, 47.7],
|
||||
BA: [44.2, 17.8],
|
||||
BB: [13.2, -59.6],
|
||||
BD: [23.9, 90.2],
|
||||
BE: [50.6, 4.6],
|
||||
BF: [12.3, -1.8],
|
||||
BG: [42.8, 25.2],
|
||||
BH: [26.1, 50.5],
|
||||
BI: [-3.4, 29.9],
|
||||
BJ: [9.6, 2.3],
|
||||
BL: [17.9, -62.8],
|
||||
BM: [32.3, -64.8],
|
||||
BN: [4.5, 114.6],
|
||||
BO: [-16.7, -64.7],
|
||||
BQ: [12.2, -68.3],
|
||||
BR: [-10.8, -53.1],
|
||||
BS: [24.7, -78],
|
||||
BT: [27.4, 90.4],
|
||||
BW: [-22.2, 23.8],
|
||||
BY: [53.5, 28],
|
||||
BZ: [17.2, -88.7],
|
||||
CA: [57.9, -102.4],
|
||||
CC: [-12.2, 96.9],
|
||||
CD: [-2.9, 23.6],
|
||||
CF: [6.6, 20.5],
|
||||
CG: [-0.8, 15.2],
|
||||
CH: [46.8, 8.2],
|
||||
CI: [7.6, -5.6],
|
||||
CK: [-21.2, -159.8],
|
||||
CL: [-35.4, -71.2],
|
||||
CM: [5.7, 12.7],
|
||||
CN: [36.6, 103.8],
|
||||
CO: [3.9, -73.1],
|
||||
CR: [10, -84.2],
|
||||
CU: [21.6, -79],
|
||||
CV: [15.1, -23.6],
|
||||
CW: [12.2, -69],
|
||||
CX: [-10.4, 105.7],
|
||||
CY: [34.9, 33],
|
||||
CZ: [49.7, 15.3],
|
||||
DE: [51.1, 10.4],
|
||||
DJ: [11.8, 42.6],
|
||||
DK: [56.2, 9.4],
|
||||
DM: [15.4, -61.4],
|
||||
DO: [18.9, -70.5],
|
||||
DZ: [28.1, 2.7],
|
||||
EC: [-1.4, -78.4],
|
||||
EE: [58.7, 25.8],
|
||||
EG: [26.5, 29.9],
|
||||
EH: [24.2, -12.2],
|
||||
ER: [15.4, 38.8],
|
||||
ES: [40.4, -3.6],
|
||||
ET: [8.6, 39.6],
|
||||
FI: [64.5, 26.3],
|
||||
FJ: [-17.8, 178],
|
||||
FK: [-51.7, -58.8],
|
||||
FM: [6.9, 158.2],
|
||||
FO: [62.1, -7],
|
||||
FR: [46.6, 2.5],
|
||||
GA: [-0.6, 11.8],
|
||||
GB: [53.9, -2.5],
|
||||
GD: [12.1, -61.7],
|
||||
GE: [42.2, 43.5],
|
||||
GF: [4.9, -52.3],
|
||||
GG: [49.5, -2.6],
|
||||
GH: [8, -1.2],
|
||||
GI: [36.1, -5.3],
|
||||
GL: [74.8, -41.4],
|
||||
GM: [13.4, -15.4],
|
||||
GN: [10.4, -10.9],
|
||||
GP: [16.2, -61.5],
|
||||
GQ: [1.6, 10.5],
|
||||
GR: [39.5, 22.6],
|
||||
GS: [-54.4, -36.7],
|
||||
GT: [15.7, -90.4],
|
||||
GU: [13.4, 144.8],
|
||||
GW: [12.1, -14.9],
|
||||
GY: [4.8, -59],
|
||||
HK: [22.4, 114.2],
|
||||
HN: [14.8, -86.6],
|
||||
HR: [45.2, 16.4],
|
||||
HT: [18.9, -72.7],
|
||||
HU: [47.2, 19.4],
|
||||
ID: [-0.2, 114],
|
||||
IE: [53.2, -8.1],
|
||||
IL: [31.4, 35],
|
||||
IM: [54.2, -4.5],
|
||||
IN: [22.9, 79.6],
|
||||
IO: [-7.3, 72.4],
|
||||
IQ: [33, 43.7],
|
||||
IR: [32.6, 54.3],
|
||||
IS: [65, -18.6],
|
||||
IT: [43.5, 12.2],
|
||||
JE: [49.2, -2.1],
|
||||
JM: [18.2, -77.3],
|
||||
JO: [31.2, 36.8],
|
||||
JP: [36.7, 138],
|
||||
KE: [0.6, 37.8],
|
||||
KG: [41.5, 74.5],
|
||||
KH: [12.7, 104.9],
|
||||
KI: [1.9, -157.4],
|
||||
KM: [-11.7, 43.3],
|
||||
KN: [17.3, -62.8],
|
||||
KP: [40.2, 127.2],
|
||||
KR: [36.5, 127.9],
|
||||
KW: [29.3, 47.6],
|
||||
KY: [19.3, -81.3],
|
||||
KZ: [48.2, 67.3],
|
||||
LA: [18.5, 103.7],
|
||||
LB: [33.9, 35.9],
|
||||
LC: [13.9, -61],
|
||||
LI: [47.1, 9.5],
|
||||
LK: [7.6, 80.7],
|
||||
LR: [6.5, -9.3],
|
||||
LS: [-29.6, 28.2],
|
||||
LT: [55.3, 23.9],
|
||||
LU: [49.8, 6.1],
|
||||
LV: [56.9, 24.9],
|
||||
LY: [27, 18],
|
||||
MA: [29.8, -8.4],
|
||||
MC: [43.7, 7.4],
|
||||
MD: [47.2, 28.5],
|
||||
ME: [42.8, 19.2],
|
||||
MF: [18.1, -63.1],
|
||||
MG: [-19.4, 46.7],
|
||||
MH: [7.1, 171.2],
|
||||
MK: [41.6, 21.7],
|
||||
ML: [17.3, -3.5],
|
||||
MM: [21.2, 96.5],
|
||||
MN: [46.8, 103.1],
|
||||
MO: [22.1, 113.6],
|
||||
MP: [15.2, 145.7],
|
||||
MQ: [14.6, -61.1],
|
||||
MR: [20.3, -10.3],
|
||||
MS: [16.7, -62.2],
|
||||
MT: [35.9, 14.4],
|
||||
MU: [-20.3, 57.6],
|
||||
MV: [4.2, 73.5],
|
||||
MW: [-13.2, 34.3],
|
||||
MX: [23.9, -102.5],
|
||||
MY: [3.6, 114.7],
|
||||
MZ: [-17.3, 35.5],
|
||||
NA: [-22.1, 17.2],
|
||||
NC: [-21.3, 165.5],
|
||||
NE: [17.4, 9.4],
|
||||
NF: [-29, 168],
|
||||
NG: [9.6, 8.1],
|
||||
NI: [12.8, -85],
|
||||
NL: [52.3, 5.6],
|
||||
NO: [64.2, 14],
|
||||
NP: [28.2, 83.9],
|
||||
NR: [-0.5, 166.9],
|
||||
NU: [-19, -169.9],
|
||||
NZ: [-44, 170.5],
|
||||
OM: [20.6, 56.1],
|
||||
PA: [8.5, -80.1],
|
||||
PE: [-9.2, -74.4],
|
||||
PF: [-17.7, -149.4],
|
||||
PG: [-6.6, 144.3],
|
||||
PH: [16, 121.4],
|
||||
PK: [29.9, 69.3],
|
||||
PL: [52.1, 19.4],
|
||||
PM: [47, -56.3],
|
||||
PN: [-24.4, -128.3],
|
||||
PR: [18.2, -66.5],
|
||||
PS: [31.9, 35.3],
|
||||
PT: [39.7, -8],
|
||||
PW: [7.5, 134.6],
|
||||
PY: [-23.2, -58.4],
|
||||
QA: [25.3, 51.2],
|
||||
RE: [-20.9, 55.5],
|
||||
RO: [45.9, 25],
|
||||
RS: [44.2, 20.8],
|
||||
RU: [61.7, 99.1],
|
||||
RW: [-2, 29.9],
|
||||
SA: [24.1, 44.5],
|
||||
SB: [-9.6, 160.2],
|
||||
SC: [-4.7, 55.5],
|
||||
SD: [16, 29.9],
|
||||
SE: [62.8, 16.7],
|
||||
SG: [1.4, 103.8],
|
||||
SH: [-16, -5.7],
|
||||
SI: [46.1, 14.8],
|
||||
SJ: [78, 16],
|
||||
SK: [48.7, 19.5],
|
||||
SL: [8.6, -11.8],
|
||||
SM: [43.9, 12.4],
|
||||
SN: [14.4, -14.5],
|
||||
SO: [4.8, 45.7],
|
||||
SR: [4.1, -55.9],
|
||||
SS: [7.3, 30.3],
|
||||
ST: [0.2, 6.6],
|
||||
SV: [13.7, -88.9],
|
||||
SX: [18, -63.1],
|
||||
SY: [35, 38.5],
|
||||
SZ: [-26.6, 31.5],
|
||||
TC: [21.8, -71.7],
|
||||
TD: [15.3, 18.6],
|
||||
TF: [-49.3, 69.5],
|
||||
TG: [8.5, 1],
|
||||
TH: [15.1, 101],
|
||||
TJ: [38.5, 71],
|
||||
TK: [-9.4, -171.2],
|
||||
TL: [-8.8, 125.9],
|
||||
TM: [39.1, 59.4],
|
||||
TN: [34.1, 9.5],
|
||||
TO: [-21.2, -175.2],
|
||||
TR: [39, 35.4],
|
||||
TT: [10.4, -61.3],
|
||||
TV: [-8.5, 179.2],
|
||||
TW: [23.8, 121],
|
||||
TZ: [-6.3, 34.8],
|
||||
UA: [49.2, 31.3],
|
||||
UG: [1.3, 32.4],
|
||||
UM: [5.9, -162.1],
|
||||
US: [39.5, -99.1],
|
||||
UY: [-32.8, -56],
|
||||
UZ: [41.8, 63.1],
|
||||
VA: [41.9, 12.5],
|
||||
VC: [13.3, -61.2],
|
||||
VE: [7.1, -66.2],
|
||||
VG: [18.4, -64.6],
|
||||
VI: [17.7, -64.8],
|
||||
VN: [16.7, 106.3],
|
||||
VU: [-15.2, 166.9],
|
||||
WF: [-13.3, -176.2],
|
||||
WS: [-13.6, -172.4],
|
||||
YE: [15.9, 47.5],
|
||||
YT: [-12.8, 45.2],
|
||||
ZA: [-29, 25.2],
|
||||
ZM: [-13.5, 27.8],
|
||||
ZW: [-19, 29.9],
|
||||
};
|
||||
|
||||
/** Time zone (tzdata and ICU names) → ISO 3166 country. */
|
||||
export const ZONE_COUNTRIES = {
|
||||
'Africa/Abidjan': 'CI',
|
||||
'Africa/Accra': 'GH',
|
||||
'Africa/Addis_Ababa': 'ET',
|
||||
'Africa/Algiers': 'DZ',
|
||||
'Africa/Asmara': 'ER',
|
||||
'Africa/Asmera': 'ER',
|
||||
'Africa/Bamako': 'ML',
|
||||
'Africa/Bangui': 'CF',
|
||||
'Africa/Banjul': 'GM',
|
||||
'Africa/Bissau': 'GW',
|
||||
'Africa/Blantyre': 'MW',
|
||||
'Africa/Brazzaville': 'CG',
|
||||
'Africa/Bujumbura': 'BI',
|
||||
'Africa/Cairo': 'EG',
|
||||
'Africa/Casablanca': 'MA',
|
||||
'Africa/Ceuta': 'ES',
|
||||
'Africa/Conakry': 'GN',
|
||||
'Africa/Dakar': 'SN',
|
||||
'Africa/Dar_es_Salaam': 'TZ',
|
||||
'Africa/Djibouti': 'DJ',
|
||||
'Africa/Douala': 'CM',
|
||||
'Africa/El_Aaiun': 'EH',
|
||||
'Africa/Freetown': 'SL',
|
||||
'Africa/Gaborone': 'BW',
|
||||
'Africa/Harare': 'ZW',
|
||||
'Africa/Johannesburg': 'ZA',
|
||||
'Africa/Juba': 'SS',
|
||||
'Africa/Kampala': 'UG',
|
||||
'Africa/Khartoum': 'SD',
|
||||
'Africa/Kigali': 'RW',
|
||||
'Africa/Kinshasa': 'CD',
|
||||
'Africa/Lagos': 'NG',
|
||||
'Africa/Libreville': 'GA',
|
||||
'Africa/Lome': 'TG',
|
||||
'Africa/Luanda': 'AO',
|
||||
'Africa/Lubumbashi': 'CD',
|
||||
'Africa/Lusaka': 'ZM',
|
||||
'Africa/Malabo': 'GQ',
|
||||
'Africa/Maputo': 'MZ',
|
||||
'Africa/Maseru': 'LS',
|
||||
'Africa/Mbabane': 'SZ',
|
||||
'Africa/Mogadishu': 'SO',
|
||||
'Africa/Monrovia': 'LR',
|
||||
'Africa/Nairobi': 'KE',
|
||||
'Africa/Ndjamena': 'TD',
|
||||
'Africa/Niamey': 'NE',
|
||||
'Africa/Nouakchott': 'MR',
|
||||
'Africa/Ouagadougou': 'BF',
|
||||
'Africa/Porto-Novo': 'BJ',
|
||||
'Africa/Sao_Tome': 'ST',
|
||||
'Africa/Tripoli': 'LY',
|
||||
'Africa/Tunis': 'TN',
|
||||
'Africa/Windhoek': 'NA',
|
||||
'America/Adak': 'US',
|
||||
'America/Anchorage': 'US',
|
||||
'America/Anguilla': 'AI',
|
||||
'America/Antigua': 'AG',
|
||||
'America/Araguaina': 'BR',
|
||||
'America/Argentina/Buenos_Aires': 'AR',
|
||||
'America/Argentina/Catamarca': 'AR',
|
||||
'America/Argentina/Cordoba': 'AR',
|
||||
'America/Argentina/Jujuy': 'AR',
|
||||
'America/Argentina/La_Rioja': 'AR',
|
||||
'America/Argentina/Mendoza': 'AR',
|
||||
'America/Argentina/Rio_Gallegos': 'AR',
|
||||
'America/Argentina/Salta': 'AR',
|
||||
'America/Argentina/San_Juan': 'AR',
|
||||
'America/Argentina/San_Luis': 'AR',
|
||||
'America/Argentina/Tucuman': 'AR',
|
||||
'America/Argentina/Ushuaia': 'AR',
|
||||
'America/Aruba': 'AW',
|
||||
'America/Asuncion': 'PY',
|
||||
'America/Atikokan': 'CA',
|
||||
'America/Bahia': 'BR',
|
||||
'America/Bahia_Banderas': 'MX',
|
||||
'America/Barbados': 'BB',
|
||||
'America/Belem': 'BR',
|
||||
'America/Belize': 'BZ',
|
||||
'America/Blanc-Sablon': 'CA',
|
||||
'America/Boa_Vista': 'BR',
|
||||
'America/Bogota': 'CO',
|
||||
'America/Boise': 'US',
|
||||
'America/Buenos_Aires': 'AR',
|
||||
'America/Cambridge_Bay': 'CA',
|
||||
'America/Campo_Grande': 'BR',
|
||||
'America/Cancun': 'MX',
|
||||
'America/Caracas': 'VE',
|
||||
'America/Catamarca': 'AR',
|
||||
'America/Cayenne': 'GF',
|
||||
'America/Cayman': 'KY',
|
||||
'America/Chicago': 'US',
|
||||
'America/Chihuahua': 'MX',
|
||||
'America/Ciudad_Juarez': 'MX',
|
||||
'America/Coral_Harbour': 'CA',
|
||||
'America/Cordoba': 'AR',
|
||||
'America/Costa_Rica': 'CR',
|
||||
'America/Coyhaique': 'CL',
|
||||
'America/Creston': 'CA',
|
||||
'America/Cuiaba': 'BR',
|
||||
'America/Curacao': 'CW',
|
||||
'America/Danmarkshavn': 'GL',
|
||||
'America/Dawson': 'CA',
|
||||
'America/Dawson_Creek': 'CA',
|
||||
'America/Denver': 'US',
|
||||
'America/Detroit': 'US',
|
||||
'America/Dominica': 'DM',
|
||||
'America/Edmonton': 'CA',
|
||||
'America/Eirunepe': 'BR',
|
||||
'America/El_Salvador': 'SV',
|
||||
'America/Fort_Nelson': 'CA',
|
||||
'America/Fortaleza': 'BR',
|
||||
'America/Glace_Bay': 'CA',
|
||||
'America/Godthab': 'GL',
|
||||
'America/Goose_Bay': 'CA',
|
||||
'America/Grand_Turk': 'TC',
|
||||
'America/Grenada': 'GD',
|
||||
'America/Guadeloupe': 'GP',
|
||||
'America/Guatemala': 'GT',
|
||||
'America/Guayaquil': 'EC',
|
||||
'America/Guyana': 'GY',
|
||||
'America/Halifax': 'CA',
|
||||
'America/Havana': 'CU',
|
||||
'America/Hermosillo': 'MX',
|
||||
'America/Indiana/Indianapolis': 'US',
|
||||
'America/Indiana/Knox': 'US',
|
||||
'America/Indiana/Marengo': 'US',
|
||||
'America/Indiana/Petersburg': 'US',
|
||||
'America/Indiana/Tell_City': 'US',
|
||||
'America/Indiana/Vevay': 'US',
|
||||
'America/Indiana/Vincennes': 'US',
|
||||
'America/Indiana/Winamac': 'US',
|
||||
'America/Indianapolis': 'US',
|
||||
'America/Inuvik': 'CA',
|
||||
'America/Iqaluit': 'CA',
|
||||
'America/Jamaica': 'JM',
|
||||
'America/Jujuy': 'AR',
|
||||
'America/Juneau': 'US',
|
||||
'America/Kentucky/Louisville': 'US',
|
||||
'America/Kentucky/Monticello': 'US',
|
||||
'America/Kralendijk': 'BQ',
|
||||
'America/La_Paz': 'BO',
|
||||
'America/Lima': 'PE',
|
||||
'America/Los_Angeles': 'US',
|
||||
'America/Louisville': 'US',
|
||||
'America/Lower_Princes': 'SX',
|
||||
'America/Maceio': 'BR',
|
||||
'America/Managua': 'NI',
|
||||
'America/Manaus': 'BR',
|
||||
'America/Marigot': 'MF',
|
||||
'America/Martinique': 'MQ',
|
||||
'America/Matamoros': 'MX',
|
||||
'America/Mazatlan': 'MX',
|
||||
'America/Mendoza': 'AR',
|
||||
'America/Menominee': 'US',
|
||||
'America/Merida': 'MX',
|
||||
'America/Metlakatla': 'US',
|
||||
'America/Mexico_City': 'MX',
|
||||
'America/Miquelon': 'PM',
|
||||
'America/Moncton': 'CA',
|
||||
'America/Monterrey': 'MX',
|
||||
'America/Montevideo': 'UY',
|
||||
'America/Montserrat': 'MS',
|
||||
'America/Nassau': 'BS',
|
||||
'America/New_York': 'US',
|
||||
'America/Nome': 'US',
|
||||
'America/Noronha': 'BR',
|
||||
'America/North_Dakota/Beulah': 'US',
|
||||
'America/North_Dakota/Center': 'US',
|
||||
'America/North_Dakota/New_Salem': 'US',
|
||||
'America/Nuuk': 'GL',
|
||||
'America/Ojinaga': 'MX',
|
||||
'America/Panama': 'PA',
|
||||
'America/Paramaribo': 'SR',
|
||||
'America/Phoenix': 'US',
|
||||
'America/Port-au-Prince': 'HT',
|
||||
'America/Port_of_Spain': 'TT',
|
||||
'America/Porto_Velho': 'BR',
|
||||
'America/Puerto_Rico': 'PR',
|
||||
'America/Punta_Arenas': 'CL',
|
||||
'America/Rankin_Inlet': 'CA',
|
||||
'America/Recife': 'BR',
|
||||
'America/Regina': 'CA',
|
||||
'America/Resolute': 'CA',
|
||||
'America/Rio_Branco': 'BR',
|
||||
'America/Santarem': 'BR',
|
||||
'America/Santiago': 'CL',
|
||||
'America/Santo_Domingo': 'DO',
|
||||
'America/Sao_Paulo': 'BR',
|
||||
'America/Scoresbysund': 'GL',
|
||||
'America/Sitka': 'US',
|
||||
'America/St_Barthelemy': 'BL',
|
||||
'America/St_Johns': 'CA',
|
||||
'America/St_Kitts': 'KN',
|
||||
'America/St_Lucia': 'LC',
|
||||
'America/St_Thomas': 'VI',
|
||||
'America/St_Vincent': 'VC',
|
||||
'America/Swift_Current': 'CA',
|
||||
'America/Tegucigalpa': 'HN',
|
||||
'America/Thule': 'GL',
|
||||
'America/Tijuana': 'MX',
|
||||
'America/Toronto': 'CA',
|
||||
'America/Tortola': 'VG',
|
||||
'America/Vancouver': 'CA',
|
||||
'America/Whitehorse': 'CA',
|
||||
'America/Winnipeg': 'CA',
|
||||
'America/Yakutat': 'US',
|
||||
'Antarctica/Casey': 'AQ',
|
||||
'Antarctica/Davis': 'AQ',
|
||||
'Antarctica/DumontDUrville': 'AQ',
|
||||
'Antarctica/Macquarie': 'AU',
|
||||
'Antarctica/Mawson': 'AQ',
|
||||
'Antarctica/McMurdo': 'AQ',
|
||||
'Antarctica/Palmer': 'AQ',
|
||||
'Antarctica/Rothera': 'AQ',
|
||||
'Antarctica/Syowa': 'AQ',
|
||||
'Antarctica/Troll': 'AQ',
|
||||
'Antarctica/Vostok': 'AQ',
|
||||
'Arctic/Longyearbyen': 'SJ',
|
||||
'Asia/Aden': 'YE',
|
||||
'Asia/Almaty': 'KZ',
|
||||
'Asia/Amman': 'JO',
|
||||
'Asia/Anadyr': 'RU',
|
||||
'Asia/Aqtau': 'KZ',
|
||||
'Asia/Aqtobe': 'KZ',
|
||||
'Asia/Ashgabat': 'TM',
|
||||
'Asia/Atyrau': 'KZ',
|
||||
'Asia/Baghdad': 'IQ',
|
||||
'Asia/Bahrain': 'BH',
|
||||
'Asia/Baku': 'AZ',
|
||||
'Asia/Bangkok': 'TH',
|
||||
'Asia/Barnaul': 'RU',
|
||||
'Asia/Beirut': 'LB',
|
||||
'Asia/Bishkek': 'KG',
|
||||
'Asia/Brunei': 'BN',
|
||||
'Asia/Calcutta': 'IN',
|
||||
'Asia/Chita': 'RU',
|
||||
'Asia/Colombo': 'LK',
|
||||
'Asia/Damascus': 'SY',
|
||||
'Asia/Dhaka': 'BD',
|
||||
'Asia/Dili': 'TL',
|
||||
'Asia/Dubai': 'AE',
|
||||
'Asia/Dushanbe': 'TJ',
|
||||
'Asia/Famagusta': 'CY',
|
||||
'Asia/Gaza': 'PS',
|
||||
'Asia/Hebron': 'PS',
|
||||
'Asia/Ho_Chi_Minh': 'VN',
|
||||
'Asia/Hong_Kong': 'HK',
|
||||
'Asia/Hovd': 'MN',
|
||||
'Asia/Irkutsk': 'RU',
|
||||
'Asia/Jakarta': 'ID',
|
||||
'Asia/Jayapura': 'ID',
|
||||
'Asia/Jerusalem': 'IL',
|
||||
'Asia/Kabul': 'AF',
|
||||
'Asia/Kamchatka': 'RU',
|
||||
'Asia/Karachi': 'PK',
|
||||
'Asia/Kathmandu': 'NP',
|
||||
'Asia/Katmandu': 'NP',
|
||||
'Asia/Khandyga': 'RU',
|
||||
'Asia/Kolkata': 'IN',
|
||||
'Asia/Krasnoyarsk': 'RU',
|
||||
'Asia/Kuala_Lumpur': 'MY',
|
||||
'Asia/Kuching': 'MY',
|
||||
'Asia/Kuwait': 'KW',
|
||||
'Asia/Macau': 'MO',
|
||||
'Asia/Magadan': 'RU',
|
||||
'Asia/Makassar': 'ID',
|
||||
'Asia/Manila': 'PH',
|
||||
'Asia/Muscat': 'OM',
|
||||
'Asia/Nicosia': 'CY',
|
||||
'Asia/Novokuznetsk': 'RU',
|
||||
'Asia/Novosibirsk': 'RU',
|
||||
'Asia/Omsk': 'RU',
|
||||
'Asia/Oral': 'KZ',
|
||||
'Asia/Phnom_Penh': 'KH',
|
||||
'Asia/Pontianak': 'ID',
|
||||
'Asia/Pyongyang': 'KP',
|
||||
'Asia/Qatar': 'QA',
|
||||
'Asia/Qostanay': 'KZ',
|
||||
'Asia/Qyzylorda': 'KZ',
|
||||
'Asia/Rangoon': 'MM',
|
||||
'Asia/Riyadh': 'SA',
|
||||
'Asia/Saigon': 'VN',
|
||||
'Asia/Sakhalin': 'RU',
|
||||
'Asia/Samarkand': 'UZ',
|
||||
'Asia/Seoul': 'KR',
|
||||
'Asia/Shanghai': 'CN',
|
||||
'Asia/Singapore': 'SG',
|
||||
'Asia/Srednekolymsk': 'RU',
|
||||
'Asia/Taipei': 'TW',
|
||||
'Asia/Tashkent': 'UZ',
|
||||
'Asia/Tbilisi': 'GE',
|
||||
'Asia/Tehran': 'IR',
|
||||
'Asia/Thimphu': 'BT',
|
||||
'Asia/Tokyo': 'JP',
|
||||
'Asia/Tomsk': 'RU',
|
||||
'Asia/Ulaanbaatar': 'MN',
|
||||
'Asia/Urumqi': 'CN',
|
||||
'Asia/Ust-Nera': 'RU',
|
||||
'Asia/Vientiane': 'LA',
|
||||
'Asia/Vladivostok': 'RU',
|
||||
'Asia/Yakutsk': 'RU',
|
||||
'Asia/Yangon': 'MM',
|
||||
'Asia/Yekaterinburg': 'RU',
|
||||
'Asia/Yerevan': 'AM',
|
||||
'Atlantic/Azores': 'PT',
|
||||
'Atlantic/Bermuda': 'BM',
|
||||
'Atlantic/Canary': 'ES',
|
||||
'Atlantic/Cape_Verde': 'CV',
|
||||
'Atlantic/Faeroe': 'FO',
|
||||
'Atlantic/Faroe': 'FO',
|
||||
'Atlantic/Madeira': 'PT',
|
||||
'Atlantic/Reykjavik': 'IS',
|
||||
'Atlantic/South_Georgia': 'GS',
|
||||
'Atlantic/St_Helena': 'SH',
|
||||
'Atlantic/Stanley': 'FK',
|
||||
'Australia/Adelaide': 'AU',
|
||||
'Australia/Brisbane': 'AU',
|
||||
'Australia/Broken_Hill': 'AU',
|
||||
'Australia/Darwin': 'AU',
|
||||
'Australia/Eucla': 'AU',
|
||||
'Australia/Hobart': 'AU',
|
||||
'Australia/Lindeman': 'AU',
|
||||
'Australia/Lord_Howe': 'AU',
|
||||
'Australia/Melbourne': 'AU',
|
||||
'Australia/Perth': 'AU',
|
||||
'Australia/Sydney': 'AU',
|
||||
'Europe/Amsterdam': 'NL',
|
||||
'Europe/Andorra': 'AD',
|
||||
'Europe/Astrakhan': 'RU',
|
||||
'Europe/Athens': 'GR',
|
||||
'Europe/Belgrade': 'RS',
|
||||
'Europe/Berlin': 'DE',
|
||||
'Europe/Bratislava': 'SK',
|
||||
'Europe/Brussels': 'BE',
|
||||
'Europe/Bucharest': 'RO',
|
||||
'Europe/Budapest': 'HU',
|
||||
'Europe/Busingen': 'DE',
|
||||
'Europe/Chisinau': 'MD',
|
||||
'Europe/Copenhagen': 'DK',
|
||||
'Europe/Dublin': 'IE',
|
||||
'Europe/Gibraltar': 'GI',
|
||||
'Europe/Guernsey': 'GG',
|
||||
'Europe/Helsinki': 'FI',
|
||||
'Europe/Isle_of_Man': 'IM',
|
||||
'Europe/Istanbul': 'TR',
|
||||
'Europe/Jersey': 'JE',
|
||||
'Europe/Kaliningrad': 'RU',
|
||||
'Europe/Kiev': 'UA',
|
||||
'Europe/Kirov': 'RU',
|
||||
'Europe/Kyiv': 'UA',
|
||||
'Europe/Lisbon': 'PT',
|
||||
'Europe/Ljubljana': 'SI',
|
||||
'Europe/London': 'GB',
|
||||
'Europe/Luxembourg': 'LU',
|
||||
'Europe/Madrid': 'ES',
|
||||
'Europe/Malta': 'MT',
|
||||
'Europe/Mariehamn': 'AX',
|
||||
'Europe/Minsk': 'BY',
|
||||
'Europe/Monaco': 'MC',
|
||||
'Europe/Moscow': 'RU',
|
||||
'Europe/Oslo': 'NO',
|
||||
'Europe/Paris': 'FR',
|
||||
'Europe/Podgorica': 'ME',
|
||||
'Europe/Prague': 'CZ',
|
||||
'Europe/Riga': 'LV',
|
||||
'Europe/Rome': 'IT',
|
||||
'Europe/Samara': 'RU',
|
||||
'Europe/San_Marino': 'SM',
|
||||
'Europe/Sarajevo': 'BA',
|
||||
'Europe/Saratov': 'RU',
|
||||
'Europe/Simferopol': 'UA',
|
||||
'Europe/Skopje': 'MK',
|
||||
'Europe/Sofia': 'BG',
|
||||
'Europe/Stockholm': 'SE',
|
||||
'Europe/Tallinn': 'EE',
|
||||
'Europe/Tirane': 'AL',
|
||||
'Europe/Ulyanovsk': 'RU',
|
||||
'Europe/Vaduz': 'LI',
|
||||
'Europe/Vatican': 'VA',
|
||||
'Europe/Vienna': 'AT',
|
||||
'Europe/Vilnius': 'LT',
|
||||
'Europe/Volgograd': 'RU',
|
||||
'Europe/Warsaw': 'PL',
|
||||
'Europe/Zagreb': 'HR',
|
||||
'Europe/Zurich': 'CH',
|
||||
'Indian/Antananarivo': 'MG',
|
||||
'Indian/Chagos': 'IO',
|
||||
'Indian/Christmas': 'CX',
|
||||
'Indian/Cocos': 'CC',
|
||||
'Indian/Comoro': 'KM',
|
||||
'Indian/Kerguelen': 'TF',
|
||||
'Indian/Mahe': 'SC',
|
||||
'Indian/Maldives': 'MV',
|
||||
'Indian/Mauritius': 'MU',
|
||||
'Indian/Mayotte': 'YT',
|
||||
'Indian/Reunion': 'RE',
|
||||
'Pacific/Apia': 'WS',
|
||||
'Pacific/Auckland': 'NZ',
|
||||
'Pacific/Bougainville': 'PG',
|
||||
'Pacific/Chatham': 'NZ',
|
||||
'Pacific/Chuuk': 'FM',
|
||||
'Pacific/Easter': 'CL',
|
||||
'Pacific/Efate': 'VU',
|
||||
'Pacific/Enderbury': 'KI',
|
||||
'Pacific/Fakaofo': 'TK',
|
||||
'Pacific/Fiji': 'FJ',
|
||||
'Pacific/Funafuti': 'TV',
|
||||
'Pacific/Galapagos': 'EC',
|
||||
'Pacific/Gambier': 'PF',
|
||||
'Pacific/Guadalcanal': 'SB',
|
||||
'Pacific/Guam': 'GU',
|
||||
'Pacific/Honolulu': 'US',
|
||||
'Pacific/Kanton': 'KI',
|
||||
'Pacific/Kiritimati': 'KI',
|
||||
'Pacific/Kosrae': 'FM',
|
||||
'Pacific/Kwajalein': 'MH',
|
||||
'Pacific/Majuro': 'MH',
|
||||
'Pacific/Marquesas': 'PF',
|
||||
'Pacific/Midway': 'UM',
|
||||
'Pacific/Nauru': 'NR',
|
||||
'Pacific/Niue': 'NU',
|
||||
'Pacific/Norfolk': 'NF',
|
||||
'Pacific/Noumea': 'NC',
|
||||
'Pacific/Pago_Pago': 'AS',
|
||||
'Pacific/Palau': 'PW',
|
||||
'Pacific/Pitcairn': 'PN',
|
||||
'Pacific/Pohnpei': 'FM',
|
||||
'Pacific/Ponape': 'FM',
|
||||
'Pacific/Port_Moresby': 'PG',
|
||||
'Pacific/Rarotonga': 'CK',
|
||||
'Pacific/Saipan': 'MP',
|
||||
'Pacific/Tahiti': 'PF',
|
||||
'Pacific/Tarawa': 'KI',
|
||||
'Pacific/Tongatapu': 'TO',
|
||||
'Pacific/Truk': 'FM',
|
||||
'Pacific/Wake': 'UM',
|
||||
'Pacific/Wallis': 'WF',
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
|
||||
import { START_VIEW } from './camera.js';
|
||||
|
||||
/**
|
||||
* The visitor's country, guessed from the browser's time zone and, for a zone
|
||||
* that belongs to no country (UTC), the region of a preferred language
|
||||
* ("en-GB"). Nothing leaves the browser. Null when neither names one.
|
||||
* @param {{timeZone?: string|null, languages?: readonly string[]}} [where]
|
||||
* @returns {string|null} ISO 3166 code, e.g. 'DE'
|
||||
*/
|
||||
export function homeCountry({
|
||||
timeZone = currentTimeZone(),
|
||||
languages = globalThis.navigator?.languages ?? [],
|
||||
} = {}) {
|
||||
const byZone = ZONE_COUNTRIES[timeZone];
|
||||
if (byZone) return byZone;
|
||||
for (const language of languages) {
|
||||
const region = regionOf(language);
|
||||
if (region && COUNTRY_CENTRES[region]) return region;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The start view over the visitor's country: the planet from `base.height`,
|
||||
* looking straight down on the country's centre. `base` where the country is
|
||||
* unknown.
|
||||
* @param {{timeZone?: string|null, languages?: readonly string[],
|
||||
* base?: {lon: number, lat: number, height: number}}} [where]
|
||||
*/
|
||||
export function homeCountryView({ base = START_VIEW, ...where } = {}) {
|
||||
const centre = COUNTRY_CENTRES[homeCountry(where)];
|
||||
if (!centre) return base;
|
||||
const [lat, lon] = centre;
|
||||
return Object.freeze({ lon, lat, height: base.height });
|
||||
}
|
||||
|
||||
function currentTimeZone() {
|
||||
try {
|
||||
return new Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function regionOf(language) {
|
||||
try {
|
||||
return new Intl.Locale(language).region ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { homeCountry, homeCountryView } from './homeCountry.js';
|
||||
import { START_VIEW } from './camera.js';
|
||||
import { COUNTRY_CENTRES, ZONE_COUNTRIES } from './data/homeCountries.js';
|
||||
|
||||
test('the time zone names the country, in its tzdata or ICU name', () => {
|
||||
assert.equal(homeCountry({ timeZone: 'Europe/Berlin', languages: [] }), 'DE');
|
||||
assert.equal(homeCountry({ timeZone: 'Asia/Kolkata', languages: [] }), 'IN');
|
||||
assert.equal(homeCountry({ timeZone: 'Asia/Calcutta', languages: [] }), 'IN');
|
||||
assert.equal(homeCountry({ timeZone: 'Europe/Kiev', languages: [] }), 'UA');
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'America/Chicago', languages: ['de-DE'] }),
|
||||
'US',
|
||||
'the zone outranks the language',
|
||||
);
|
||||
});
|
||||
|
||||
test("a zone of no country falls back to a language's region", () => {
|
||||
assert.equal(
|
||||
homeCountry({ timeZone: 'UTC', languages: ['fr', 'en-GB'] }),
|
||||
'GB',
|
||||
);
|
||||
assert.equal(homeCountry({ timeZone: 'Etc/UTC', languages: ['ru'] }), null);
|
||||
assert.equal(homeCountry({ timeZone: null, languages: [] }), null);
|
||||
});
|
||||
|
||||
test('the start view looks down on the country from the planet height', () => {
|
||||
const view = homeCountryView({ timeZone: 'Asia/Tokyo', languages: [] });
|
||||
assert.deepEqual(
|
||||
[view.lat, view.lon, view.height],
|
||||
[...COUNTRY_CENTRES.JP, START_VIEW.height],
|
||||
);
|
||||
assert.equal(
|
||||
homeCountryView({ timeZone: 'UTC', languages: [] }),
|
||||
START_VIEW,
|
||||
'unknown: the default start',
|
||||
);
|
||||
});
|
||||
|
||||
test('every zone has a country with a centre on the globe', () => {
|
||||
for (const [zone, country] of Object.entries(ZONE_COUNTRIES)) {
|
||||
const centre = COUNTRY_CENTRES[country];
|
||||
assert.ok(centre, `${zone} → ${country}`);
|
||||
const [lat, lon] = centre;
|
||||
assert.ok(Math.abs(lat) <= 90 && Math.abs(lon) <= 180, country);
|
||||
}
|
||||
// Countries whose largest part is not where their centroid would be.
|
||||
const [usLat, usLon] = COUNTRY_CENTRES.US;
|
||||
assert.ok(usLat > 30 && usLat < 45 && usLon > -110 && usLon < -85);
|
||||
const [frLat, frLon] = COUNTRY_CENTRES.FR;
|
||||
assert.ok(frLat > 42 && frLat < 50 && frLon > -2 && frLon < 8);
|
||||
});
|
||||
@@ -1,120 +0,0 @@
|
||||
// A 429 from /api/adsbdb must not leave an aircraft's metadata empty for the
|
||||
// rest of the session.
|
||||
//
|
||||
// Both enrichment queues (Flights and Local ADS-B) mark a key as seen before
|
||||
// they dispatch it, so a second request for the same aircraft is dropped. That
|
||||
// is right for an answer or a 404, and wrong for a refusal: the server said
|
||||
// "later", not "no". These cases drive the real queues against a source that
|
||||
// refuses once and then answers.
|
||||
//
|
||||
// Run with: npm test
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { LiveSourceError } from '../sources/live/contract.js';
|
||||
import { createLocalAdsbEnrichment } from './localAdsb/enrichment.js';
|
||||
import { createFlightState } from './flights/state.js';
|
||||
import { createEnrichment } from './flights/enrichment.js';
|
||||
|
||||
/** Short real delay, so the case needs no clock control. */
|
||||
const RETRY_AFTER_MS = 20;
|
||||
|
||||
/** A source that refuses the first lookup with a 429, then answers. */
|
||||
function refusingOnce() {
|
||||
const calls = [];
|
||||
return {
|
||||
calls,
|
||||
async getEnrichment(query) {
|
||||
calls.push(query);
|
||||
if (calls.length === 1)
|
||||
throw new LiveSourceError('limited', 'Flights rate limited', {
|
||||
status: 429,
|
||||
retryAfterMs: RETRY_AFTER_MS,
|
||||
});
|
||||
return { found: true, typeCode: 'B738', typeName: 'Boeing 737-800' };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const settle = (ms) => new Promise((done) => setTimeout(done, ms));
|
||||
|
||||
/** The services Flights enrichment reads: neither military nor a TR-3B. */
|
||||
const enrichServices = {
|
||||
militaryRegistry: { isMilitaryIcao: () => false },
|
||||
aircraftPresentation: { isTr3b: () => false },
|
||||
};
|
||||
|
||||
test('Local ADS-B asks again after a 429 once the refusal has passed', async (t) => {
|
||||
const source = refusingOnce();
|
||||
const enrichment = createLocalAdsbEnrichment({ source, onChange() {} });
|
||||
t.after(() => enrichment.destroy());
|
||||
const record = { icao: 'abc123', category: 'A3' };
|
||||
|
||||
enrichment.request(record);
|
||||
await settle(0);
|
||||
assert.equal(source.calls.length, 1);
|
||||
enrichment.request(record);
|
||||
await settle(0);
|
||||
assert.equal(source.calls.length, 1, 'no retry inside the refusal window');
|
||||
|
||||
await settle(RETRY_AFTER_MS + 250); // refusal window, then the 200 ms drip
|
||||
enrichment.request(record);
|
||||
await settle(250);
|
||||
assert.equal(source.calls.length, 2, 'the aircraft is asked for again');
|
||||
assert.equal(enrichment.get('abc123')?.typeCode, 'B738');
|
||||
});
|
||||
|
||||
test('an answered lookup is still asked for only once', async (t) => {
|
||||
const calls = [];
|
||||
const enrichment = createLocalAdsbEnrichment({
|
||||
source: {
|
||||
async getEnrichment(query) {
|
||||
calls.push(query);
|
||||
return { found: false };
|
||||
},
|
||||
},
|
||||
onChange() {},
|
||||
});
|
||||
t.after(() => enrichment.destroy());
|
||||
enrichment.request({ icao: 'def456' });
|
||||
await settle(RETRY_AFTER_MS + 250);
|
||||
enrichment.request({ icao: 'def456' });
|
||||
await settle(250);
|
||||
assert.equal(calls.length, 1, 'a 404 is an answer, not a refusal');
|
||||
});
|
||||
|
||||
test('Flights asks again after a 429 once the refusal has passed', async (t) => {
|
||||
const source = refusingOnce();
|
||||
const flightState = createFlightState({
|
||||
source,
|
||||
services: {
|
||||
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
|
||||
},
|
||||
});
|
||||
t.after(() => flightState.lifetime.abort());
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices,
|
||||
parts: {},
|
||||
});
|
||||
let applied = null;
|
||||
const ask = () =>
|
||||
enrichment._enqueueEnrich(
|
||||
't:abc123',
|
||||
{ kind: 'type', id: 'abc123' },
|
||||
(data) => {
|
||||
applied = data;
|
||||
},
|
||||
);
|
||||
|
||||
ask();
|
||||
await settle(0);
|
||||
ask();
|
||||
await settle(0);
|
||||
assert.equal(source.calls.length, 1, 'no retry inside the refusal window');
|
||||
|
||||
await settle(RETRY_AFTER_MS + 250);
|
||||
ask();
|
||||
await settle(250);
|
||||
assert.equal(source.calls.length, 2, 'the aircraft is asked for again');
|
||||
assert.equal(applied?.typeCode, 'B738');
|
||||
});
|
||||
@@ -63,25 +63,10 @@ export function createEnrichment({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a temporarily failed lookup stays unasked. A rate-limit refusal
|
||||
* says itself when to ask again (`retryAfterMs`), so that wins; any other
|
||||
* temporary failure waits ENRICH_RETRY_COOLDOWN_MS.
|
||||
* @param {*} error The rejection, as `LiveSourceError` carries it.
|
||||
* @returns {number} Milliseconds.
|
||||
*/
|
||||
function _enrichCooldownMs(error) {
|
||||
const hinted = Number(error?.retryAfterMs);
|
||||
return error?.code === 'limited' && Number.isFinite(hinted) && hinted > 0
|
||||
? hinted
|
||||
: ENRICH_RETRY_COOLDOWN_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask each key at most once per session, except that a lookup whose source
|
||||
* failed temporarily (rejected or threw) may be asked again after
|
||||
* ENRICH_RETRY_COOLDOWN_MS, or after the refusal's own `retryAfterMs` for a
|
||||
* rate limit (see _enrichCooldownMs); an answer, found or not, and a permanent
|
||||
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
|
||||
* refusal (see _enrichFailureIsFinal) are final.
|
||||
* @param {string} key Session-unique lookup key.
|
||||
* @param {object} query The source's enrichment query.
|
||||
@@ -148,7 +133,7 @@ export function createEnrichment({
|
||||
flightState._enrichSeen.delete(job.key);
|
||||
flightState._enrichRetryAfter.set(
|
||||
job.key,
|
||||
Date.now() + _enrichCooldownMs(error),
|
||||
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
|
||||
);
|
||||
},
|
||||
)
|
||||
|
||||
@@ -35,8 +35,7 @@ export function localAdsbClass(record, meta = null) {
|
||||
* session, at most four requests are in flight and dispatches are dripped
|
||||
* 200 ms apart. Only the selected aircraft (type + route) and aircraft that
|
||||
* are about to render as 3D models (type) are ever looked up — never one
|
||||
* request per contact per tick. A rate-limit refusal is not an answer: the key
|
||||
* becomes askable again once the refusal's retry-after has passed.
|
||||
* request per contact per tick.
|
||||
* @param {object} options
|
||||
* @param {{getEnrichment?: Function}|null} options.source Flights source.
|
||||
* @param {() => void} options.onChange Called when metadata arrives.
|
||||
@@ -54,7 +53,6 @@ export function createLocalAdsbEnrichment({
|
||||
let active = 0;
|
||||
let lastDispatchAt = -Infinity;
|
||||
let dripTimer = null;
|
||||
const retryTimers = new Set();
|
||||
let lifetime = new AbortController();
|
||||
|
||||
function entry(icao) {
|
||||
@@ -70,7 +68,7 @@ export function createLocalAdsbEnrichment({
|
||||
function enqueue(key, query, apply, priority) {
|
||||
if (typeof source?.getEnrichment !== 'function' || seen.has(key)) return;
|
||||
seen.add(key);
|
||||
const job = { key, query, apply };
|
||||
const job = { query, apply };
|
||||
if (priority) queue.unshift(job);
|
||||
else queue.push(job);
|
||||
drain();
|
||||
@@ -99,10 +97,8 @@ export function createLocalAdsbEnrichment({
|
||||
onChange?.();
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
// Enrichment never surfaces errors; a 429 only defers the key.
|
||||
if (error?.code === 'limited')
|
||||
forgetLater(job.key, error.retryAfterMs);
|
||||
.catch(() => {
|
||||
/* enrichment never surfaces errors */
|
||||
})
|
||||
.finally(() => {
|
||||
if (signal.aborted) return;
|
||||
@@ -112,14 +108,6 @@ export function createLocalAdsbEnrichment({
|
||||
}
|
||||
}
|
||||
|
||||
function forgetLater(key, delayMs) {
|
||||
const timer = setTimeout(() => {
|
||||
retryTimers.delete(timer);
|
||||
seen.delete(key);
|
||||
}, delayMs);
|
||||
retryTimers.add(timer);
|
||||
}
|
||||
|
||||
return {
|
||||
/** @param {string} icao @returns {object|null} */
|
||||
get(icao) {
|
||||
@@ -172,8 +160,6 @@ export function createLocalAdsbEnrichment({
|
||||
lifetime = new AbortController();
|
||||
clearTimeout(dripTimer);
|
||||
dripTimer = null;
|
||||
for (const timer of retryTimers) clearTimeout(timer);
|
||||
retryTimers.clear();
|
||||
queue.length = 0;
|
||||
active = 0;
|
||||
},
|
||||
|
||||
@@ -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}` }));
|
||||
|
||||
@@ -581,6 +581,8 @@ export function createRecentImageryLayer({
|
||||
for (const slotId of SLOT_IDS) {
|
||||
const candidate = candidateFor(shown[slotId]);
|
||||
if (candidate && _hostInfo.collection) {
|
||||
const { availableBoxes, emptyBoxes } =
|
||||
thumbnails.get(candidate.key) ?? {};
|
||||
renderer.showSlot(slotId, candidate, _box, {
|
||||
alpha: _alpha,
|
||||
splitDirection: !live
|
||||
@@ -588,6 +590,8 @@ export function createRecentImageryLayer({
|
||||
: (slotId === 'a') !== _swapped
|
||||
? 'left'
|
||||
: 'right',
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
});
|
||||
} else {
|
||||
renderer.hideSlot(slotId);
|
||||
@@ -897,21 +901,22 @@ export function createRecentImageryLayer({
|
||||
// The new automatic day's probe may have been cancelled off-screen.
|
||||
requestThumbnails();
|
||||
}
|
||||
if (pruned) syncRender();
|
||||
const followed =
|
||||
Boolean(_followKey) &&
|
||||
_followKey === _focusKey &&
|
||||
drapable(candidateFor(_followKey)) &&
|
||||
applyPreview(_followKey);
|
||||
// A pinned or previewed day that was still being probed drapes now.
|
||||
const shown = plan();
|
||||
const owned = renderer.getOwned?.() || {};
|
||||
const drapesChanged = SLOT_IDS.some(
|
||||
(slotId) => (owned[slotId]?.key || null) !== shown[slotId],
|
||||
);
|
||||
if (drapesChanged && !pruned && !followed) syncRender();
|
||||
// One render per probe: the key can stay the same while its halves change.
|
||||
// A host found moved changes the divider, so the panel renders in full.
|
||||
const moved = !followed && syncHost();
|
||||
if (!followed) syncRender();
|
||||
notify('thumbnail');
|
||||
if (pruned || followed || drapesChanged) notify();
|
||||
if (pruned || followed || drapesChanged || moved) notify();
|
||||
});
|
||||
syncHost();
|
||||
if (_box && !_candidates.length) void runSearch();
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import assert from 'node:assert/strict';
|
||||
import { until } from '../../testSupport/kartaViewFakes.mjs';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { boxKey, nonCrossingBoxes } from './model.js';
|
||||
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
|
||||
import { acquireImageryComparison } from '../../maps/imageryComparison.js';
|
||||
import { MapSourceController } from '../../maps/controller.js';
|
||||
@@ -14,11 +18,16 @@ import {
|
||||
SPLIT_PUBLISH_MS,
|
||||
createRecentImageryLayer,
|
||||
} from './index.js';
|
||||
import { createImageryBoxPreview } from './rendering.js';
|
||||
import {
|
||||
createImageryBoxPreview,
|
||||
createRecentImageryRenderer,
|
||||
} from './rendering.js';
|
||||
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import {
|
||||
BOX,
|
||||
CANDIDATES,
|
||||
FIJI_BOX,
|
||||
boxToolFakes,
|
||||
candidate,
|
||||
fakeCatalog,
|
||||
@@ -1564,6 +1573,424 @@ test('a voice search cancelled mid-flight says so instead of looking empty', asy
|
||||
assert.equal(f.snap().notice, 'Search cancelled');
|
||||
});
|
||||
|
||||
test('a box dragged across the dateline is searched, listed and draped as one box', async () => {
|
||||
const f = fixture();
|
||||
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
|
||||
f.layer.enable();
|
||||
assert.equal(f.layer.setBox(box), true);
|
||||
assert.equal(f.snap().boxError, null);
|
||||
assert.deepEqual(f.catalog.searches.at(-1).request.box, box);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.equal(f.snap().candidates.length, 4);
|
||||
assert.equal(f.snap().preview.key, S18);
|
||||
assert.equal(f.drapes().a, `${S18}|none`, 'the crossing box is draped');
|
||||
assert.equal(f.snap().boxSizeKm.width < 100, true, 'the short arc, not 360°');
|
||||
});
|
||||
|
||||
test('a new probe of a shown dateline day hands the renderer the halves it now allows', async () => {
|
||||
const f = fixture();
|
||||
const priorGet = f.thumbnails.get;
|
||||
const box = { west: 179.8, south: 10, east: -179.8, north: 10.4 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
let boxes = [west];
|
||||
f.thumbnails.get = (key) => ({ ...priorGet(key), availableBoxes: boxes });
|
||||
f.layer.enable();
|
||||
f.layer.setBox(box);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
f.thumbnails.probeRequested();
|
||||
const slot = Object.keys(f.owned()).find((id) => f.owned()[id]);
|
||||
assert.ok(slot, 'a day is already on the map');
|
||||
const key = f.owned()[slot].key;
|
||||
assert.deepEqual(f.owned()[slot].availableBoxes, [west]);
|
||||
boxes = [west, east];
|
||||
f.thumbnails.probe(key, 'present');
|
||||
assert.deepEqual(f.owned()[slot].availableBoxes, boxes);
|
||||
f.layer.destroy();
|
||||
});
|
||||
|
||||
const sideOf = (url) =>
|
||||
Number(new URL(url).searchParams.get('BBOX').split(',')[1]) > 0
|
||||
? 'west'
|
||||
: 'east';
|
||||
/** A snapshot response; `present: null` sends no Data-Present header. */
|
||||
const snapshotAnswer = (present, status = 200) =>
|
||||
new Response('img', {
|
||||
status,
|
||||
headers: present === null ? {} : { 'Data-Present': String(present) },
|
||||
});
|
||||
|
||||
function realLayer({
|
||||
fetchImpl,
|
||||
candidates,
|
||||
maxDecoded = 16,
|
||||
halfDeadlineMs = 50,
|
||||
}) {
|
||||
const source = createRecentImagerySource({ fetchImpl, halfDeadlineMs });
|
||||
let nextUrl = 0;
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
createObjectUrl: () => `blob:${++nextUrl}`,
|
||||
revokeObjectUrl: () => {},
|
||||
maxDecoded,
|
||||
});
|
||||
const globe = fakeGlobePort();
|
||||
const layer = createRecentImageryLayer({
|
||||
catalog: {
|
||||
searchHls: async () => ({ candidates, truncated: false, errors: [] }),
|
||||
},
|
||||
renderer: createRecentImageryRenderer(),
|
||||
thumbnails: loader,
|
||||
host: () => ({ collection: globe.imagery, kind: 'globe' }),
|
||||
globeOf: () => globe,
|
||||
now: () => new Date('2026-11-13T15:00:00Z'),
|
||||
});
|
||||
layer.init({ camera: {} });
|
||||
return { layer, loader, globe };
|
||||
}
|
||||
|
||||
test('a VIIRS dateline day with data on one side drapes only that side through the real layer', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-10');
|
||||
const sides = [];
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async (url) => {
|
||||
const side = sideOf(url);
|
||||
sides.push(side);
|
||||
return snapshotAnswer(side === 'east');
|
||||
},
|
||||
});
|
||||
layer.setSources({ viirs: true });
|
||||
layer.enable();
|
||||
assert.equal(layer.setBox(FIJI_BOX), true);
|
||||
// The probe asks about both halves, wider first. The layer drapes the one with data.
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length > 0, { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(sides, ['east', 'west']);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[nonCrossingBoxes(FIJI_BOX)[1]],
|
||||
);
|
||||
assert.equal(loader.get(day.key).status, 'present');
|
||||
const snapshot = layer.getSnapshot();
|
||||
assert.equal(snapshot.candidates[0].thumbnail.status, 'present');
|
||||
assert.equal(snapshot.candidates[0].drapable, true);
|
||||
assert.equal(snapshot.auto?.key, day.key);
|
||||
layer.destroy();
|
||||
assert.equal(globe.layers.length, 0);
|
||||
});
|
||||
|
||||
test('a dateline day both halves confirm empty never drapes and leaves the strip', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-10');
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async () => snapshotAnswer(false),
|
||||
});
|
||||
layer.setSources({ viirs: true });
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'empty', { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(
|
||||
layer.getSnapshot().candidates.some((c) => c.key === day.key),
|
||||
false,
|
||||
'an empty day leaves the strip',
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
for (const [label, box] of [
|
||||
['a plain box', { west: -98, south: 30, east: -97, north: 31 }],
|
||||
['a dateline box', FIJI_BOX],
|
||||
]) {
|
||||
test(`an HLS day draped before its probe keeps its layers when the probe confirms ${label}`, async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async () => {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(box);
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length === nonCrossingBoxes(box).length, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const before = [...globe.layers];
|
||||
const added = globe.added.length;
|
||||
release();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(globe.added.length, added);
|
||||
assert.deepEqual(globe.layers, before);
|
||||
layer.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('a re-probe of a present VIIRS dateline day keeps a half that failed this time', async () => {
|
||||
const day1 = candidate('VIIRS', '2026-11-10');
|
||||
const day2 = candidate('VIIRS', '2026-11-11');
|
||||
let eastCalls = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((resolve) => {
|
||||
releaseDay2 = resolve;
|
||||
});
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) await gate;
|
||||
else if (sideOf(url) === 'east' && ++eastCalls === 2)
|
||||
throw new TypeError('Failed to fetch');
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.setSources({ hls: false, viirs: true });
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day2.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
layer.setAssignment('a', day1.key);
|
||||
assert.equal(
|
||||
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).status, 'present');
|
||||
assert.equal(loader.get(day1.key).availableBoxes.length, 2);
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[west, east],
|
||||
'a half that failed on the re-probe stays draped',
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present HLS dateline day keeps a half confirmed empty when that half fails this time', async () => {
|
||||
const day1 = candidate('S30', '2026-11-10');
|
||||
const day2 = candidate('S30', '2026-11-11');
|
||||
let eastCalls = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((r) => (releaseDay2 = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
}
|
||||
if (sideOf(url) === 'east') {
|
||||
eastCalls += 1;
|
||||
if (eastCalls === 1) return snapshotAnswer(false);
|
||||
throw new TypeError('Failed to fetch');
|
||||
}
|
||||
return snapshotAnswer(true);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const [west] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
assert.equal(loader.get(day1.key).emptyBoxes.length, 1);
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day2.key).status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
layer.setAssignment('a', day1.key);
|
||||
assert.equal(
|
||||
await until(() => eastCalls === 2 && !loader.get(day1.key).loading, {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day1.key);
|
||||
assert.deepEqual(
|
||||
{
|
||||
available: entry.availableBoxes.length,
|
||||
empty: entry.emptyBoxes.length,
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ available: 1, empty: 1, layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a shown HLS day on a plain box stays draped after a probe without Data-Present', async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
let release;
|
||||
const gate = new Promise((r) => (release = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async () => {
|
||||
await gate;
|
||||
return snapshotAnswer(null);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox({ west: -98, south: 30, east: -97, north: 31 });
|
||||
assert.equal(
|
||||
await until(() => globe.layers.length === 1, { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
release();
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key).status === 'error', { ticks: 2000 }),
|
||||
true,
|
||||
);
|
||||
await until(() => false, { ticks: 50 });
|
||||
assert.equal(globe.layers.length, 1);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
for (const [label, failEast] of [
|
||||
['answers 503', async () => snapshotAnswer(null, 503)],
|
||||
[
|
||||
'rejects',
|
||||
async () => {
|
||||
throw new TypeError('Failed to fetch');
|
||||
},
|
||||
],
|
||||
['never answers', () => new Promise(() => {})],
|
||||
]) {
|
||||
test(`an HLS dateline day leaves out a half confirmed empty when the other half ${label}`, async () => {
|
||||
const day = candidate('S30', '2026-11-10');
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day],
|
||||
fetchImpl: async (url) =>
|
||||
sideOf(url) === 'west' ? snapshotAnswer(false) : failEast(),
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day.key)?.status === 'error', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
layer.setAssignment('a', day.key);
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day.key);
|
||||
const [west] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
{
|
||||
empty: (entry.emptyBoxes ?? []).map(boxKey),
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ empty: [boxKey(west)], layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('a re-probe of a present HLS dateline day takes a fresh empty half when the shown half has no Data-Present', async () => {
|
||||
const day1 = candidate('S30', '2026-11-10');
|
||||
const day2 = candidate('S30', '2026-11-11');
|
||||
let round = 0;
|
||||
let releaseDay2;
|
||||
const gate = new Promise((r) => (releaseDay2 = r));
|
||||
const { layer, loader, globe } = realLayer({
|
||||
candidates: [day2, day1],
|
||||
maxDecoded: 1,
|
||||
halfDeadlineMs: 5000,
|
||||
fetchImpl: async (url) => {
|
||||
if (new URL(url).searchParams.get('TIME') === day2.day) {
|
||||
await gate;
|
||||
return snapshotAnswer(true);
|
||||
}
|
||||
if (round === 0)
|
||||
return sideOf(url) === 'west'
|
||||
? snapshotAnswer(true)
|
||||
: snapshotAnswer(null);
|
||||
return sideOf(url) === 'west'
|
||||
? snapshotAnswer(null)
|
||||
: snapshotAnswer(false);
|
||||
},
|
||||
});
|
||||
layer.enable();
|
||||
layer.setBox(FIJI_BOX);
|
||||
assert.equal(
|
||||
await until(() => loader.get(day1.key)?.status === 'present', {
|
||||
ticks: 2000,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
round = 1;
|
||||
releaseDay2();
|
||||
assert.equal(
|
||||
await until(
|
||||
() =>
|
||||
loader.get(day2.key)?.status === 'present' &&
|
||||
loader.get(day1.key).objectUrl === null,
|
||||
{ ticks: 2000 },
|
||||
),
|
||||
true,
|
||||
);
|
||||
layer.setAssignment('a', day1.key);
|
||||
await until(() => false, { ticks: 50 });
|
||||
await until(() => !loader.get(day1.key).loading, { ticks: 2000 });
|
||||
await until(() => false, { ticks: 50 });
|
||||
const entry = loader.get(day1.key);
|
||||
const [, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.deepEqual(
|
||||
{
|
||||
status: entry.status,
|
||||
empty: (entry.emptyBoxes ?? []).map(boxKey),
|
||||
layers: globe.layers.length,
|
||||
},
|
||||
{ status: 'present', empty: [boxKey(east)], layers: 1 },
|
||||
);
|
||||
layer.destroy();
|
||||
});
|
||||
|
||||
test('a pick that probes empty after the automatic day lets the next ranked day drape', async () => {
|
||||
for (const order of [
|
||||
[S18, V15],
|
||||
|
||||
@@ -72,13 +72,11 @@ export const PRODUCTS = Object.freeze({
|
||||
|
||||
const finite = (value) => typeof value === 'number' && Number.isFinite(value);
|
||||
const toRadians = (degrees) => (degrees * Math.PI) / 180;
|
||||
/** A longitude brought back into ±180 after one step past it. */
|
||||
const wrapLon = (value) =>
|
||||
value > 180 ? value - 360 : value < -180 ? value + 360 : value;
|
||||
const pad2 = (value) => String(value).padStart(2, '0');
|
||||
|
||||
/**
|
||||
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
|
||||
* east are not swapped: west > east crosses the dateline and `validateBox`
|
||||
* rejects it. Null when any edge is nonfinite.
|
||||
*/
|
||||
/** A box edge as a number, or null when it is missing, blank or not numeric. */
|
||||
function edgeNumber(value) {
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? value : null;
|
||||
@@ -87,6 +85,11 @@ function edgeNumber(value) {
|
||||
return Number.isFinite(number) ? number : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce a box to `{ west, south, east, north }` with south ≤ north. West and
|
||||
* east are not swapped: west > east is the short arc across the dateline.
|
||||
* Null when any edge is nonfinite.
|
||||
*/
|
||||
function normalizeBox(box) {
|
||||
if (!box || typeof box !== 'object') return null;
|
||||
const [west, south, east, north] = [
|
||||
@@ -105,8 +108,45 @@ function normalizeBox(box) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Side lengths of a box in km: the box's own longitude span (never the
|
||||
* shorter way round the globe) at its mid-latitude, and its latitude span.
|
||||
* Degrees of longitude going east from `west` to `east`. A west > east pair
|
||||
* wraps across the antimeridian (`lonSpanDeg(170, -170)` is 20 and
|
||||
* `lonSpanDeg(10, -10)` is 340). A west <= east pair is `east - west`,
|
||||
* even the long way round.
|
||||
* @param {number} west Degrees.
|
||||
* @param {number} east Degrees.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function lonSpanDeg(west, east) {
|
||||
return east >= west ? east - west : east + 360 - west;
|
||||
}
|
||||
|
||||
/** A comparable key for a degrees box. */
|
||||
export const boxKey = (box) =>
|
||||
[box.west, box.south, box.east, box.north].map(Number).join(',');
|
||||
|
||||
/**
|
||||
* One or two boxes with west <= east that cover the same area. A dateline
|
||||
* box is split at ±180 so each side is a plain rectangle for a draped layer
|
||||
* or a Worldview request. A box with a missing or nonfinite edge is [].
|
||||
* So is a dateline box of zero width (west 180, east -180).
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {Array<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 +156,7 @@ export function boxSideKm(box) {
|
||||
const midLat = (normalized.south + normalized.north) / 2;
|
||||
return {
|
||||
width:
|
||||
(normalized.east - normalized.west) *
|
||||
lonSpanDeg(normalized.west, normalized.east) *
|
||||
KM_PER_DEG_LAT *
|
||||
Math.cos(toRadians(midLat)),
|
||||
height: (normalized.north - normalized.south) * KM_PER_DEG_LAT,
|
||||
@@ -126,9 +166,11 @@ export function boxSideKm(box) {
|
||||
const refuse = (reason, message) => ({ ok: false, reason, message });
|
||||
|
||||
/**
|
||||
* Validate a selection box for the catalog and the tile providers.
|
||||
* Validate a selection box for the catalog and the tile providers. A box
|
||||
* with west > east is the short arc across the dateline and is accepted
|
||||
* when that arc is under the size cap.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ ok: true, box: object } | { ok: false, reason: 'dateline' | 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
|
||||
* @returns {{ ok: true, box: object } | { ok: false, reason: 'polar' | 'degenerate' | 'too-large' | 'invalid', message: string }}
|
||||
*/
|
||||
export function validateBox(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
@@ -136,8 +178,6 @@ export function validateBox(box) {
|
||||
const { west, south, east, north } = normalized;
|
||||
if (Math.abs(west) > 180 || Math.abs(east) > 180)
|
||||
return refuse('invalid', msg('Longitudes must be within ±180°'));
|
||||
if (west > east)
|
||||
return refuse('dateline', msg('Select one side of the dateline'));
|
||||
if (
|
||||
Math.abs(south) > MERCATOR_LAT_LIMIT ||
|
||||
Math.abs(north) > MERCATOR_LAT_LIMIT
|
||||
@@ -146,7 +186,7 @@ export function validateBox(box) {
|
||||
'polar',
|
||||
`Imagery stops at ±${MERCATOR_LAT_LIMIT.toFixed(2)}° latitude`,
|
||||
);
|
||||
if (east === west || north === south)
|
||||
if (lonSpanDeg(west, east) === 0 || north === south)
|
||||
return refuse('degenerate', msg('Box must enclose an area'));
|
||||
const { width, height } = boxSideKm(normalized);
|
||||
if (width > MAX_BOX_SIDE_KM || height > MAX_BOX_SIDE_KM)
|
||||
@@ -183,7 +223,9 @@ export function fitViewHeightM({ width, height, fovy } = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The centre of a box that does not cross the dateline, in degrees.
|
||||
* The centre of a box, in degrees. A dateline box (west > east) is centred
|
||||
* on the short arc, not the arithmetic mean, which would be the other side
|
||||
* of the globe.
|
||||
* @param {object} box Degrees box.
|
||||
* @returns {{ lon: number, lat: number } | null}
|
||||
*/
|
||||
@@ -191,14 +233,18 @@ export function boxCentre(box) {
|
||||
const normalized = normalizeBox(box);
|
||||
if (!normalized) return null;
|
||||
return {
|
||||
lon: (normalized.west + normalized.east) / 2,
|
||||
lon: wrapLon(
|
||||
normalized.west + lonSpanDeg(normalized.west, normalized.east) / 2,
|
||||
),
|
||||
lat: (normalized.south + normalized.north) / 2,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A square box centred on a pin, `sideKm` on the ground (the east–west extent
|
||||
* widens by 1/cos(lat)); null when the result would not validate.
|
||||
* widens by 1/cos(lat)); null when the result would not validate. A pin whose
|
||||
* box passes ±180 gets the short-arc box (west > east), the same convention
|
||||
* as a dragged dateline box, with edges wrapped into ±180.
|
||||
* @param {number} lon Degrees.
|
||||
* @param {number} lat Degrees.
|
||||
* @param {number} [sideKm]
|
||||
@@ -207,16 +253,19 @@ export function boxCentre(box) {
|
||||
export function boxFromPin(lon, lat, sideKm = PIN_BOX_SIDE_KM) {
|
||||
if (!finite(lon) || !finite(lat) || !finite(sideKm) || sideKm <= 0)
|
||||
return null;
|
||||
if (Math.abs(lon) > 180) return null;
|
||||
const cosLat = Math.cos(toRadians(lat));
|
||||
if (cosLat <= 0) return null;
|
||||
const halfLat = sideKm / 2 / KM_PER_DEG_LAT;
|
||||
const halfLon = sideKm / 2 / (KM_PER_DEG_LAT * cosLat);
|
||||
// A half-width of 90° or more is not a short arc; refuse rather than wrap.
|
||||
if (halfLon >= 90) return null;
|
||||
const clampLat = (value) =>
|
||||
Math.max(-MERCATOR_LAT_LIMIT, Math.min(MERCATOR_LAT_LIMIT, value));
|
||||
const result = validateBox({
|
||||
west: lon - halfLon,
|
||||
west: wrapLon(lon - halfLon),
|
||||
south: clampLat(lat - halfLat),
|
||||
east: lon + halfLon,
|
||||
east: wrapLon(lon + halfLon),
|
||||
north: clampLat(lat + halfLat),
|
||||
});
|
||||
return result.ok ? result.box : null;
|
||||
@@ -449,15 +498,31 @@ export function coverageFor(candidate, box) {
|
||||
.filter((ring) => Array.isArray(ring) && ring.length >= 3);
|
||||
if (!normalized || !footprints.length) return 'unknown';
|
||||
const { west, south, east, north } = normalized;
|
||||
const centre = boxCentre(normalized);
|
||||
// A dateline box is one continuous range starting at its west edge. A
|
||||
// longitude on the east side (at or past ±180) shifts by 360. One just
|
||||
// outside the west corner stays put: shifting every value below west would
|
||||
// send that corner the long way round and miss a footprint that covers it.
|
||||
const crossing = west > east;
|
||||
const project = (lon) =>
|
||||
crossing && lon < west && (lon <= east || lon - east < west - lon)
|
||||
? lon + 360
|
||||
: lon;
|
||||
const samples = [
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
[(west + east) / 2, (south + north) / 2],
|
||||
[project(west), south],
|
||||
[project(east), south],
|
||||
[project(east), north],
|
||||
[project(west), north],
|
||||
[project(centre.lon), centre.lat],
|
||||
];
|
||||
return samples.every(([lon, lat]) =>
|
||||
footprints.some((ring) => pointInPolygon(lon, lat, ring)),
|
||||
footprints.some((ring) =>
|
||||
pointInPolygon(
|
||||
lon,
|
||||
lat,
|
||||
crossing ? ring.map(([x, y]) => [project(x), y]) : ring,
|
||||
),
|
||||
),
|
||||
)
|
||||
? 'full'
|
||||
: 'partial';
|
||||
@@ -606,6 +671,10 @@ export function wvsSnapshotUrl({
|
||||
const normalized = normalizeBox(box);
|
||||
if (!spec) throw new TypeError(`Unknown imagery product: ${product}`);
|
||||
if (!normalized) throw new TypeError('A finite box is required');
|
||||
// Worldview Snapshots rejects a BBOX whose west is greater than its east
|
||||
// (HTTP 200, XML "Invalid value for BBOX"). Callers split or refuse.
|
||||
if (normalized.west > normalized.east)
|
||||
throw new TypeError('A snapshot cannot cross the dateline');
|
||||
const bbox = [
|
||||
normalized.south,
|
||||
normalized.west,
|
||||
|
||||
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
boxFromPin,
|
||||
lonSpanDeg,
|
||||
nonCrossingBoxes,
|
||||
boxFromRectangle,
|
||||
boxSideKm,
|
||||
coverageFor,
|
||||
@@ -51,11 +53,20 @@ function hls(product, day, clouds, extra = {}) {
|
||||
return { ...groupGranulesByDay(granules)[0], ...extra };
|
||||
}
|
||||
|
||||
test('validateBox refuses dateline, polar, degenerate, invalid and oversized boxes', () => {
|
||||
test('validateBox refuses polar, degenerate, invalid and oversized boxes, and accepts a short dateline arc', () => {
|
||||
const reason = (box) => validateBox(box).reason;
|
||||
const dateline = validateBox({ west: 179, south: 0, east: -179, north: 1 });
|
||||
assert.equal(dateline.ok, true);
|
||||
assert.equal(dateline.box.west, 179);
|
||||
assert.equal(dateline.box.east, -179);
|
||||
assert.equal(
|
||||
reason({ west: 179, south: 0, east: -179, north: 1 }),
|
||||
'dateline',
|
||||
reason({ west: 170, south: 0, east: -170, north: 1 }),
|
||||
'too-large',
|
||||
'a 20° dateline arc is still over the 1,000 km cap',
|
||||
);
|
||||
assert.equal(
|
||||
reason({ west: 180, south: 0, east: -180, north: 1 }),
|
||||
'degenerate',
|
||||
);
|
||||
assert.equal(
|
||||
reason({ west: 0, south: 84, east: 0.5, north: 85.05111 }),
|
||||
@@ -70,10 +81,6 @@ test('validateBox refuses dateline, polar, degenerate, invalid and oversized box
|
||||
validateBox({ west: 0, south: 84, east: 0.5, north: 85.05111 }).message,
|
||||
'Imagery stops at ±85.05° latitude',
|
||||
);
|
||||
assert.equal(
|
||||
validateBox({ west: 179, south: 0, east: -179, north: 1 }).message,
|
||||
'Select one side of the dateline',
|
||||
);
|
||||
assert.equal(
|
||||
validateBox({ west: 0, south: 84.9, east: 0.05, north: 85 }).ok,
|
||||
true,
|
||||
@@ -137,10 +144,14 @@ test('ZOOM IN: the height whose top-down view is 400 km wide, clamped to 5–400
|
||||
lon: 10,
|
||||
lat: 5,
|
||||
});
|
||||
assert.deepEqual(boxCentre({ west: 179, south: 0, east: -179, north: 2 }), {
|
||||
lon: 180,
|
||||
lat: 1,
|
||||
});
|
||||
assert.equal(boxCentre(null), null);
|
||||
});
|
||||
|
||||
test('box width is the longitude span at the mid-latitude, never the shortest arc', () => {
|
||||
test('box width is the longitude span at the mid-latitude; a dateline box uses the short arc', () => {
|
||||
const equator = boxSideKm({ west: 0, south: -0.5, east: 1, north: 0.5 });
|
||||
assert.ok(Math.abs(equator.width - 111.32) < 1e-6);
|
||||
assert.ok(Math.abs(equator.height - 111.32) < 1e-6);
|
||||
@@ -149,6 +160,13 @@ test('box width is the longitude span at the mid-latitude, never the shortest ar
|
||||
const nearlyGlobal = { west: -179.9, south: 30, east: 179.9, north: 30.1 };
|
||||
assert.ok(boxSideKm(nearlyGlobal).width > 30000);
|
||||
assert.equal(validateBox(nearlyGlobal).reason, 'too-large');
|
||||
const crossing = boxSideKm({
|
||||
west: 179,
|
||||
south: -0.5,
|
||||
east: -179,
|
||||
north: 0.5,
|
||||
});
|
||||
assert.ok(Math.abs(crossing.width - 222.64) < 0.01, String(crossing.width));
|
||||
});
|
||||
|
||||
test('boxFromPin builds a 10 km square within 2% at any latitude and refuses what cannot validate', () => {
|
||||
@@ -167,7 +185,12 @@ test('boxFromPin builds a 10 km square within 2% at any latitude and refuses wha
|
||||
assert.ok(Math.abs(boxSideKm(boxFromPin(10, 10, 50)).width - 50) < 1);
|
||||
assert.equal(boxFromPin(NaN, 0), null);
|
||||
assert.equal(boxFromPin(0, 0, 5000), null, 'over the cap');
|
||||
assert.equal(boxFromPin(179.99, 0), null, 'would cross the dateline');
|
||||
assert.equal(boxFromPin(181, 0), null, 'longitude out of range');
|
||||
assert.equal(
|
||||
boxFromPin(0, 0, 400000),
|
||||
null,
|
||||
'half-width of 90 degrees or more',
|
||||
);
|
||||
assert.equal(boxFromPin(0, 89), null, 'clamped to a degenerate polar box');
|
||||
assert.equal(boxFromPin(0, 85.04).north, 85.0511, 'clamped, still valid');
|
||||
});
|
||||
@@ -298,6 +321,34 @@ test('coverage samples the box corners and centre against the union of footprint
|
||||
assert.equal(coverageFor(withRings(null), BOX), 'unknown');
|
||||
});
|
||||
|
||||
test('coverage of a dateline box uses the short arc, not the long way', () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const ring = (west, east, south = -0.1, north = 1.1) => [
|
||||
[west, south],
|
||||
[east, south],
|
||||
[east, north],
|
||||
[west, north],
|
||||
];
|
||||
const withRings = (...rings) => ({
|
||||
granules: rings.map((footprint) => granule({ footprint })),
|
||||
});
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(178.5, -178.5)), box),
|
||||
'full',
|
||||
'one footprint that crosses ±180',
|
||||
);
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(178.9, 180), ring(-180, -178.9)), box),
|
||||
'full',
|
||||
'a pair split exactly at ±180',
|
||||
);
|
||||
assert.equal(
|
||||
coverageFor(withRings(ring(179, 180)), box),
|
||||
'partial',
|
||||
'one side does not cover the other',
|
||||
);
|
||||
});
|
||||
|
||||
test('START HERE is the newest all-clear HLS day; unknown cloud is never clear', () => {
|
||||
const candidates = [
|
||||
hls('S30', '2026-09-20', [10, null]),
|
||||
@@ -429,6 +480,17 @@ test('GIBS templates put y before x; Worldview snapshots take south,west,north,e
|
||||
() => wvsSnapshotUrl({ product: 'S30', day: 'x', box: null }),
|
||||
TypeError,
|
||||
);
|
||||
assert.throws(
|
||||
() =>
|
||||
wvsSnapshotUrl({
|
||||
product: 'S30',
|
||||
day: '2026-09-18',
|
||||
box: { west: 179, south: 0, east: -179, north: 1 },
|
||||
width: 64,
|
||||
height: 64,
|
||||
}),
|
||||
/snapshot cannot cross the dateline/,
|
||||
);
|
||||
});
|
||||
|
||||
test('thumbnails load the focused card, then the visible cards outward, then the margins', () => {
|
||||
@@ -437,3 +499,52 @@ test('thumbnails load the focused card, then the visible cards outward, then the
|
||||
assert.deepEqual(thumbnailOrder(50, 7, 3, 10), [7, 6, 5, 4, 3, 8, 2, 9, 1]);
|
||||
assert.deepEqual(thumbnailOrder(0, 0, 0, 0), []);
|
||||
});
|
||||
|
||||
test('boxFromPin returns the short-arc box for a pin near the dateline', () => {
|
||||
const near = (a, b) => Math.abs(a - b) < 1e-6;
|
||||
const half = 5 / 111.32; // 5 km in degrees at the equator, about 0.04492
|
||||
const spanOk = (box) => {
|
||||
const { width, height } = boxSideKm(box);
|
||||
assert.ok(Math.abs(width - 10) < 0.2, `width ${width}`);
|
||||
assert.ok(Math.abs(height - 10) < 0.2, `height ${height}`);
|
||||
assert.ok(lonSpanDeg(box.west, box.east) < 1, 'never a ~360 degree span');
|
||||
};
|
||||
// 179.9 and -179.9 are 0.1 degrees from the line: a 10 km box stays on one side.
|
||||
for (const lon of [179.9, -179.9]) {
|
||||
const box = boxFromPin(lon, 0);
|
||||
spanOk(box);
|
||||
assert.ok(box.west < box.east, `no wrap needed at ${lon}`);
|
||||
assert.ok(near((box.west + box.east) / 2, lon));
|
||||
}
|
||||
// A pin on the line, or close enough that the box passes it, wraps.
|
||||
for (const lon of [180, -180, 179.99, -179.99]) {
|
||||
const box = boxFromPin(lon, 0);
|
||||
spanOk(box);
|
||||
assert.ok(box.west > box.east, `crossing at ${lon}`);
|
||||
assert.ok(box.west <= 180 && box.east >= -180, 'edges stay within +-180');
|
||||
assert.ok(
|
||||
near(
|
||||
box.west,
|
||||
(lon > 0 || lon === -180 ? Math.abs(lon) : 360 + lon) - half,
|
||||
),
|
||||
);
|
||||
assert.equal(
|
||||
nonCrossingBoxes(box).length,
|
||||
2,
|
||||
'splits for tiling and Worldview',
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(
|
||||
Math.abs(boxCentre(box).lon) - Math.abs(lon === -180 ? 180 : lon),
|
||||
) < 1e-6,
|
||||
);
|
||||
}
|
||||
// 0 is an ordinary box.
|
||||
const mid = boxFromPin(0, 0);
|
||||
spanOk(mid);
|
||||
assert.ok(mid.west < mid.east && near(mid.west, -half));
|
||||
// Off the equator the east-west extent widens but stays a short arc.
|
||||
const high = boxFromPin(-179.99, 60);
|
||||
spanOk(high);
|
||||
assert.ok(high.west > high.east);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Draped-imagery renderer for the Recent Imagery layer: at most two GIBS
|
||||
* imagery layers (slot `a`, left of a swipe; slot `b`, right) through the
|
||||
* renderer's globe port, draped on whichever surface the map stack draws.
|
||||
* Recent Imagery drapes two slots through the renderer's globe port, slot
|
||||
* `a` left of a swipe and slot `b` right. Each slot drapes up to two GIBS
|
||||
* layers, one per available part, on whichever surface the map stack draws.
|
||||
* Against the basemap slot `a` splits left and slot `b` stays empty. Tile
|
||||
* requests pass a small semaphore of our own, shared by both slots, through
|
||||
* each layer's admission hook; the renderer's own request limits stay
|
||||
@@ -15,7 +15,13 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { markBaseTileset } from '../../render/baseTilesets.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { PRODUCTS, gibsTemplate } from './model.js';
|
||||
import {
|
||||
PRODUCTS,
|
||||
boxKey,
|
||||
gibsTemplate,
|
||||
lonSpanDeg,
|
||||
nonCrossingBoxes,
|
||||
} from './model.js';
|
||||
|
||||
const SLOT_IDS = ['a', 'b'];
|
||||
const SPLITS = new Set(['left', 'right', 'none']);
|
||||
@@ -29,8 +35,27 @@ function clampAlpha(value) {
|
||||
return Number.isFinite(alpha) ? Math.max(0, Math.min(1, alpha)) : 1;
|
||||
}
|
||||
|
||||
const boxKey = (box) =>
|
||||
[box.west, box.south, box.east, box.north].map(Number).join(',');
|
||||
/** One comparable key for a slot's draped parts. */
|
||||
const partsKey = (parts) => parts.map(boxKey).sort().join(';');
|
||||
|
||||
/**
|
||||
* The parts of a box a slot drapes. The VIIRS JPEG has no alpha and would
|
||||
* draw an empty side black, so it drapes only parts Worldview confirmed
|
||||
* present, and no part of a dateline box before the probe answers. A PNG
|
||||
* drapes every part not confirmed empty.
|
||||
*/
|
||||
function drapedParts(candidate, box, { availableBoxes, emptyBoxes }) {
|
||||
const parts = nonCrossingBoxes(box);
|
||||
const keys = (list) => new Set(list.map(boxKey));
|
||||
if (PRODUCTS[candidate.product]?.format !== 'jpg') {
|
||||
if (!Array.isArray(emptyBoxes)) return parts;
|
||||
const empty = keys(emptyBoxes);
|
||||
return parts.filter((part) => !empty.has(boxKey(part)));
|
||||
}
|
||||
if (!Array.isArray(availableBoxes)) return parts.length > 1 ? [] : parts;
|
||||
const proven = keys(availableBoxes);
|
||||
return parts.filter((part) => proven.has(boxKey(part)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Admit a tile request while the semaphore has room. A request that finds
|
||||
@@ -77,7 +102,7 @@ export function createRecentImageryRenderer({
|
||||
let host = NO_HOST;
|
||||
let destroyed = false;
|
||||
const admission = { limit: maxTileRequests, inFlight: 0 };
|
||||
/** @type {Record<'a'|'b', null | { layer: object, globe: object, candidate: object, box: object, alpha: number, split: string }>} */
|
||||
/** @type {Record<'a'|'b', null | { layers: Array<object>, globe: object, candidate: object, parts: Array<object>, alpha: number, split: string }>} */
|
||||
const owned = { a: null, b: null };
|
||||
const admit = admitTileRequests(admission, requestRender);
|
||||
|
||||
@@ -105,36 +130,53 @@ export function createRecentImageryRenderer({
|
||||
const record = owned[slotId];
|
||||
if (!record) return false;
|
||||
owned[slotId] = null;
|
||||
record.layer.remove();
|
||||
for (const layer of record.layers) layer.remove();
|
||||
return true;
|
||||
}
|
||||
|
||||
function applyLook(record) {
|
||||
record.layer.alpha = record.alpha;
|
||||
record.layer.split = SPLITS.has(record.split) ? record.split : 'none';
|
||||
for (const layer of record.layers) {
|
||||
layer.alpha = record.alpha;
|
||||
layer.split = SPLITS.has(record.split) ? record.split : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function mount(slotId, { candidate, box, alpha, split }) {
|
||||
const layer = host.globe.imagery.add(specFor(candidate, box));
|
||||
owned[slotId] = { layer, globe: host.globe, candidate, box, alpha, split };
|
||||
function mount(slotId, { candidate, parts, alpha, split }) {
|
||||
if (!parts.length) return false;
|
||||
owned[slotId] = {
|
||||
layers: parts.map((part) =>
|
||||
host.globe.imagery.add(specFor(candidate, part)),
|
||||
),
|
||||
globe: host.globe,
|
||||
candidate,
|
||||
parts,
|
||||
alpha,
|
||||
split,
|
||||
};
|
||||
applyLook(owned[slotId]);
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
/**
|
||||
* Drape a candidate into a slot. The same candidate on the same host only
|
||||
* updates its look; anything else replaces the slot's layer.
|
||||
* Drape the parts of a candidate's box that the evidence allows (see drapedParts).
|
||||
* The same candidate on the same port keeps the layer of each unchanged part.
|
||||
* @param {'a'|'b'} slotId
|
||||
* @param {object} candidate
|
||||
* @param {object} box Degrees box.
|
||||
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none' }} [look]
|
||||
* @param {{ alpha?: number, splitDirection?: 'left'|'right'|'none', availableBoxes?: object[] | null, emptyBoxes?: object[] | null }} [look]
|
||||
* @returns {boolean} Whether a layer is now draped for the slot.
|
||||
*/
|
||||
showSlot(
|
||||
slotId,
|
||||
candidate,
|
||||
box,
|
||||
{ alpha = 1, splitDirection = 'none' } = {},
|
||||
{
|
||||
alpha = 1,
|
||||
splitDirection = 'none',
|
||||
availableBoxes = null,
|
||||
emptyBoxes = null,
|
||||
} = {},
|
||||
) {
|
||||
if (destroyed || !candidate?.key || !box) return false;
|
||||
if (!host.globe) {
|
||||
@@ -143,21 +185,52 @@ export function createRecentImageryRenderer({
|
||||
}
|
||||
const current = owned[slotId];
|
||||
const look = { alpha: clampAlpha(alpha), split: splitDirection };
|
||||
const parts = drapedParts(candidate, box, { availableBoxes, emptyBoxes });
|
||||
if (
|
||||
current &&
|
||||
current.globe === host.globe &&
|
||||
current.candidate.key === candidate.key &&
|
||||
boxKey(current.box) === boxKey(box)
|
||||
parts.length
|
||||
) {
|
||||
if (current.alpha !== look.alpha || current.split !== look.split) {
|
||||
if (partsKey(current.parts) !== partsKey(parts)) {
|
||||
const previous = new Map(
|
||||
current.parts.map((part, i) => [boxKey(part), current.layers[i]]),
|
||||
);
|
||||
// A new half goes right above the slot's surviving half, so both
|
||||
// halves keep the same place against the other slot.
|
||||
const survivor = parts
|
||||
.map((part) => previous.get(boxKey(part)))
|
||||
.find(Boolean);
|
||||
const at = survivor
|
||||
? host.globe.imagery.list().indexOf(survivor) + 1
|
||||
: undefined;
|
||||
const layers = parts.map((part) => {
|
||||
const key = boxKey(part);
|
||||
const layer = previous.get(key);
|
||||
previous.delete(key);
|
||||
return (
|
||||
layer ?? host.globe.imagery.add(specFor(candidate, part), at)
|
||||
);
|
||||
});
|
||||
for (const layer of previous.values()) layer.remove();
|
||||
Object.assign(current, { layers, parts, ...look });
|
||||
applyLook(current);
|
||||
requestRender('recent-imagery-show');
|
||||
} else if (
|
||||
current.alpha !== look.alpha ||
|
||||
current.split !== look.split
|
||||
) {
|
||||
Object.assign(current, look);
|
||||
applyLook(current);
|
||||
requestRender('recent-imagery-look');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
removeOwned(slotId);
|
||||
mount(slotId, { candidate, box, ...look });
|
||||
const removed = removeOwned(slotId);
|
||||
if (!mount(slotId, { candidate, parts, ...look })) {
|
||||
if (removed) requestRender('recent-imagery-hide');
|
||||
return false;
|
||||
}
|
||||
requestRender('recent-imagery-show');
|
||||
return true;
|
||||
},
|
||||
@@ -221,7 +294,7 @@ export function createRecentImageryRenderer({
|
||||
return out;
|
||||
},
|
||||
|
||||
/** Number of layers this renderer owns (never above two). */
|
||||
/** Number of slots this renderer owns (never above two). A dateline box uses up to two imagery layers in its slot. */
|
||||
ownedCount() {
|
||||
return SLOT_IDS.filter((slotId) => owned[slotId]).length;
|
||||
},
|
||||
@@ -247,11 +320,11 @@ let previewSeq = 0;
|
||||
|
||||
/** A box with no area has no fill: a press, or a drag along one axis. */
|
||||
const hasArea = (box) =>
|
||||
Boolean(box) && box.east > box.west && box.north > box.south;
|
||||
Boolean(box) && lonSpanDeg(box.west, box.east) > 0 && box.north > box.south;
|
||||
|
||||
/** A box with no extent draws nothing: a press that has not moved yet. */
|
||||
const hasExtent = (box) =>
|
||||
Boolean(box) && (box.east > box.west || box.north > box.south);
|
||||
Boolean(box) && (lonSpanDeg(box.west, box.east) > 0 || box.north > box.south);
|
||||
|
||||
/**
|
||||
* The box tool's preview: the box being dragged, a translucent fill and a
|
||||
|
||||
@@ -5,7 +5,9 @@ import {
|
||||
createImageryBoxPreview,
|
||||
createRecentImageryRenderer,
|
||||
} from './rendering.js';
|
||||
import { BOX } from './testDoubles.mjs';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { boxKey, nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX } from './testDoubles.mjs';
|
||||
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
@@ -271,3 +273,210 @@ test('the box preview draws a ground fill and a draped dashed edge, hidden rathe
|
||||
box = { west: -96, south: 32, east: -95, north: 33 };
|
||||
assert.doesNotThrow(() => preview.changed());
|
||||
});
|
||||
|
||||
test('a dateline box drapes one layer on each side of ±180 and removes both', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
assert.equal(
|
||||
renderer.showSlot('a', S30, box, { alpha: 0.4, splitDirection: 'left' }),
|
||||
true,
|
||||
);
|
||||
assert.equal(renderer.ownedCount(), 1);
|
||||
assert.equal(globe.layers.length, 2);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((item) => item.spec.rectangle),
|
||||
[
|
||||
{ west: 179, south: 0, east: 180, north: 1 },
|
||||
{ west: -180, south: 0, east: -179, north: 1 },
|
||||
],
|
||||
);
|
||||
assert.equal(globe.layers[0].alpha, 0.4);
|
||||
assert.equal(globe.layers[1].alpha, 0.4);
|
||||
assert.equal(globe.layers[0].split, 'left');
|
||||
assert.equal(globe.layers[1].split, 'left');
|
||||
renderer.setAlpha('a', 0.2);
|
||||
assert.equal(globe.layers[0].alpha, 0.2);
|
||||
assert.equal(globe.layers[1].alpha, 0.2);
|
||||
renderer.showSlot('a', S30, box, { alpha: 0.2 });
|
||||
assert.equal(globe.added.length, 2, 'the same box does not remount');
|
||||
renderer.hideSlot('a');
|
||||
assert.equal(globe.layers.length, 0);
|
||||
});
|
||||
|
||||
test('the renderer drapes only the halves the probe allows, and rebind keeps them', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
assert.equal(
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [east] }),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
[east],
|
||||
);
|
||||
renderer.showSlot('b', VIIRS, FIJI_BOX, {
|
||||
availableBoxes: [east, west],
|
||||
splitDirection: 'right',
|
||||
});
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.split),
|
||||
['none', 'right', 'right'],
|
||||
);
|
||||
assert.equal(globe.layers.length, 3);
|
||||
|
||||
const next = fakeGlobePort();
|
||||
renderer.rebind({ collection: {}, kind: 'globe', globe: next });
|
||||
assert.deepEqual(
|
||||
next.layers.map((layer) => layer.spec.rectangle),
|
||||
[east, west, east],
|
||||
);
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes: [west, east] });
|
||||
assert.equal(next.layers.length, 4);
|
||||
renderer.destroy();
|
||||
assert.equal(next.layers.length, 0);
|
||||
});
|
||||
|
||||
test('no allowed half, or halves of another box, drapes nothing', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
for (const availableBoxes of [[], [BOX]]) {
|
||||
assert.equal(
|
||||
renderer.showSlot('a', VIIRS, FIJI_BOX, { availableBoxes }),
|
||||
false,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('without per-half evidence a VIIRS dateline box drapes nothing, a plain VIIRS box and an HLS dateline box still drape', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
assert.equal(renderer.showSlot('a', VIIRS, FIJI_BOX), false);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
assert.equal(renderer.showSlot('a', VIIRS, BOX), true);
|
||||
assert.equal(globe.layers.length, 1);
|
||||
assert.equal(renderer.showSlot('b', S30, FIJI_BOX), true);
|
||||
assert.equal(globe.layers.length, 3);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('evidence going from none to empty removes the drape', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
renderer.showSlot('a', S30, FIJI_BOX);
|
||||
assert.equal(globe.layers.length, 2);
|
||||
assert.equal(
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
availableBoxes: [],
|
||||
emptyBoxes: nonCrossingBoxes(FIJI_BOX),
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(globe.layers.length, 0);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('an HLS dateline day drapes every half not confirmed empty, a VIIRS one only the confirmed halves', () => {
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
for (const [product, expected] of [
|
||||
[S30, [west, east]],
|
||||
[VIIRS, [east]],
|
||||
]) {
|
||||
const { renderer, globe } = fixture();
|
||||
renderer.showSlot('a', product, FIJI_BOX, {
|
||||
availableBoxes: [east],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
assert.deepEqual(
|
||||
globe.layers.map((layer) => layer.spec.rectangle),
|
||||
expected,
|
||||
);
|
||||
renderer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('a probe that narrows or widens a dateline drape keeps the layer of the unchanged half', () => {
|
||||
const renderer = createRecentImageryRenderer();
|
||||
const globe = fakeGlobePort();
|
||||
renderer.rebind({ collection: {}, kind: 'globe', globe });
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
const layerFor = (box) =>
|
||||
globe.layers.find((layer) => boxKey(layer.spec.rectangle) === boxKey(box));
|
||||
|
||||
// An HLS day drapes both halves before its probe answers.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { alpha: 0.4, splitDirection: 'left' });
|
||||
const kept = layerFor(west);
|
||||
assert.ok(kept);
|
||||
const added = globe.added.length;
|
||||
|
||||
// The probe confirms the east half empty: only the east layer goes.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
alpha: 0.4,
|
||||
splitDirection: 'left',
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [east],
|
||||
});
|
||||
assert.equal(kept.removed, false, 'the west layer survives the narrowing');
|
||||
assert.equal(globe.added.length, added, 'narrowing adds no layer');
|
||||
assert.equal(layerFor(east), undefined);
|
||||
|
||||
// A later probe admits east again: only the east layer is added.
|
||||
renderer.showSlot('a', S30, FIJI_BOX, {
|
||||
alpha: 0.4,
|
||||
splitDirection: 'left',
|
||||
availableBoxes: [west, east],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
assert.equal(kept.removed, false, 'the west layer survives the widening');
|
||||
assert.equal(globe.added.length, added + 1);
|
||||
assert.equal(kept.alpha, 0.4);
|
||||
assert.equal(kept.split, 'left');
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('widening slot a over the dateline keeps it below slot b on both sides', () => {
|
||||
const { renderer, globe } = fixture();
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
const topOn = (box) =>
|
||||
globe.layers
|
||||
.filter((layer) => boxKey(layer.spec.rectangle) === boxKey(box))
|
||||
.at(-1)
|
||||
.spec.url.includes('S30')
|
||||
? 'A'
|
||||
: 'B';
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [east] });
|
||||
renderer.showSlot('b', L30, FIJI_BOX, { emptyBoxes: [] });
|
||||
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
|
||||
renderer.showSlot('a', S30, FIJI_BOX, { emptyBoxes: [] });
|
||||
assert.deepEqual([topOn(west), topOn(east)], ['B', 'B']);
|
||||
renderer.destroy();
|
||||
});
|
||||
|
||||
test('the drag preview draws a wrapped fill and outline across the dateline', async () => {
|
||||
const draw = fakeDrawPort();
|
||||
let box = { west: 179, south: 0, east: 179, north: 0 };
|
||||
const preview = createImageryBoxPreview({}, () => box, { draw });
|
||||
const [fills, outlines] = draw.sets.values();
|
||||
preview.setVisible(true);
|
||||
|
||||
box = { ...box, east: -179 };
|
||||
preview.changed();
|
||||
assert.equal(fills.items.size, 0);
|
||||
assert.equal(outlines.items.get('edge').show, true);
|
||||
assert.deepEqual(
|
||||
outlines.items.get('edge').positions[1],
|
||||
fromDegrees(-179, 0),
|
||||
);
|
||||
|
||||
box = { ...box, north: 1 };
|
||||
preview.changed();
|
||||
assert.equal(fills.items.get('box').show, true);
|
||||
assert.deepEqual(fills.items.get('box').geometry.rect, box);
|
||||
const edge = outlines.items.get('edge');
|
||||
assert.equal(edge.show, true);
|
||||
assert.deepEqual(edge.positions, [
|
||||
fromDegrees(179, 0),
|
||||
fromDegrees(-179, 0),
|
||||
fromDegrees(-179, 1),
|
||||
fromDegrees(179, 1),
|
||||
fromDegrees(179, 0),
|
||||
]);
|
||||
await preview.destroy();
|
||||
});
|
||||
@@ -1,10 +1,107 @@
|
||||
import { searchHls } from './catalog.js';
|
||||
import { gibsTemplate, wvsSnapshotUrl } from './model.js';
|
||||
import { gibsTemplate, nonCrossingBoxes, wvsSnapshotUrl } from './model.js';
|
||||
|
||||
/**
|
||||
* Deadline for one half's response headers, so a day whose other half
|
||||
* answered is not held at "checking".
|
||||
*/
|
||||
const DEFAULT_HALF_DEADLINE_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Worldview Snapshots rejects a BBOX with west > east, so a dateline box is
|
||||
* probed as its two non-crossing halves, wider first. A plain box is its
|
||||
* one normalized half. A day has data when either half does.
|
||||
*/
|
||||
function requestBoxes(box) {
|
||||
return nonCrossingBoxes(box).sort(
|
||||
(a, b) => b.east - b.west - (a.east - a.west),
|
||||
);
|
||||
}
|
||||
|
||||
/** A response's Data-Present answer in lower case, or '' when it failed or has none. */
|
||||
export const dataPresent = (response) =>
|
||||
response?.ok
|
||||
? String(response.headers?.get?.('Data-Present') ?? '').toLowerCase()
|
||||
: '';
|
||||
|
||||
/**
|
||||
* One half's snapshot fetch, raced against its own deadline so a half that
|
||||
* never answers, even over a transport that ignores AbortSignal, still
|
||||
* settles. Its deadline cancels only this half. The caller can cancel it
|
||||
* at any time, including while its body is being read.
|
||||
*/
|
||||
function probeHalf(
|
||||
url,
|
||||
{ fetchImpl, signal, deadlineMs, setTimeoutImpl, clearTimeoutImpl },
|
||||
) {
|
||||
const controller = new AbortController();
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = null;
|
||||
const finishTimeout = () => {
|
||||
if (timer !== null) clearTimeoutImpl(timer);
|
||||
timer = null;
|
||||
};
|
||||
const stop = (reason) => {
|
||||
controller.abort(reason);
|
||||
finishTimeout();
|
||||
// Settle even if the transport ignores abort.
|
||||
reject(reason);
|
||||
};
|
||||
if (signal?.aborted) {
|
||||
stop(signal.reason);
|
||||
return;
|
||||
}
|
||||
signal?.addEventListener('abort', () => stop(signal.reason), {
|
||||
once: true,
|
||||
});
|
||||
if (deadlineMs > 0)
|
||||
timer = setTimeoutImpl(
|
||||
() =>
|
||||
stop(new DOMException('Thumbnail half timed out', 'TimeoutError')),
|
||||
deadlineMs,
|
||||
);
|
||||
let promise;
|
||||
try {
|
||||
promise = Promise.resolve(fetchImpl(url, { signal: controller.signal }));
|
||||
} catch (error) {
|
||||
finishTimeout();
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
promise.then(
|
||||
(value) => {
|
||||
finishTimeout();
|
||||
resolve(value);
|
||||
},
|
||||
(error) => {
|
||||
finishTimeout();
|
||||
reject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-enumerable per-half evidence for the box's non-crossing halves:
|
||||
* presentBoxes lists the halves Worldview confirmed present, emptyBoxes
|
||||
* the halves it confirmed empty. What drapes is decided by drapedParts in rendering.js.
|
||||
*/
|
||||
function withHalves(response, { presentBoxes, emptyBoxes }) {
|
||||
Object.defineProperties(response, {
|
||||
presentBoxes: { value: presentBoxes, configurable: true },
|
||||
emptyBoxes: { value: emptyBoxes, configurable: true },
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* NASA-compatible imagery acquisition; transport and URL builders are replaceable.
|
||||
* Thumbnail responses must expose Data-Present: true for image admission, or
|
||||
* false for confirmed empty coverage, including injected getThumbnail sources.
|
||||
* getThumbnail also sets presentBoxes and emptyBoxes (see withHalves),
|
||||
* also on the error it throws when another half was confirmed empty.
|
||||
* Without per-half evidence the renderer drapes every side of an HLS
|
||||
* dateline box and no side of a VIIRS one.
|
||||
*/
|
||||
export function createRecentImagerySource({
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
@@ -12,24 +109,68 @@ export function createRecentImagerySource({
|
||||
thumbnailUrl = wvsSnapshotUrl,
|
||||
tileTemplate = gibsTemplate,
|
||||
credit = 'NASA GIBS',
|
||||
halfDeadlineMs = DEFAULT_HALF_DEADLINE_MS,
|
||||
setTimeoutImpl = (fn, ms) => globalThis.setTimeout(fn, ms),
|
||||
clearTimeoutImpl = (id) => globalThis.clearTimeout(id),
|
||||
} = {}) {
|
||||
return {
|
||||
credit,
|
||||
searchHls: (query) => search({ ...query, fetchImpl }),
|
||||
async getThumbnail(candidate, box, { size = 256, signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl(
|
||||
thumbnailUrl({
|
||||
product: candidate.product,
|
||||
day: candidate.day,
|
||||
box,
|
||||
width: size,
|
||||
height: size,
|
||||
}),
|
||||
{ signal },
|
||||
const halves = requestBoxes(box);
|
||||
const deadlineMs = halves.length > 1 ? halfDeadlineMs : 0;
|
||||
const results = await Promise.allSettled(
|
||||
halves.map((half) =>
|
||||
probeHalf(
|
||||
thumbnailUrl({
|
||||
product: candidate.product,
|
||||
day: candidate.day,
|
||||
box: half,
|
||||
width: size,
|
||||
height: size,
|
||||
}),
|
||||
{
|
||||
fetchImpl,
|
||||
signal,
|
||||
deadlineMs,
|
||||
setTimeoutImpl,
|
||||
clearTimeoutImpl,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
return response;
|
||||
// Per half, its Data-Present answer or null when it did not answer.
|
||||
const answers = results.map((result) =>
|
||||
result.status === 'fulfilled' ? dataPresent(result.value) : null,
|
||||
);
|
||||
const halvesWhere = (value) =>
|
||||
halves.filter((_, i) => answers[i] === value);
|
||||
// A missing answer is an error unless another half proved data. The
|
||||
// error keeps a half confirmed empty (see withHalves).
|
||||
const failure = results.find((result) => result.status === 'rejected');
|
||||
if (failure && !answers.includes('true')) {
|
||||
const emptyBoxes = halvesWhere('false');
|
||||
if (Object.isExtensible(failure.reason))
|
||||
withHalves(
|
||||
failure.reason,
|
||||
emptyBoxes.length
|
||||
? { presentBoxes: [], emptyBoxes }
|
||||
: { presentBoxes: null, emptyBoxes: null },
|
||||
);
|
||||
throw failure.reason;
|
||||
}
|
||||
// Show the first half with data (the wider wins a tie), else the first
|
||||
// not confirmed empty, so an unreadable answer is never called empty.
|
||||
// Every half answered here unless one proved data.
|
||||
let shown = answers.indexOf('true');
|
||||
if (shown < 0) shown = answers.findIndex((answer) => answer !== 'false');
|
||||
if (shown < 0) shown = 0;
|
||||
return withHalves(results[shown].value, {
|
||||
presentBoxes: halvesWhere('true'),
|
||||
emptyBoxes: halvesWhere('false'),
|
||||
});
|
||||
},
|
||||
getTileTemplate: (product, day) => tileTemplate(product, day),
|
||||
};
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { manualTimers } from './testDoubles.mjs';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
|
||||
test('imagery source routes catalog, thumbnails and tiles through supplied adapters', async () => {
|
||||
const controller = new AbortController();
|
||||
const query = { box: { west: 0, east: 1, south: 0, north: 1 }, signal: controller.signal };
|
||||
const query = {
|
||||
box: { west: 0, east: 1, south: 0, north: 1 },
|
||||
signal: controller.signal,
|
||||
};
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
const calls = [];
|
||||
const fetchImpl = async (...args) => { calls.push(args); return new Response('image'); };
|
||||
const fetchImpl = async (...args) => {
|
||||
calls.push(args);
|
||||
return new Response('image');
|
||||
};
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl,
|
||||
search: async (request) => {
|
||||
@@ -16,27 +23,263 @@ test('imagery source routes catalog, thumbnails and tiles through supplied adapt
|
||||
assert.equal(request.box, query.box);
|
||||
return [candidate];
|
||||
},
|
||||
thumbnailUrl: ({ product, day, width }) => `https://imagery.example/${product}/${day}/${width}`,
|
||||
tileTemplate: (product, day) => `https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
|
||||
thumbnailUrl: ({ product, day, width }) =>
|
||||
`https://imagery.example/${product}/${day}/${width}`,
|
||||
tileTemplate: (product, day) =>
|
||||
`https://tiles.example/${product}/${day}/{z}/{x}/{y}`,
|
||||
credit: 'Example imagery',
|
||||
});
|
||||
assert.deepEqual(await source.searchHls(query), [candidate]);
|
||||
assert.equal(await (await source.getThumbnail(candidate, query.box, { signal: controller.signal })).text(), 'image');
|
||||
assert.equal(
|
||||
await (
|
||||
await source.getThumbnail(candidate, query.box, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
).text(),
|
||||
'image',
|
||||
);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][0], 'https://imagery.example/S30/2026-10-01/256');
|
||||
assert.equal(calls[0][1].signal, controller.signal);
|
||||
assert.equal(source.getTileTemplate(candidate.product, candidate.day), 'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}');
|
||||
// The fetch gets a private signal chained to the caller's.
|
||||
const halfSignal = calls[0][1].signal;
|
||||
assert.notEqual(halfSignal, controller.signal);
|
||||
assert.equal(halfSignal.aborted, false);
|
||||
controller.abort();
|
||||
assert.equal(halfSignal.aborted, true);
|
||||
assert.equal(
|
||||
source.getTileTemplate(candidate.product, candidate.day),
|
||||
'https://tiles.example/S30/2026-10-01/{z}/{x}/{y}',
|
||||
);
|
||||
assert.equal(source.credit, 'Example imagery');
|
||||
});
|
||||
|
||||
test('cancelled thumbnail acquisition does not return stale responses or retry', async () => {
|
||||
const controller = new AbortController();
|
||||
const box = { west: 0, south: 0, east: 1, north: 1 };
|
||||
let calls = 0;
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: () => 'https://imagery.example/thumbnail',
|
||||
fetchImpl: async () => { calls++; controller.abort(); return new Response('image'); },
|
||||
fetchImpl: async () => {
|
||||
calls++;
|
||||
controller.abort();
|
||||
return new Response('image');
|
||||
},
|
||||
});
|
||||
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
|
||||
await assert.rejects(source.getThumbnail({}, {}, { signal: controller.signal }), { name: 'AbortError' });
|
||||
await assert.rejects(
|
||||
source.getThumbnail({}, box, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
await assert.rejects(
|
||||
source.getThumbnail({}, box, { signal: controller.signal }),
|
||||
{ name: 'AbortError' },
|
||||
);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('a dateline thumbnail is requested as two non-crossing halves, never as a crossing BBOX', async () => {
|
||||
const requested = [];
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: ({ box }) => {
|
||||
requested.push(box);
|
||||
return 'https://imagery.example/thumbnail';
|
||||
},
|
||||
fetchImpl: async () => new Response('image'),
|
||||
});
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
await source.getThumbnail(candidate, {
|
||||
west: 179.9,
|
||||
south: 0,
|
||||
east: -179,
|
||||
north: 1,
|
||||
});
|
||||
assert.deepEqual(requested, [
|
||||
{ west: -180, south: 0, east: -179, north: 1 },
|
||||
{ west: 179.9, south: 0, east: 180, north: 1 },
|
||||
]);
|
||||
requested.length = 0;
|
||||
await source.getThumbnail(candidate, {
|
||||
west: 179,
|
||||
south: 0,
|
||||
east: -179.9,
|
||||
north: 1,
|
||||
});
|
||||
assert.deepEqual(requested[0], { west: 179, south: 0, east: 180, north: 1 });
|
||||
assert.equal(requested.length, 2);
|
||||
assert.ok(requested.every((box) => box.west <= box.east));
|
||||
});
|
||||
|
||||
const NARROW_WEST = { west: 179.9, south: 0, east: -179, north: 1 };
|
||||
// VIIRS is a JPEG without alpha. S30 (candidate) is a PNG.
|
||||
const JPEG_CANDIDATE = { product: 'VIIRS', day: '2026-10-01' };
|
||||
const WIDE_BOX = { west: -180, south: 0, east: -179, north: 1 };
|
||||
const NARROW_BOX = { west: 179.9, south: 0, east: 180, north: 1 };
|
||||
|
||||
const dated = (present, body = 'image') =>
|
||||
new Response(body, { headers: { 'Data-Present': present } });
|
||||
function halvesSource(answers, options = {}) {
|
||||
const requested = [];
|
||||
const source = createRecentImagerySource({
|
||||
...options,
|
||||
thumbnailUrl: ({ box }) =>
|
||||
`https://imagery.example/${box.west}/${box.east}`,
|
||||
fetchImpl: async (url) => {
|
||||
requested.push(url);
|
||||
const answer = answers[url.split('imagery.example/')[1]];
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer.clone ? answer : answer();
|
||||
},
|
||||
});
|
||||
return { source, requested };
|
||||
}
|
||||
const candidate = { product: 'S30', day: '2026-10-01' };
|
||||
|
||||
test('a crossing box probes both halves and is present when only the narrow half has data', async () => {
|
||||
const { source, requested } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(requested.length, 2);
|
||||
assert.equal(response.headers.get('Data-Present'), 'true');
|
||||
assert.equal(await response.text(), 'narrow');
|
||||
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
|
||||
assert.deepEqual(response.emptyBoxes, [WIDE_BOX]);
|
||||
});
|
||||
|
||||
test('a crossing box with data only on the wider half is present and shows the wider side', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('true', 'wide'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'wide');
|
||||
});
|
||||
|
||||
test('a crossing box is empty only when both halves are confirmed empty', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(response.headers.get('Data-Present'), 'false');
|
||||
assert.deepEqual(response.presentBoxes, []);
|
||||
assert.deepEqual(response.emptyBoxes, [WIDE_BOX, NARROW_BOX]);
|
||||
});
|
||||
|
||||
test('a crossing box is not called empty when the other half failed', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('false'),
|
||||
'179.9/180': () => new Response('x', { status: 503 }),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(response.ok, false);
|
||||
});
|
||||
|
||||
test('a crossing box with both halves present shows the wider half and keeps both presentBoxes', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': dated('true', 'wide'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'wide');
|
||||
assert.deepEqual(response.presentBoxes, [WIDE_BOX, NARROW_BOX]);
|
||||
});
|
||||
|
||||
test('a rejected half does not hide data on the other half, and never reads as empty', async () => {
|
||||
const { source } = halvesSource({
|
||||
'-180/-179': new Error('network'),
|
||||
'179.9/180': dated('true', 'narrow'),
|
||||
});
|
||||
const response = await source.getThumbnail(candidate, NARROW_WEST);
|
||||
assert.equal(await response.text(), 'narrow');
|
||||
const failing = halvesSource({
|
||||
'-180/-179': new Error('network'),
|
||||
'179.9/180': dated('false'),
|
||||
});
|
||||
await assert.rejects(
|
||||
failing.source.getThumbnail(candidate, NARROW_WEST),
|
||||
/network/,
|
||||
);
|
||||
});
|
||||
|
||||
for (const [label, answer] of [
|
||||
['rejected', new Error('network')],
|
||||
['hung', () => new Promise(() => {})],
|
||||
['answered without a presence', () => dated('unknown', 'maybe')],
|
||||
]) {
|
||||
for (const product of [JPEG_CANDIDATE, candidate]) {
|
||||
test(`a ${product.product} half that ${label} is neither present nor empty`, async () => {
|
||||
const { source } = halvesSource(
|
||||
{ '-180/-179': answer, '179.9/180': () => dated('true', 'narrow') },
|
||||
{ halfDeadlineMs: 20 },
|
||||
);
|
||||
const response = await source.getThumbnail(product, NARROW_WEST);
|
||||
assert.equal(response.headers.get('Data-Present'), 'true');
|
||||
assert.deepEqual(response.presentBoxes, [NARROW_BOX]);
|
||||
assert.deepEqual(response.emptyBoxes, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('synchronous abort inside an abort-ignoring fetch settles immediately', async () => {
|
||||
const controller = new AbortController();
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: () => 'https://example.invalid/',
|
||||
halfDeadlineMs: 10000,
|
||||
fetchImpl: () => {
|
||||
controller.abort();
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
const outcome = await Promise.race([
|
||||
source
|
||||
.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, { signal: controller.signal })
|
||||
.then(
|
||||
() => 'resolved',
|
||||
(error) => error.name,
|
||||
),
|
||||
new Promise((resolve) => setTimeout(() => resolve('stalled'), 50)),
|
||||
]);
|
||||
assert.equal(outcome, 'AbortError');
|
||||
});
|
||||
|
||||
test('a half whose transport ignores AbortSignal is still bounded by its deadline', async () => {
|
||||
const hang = () => new Promise(() => {});
|
||||
const { source, requested } = halvesSource(
|
||||
{ '-180/-179': hang, '179.9/180': hang },
|
||||
{ halfDeadlineMs: 10 },
|
||||
);
|
||||
await assert.rejects(source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST), {
|
||||
name: 'TimeoutError',
|
||||
});
|
||||
assert.equal(requested.length, 2);
|
||||
});
|
||||
|
||||
test("the caller's cancellation rejects at once and stops every half", async () => {
|
||||
const aborted = [];
|
||||
const source = createRecentImagerySource({
|
||||
thumbnailUrl: ({ box }) => String(box.west),
|
||||
fetchImpl: (url, { signal }) => {
|
||||
signal.addEventListener('abort', () => aborted.push(url), { once: true });
|
||||
return new Promise(() => {});
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
const result = source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
await assert.rejects(result, { name: 'AbortError' });
|
||||
assert.deepEqual(aborted, ['-180', '179.9']);
|
||||
});
|
||||
|
||||
test('a successful probe leaves no deadline timer behind', async () => {
|
||||
const timers = manualTimers();
|
||||
const { source } = halvesSource(
|
||||
{ '-180/-179': dated('true'), '179.9/180': dated('false') },
|
||||
timers,
|
||||
);
|
||||
await source.getThumbnail(JPEG_CANDIDATE, NARROW_WEST);
|
||||
assert.equal(timers.armed(), 0);
|
||||
assert.equal(timers.cleared.length, 2);
|
||||
});
|
||||
@@ -16,6 +16,13 @@ export const BOX = Object.freeze({
|
||||
north: 30.3,
|
||||
});
|
||||
|
||||
export const FIJI_BOX = Object.freeze({
|
||||
west: 179,
|
||||
south: -18,
|
||||
east: -177,
|
||||
north: -17,
|
||||
});
|
||||
|
||||
export const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
/** Timers that fire only when the test says so. */
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Thumbnail loader for the Recent Imagery strip: one Worldview snapshot per
|
||||
* candidate day. The response's `Data-Present` header is the only proof that
|
||||
* candidate day (one per side of a dateline box). The response's `Data-Present` header is the only proof that
|
||||
* a day has pixels in the box (GIBS answers an empty tile with HTTP 200), and
|
||||
* `Acquisition-Time` carries the sensing time. Fetches are bounded, and so
|
||||
* are decoded images: residency is least-recently-USED, where a request or a
|
||||
@@ -8,16 +8,28 @@
|
||||
* card on every render, so a read that counted would evict the visible cards
|
||||
* first). Eviction revokes the image only; what the probe proved is kept.
|
||||
*/
|
||||
import { thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { boxKey, thumbnailOrder } from './model.js';
|
||||
import { createRecentImagerySource, dataPresent } from './source.js';
|
||||
|
||||
const EMPTY = Object.freeze({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
/** Keep earlier halves of one answer (present or empty) unless the new probe answered them. */
|
||||
function keepProvenHalves(previous, next, opposite) {
|
||||
if (!Array.isArray(next) || !Array.isArray(opposite)) return previous;
|
||||
const drop = new Set([...next, ...opposite].map(boxKey));
|
||||
return [
|
||||
...next,
|
||||
...(previous ?? []).filter((half) => !drop.has(boxKey(half))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ fetchImpl?: typeof fetch, maxInFlight?: number, maxDecoded?: number, createObjectUrl?: (blob: Blob) => string, revokeObjectUrl?: (url: string) => void, size?: number }} [options]
|
||||
*/
|
||||
@@ -90,18 +102,22 @@ export function createThumbnailLoader({
|
||||
let status = 'error';
|
||||
let objectUrl = null;
|
||||
let acquisitionTime = null;
|
||||
// Per-half evidence (see withHalves in source.js), or null without it.
|
||||
let availableBoxes = null;
|
||||
let emptyBoxes = null;
|
||||
let cancelled = false;
|
||||
try {
|
||||
const response = await requestThumbnail(entry.candidate, entry.box, {
|
||||
size,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Each half's explicit answer counts even when the shown response fails.
|
||||
availableBoxes = response?.presentBoxes ?? null;
|
||||
emptyBoxes = response?.emptyBoxes ?? null;
|
||||
if (controller.signal.aborted) {
|
||||
cancelled = true;
|
||||
} else if (response?.ok) {
|
||||
const present = String(
|
||||
response.headers?.get?.('Data-Present') ?? '',
|
||||
).toLowerCase();
|
||||
const present = dataPresent(response);
|
||||
acquisitionTime = response.headers?.get?.('Acquisition-Time') || null;
|
||||
if (present === 'false') {
|
||||
status = 'empty';
|
||||
@@ -117,7 +133,11 @@ export function createThumbnailLoader({
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || error?.name === 'AbortError')
|
||||
cancelled = true;
|
||||
else status = 'error';
|
||||
else {
|
||||
status = 'error';
|
||||
availableBoxes = error?.presentBoxes ?? availableBoxes;
|
||||
emptyBoxes = error?.emptyBoxes ?? emptyBoxes;
|
||||
}
|
||||
} finally {
|
||||
inFlight -= 1;
|
||||
entry.loading = false;
|
||||
@@ -129,6 +149,17 @@ export function createThumbnailLoader({
|
||||
pump();
|
||||
return;
|
||||
}
|
||||
// Each half keeps its latest explicit answer.
|
||||
entry.availableBoxes = keepProvenHalves(
|
||||
entry.availableBoxes,
|
||||
availableBoxes,
|
||||
emptyBoxes,
|
||||
);
|
||||
entry.emptyBoxes = keepProvenHalves(
|
||||
entry.emptyBoxes,
|
||||
emptyBoxes,
|
||||
availableBoxes,
|
||||
);
|
||||
// A failed re-fetch of an evicted image keeps what the day proved.
|
||||
if (status !== 'error' || entry.status !== 'present') {
|
||||
entry.status = status;
|
||||
@@ -196,6 +227,8 @@ export function createThumbnailLoader({
|
||||
status: 'unknown',
|
||||
objectUrl: null,
|
||||
acquisitionTime: null,
|
||||
availableBoxes: null,
|
||||
emptyBoxes: null,
|
||||
loading: false,
|
||||
controller: null,
|
||||
touched: 0,
|
||||
@@ -272,7 +305,7 @@ export function createThumbnailLoader({
|
||||
/**
|
||||
* Read a day's state. A read is not a use: it never changes residency.
|
||||
* @param {string} key Candidate key.
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, loading: boolean }}
|
||||
* @returns {{ status: 'unknown'|'present'|'empty'|'error', objectUrl: string | null, acquisitionTime: string | null, availableBoxes: Array<object> | null, emptyBoxes: Array<object> | null, loading: boolean }}
|
||||
*/
|
||||
get(key) {
|
||||
const entry = entries.get(key);
|
||||
@@ -281,6 +314,8 @@ export function createThumbnailLoader({
|
||||
status: entry.status,
|
||||
objectUrl: entry.objectUrl,
|
||||
acquisitionTime: entry.acquisitionTime,
|
||||
availableBoxes: entry.availableBoxes,
|
||||
emptyBoxes: entry.emptyBoxes,
|
||||
loading: entry.loading,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createThumbnailLoader } from './thumbnails.js';
|
||||
import { BOX, response, settle } from './testDoubles.mjs';
|
||||
|
||||
const candidate = (product, day) => ({
|
||||
key: `${product}:${day}`,
|
||||
product,
|
||||
day,
|
||||
});
|
||||
import { createRecentImagerySource } from './source.js';
|
||||
import { nonCrossingBoxes } from './model.js';
|
||||
import { BOX, FIJI_BOX, candidate, response, settle } from './testDoubles.mjs';
|
||||
|
||||
/** A fetch whose responses the test releases, in any order. */
|
||||
function fakeFetch() {
|
||||
@@ -68,6 +64,8 @@ test('Data-Present decides the day: present with an object URL and sensing time,
|
||||
status: 'present',
|
||||
objectUrl: 'blob:1',
|
||||
acquisitionTime: '2026-09-18T17:12:00Z',
|
||||
availableBoxes: [BOX],
|
||||
emptyBoxes: [],
|
||||
loading: false,
|
||||
});
|
||||
assert.equal(loader.get('L30:2026-09-16').status, 'empty');
|
||||
@@ -337,6 +335,75 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
|
||||
assert.deepEqual(revoked, ['blob:1']);
|
||||
});
|
||||
|
||||
test('the loader proves a dateline day present from one half and hands that half on', async () => {
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const time = day.day + 'T22:10:00Z';
|
||||
const { loader } = fixture({
|
||||
fetchImpl: async (url) => {
|
||||
const east =
|
||||
new URL(url).searchParams.get('BBOX').split(',')[1] === '-180';
|
||||
return response({
|
||||
headers: east
|
||||
? { 'Data-Present': 'true', 'Acquisition-Time': time }
|
||||
: { 'Data-Present': 'false' },
|
||||
});
|
||||
},
|
||||
});
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settle();
|
||||
const entry = loader.get(day.key);
|
||||
assert.equal(entry.status, 'present');
|
||||
assert.equal(entry.acquisitionTime, time);
|
||||
assert.ok(entry.objectUrl);
|
||||
assert.deepEqual(entry.availableBoxes, [nonCrossingBoxes(FIJI_BOX)[1]]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a dateline day whose halves both hang is an error, not "checking" forever', async () => {
|
||||
const source = createRecentImagerySource({
|
||||
fetchImpl: () => new Promise(() => {}),
|
||||
halfDeadlineMs: 20,
|
||||
});
|
||||
const loader = createThumbnailLoader({
|
||||
requestThumbnail: source.getThumbnail,
|
||||
});
|
||||
const day = candidate('VIIRS', '2026-11-04');
|
||||
const settled = new Promise((resolve) => loader.subscribe(resolve));
|
||||
loader.request(day, FIJI_BOX);
|
||||
await settled;
|
||||
assert.equal(loader.get(day.key).status, 'error');
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('a re-probe of a present day drops a half only when it is confirmed empty', async () => {
|
||||
const box = { west: 179, south: 0, east: -179, north: 1 };
|
||||
const [west, east] = nonCrossingBoxes(box);
|
||||
const answers = [
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west, east], emptyBoxes: [] },
|
||||
{ presentBoxes: [west], emptyBoxes: [east] },
|
||||
];
|
||||
const { loader } = fixture({
|
||||
maxDecoded: 1,
|
||||
requestThumbnail: async () =>
|
||||
Object.assign(
|
||||
response({ headers: { 'Data-Present': 'true' } }),
|
||||
answers.shift(),
|
||||
),
|
||||
});
|
||||
const day1 = candidate('VIIRS', '2026-11-04');
|
||||
const day2 = candidate('VIIRS', '2026-11-05');
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
loader.request(day2, box);
|
||||
await settle();
|
||||
assert.equal(loader.get(day1.key).objectUrl, null);
|
||||
loader.request(day1, box);
|
||||
await settle();
|
||||
assert.deepEqual(loader.get(day1.key).availableBoxes, [west]);
|
||||
loader.destroy();
|
||||
});
|
||||
|
||||
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
|
||||
const { loader, fetch } = fixture({ maxInFlight: 1 });
|
||||
const stale = candidate('S30', '2026-09-10');
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from 'node:path';
|
||||
import { providerCooldownMs } from '../server/providers/space/cooldown.js';
|
||||
import { parseTerrainPoints } from './data/terrainHeightsProxy.js';
|
||||
import { readResponseTextCapped, coalesceProxyRequest } from './sources/httpBody.js';
|
||||
import { makeRateLimiter, clientKey, resolvePerMinuteCap } from '../server/providers/common/rate-limit.js';
|
||||
import { makeRateLimiter, clientKey } from '../server/providers/common/rate-limit.js';
|
||||
|
||||
const source = ['local.js', 'common/http.js', 'aircraft/enrichment.js', 'terrain.js', 'space/celestrak.js', 'space/launch-library.js', '../../src/data/spaceProviderRequests.js']
|
||||
.map(file => readFileSync(new URL(`../server/providers/${file}`, import.meta.url), 'utf8'))
|
||||
@@ -27,7 +27,7 @@ function fixture(name, overrides = {}, preview = false) {
|
||||
readResponseTextCapped, coalesceProxyRequest, providerCooldownMs,
|
||||
// The rate-limited proxies reach for these; give them the real ones so a
|
||||
// fixture request is throttled exactly as production would be.
|
||||
makeRateLimiter, clientKey, resolvePerMinuteCap,
|
||||
makeRateLimiter, clientKey,
|
||||
// terrain.js gates cross-site requests first; fixture requests carry no
|
||||
// browser headers, so admit them like a loopback tool.
|
||||
admitSameSiteKeyless: () => false,
|
||||
|
||||
Vendored
+3
@@ -1,8 +1,11 @@
|
||||
import { createApplicationControls } from '../app/controls.js';
|
||||
import { getStandaloneCatalog } from './catalog.js';
|
||||
import { homeCountryView } from '../homeCountry.js';
|
||||
export function createStandaloneControls(options) {
|
||||
return createApplicationControls({
|
||||
catalog: options?.catalog ?? getStandaloneCatalog(),
|
||||
// The planet over the visitor's country; the title's logo goes back here.
|
||||
startView: homeCountryView(),
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import { startApplicationChrome } from '../app/startupChrome.js';
|
||||
import { playOpeningIntro } from '../app/openingIntro.js';
|
||||
import { initKeySetup } from '../keySetup.js';
|
||||
export function startStandaloneChrome(options) {
|
||||
return startApplicationChrome({
|
||||
initializeSettings: initKeySetup,
|
||||
playOpening: playOpeningIntro,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -10,7 +10,7 @@ const source = readFileSync(
|
||||
.replace(/^import .*;\n/gm, '')
|
||||
.replace('export function', 'function');
|
||||
|
||||
function fixture() {
|
||||
function fixture({ playOpening, hasShareState = false } = {}) {
|
||||
const timers = new Map();
|
||||
const listeners = new Map();
|
||||
const events = [];
|
||||
@@ -44,7 +44,10 @@ function fixture() {
|
||||
addEventListener: (type, listener) => listeners.set(type, listener),
|
||||
removeEventListener: (type) => listeners.delete(type),
|
||||
},
|
||||
playOpening,
|
||||
styleManager: {
|
||||
hasShareState,
|
||||
viewer: 'viewer',
|
||||
initialRestorePromise: new Promise((resolve) => {
|
||||
restored = resolve;
|
||||
}),
|
||||
@@ -124,3 +127,59 @@ test('shutdown during the cover transition cancels the listener and fallback', a
|
||||
f.fire(900);
|
||||
assert.deepEqual(f.events, ['hidden', 'settings:destroy']);
|
||||
});
|
||||
|
||||
function openingStub(events) {
|
||||
let land;
|
||||
const calls = [];
|
||||
const play = (options) => {
|
||||
calls.push(options);
|
||||
events.push('opening');
|
||||
return {
|
||||
done: new Promise((resolve) => {
|
||||
land = resolve;
|
||||
}),
|
||||
cancel: () => events.push('opening:cancel'),
|
||||
};
|
||||
};
|
||||
return { play, calls, land: () => land() };
|
||||
}
|
||||
|
||||
test('a bare address plays the opening, and welcome waits for its end', async () => {
|
||||
const events = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({ playOpening: opening.play });
|
||||
f.events.push = (value) => events.push(value);
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(events, ['opening']);
|
||||
assert.equal(opening.calls[0].viewer, 'viewer');
|
||||
f.fire(900);
|
||||
assert.deepEqual(events, ['opening'], 'no fallback timer while it plays');
|
||||
opening.land();
|
||||
await flush();
|
||||
assert.deepEqual(events, ['opening', 'welcome']);
|
||||
await f.stop();
|
||||
assert.ok(events.includes('opening:cancel'));
|
||||
});
|
||||
|
||||
test('a shared view opens without the opening', async () => {
|
||||
const events = [];
|
||||
const opening = openingStub(events);
|
||||
const f = fixture({ playOpening: opening.play, hasShareState: true });
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.equal(opening.calls.length, 0);
|
||||
assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
|
||||
test('without an opening to play the cover hides as before', async () => {
|
||||
const f = fixture({ playOpening: () => null });
|
||||
f.restored();
|
||||
f.fire(1000);
|
||||
await flush();
|
||||
assert.deepEqual(f.events, ['hidden']);
|
||||
await f.stop();
|
||||
});
|
||||
@@ -31,11 +31,6 @@ export const getRecentImagery = defineTool({
|
||||
requires: ['imagery'],
|
||||
async run(args, { services, signal }) {
|
||||
const area = await resolveArea(args.area, { services, signal });
|
||||
if (area.west > area.east)
|
||||
throw new ToolError(
|
||||
'invalid_arguments',
|
||||
'The area must not cross the antimeridian',
|
||||
);
|
||||
if (
|
||||
Math.abs(area.south) > MAX_LATITUDE ||
|
||||
Math.abs(area.north) > MAX_LATITUDE
|
||||
@@ -55,6 +50,13 @@ export const getRecentImagery = defineTool({
|
||||
east: area.east,
|
||||
north: area.north,
|
||||
};
|
||||
// Worldview Snapshots rejects a west > east BBOX, so a dateline area can
|
||||
// never produce the image this tool returns: refuse before searching.
|
||||
if (box.west > box.east)
|
||||
throw new ToolError(
|
||||
'invalid_arguments',
|
||||
'The area must not cross the antimeridian',
|
||||
);
|
||||
let latest;
|
||||
try {
|
||||
latest = await services.imagery.latest({ box, signal });
|
||||
|
||||
@@ -82,8 +82,30 @@ test('overview fallback, empty results and invalid areas are reported', async ()
|
||||
);
|
||||
await assert.rejects(
|
||||
none.call('get_recent_imagery', { area: { bbox: [170, 0, -170, 5] } }),
|
||||
/antimeridian/,
|
||||
/too large for imagery/,
|
||||
);
|
||||
const crossing = imagery({
|
||||
candidate: {
|
||||
product: 'S30',
|
||||
day: '2026-10-01',
|
||||
cloud: { min: 1, max: 2 },
|
||||
coverage: 'full',
|
||||
},
|
||||
reason: 'clear',
|
||||
errors: [],
|
||||
});
|
||||
const wrapped = composeCatalog({
|
||||
tools: coreTools,
|
||||
services: { imagery: crossing },
|
||||
});
|
||||
await assert.rejects(
|
||||
wrapped.call('get_recent_imagery', {
|
||||
area: { bbox: [179, 0, -179, 1] },
|
||||
}),
|
||||
/must not cross the antimeridian/,
|
||||
);
|
||||
assert.equal(crossing.snapshots.length, 0);
|
||||
assert.equal(crossing.boxes.length, 0);
|
||||
await assert.rejects(
|
||||
none.call('get_recent_imagery', { area: { bbox: [0, 85.5, 1, 86] } }),
|
||||
/±85° latitude/,
|
||||
|
||||
@@ -48,13 +48,20 @@ export function initImageryBoxTool({
|
||||
let lease = null;
|
||||
let releaseCamera = null;
|
||||
|
||||
const dragBox = () =>
|
||||
anchor && {
|
||||
west: Math.min(anchor.lon, corner.lon),
|
||||
const dragBox = () => {
|
||||
if (!anchor) return null;
|
||||
const lo = Math.min(anchor.lon, corner.lon);
|
||||
const hi = Math.max(anchor.lon, corner.lon);
|
||||
// Corners more than half the globe apart are the short way round, over
|
||||
// the dateline: west gets the larger longitude, east the smaller.
|
||||
const crosses = hi - lo > 180;
|
||||
return {
|
||||
west: crosses ? hi : lo,
|
||||
south: Math.min(anchor.lat, corner.lat),
|
||||
east: Math.max(anchor.lon, corner.lon),
|
||||
east: crosses ? lo : hi,
|
||||
north: Math.max(anchor.lat, corner.lat),
|
||||
};
|
||||
};
|
||||
|
||||
const preview = createPreview(viewer, dragBox);
|
||||
const setPreview = (visible) => preview.setVisible(visible);
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
IMAGERY_BOX_POINTER_OWNER,
|
||||
initImageryBoxTool,
|
||||
} from './imageryBoxTool.js';
|
||||
import { lonSpanDeg, validateBox } from '../layers/recentImagery/model.js';
|
||||
import { boxToolFakes } from '../layers/recentImagery/testDoubles.mjs';
|
||||
import { createImageryBoxPreview } from '../layers/recentImagery/rendering.js';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
@@ -209,3 +210,40 @@ test('destroy mid-drag restores the camera, releases the claim and detaches the
|
||||
assert.equal(f.tool.start(), false);
|
||||
assert.equal(initImageryBoxTool({ viewer: null, onBox() {} }), null);
|
||||
});
|
||||
|
||||
test('a drag across the dateline is the short box, not a box round the world', async () => {
|
||||
const pickWorld = (_viewer, nx, ny) =>
|
||||
ny < 0.05 ? null : { lon: nx < 0.5 ? 179.99 : -179.99, lat: ny };
|
||||
const f = fixture({ pickWorld });
|
||||
f.tool.start();
|
||||
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
|
||||
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
|
||||
assert.deepEqual(f.cancels, []);
|
||||
assert.equal(f.boxes.length, 1);
|
||||
const { west, east } = f.boxes[0];
|
||||
assert.ok(west > east, `west ${west} is east of east ${east}`);
|
||||
assert.ok(Math.abs(east + 360 - west - 0.02) < 1e-9, 'a 0.02 degree span');
|
||||
await f.tool.destroy();
|
||||
});
|
||||
|
||||
test('a drag whose short arc is still over the size limit is refused as too large', async () => {
|
||||
const pickWorld = (_viewer, nx, ny) => ({
|
||||
lon: nx < 0.5 ? 100 : -100,
|
||||
lat: ny,
|
||||
});
|
||||
const refused = [];
|
||||
const f = fixture({
|
||||
pickWorld,
|
||||
onCancel: (reason, message, box) => refused.push({ reason, message, box }),
|
||||
});
|
||||
f.tool.start();
|
||||
f.fire('LEFT_DOWN', { position: { x: 100, y: 200 } });
|
||||
f.fire('LEFT_UP', { position: { x: 800, y: 250 } });
|
||||
assert.equal(f.boxes.length, 0);
|
||||
const { reason, message, box } = refused.at(-1);
|
||||
assert.equal(reason, 'too-large');
|
||||
assert.deepEqual([box.west, box.east], [100, -100], 'the short arc');
|
||||
assert.equal(lonSpanDeg(box.west, box.east), 160);
|
||||
assert.equal(message, validateBox(box).message);
|
||||
await f.tool.destroy();
|
||||
});
|
||||
+27
-5
@@ -22,6 +22,7 @@ import RecentImageryReadout from './recentImagery/RecentImageryReadout.vue';
|
||||
import {
|
||||
PRODUCTS,
|
||||
hhmm,
|
||||
nonCrossingBoxes,
|
||||
wvsSnapshotUrl,
|
||||
} from '../layers/recentImagery/model.js';
|
||||
import { displayDay, displayMetres } from '../layers/recentImagery/display.js';
|
||||
@@ -135,6 +136,20 @@ function coverageText(coverage) {
|
||||
return t('unknown');
|
||||
}
|
||||
|
||||
/** A confirmed-empty side means partial coverage. An unanswered side leaves coverage unknown. */
|
||||
function shownCoverage(candidate, box) {
|
||||
const { status, availableBoxes, emptyBoxes } = candidate.thumbnail ?? {};
|
||||
const halves = nonCrossingBoxes(box).length;
|
||||
if (emptyBoxes?.length && emptyBoxes.length < halves) return 'partial';
|
||||
if (
|
||||
status !== 'present' ||
|
||||
!Array.isArray(availableBoxes) ||
|
||||
availableBoxes.length >= halves
|
||||
)
|
||||
return candidate.coverage;
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function cloudText(candidate) {
|
||||
if (candidate.thumbnail?.status === 'empty') return t('no imagery');
|
||||
if (!candidate.cloud) return t('cloud unknown');
|
||||
@@ -516,6 +531,9 @@ export function createRecentImageryPanel({
|
||||
|
||||
function exportsView() {
|
||||
const ab = snapshot.mode === 'ab';
|
||||
const crossing = Boolean(
|
||||
snapshot.box && snapshot.box.west > snapshot.box.east,
|
||||
);
|
||||
return [
|
||||
{
|
||||
id: 'export',
|
||||
@@ -525,10 +543,12 @@ export function createRecentImageryPanel({
|
||||
label: ab
|
||||
? t('EXPORT {slot}', { slot: slotId.toUpperCase() })
|
||||
: t('EXPORT'),
|
||||
title: ab
|
||||
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
|
||||
: t('Download the image as a PNG'),
|
||||
disabled: !exportTarget(slotId) || exporting.has(slotId),
|
||||
title: crossing
|
||||
? t('Select one side of the dateline')
|
||||
: ab
|
||||
? t('Download {slot} as a PNG', { slot: slotId.toUpperCase() })
|
||||
: t('Download the image as a PNG'),
|
||||
disabled: crossing || !exportTarget(slotId) || exporting.has(slotId),
|
||||
reserved: slotId === 'b' ? !ab : undefined,
|
||||
onClick: () => void exportImage(slotId),
|
||||
})),
|
||||
@@ -566,7 +586,9 @@ export function createRecentImageryPanel({
|
||||
}),
|
||||
);
|
||||
times.push(
|
||||
t('Coverage {coverage}', { coverage: coverageText(focus.coverage) }),
|
||||
t('Coverage {coverage}', {
|
||||
coverage: coverageText(shownCoverage(focus, snapshot.box)),
|
||||
}),
|
||||
);
|
||||
lines.push({ id: 'acquired', text: times.join(' · ') });
|
||||
(focus.granules || []).forEach((granule, index) => {
|
||||
|
||||
@@ -5,9 +5,11 @@ import assert from 'node:assert/strict';
|
||||
import { assertSameNode } from '../testSupport/domAssert.mjs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRecentImageryPanel } from './recentImagery.js';
|
||||
import { nonCrossingBoxes } from '../layers/recentImagery/model.js';
|
||||
import { createRecentImageryLayer } from '../layers/recentImagery/index.js';
|
||||
import {
|
||||
BOX,
|
||||
FIJI_BOX,
|
||||
fakeCatalog,
|
||||
fakeController,
|
||||
fakeRenderer,
|
||||
@@ -977,6 +979,29 @@ test('opacity drives both images; EXPORT downloads the pin or the preview and EX
|
||||
await settle();
|
||||
assert.equal(await f.readout.exportImage('a'), true);
|
||||
assert.match(f.fetches.at(-1), /WIDTH=1024&HEIGHT=512/);
|
||||
// A dateline box is drawn on the map, but Worldview rejects a crossing BBOX.
|
||||
const before = f.fetches.length;
|
||||
f.layer.setBox({ west: 179, south: 0, east: -179, north: 1 });
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.notEqual(
|
||||
f.byId('ri-notice-text').textContent,
|
||||
'Select one side of the dateline',
|
||||
'the drawn box is not a warning until an export is tried',
|
||||
);
|
||||
const crossingExport = f.byAction('export-a');
|
||||
assert.equal(crossingExport.disabled, true, 'EXPORT is off up front');
|
||||
assert.equal(crossingExport.title, 'Select one side of the dateline');
|
||||
assert.equal(await f.readout.exportImage('a'), false);
|
||||
assert.equal(
|
||||
f.byId('ri-notice-text').textContent,
|
||||
'Export failed · A snapshot cannot cross the dateline',
|
||||
);
|
||||
assert.equal(
|
||||
f.fetches.length,
|
||||
before,
|
||||
'export does not request a crossing BBOX',
|
||||
);
|
||||
f.layer.setMode('ab');
|
||||
assert.deepEqual(
|
||||
[
|
||||
@@ -1040,6 +1065,31 @@ test('DETAILS is a collapsed rail card holding every note, and the empty-days to
|
||||
assert.equal(article.dataset.open, 'false');
|
||||
});
|
||||
|
||||
test('DETAILS shows partial coverage for a dateline day with one side empty, unknown when a side did not answer', async () => {
|
||||
const f = fixture();
|
||||
f.layer.enable();
|
||||
f.layer.setBox(FIJI_BOX);
|
||||
f.catalog.resolveLast();
|
||||
await settle();
|
||||
assert.match(f.byId('ri-details').textContent, /Coverage full/);
|
||||
const get = f.thumbnails.get;
|
||||
const [west, east] = nonCrossingBoxes(FIJI_BOX);
|
||||
f.thumbnails.get = (key) => ({
|
||||
...get(key),
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [east],
|
||||
});
|
||||
f.thumbnails.probe(f.snap().focus.key, 'present');
|
||||
assert.match(f.byId('ri-details').textContent, /Coverage partial/);
|
||||
f.thumbnails.get = (key) => ({
|
||||
...get(key),
|
||||
availableBoxes: [west],
|
||||
emptyBoxes: [],
|
||||
});
|
||||
f.thumbnails.probe(f.snap().focus.key, 'present');
|
||||
assert.match(f.byId('ri-details').textContent, /Coverage unknown/);
|
||||
});
|
||||
|
||||
test('the body scroll position survives renders even when DOM mutations reset it', async () => {
|
||||
const f = fixture();
|
||||
await f.ready();
|
||||
|
||||
@@ -13,11 +13,11 @@ const REFUSALS = [
|
||||
'Point the camera at the ground to use the view', // layers/recentImagery/index.js
|
||||
'That point cannot anchor a box', // layers/recentImagery/index.js
|
||||
...[
|
||||
{ west: 170, south: 10, east: -170, north: 20 }, // dateline
|
||||
{ west: 10, south: 80, east: 20, north: 89 }, // polar
|
||||
{ west: 10, south: 10, east: 10, north: 20 }, // degenerate
|
||||
{ west: 10, south: 10, east: 200, north: 20 }, // longitude range
|
||||
{ west: Number.NaN, south: 10, east: 20, north: 20 }, // not finite
|
||||
{ west: 170, south: 10, east: -170, north: 20 }, // dateline, over the size cap
|
||||
{ west: 10, south: 80, east: 20, north: 89 },
|
||||
{ west: 10, south: 10, east: 10, north: 20 },
|
||||
{ west: 10, south: 10, east: 200, north: 20 },
|
||||
{ west: Number.NaN, south: 10, east: 20, north: 20 },
|
||||
].map((box) => {
|
||||
const result = validateBox(box);
|
||||
assert.equal(result.ok, false);
|
||||
@@ -27,7 +27,14 @@ const REFUSALS = [
|
||||
|
||||
test('en: refusals stay English', () => {
|
||||
setLocale('en');
|
||||
for (const text of REFUSALS) assert.equal(localizeNotice(text), text);
|
||||
for (const text of REFUSALS) {
|
||||
const shown = localizeNotice(text);
|
||||
// Size refusals are rewritten with a non-breaking space before the unit.
|
||||
const expected = / km wide/.test(text)
|
||||
? text.replaceAll(' km', '\u00a0km')
|
||||
: text;
|
||||
assert.equal(shown, expected);
|
||||
}
|
||||
assert.ok(REFUSALS.includes('Imagery stops at ±85.05° latitude'));
|
||||
});
|
||||
|
||||
|
||||
@@ -431,6 +431,35 @@ html:not([lang='en']):not(:lang(zh)):not(:lang(ja))
|
||||
}
|
||||
}
|
||||
|
||||
/* The opening (src/app/openingIntro.js) sets these each frame. */
|
||||
#loading-screen.opening {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--bg-dark) calc(var(--opening-veil, 1) * 100%),
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
#loading-screen.opening .loader-logo {
|
||||
animation: none;
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
#loading-screen.opening .loader-logo svg {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
#loading-screen.opening .loader-logo svg > path {
|
||||
transform-box: fill-box;
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
#loading-screen.opening h2,
|
||||
#loading-screen.opening .loader-status {
|
||||
animation: none;
|
||||
opacity: var(--opening-text, 1);
|
||||
}
|
||||
|
||||
.loader-content h2 {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 18px;
|
||||
|
||||
+11
-11
@@ -17,7 +17,12 @@
|
||||
* @module voice/imageryActions
|
||||
*/
|
||||
|
||||
import { PRODUCTS, rankLatest } from '../layers/recentImagery/model.js';
|
||||
import {
|
||||
PRODUCTS,
|
||||
boxCentre,
|
||||
boxSideKm,
|
||||
rankLatest,
|
||||
} from '../layers/recentImagery/model.js';
|
||||
import {
|
||||
displacedLayerResult,
|
||||
watchExplicitLayerOff,
|
||||
@@ -203,19 +208,14 @@ export async function findImagery(
|
||||
`No area "${args.areaId}" on this page — call resolve_area again.`,
|
||||
);
|
||||
const [west, south, east, north] = record.bbox;
|
||||
if (west > east)
|
||||
return fail(
|
||||
'DATELINE',
|
||||
`${record.name} crosses the date line; the imagery box needs one side of it.`,
|
||||
);
|
||||
// 30 m pixels over a landmark-sized area show a handful of blobs: a small
|
||||
// area gets the layer's own 10 km box around its centre instead.
|
||||
const small =
|
||||
(north - south) * 111 < 5 &&
|
||||
(east - west) * 111 * Math.cos((((north + south) / 2) * Math.PI) / 180) <
|
||||
5;
|
||||
// west > east is the short arc across the date line. The layer's helpers
|
||||
// measure and centre it.
|
||||
const { width, height } = boxSideKm({ west, south, east, north });
|
||||
const small = width < 5 && height < 5;
|
||||
box = small
|
||||
? { pin: { lon: (west + east) / 2, lat: (south + north) / 2 } }
|
||||
? { pin: boxCentre({ west, south, east, north }) }
|
||||
: { west, south, east, north };
|
||||
areaName = record.name;
|
||||
} else if (where === 'point') {
|
||||
|
||||
@@ -236,7 +236,7 @@ test('an area handle searches its bounding box; the view and pointer have their
|
||||
assert.equal(unknown.code, 'AREA_UNKNOWN');
|
||||
});
|
||||
|
||||
test('a mixed antimeridian area gets the deliberate imagery date-line refusal', async () => {
|
||||
test('a mixed antimeridian area is searched as its short-arc box', async () => {
|
||||
const square = (w, s, e, n) => [
|
||||
[w, s],
|
||||
[e, s],
|
||||
@@ -251,6 +251,7 @@ test('a mixed antimeridian area gets the deliberate imagery date-line refusal',
|
||||
[178, 1],
|
||||
[178, 0],
|
||||
];
|
||||
const layer = fakeLayer();
|
||||
const store = createAreaStore();
|
||||
const area = store.put({
|
||||
geometry: [[crossing], [square(-176, 0.2, -174, 0.8)]],
|
||||
@@ -258,11 +259,33 @@ test('a mixed antimeridian area gets the deliberate imagery date-line refusal',
|
||||
source: 'osm',
|
||||
});
|
||||
assert.deepEqual(area.bbox, [178, 0, -174, 1]);
|
||||
const result = await findImagery(deps(fakeLayer(), { area }).value, {
|
||||
const result = await findImagery(deps(layer, { area }).value, {
|
||||
areaId: area.areaId,
|
||||
});
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.code, 'DATELINE');
|
||||
assert.equal(result.ok, true, 'the guard is lifted');
|
||||
assert.deepEqual(layer.calls.find((c) => c[0] === 'setBox')[1], {
|
||||
west: 178,
|
||||
south: 0,
|
||||
east: -174,
|
||||
north: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test('a small area across the date line is pinned at its short-arc centre', async () => {
|
||||
const layer = fakeLayer();
|
||||
await findImagery(
|
||||
deps(layer, {
|
||||
area: {
|
||||
areaId: 'd',
|
||||
name: 'Dateline Islet',
|
||||
bbox: [179.998, 0, -179.998, 0.01],
|
||||
},
|
||||
}).value,
|
||||
{ areaId: 'd' },
|
||||
);
|
||||
const [, lon, lat] = layer.calls.find((c) => c[0] === 'boxFromPinAt');
|
||||
assert.ok(Math.abs(Math.abs(lon) - 180) < 1e-9, `pin lon ${lon}, not 0`);
|
||||
assert.equal(lat, 0.005);
|
||||
});
|
||||
|
||||
test('a box the layer refuses is refused with its reason, and the layer is turned on first', async () => {
|
||||
|
||||
Reference in new issue
Block a user